diff --git a/AGENTS.md b/AGENTS.md index a2570b05..f6795489 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -76,6 +76,7 @@ Do not weaken these unless the user explicitly asks for a product change. - **INV-28:** Network or unclassifiable destinations use the remote copy policy. Copy verification can't be turned off; flushing uses `F_FULLFSYNC` and falls back only to `fsync`, whose failure fails the copy; installation needs native `renamex_np`/`RENAME_EXCL`, an ENOTSUP aborts the run, and the placeholder check-then-rename fallback is never used; a destination volume change aborts before the next copy; `.organize_cache.db` opens with rollback `journal_mode=DELETE` verified by readback; app mutations hold the per-share Application Support lease (a network destination with no lease directory configured is refused, never run without it); Organize preview/transfer and Reorganize/Undo Reorganize prove atomic no-replace before planning or moving; an Organize transfer with verification off is refused in `prepare` before anything is written; and the CLI refuses these destinations before writing anything. - **INV-29:** Saved Deduplicate review state (`Application Support/Chronoframe/dedupe_reviews/*.json`) is review state only. On restore, a saved Keep/Delete choice applies to a path only when the current scan identity equals the saved identity, and a saved group approval applies only when the group's member identities are unchanged; everything else is dropped and reported. Restoring never builds a plan, never pre-approves a commit, and never bypasses the reviewed-plan confirmation. - **INV-31:** An edited variant exported from Apple Photos (`-edited.` beside `.` in one folder, matched case-insensitively) is never Trashed unless the user explicitly marks that file Delete. It is never selected by a cluster's automatic suggestion, never added by pair, sidecar or fanout rules, and is never a deletion consequence of its original being Deleted. Deleting the original leaves the variant in place. +- **INV-32:** A Deduplicate plan never empties a group. A group whose members are all marked Delete is skipped, and its members then stay whichever route would remove them: neither pair fan-out from another group nor a second group that lists the same files adds them to the plan. Invariant IDs are permanent: do not renumber or reuse them. Add new invariants with a new unused ID; `// AGENTS-INVARIANT: N` test tags refer to that explicit ID, not list position. diff --git a/ui/Sources/ChronoframeCore/DeduplicationPlanner.swift b/ui/Sources/ChronoframeCore/DeduplicationPlanner.swift index f5074f9a..49aa62ed 100644 --- a/ui/Sources/ChronoframeCore/DeduplicationPlanner.swift +++ b/ui/Sources/ChronoframeCore/DeduplicationPlanner.swift @@ -14,7 +14,8 @@ import Foundation /// where an explicit Keep on one half got silently overridden by a /// Delete on the other half. /// 3. Per-cluster safety rail: skip any cluster whose effective decisions -/// are all Delete after step 2 (never empty a cluster). +/// are all Delete after step 2 (never empty a cluster). Its members are +/// then protected from steps 4 and 5 as well (INV-32). /// 4. Emit Items for direct cluster-member Deletes, with cluster ownership. /// 5. Pair expansion for partners outside any cluster (Live Photo MOV /// halves, mainly). Each toggle is honored independently — disabling @@ -112,12 +113,21 @@ public enum DeduplicationPlanner { } if allDelete { skipped.insert(cluster.id) } } + // INV-32: the members of a skipped cluster stay, whichever route + // would remove them. Without this a cluster the rail skipped could + // still be emptied by pair fanout from another cluster (step 5) or + // by an overlapping cluster that lists the same files (step 4). + var railProtectedPaths: Set = [] + for cluster in clusters where skipped.contains(cluster.id) { + railProtectedPaths.formUnion(cluster.members.map(\.path)) + } // 4. Direct deletes (cluster members marked Delete). var planItems: [String: DeduplicationPlan.Item] = [:] for cluster in clusters where !skipped.contains(cluster.id) { for member in cluster.members { guard effective[member.path]?.decision == .delete else { continue } + if railProtectedPaths.contains(member.path) { continue } guard let expectedIdentity = snapshot.identitiesByPath[member.path] else { continue } @@ -150,6 +160,7 @@ public enum DeduplicationPlanner { if effective[partner]?.decision == .keep { continue } + if railProtectedPaths.contains(partner) { continue } // INV-31: pair fanout never adds an edited variant. A partner // outside every cluster carries no scanner flag, so the file // name convention is the fail-closed fallback. diff --git a/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerGroupRailTests.swift b/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerGroupRailTests.swift new file mode 100644 index 00000000..59dfdafc --- /dev/null +++ b/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerGroupRailTests.swift @@ -0,0 +1,138 @@ +import Foundation +import XCTest +@testable import ChronoframeCore + +/// Fixed regressions for the per-group safety rail: a group whose members +/// are all marked Delete is skipped, and nothing else in the plan may then +/// remove its members by another route. +final class DeduplicationPlannerGroupRailTests: XCTestCase { + // AGENTS-INVARIANT: 32 + func testPairFanoutNeverEmptiesAGroupTheRailSkipped() { + // The same RAW+JPEG folder imported twice, plus a third JPEG copy. + let rawA = candidate("/lib/A/1.CR2", isRaw: true, pairedPath: "/lib/A/1.JPG") + let rawB = candidate("/lib/B/1.CR2", isRaw: true, pairedPath: "/lib/B/1.JPG") + let jpegA = candidate("/lib/A/1.JPG", pairedPath: "/lib/A/1.CR2") + let jpegB = candidate("/lib/B/1.JPG", pairedPath: "/lib/B/1.CR2") + let jpegC = candidate("/lib/C/1.JPG") + let raws = cluster([rawA, rawB]) + let jpegs = cluster([jpegC, jpegA, jpegB]) + let decisions = DedupeDecisions(byPath: [ + rawA.path: .delete, rawB.path: .delete, + jpegA.path: .delete, jpegB.path: .delete, + jpegC.path: .keep, + ]) + + let plan = DeduplicationPlanner.plan( + decisions: decisions, + clusters: [raws, jpegs], + configuration: configuration(), + snapshot: testScanSnapshot(for: [raws, jpegs]) + ) + + let planned = Set(plan.items.map(\.path)) + XCTAssertEqual(planned, [jpegA.path, jpegB.path]) + XCTAssertFalse(planned.contains(rawA.path), "the skipped group must stay whole") + XCTAssertFalse(planned.contains(rawB.path), "the skipped group must stay whole") + } + + // AGENTS-INVARIANT: 32 + func testPairFanoutNeverEmptiesASkippedGroupWhateverTheGroupOrder() { + let rawA = candidate("/lib/A/1.CR2", isRaw: true, pairedPath: "/lib/A/1.JPG") + let rawB = candidate("/lib/B/1.CR2", isRaw: true, pairedPath: "/lib/B/1.JPG") + let jpegA = candidate("/lib/A/1.JPG", pairedPath: "/lib/A/1.CR2") + let jpegB = candidate("/lib/B/1.JPG", pairedPath: "/lib/B/1.CR2") + let jpegC = candidate("/lib/C/1.JPG") + let raws = cluster([rawA, rawB]) + let jpegs = cluster([jpegC, jpegA, jpegB]) + let decisions = DedupeDecisions(byPath: [ + rawA.path: .delete, rawB.path: .delete, + jpegA.path: .delete, jpegB.path: .delete, + jpegC.path: .keep, + ]) + + let plan = DeduplicationPlanner.plan( + decisions: decisions, + clusters: [jpegs, raws], + configuration: configuration(), + snapshot: testScanSnapshot(for: [jpegs, raws]) + ) + + XCTAssertEqual(Set(plan.items.map(\.path)), [jpegA.path, jpegB.path]) + } + + // AGENTS-INVARIANT: 32 + func testOverlappingGroupNeverEmptiesAGroupTheRailSkipped() { + // Two identical copies form an exact group; the same two plus a + // look-alike form a second group. Deleting both copies would empty + // the exact group, so the rail skips it and the copies stay. + let copyA = candidate("/lib/A/1.jpg") + let copyB = candidate("/lib/B/1.jpg") + let lookAlike = candidate("/lib/A/1b.jpg") + let exact = cluster([copyA, copyB], kind: .exactDuplicate) + let near = cluster([lookAlike, copyA, copyB], kind: .nearDuplicate) + let decisions = DedupeDecisions(byPath: [ + copyA.path: .delete, copyB.path: .delete, lookAlike.path: .keep, + ]) + + for clusters in [[exact, near], [near, exact]] { + let plan = DeduplicationPlanner.plan( + decisions: decisions, + clusters: clusters, + configuration: configuration(), + snapshot: testScanSnapshot(for: clusters) + ) + XCTAssertEqual(plan.items.map(\.path), [], "both copies must survive") + } + } + + func testAGroupWithAKeptMemberStillFansOutToItsPairPartner() { + // The rail change must not stop ordinary pair fan-out. + let rawA = candidate("/lib/A/1.CR2", isRaw: true, pairedPath: "/lib/A/1.JPG") + let rawB = candidate("/lib/B/1.CR2", isRaw: true, pairedPath: "/lib/B/1.JPG") + let jpegA = candidate("/lib/A/1.JPG", pairedPath: "/lib/A/1.CR2") + let jpegB = candidate("/lib/B/1.JPG", pairedPath: "/lib/B/1.CR2") + let raws = cluster([rawA, rawB]) + let jpegs = cluster([jpegA, jpegB]) + let decisions = DedupeDecisions(byPath: [ + rawA.path: .keep, rawB.path: .delete, + jpegA.path: .keep, jpegB.path: .delete, + ]) + + let plan = DeduplicationPlanner.plan( + decisions: decisions, + clusters: [raws, jpegs], + configuration: configuration(), + snapshot: testScanSnapshot(for: [raws, jpegs]) + ) + + XCTAssertEqual(Set(plan.items.map(\.path)), [rawB.path, jpegB.path]) + } + + // MARK: Helpers + + private func candidate(_ path: String, isRaw: Bool = false, pairedPath: String? = nil) -> PhotoCandidate { + PhotoCandidate(path: path, size: 1_000, modificationTime: 0, isRaw: isRaw, pairedPath: pairedPath) + } + + private func cluster(_ members: [PhotoCandidate], kind: ClusterKind = .exactDuplicate) -> DuplicateCluster { + DuplicateCluster( + id: UUID(), + kind: kind, + members: members, + suggestedKeeperIDs: [members[0].id], + bytesIfPruned: 0, + annotation: ClusterAnnotation(confidence: .high, matchReason: MatchReason(kind: kind), warnings: []) + ) + } + + private func configuration() -> DeduplicateConfiguration { + DeduplicateConfiguration( + destinationPath: "/tmp/destination", + timeWindowSeconds: 30, + similarityThreshold: 0.9, + dhashHammingThreshold: 5, + treatRawJpegPairsAsUnit: true, + treatLivePhotoPairsAsUnit: true + ) + } +} diff --git a/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerPropertyTests.swift b/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerPropertyTests.swift index cb94869f..9833fc22 100644 --- a/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerPropertyTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerPropertyTests.swift @@ -115,6 +115,33 @@ final class DeduplicationPlannerPropertyTests: XCTestCase { } } + /// The same property when pairs cross clusters (the RAW halves in one + /// cluster, the JPEG halves in another) and when a cluster lists files + /// another cluster also lists. + // AGENTS-INVARIANT: 32 + func testPropertyNoClusterIsEmptiedWithCrossClusterPairsAndOverlap() { + var prng = SeededPRNG(seed: 0x0C12_055C_1A57_E125) + for iteration in 0..<(Self.iterations * 4) { + let scenario = randomScenario(prng: &prng, crossClusterStructure: true) + let plan = DeduplicationPlanner.plan( + decisions: scenario.decisions, + clusters: scenario.clusters, + configuration: scenario.configuration, + snapshot: testScanSnapshot(for: scenario.clusters) + ) + let deletedPaths = Set(plan.items.map(\.path)) + for cluster in scenario.clusters { + let memberPaths = Set(cluster.members.map(\.path)) + let survivors = memberPaths.subtracting(deletedPaths) + XCTAssertFalse( + survivors.isEmpty, + "iteration \(iteration): cluster \(cluster.id) was completely emptied. " + + "members=\(memberPaths) deleted=\(deletedPaths)" + ) + } + } + } + /// Per-pair-kind toggles are independent. /// AGENTS.md: "disabling RAW pairing must not affect Live Photo /// behaviour and vice versa." @@ -255,7 +282,8 @@ private func scenarioPairKind( private func randomScenario( prng: inout SeededPRNG, - forbidExplicitDecisions: Bool = false + forbidExplicitDecisions: Bool = false, + crossClusterStructure: Bool = false ) -> GeneratedScenario { let clusterCount = prng.intInRange(1...4) var clusters: [DuplicateCluster] = [] @@ -265,6 +293,9 @@ private func randomScenario( var autoSuggestedKeepers: [UUID: Set] = [:] var counter = 0 + var memberLists: [[PhotoCandidate]] = [] + var confidences: [ConfidenceLevel] = [] + var kinds: [ClusterKind] = [] for _ in 0..