Skip to content

🐛 [fix] CloudKit 동기화 데이터 유실 방지 강화#172

Merged
leeari95 merged 7 commits into
release/3.2.2from
fix/icloud
Apr 8, 2026
Merged

🐛 [fix] CloudKit 동기화 데이터 유실 방지 강화#172
leeari95 merged 7 commits into
release/3.2.2from
fix/icloud

Conversation

@leeari95

@leeari95 leeari95 commented Apr 8, 2026

Copy link
Copy Markdown
Owner

문제

기존 유저로부터 앱 업데이트 후 데이터가 반복적으로 초기화된다는 피드백 접수.

최근들어 초기화만 세번째인데 로컬데이터를 아이클라우드 데이터에 올라가는 과정에 잘못이 된건지.. 기존에 있던 데이터가 초기화되는 업데이트 하면서 또 초기화가 됐네요..

근본 원인

앱 업데이트 / iCloud 재로그인 시 NSPersistentCloudKitContainer가 CloudKit 미러를 재구성하면서 로컬 UC가 일시적으로 0개가 되는 구간이 발생. 이때 getUserCollection()빈 UC를 자동 생성하고, 이 빈 UC가 CloudKit에 Export되면서 기존 클라우드 데이터가 오염됨.

sequenceDiagram
    participant App
    participant CoreData as CoreData (Local)
    participant CloudKit as CloudKit (Server)

    Note over App: 앱 업데이트 후 실행
    App->>CoreData: getUserCollection()
    CoreData-->>App: UC 0개 (미러 재구성 중)

    rect rgb(255,230,230)
    Note over App: ❌ 기존 동작 (데이터 유실)
    App->>CoreData: 빈 UC 생성
    CoreData->>CloudKit: Export 빈 UC
    Note over CloudKit: 기존 데이터 오염
    end
Loading

해결

1. 기존 유저 플래그 도입 (hasEverHadUserCollection) — P0

flowchart TD
    A[getUserCollection 호출] --> B{UC 존재?}
    B -->|Yes| C[✅ 반환 + 플래그 true 기록]
    B -->|No| D{억제 조건 체크}
    D -->|import/syncReset/gracePeriod| E[🛡️ .notFound throw]
    D -->|hasEverHadUserCollection=true| F[🛡️ .notFound throw<br/>빈 UC 생성 차단]
    D -->|모두 false + 신규유저| G[새 UC 생성]

    style F fill:#ffe0e0
    style E fill:#ffe0e0
    style G fill:#e0ffe0
Loading
  • UserDefaults 기반 hasEverHadUserCollection 플래그
  • UC를 한 번이라도 fetch 성공하면 true 기록
  • 이후 UC가 0개여도 빈 UC 생성을 차단하여 CloudKit 데이터 오염 방지
  • "데이터 초기화" 시에는 clearHasEverHadUserCollection()으로 리셋하여 정상 동작 보장

2. DailyTask 기본값 자동 생성 보호 — P0

  • 기존: isImportInProgress만 체크
  • 변경: shouldSuppressDataCreation 통합 프로퍼티로 교체 (import/syncReset/gracePeriod 모두 체크)
  • 기존 유저의 커스텀 태스크가 하드코딩된 9개 기본 태스크로 덮어씌워지는 문제 방지

3. Grace Period 연장 (30s → 120s) — P0

대용량 데이터의 CloudKit re-import 시간을 충분히 확보.

4. 동기화 상태 표시 — P1

유저 요청사항:

아이클라우드에 업로드가 되어 있는지, 다운로드 가능한 데이터가 언제 데이터인지 알 수 있다면 좋을 거 같은데

설정 화면에 iCloud 동기화 상태를 한 줄로 표시:

  • 동기화 중: 동기화 중...
  • 정상: 3분 전 동기화 · 152개 저장됨
  • 데이터 대기: iCloud 데이터 대기 중...

5. 에러 로깅 강화 — P1

모든 Storage 클래스의 debugPrint(error)os_log(.error) 교체.
Release 빌드에서도 Console.app으로 프로덕션 에러 추적 가능.

변경 파일

파일 변경 내용
CoreDataStorage.swift hasEverHadUserCollection, shouldSuppressDataCreation, SyncStatusInfo, fetchSyncStatus(), grace period 120s, 동기화 시각 추적
CoreDataDailyTaskStorage.swift 기본 태스크 생성 조건 shouldSuppressDataCreation 적용
CoreDataUserInfoStorage.swift 데이터 초기화 시 clearHasEverHadUserCollection() 호출
AppSettingReactor.swift loadSyncStatus Action/Mutation 추가
AppSettingView.swift 동기화 상태 라벨 + Row 간격 조정
Localizable.strings (ko/en) 동기화 상태 문자열 5개 추가
7개 Storage + Items + TasksEditReactor debugPrintos_log 교체
icloud-sync.md Known User Protection, Sync Status, Error Logging 섹션 추가

시나리오 검증

시나리오 결과
A. 앱 업데이트 후 CloudKit 미러 재구성 ✅ 빈 UC 생성 차단
B. 완전히 새로운 유저 (첫 설치) ✅ 정상 UC 생성
C. 기존 유저, CloudKit re-import 완료 ✅ 정상 복구
D. 유저가 "데이터 초기화" 실행 ✅ 플래그 리셋 → 새 UC 정상 생성
E. 기존 유저의 DailyTask 자동 생성 ✅ 정상 동작 (영구 차단 아님)
F. 앱 업데이트 중 DailyTask 보호 ✅ 기본 태스크 덮어쓰기 방지

Test Plan

  • 기존 데이터가 있는 기기에서 앱 업데이트 후 데이터 유지 확인
  • 신규 설치 시 정상 UC 생성 및 DailyTask 기본값 생성 확인
  • "데이터 초기화" 후 새 데이터 입력 가능 확인
  • "iCloud에서 데이터 복구" 후 정상 복구 확인
  • 설정 화면에서 동기화 상태 표시 확인 (동기화 시각, 저장 개수)
  • iCloud 로그아웃/재로그인 시 데이터 유지 확인

leeari95 added 5 commits April 8, 2026 22:40
- 기존 유저 플래그(hasEverHadUserCollection) 도입하여 앱 업데이트/iCloud 재구성 시
  빈 UC 자동 생성으로 인한 클라우드 데이터 오염 차단
- Grace period 30초 → 120초 연장 (대용량 re-import 대응)
- DailyTask 기본값 자동 생성에 shouldSuppressDataCreation 통합 보호 적용
- 의도적 데이터 초기화 시 hasEverHadUserCollection 리셋 (clearHasEverHadUserCollection)
- 설정 화면에 동기화 상태 표시 (로컬 레코드 수, 마지막 동기화 시각, 동기화 진행 상태)
Release 빌드에서도 에러 추적이 가능하도록 모든 CoreData Storage 클래스와
Items.swift, TasksEditReactor의 debugPrint(error)를 os_log(.error)로 교체
- Known User Protection (hasEverHadUserCollection) 섹션 추가
- shouldSuppressDataCreation 통합 프로퍼티 설명
- UC 생성 억제 조건 4가지 → 5가지로 업데이트 (grace period 120초)
- Sync Status Display 섹션 추가
- Error Logging 강화 섹션 추가
- "로컬 레코드: N개" → "N개 저장됨" (사용자 친화적 문구)
- 동기화 시각 있을 때 "3분 전 동기화 · N개 저장됨" 형태로 통합
- 여러 줄 → 한 줄 표시 (numberOfLines=1, textAlignment=.right)
@coderabbitai

coderabbitai Bot commented Apr 8, 2026

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 443ff25a-f3cf-4fb4-82a3-03a83edd71ac

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/icloud

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@leeari95
leeari95 marked this pull request as ready for review April 8, 2026 13:57
@leeari95 leeari95 self-assigned this Apr 8, 2026
@leeari95 leeari95 added the bug Something isn't working label Apr 8, 2026
leeari95 added 2 commits April 8, 2026 23:04
- grace period 상수(120s) + isWithinGracePeriod 추출 (DRY)
- entityCounts(in:) 헬퍼 추출하여 logSyncDiagnostics/fetchSyncStatus 공용화
- hasEverHadUserCollection 메모리 캐싱 (매 호출 UserDefaults 읽기 제거)
- RelativeDateTimeFormatter를 DateFormatters.syncRelativeDate로 캐싱
@leeari95
leeari95 merged commit 483212e into release/3.2.2 Apr 8, 2026
1 of 2 checks passed
@leeari95
leeari95 deleted the fix/icloud branch April 8, 2026 14:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant