Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 (`<stem>-edited.<ext>` beside `<stem>.<ext>` 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.

Expand Down
13 changes: 12 additions & 1 deletion ui/Sources/ChronoframeCore/DeduplicationPlanner.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<String> = []
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
}
Expand Down Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
@@ -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
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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."
Expand Down Expand Up @@ -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] = []
Expand All @@ -265,6 +293,9 @@ private func randomScenario(
var autoSuggestedKeepers: [UUID: Set<String>] = [:]

var counter = 0
var memberLists: [[PhotoCandidate]] = []
var confidences: [ConfidenceLevel] = []
var kinds: [ClusterKind] = []
for _ in 0..<clusterCount {
let memberCount = prng.intInRange(2...4)
let conf: ConfidenceLevel = [.high, .medium, .low][prng.intInRange(0...2)]
Expand All @@ -273,7 +304,7 @@ private func randomScenario(
for _ in 0..<memberCount {
let pathIndex = counter
counter += 1
let path = "/test/c\(clusters.count)/m\(pathIndex).jpg"
let path = "/test/c\(memberLists.count)/m\(pathIndex).jpg"
let isRaw = prng.bool()
members.append(
PhotoCandidate(
Expand All @@ -298,7 +329,48 @@ private func randomScenario(
pairKinds[a] = kind
pairKinds[b] = kind
}
memberLists.append(members)
confidences.append(conf)
kinds.append(kind)
}

if crossClusterStructure {
// Pair still-unpaired members of neighbouring clusters, index by index.
for index in 0..<(memberLists.count - 1) {
for position in 0..<min(memberLists[index].count, memberLists[index + 1].count) where prng.bool() {
let a = memberLists[index][position]
let b = memberLists[index + 1][position]
guard a.pairedPath == nil, b.pairedPath == nil else { continue }
let kind: DeduplicatePairDetector.Pair.Kind = prng.bool() ? .rawJpeg : .livePhoto
memberLists[index][position] = withPairedPath(a, partner: b.path, isLivePhoto: kind == .livePhoto)
memberLists[index + 1][position] = withPairedPath(b, partner: a.path, isLivePhoto: kind == .livePhoto)
pairPartners[a.path] = b.path
pairPartners[b.path] = a.path
pairKinds[a.path] = kind
pairKinds[b.path] = kind
}
}
// Sometimes add a cluster that lists another cluster's members
// again, plus one file of its own.
if prng.bool() {
let source = prng.intInRange(0...(memberLists.count - 1))
let extra = PhotoCandidate(
path: "/test/overlap/m\(counter).jpg",
size: 1_000,
modificationTime: 0,
isRaw: false
)
let conf: ConfidenceLevel = [.high, .medium, .low][prng.intInRange(0...2)]
clusterConfidence[extra.path] = conf
memberLists.append([extra] + memberLists[source])
confidences.append(conf)
kinds.append(.nearDuplicate)
}
}

for (index, members) in memberLists.enumerated() {
let conf = confidences[index]
let kind = kinds[index]
let id = UUID()
let suggestedKeeperID = members.first?.id ?? ""
let clusterMembers = members
Expand Down
Loading