fix: comprehensive codebase hardening — crashes, silent failures, performance, and security

Fixes ~95 issues from deep audit across 12 categories in 82 files:

- Crash prevention: double-resume in PhotoMetadataExtractor, force unwraps in
  DateRangePicker, array bounds checks in polls/achievements, ProGate hit-test
  bypass, Dictionary(uniqueKeysWithValues:) → uniquingKeysWith in 4 files
- Silent failure elimination: all 34 try? sites replaced with do/try/catch +
  logging (SavedTrip, TripDetailView, CanonicalSyncService, BootstrapService,
  CanonicalModels, CKModels, SportsTimeApp, and more)
- Performance: cached DateFormatters (7 files), O(1) team lookups via
  AppDataProvider, achievement definition dictionary, AnimatedBackground
  consolidated from 19 Tasks to 1, task cancellation in SharePreviewView
- Concurrency: UIKit drawing → MainActor.run, background fetch timeout guard,
  @MainActor on ThemeManager/AppearanceManager, SyncLogger read/write race fix
- Planning engine: game end time in travel feasibility, state-aware city
  normalization, exact city matching, DrivingConstraints parameter propagation
- IAP: unknown subscription states → expired, unverified transaction logging,
  entitlements updated before paywall dismiss, restore visible to all users
- Security: API key to Info.plist lookup, filename sanitization in PDF export,
  honest User-Agent, removed stale "Feels" analytics super properties
- Navigation: consolidated competing navigationDestination, boolean → value-based
- Testing: 8 sleep() → waitForExistence, duplicates extracted, Swift 6 compat
- Service bugs: infinite retry cap, duplicate achievement prevention, TOCTOU vote
  fix, PollVote.odg → voterId rename, deterministic placeholder IDs, parallel
  MKDirections, Sendable-safe POI struct

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Trey t
2026-02-27 17:03:09 -06:00
parent e046cb6b34
commit c94e373e33
82 changed files with 1163 additions and 599 deletions

View File

@@ -323,7 +323,11 @@ final class CanonicalSyncService {
// Graceful cancellation - progress already saved
syncState.syncInProgress = false
syncState.lastSyncError = "Sync cancelled - partial progress saved"
try? context.save()
do {
try context.save()
} catch {
SyncLogger.shared.log("⚠️ [SYNC] Failed to save cancellation state: \(error.localizedDescription)")
}
#if DEBUG
SyncStatusMonitor.shared.syncFailed(error: CancellationError())
@@ -354,23 +358,20 @@ final class CanonicalSyncService {
} else {
syncState.consecutiveFailures += 1
// Pause sync after too many failures
// Pause sync after too many failures (consistent in all builds)
if syncState.consecutiveFailures >= 5 {
#if DEBUG
syncState.syncEnabled = false
syncState.syncPausedReason = "Too many consecutive failures. Sync paused."
#else
syncState.consecutiveFailures = 5
syncState.syncPausedReason = nil
#endif
}
}
try? context.save()
do {
try context.save()
} catch let saveError {
SyncLogger.shared.log("⚠️ [SYNC] Failed to save error state: \(saveError.localizedDescription)")
}
#if DEBUG
SyncStatusMonitor.shared.syncFailed(error: error)
#endif
throw error
}
@@ -396,7 +397,11 @@ final class CanonicalSyncService {
syncState.syncEnabled = true
syncState.syncPausedReason = nil
syncState.consecutiveFailures = 0
try? context.save()
do {
try context.save()
} catch {
SyncLogger.shared.log("⚠️ [SYNC] Failed to save resume sync state: \(error.localizedDescription)")
}
}
nonisolated private func isTransientCloudKitError(_ error: Error) -> Bool {
@@ -524,9 +529,14 @@ final class CanonicalSyncService {
var skippedIncompatible = 0
var skippedOlder = 0
// Batch-fetch all existing games to avoid N+1 FetchDescriptor lookups
// Batch-fetch existing games to avoid N+1 FetchDescriptor lookups
// Build lookup only for games matching incoming sync data to reduce dictionary size
let syncCanonicalIds = Set(syncGames.map(\.canonicalId))
let allExistingGames = try context.fetch(FetchDescriptor<CanonicalGame>())
let existingGamesByCanonicalId = Dictionary(grouping: allExistingGames, by: \.canonicalId).compactMapValues(\.first)
let existingGamesByCanonicalId = Dictionary(
grouping: allExistingGames.filter { syncCanonicalIds.contains($0.canonicalId) },
by: \.canonicalId
).compactMapValues(\.first)
for syncGame in syncGames {
// Use canonical IDs directly from CloudKit - no UUID lookups!