// THE FIRST PASS, AND EVERY ONE AFTER (assets/design/albums/DECISIONS.md "The first pass, honest"; RESEARCH.md §1// "Background"): every photo is looked at once, on this phone, newest first, and what was found is kept// (`AlbumsStore`) after every 200: a checkpoint, so a pass stopped anywhere carries on where it stopped and never looks// twice. Four pictures at once (Apple: about five requests at a time).//// When it runs:// - while Albums is open, always;// - after Start, on in the background as a continued task (iOS 26: the person started it with a tap; the phone// shows its progress and the person can stop it; swiping Albums away ends it);// - otherwise in the phone's processing time, only on the charger (`requiresExternalPower`), until the phone says// stop.// The time left is measured from the last 500 looked at, never guessed. A photo with no picture on the phone (only in// iCloud, Optimise Storage) is counted and said, and looked at later on Wi-Fi at the same small size; never the// original.#if os(iOS)importBackgroundTasksimportCottonKitimportFoundationimportNetworkimportObservationimport UIKit@MainActor@ObservablefinalclassAlbumsPass {staticlet shared = AlbumsPass()enumPause: Equatable { case none, battery, away }/// A task the scheduler hands over on its own queue, carried to the main actor that alone touches it after.privatestructHeldTask: @unchecked Sendable {let task: BGTaskinit(_ task: BGTask) { self.task = task } }private(set) var counts = AlbumsStore.Counts()private(set) var running = falseprivate(set) var pause: Pause = .none/// The library has been read at least once (the counts mean something).private(set) var read = false/// Changes every checkpoint: what the screens show follows it.var revision = 0var store: AlbumsStore { AlbumsStore.shared } @ObservationIgnored privatevar stopAsked = false @ObservationIgnored privatevar observer: UUID? @ObservationIgnored privatevar continued: BGTask? @ObservationIgnored privatevar retried = false/// Faces on (the coordinator's word: on by default, grouping on this phone; one switch in You turns them off). @ObservationIgnored var faces: Bool { get { UserDefaults.standard.object(forKey: "albums.faces") as? Bool ?? true } set { UserDefaults.standard.set(newValue, forKey: "albums.faces") } } nonisolated staticlet batch = 200 nonisolated staticlet atOnce = 4var minutesLeft: Int? {guardlet rate = counts.perMinute, rate > 0else { returnnil }returnInt((Double(counts.waiting) / rate).rounded(.up)) }var finished: Bool { read && counts.waiting == 0 && counts.photos > 0 }// MARK: Reading the library/// Brings the store to the library: the whole library the first time (or when the change token expired), only/// what changed after that.func readLibrary() async {guardAlbumsLibrary.access.reads else { return }let library = AlbumsLibrary.sharedlet store = self.storelet (change, token) = awaitTask.detached(priority: .userInitiated) { (try? library.changes()) ?? (.wholePass, nil) }.valuelet (fed, fedSizes, removed, complete, whole) = awaitTask.detached(priority: .userInitiated) { () -> ([LibraryAsset], [String: LibrarySize], [String], Bool, Bool) inswitch change {case .wholePass:// Metadata first (fast), so the pass starts; each asset's size on disk is asked after (`fillSizes`).let (assets, complete) = library.enumerate() store.reconcile(assets, sizes: [:], complete: complete)return (assets, [String: LibrarySize](), [String](), complete, true)case .changed(let inserted, let removed, let updated):let fresh = library.assets(inserted + updated)let sizes = library.sizes(fresh) store.apply(inserted: fresh, removed: removed, sizes: sizes)return (fresh, sizes, removed, false, false) } }.valueif whole { lastReadComplete = complete }// Handed to the core's queue before the token moves on; the pass never waits for the core.let all = whole && complete ? fed.map(\.id) : nil feed?.later { await $0.take(fed, sizes: fedSizes, all: all, removed: removed) }iflet token { library.saveToken(token) } read = true refresh() fillSizes() #if COTTON_DEVifProcessInfo.processInfo.arguments.contains("-albums-sizes"), !sizesMeasured { sizesMeasured = trueTask.detached(priority: .utility) { awaitAlbumsLibrary.shared.measureSizes(count: 200) } } #endifif observer == nil { observer = library.observe { [weakself] _ inTask { @MainActor inawaitself?.libraryChanged() } } } } @ObservationIgnored privatevar sizing = false/// The core's feed (`AlbumsFeed`): set once the root has a core (`use`); until then the pass only keeps its own. @ObservationIgnored private(set) var feed: AlbumsFeed?func use(_ core: any CottonCalling) {guard feed == nilelse { return } feed = AlbumsFeed(core: core)// What was read before the core came: every item once, so the index starts whole.if read { Task { await feedEverything() } } // its own calls go through the queue }/// Every item the store holds, with what is known of its size; `all_ids` only when the last read was complete.privatefunc feedEverything() async {guardlet feed else { return }let store = self.storelet complete = lastReadCompleteawaitTask.detached(priority: .utility) {let items = store.items()var sizes: [String: LibrarySize] = [:]for item in items where item.exact { sizes[item.asset.id] = LibrarySize(bytes: item.bytes, exact: true, filename: item.filename) }let all = complete ? items.map(\.asset.id) : nillet fedSizes = sizes feed.later { await $0.take(items.map(\.asset), sizes: fedSizes, all: all) } }.value } @ObservationIgnored privatevar lastReadComplete = false @ObservationIgnored privatevar sizesMeasured = false/// The size on disk of every asset still "about", 500 at a time, behind the pass.privatefunc fillSizes() {guard !sizing else { return } sizing = truelet store = self.storeTask.detached(priority: .utility) {whiletrue {let ids = store.unsized(500)if ids.isEmpty { break }let assets = AlbumsLibrary.shared.assets(ids)var sizes = AlbumsLibrary.shared.sizes(assets)// An asset gone from the library meanwhile keeps its row until the next read takes it out.for id in ids where sizes[id] == nil { sizes[id] = LibrarySize(bytes: 0, exact: false, filename: "") } store.setSizes(sizes)let fedSizes = sizeslet feed = awaitAlbumsPass.shared.feed feed?.later { await $0.take(assets, sizes: fedSizes) }await feed?.caughtUp(most: 4) }awaitMainActor.run {AlbumsPass.shared.sizing = falseAlbumsPass.shared.refresh() } } }privatefunc libraryChanged() async {await readLibrary()if !running, UIApplication.shared.applicationState == .active { run() }// A kept album gained a photo (kept too) or lost one (its copy stays, listed).AlbumsKeeper.shared.members()AlbumsKeeper.shared.resume() }func refresh() { counts = store.counts() revision += 1 }// MARK: Running/// Runs while Albums is open, until every photo has been looked at or something stops it.func run() {guard !running, AlbumsLibrary.access.reads else { return }Task { await loop(reason: "open") } }/// Start: the pass begins now and carries on in the background as a continued task, with the phone's own/// progress and Stop.func start() { run() submitContinued() }func stop() { stopAsked = true }/// The loop itself: batches of 200, four at a time, a checkpoint after each.func loop(reason: String, progress: Progress? = nil) async {guard !running else {// Already running in this process: the background task only has to wait for it.while running && !stopAsked { try? awaitTask.sleep(for: .seconds(1)) }return } running = true stopAsked = false pause = .noneif !read { await readLibrary() }if !retried { retried = true store.retryFailed() refresh() } store.restartRate() store.setMeta("pass.began", ISO8601DateFormatter().string(from: .now))Log.write("albums: pass \(reason), \(counts.waiting) waiting")let charging = Self.charging feed?.later { await $0.lines(.running, charging: charging) }let store = self.storelet faces = self.facesvar since = ContinuousClock.nowwhile !stopAsked {let next = store.waiting(Self.batch)if next.isEmpty { break }let found = awaitSelf.look(next, faces: faces) store.record(found)// The checkpoint is the store's; the core hears the same batch at once (SHELL BRIEF: after every look). feed?.later { await $0.looks(found) } refresh()// Never more than a few batches ahead of the core (memory stays flat; the pace is the slower of the two).await feed?.caughtUp(most: 4) tick(&since)Self.sampleMemory() regroup(force: false) sayFirstLook(force: false)await coolDown()iflet progress { progress.totalUnitCount = Int64(counts.photos) progress.completedUnitCount = Int64(counts.photos - counts.waiting) } }// Owed a closer look (only in iCloud, or looked at from a picture short of enough): once more on Wi-Fi with// the network allowed, at the same size, never the original (DECISIONS: "then once with it on Wi-Fi").ifSelf.asksICloud, counts.waiting == 0, Self.onWiFi, !stopAsked {var after = Double.infinitywhile !stopAsked, Self.onWiFi {let owed = store.owed(Self.batch, after: after)guardlet oldest = owed.last else { break } after = oldest.created?.timeIntervalSince1970 ?? 0let found = awaitSelf.look(owed, faces: faces, network: true)// A second try that still gave nothing keeps what the first look had.let better = found.filter { $0.look != nil || $0.state == .onlyInCloud } store.record(better.filter { !($0.state == .onlyInCloud && $0.look == nil && store.state($0.id) == .small) }) feed?.later { await $0.looks(better, network: true) } refresh()if after == 0 { break } } } tick(&since) regroup(force: true) sayFirstLook(force: true)if counts.waiting == 0 {if store.meta("pass.finished") == nil { store.setMeta("pass.finished", ISO8601DateFormatter().string(from: .now)) } #if COTTON_DEVifProcessInfo.processInfo.arguments.contains("-albums-faces-mac") { Self.facesFromMac() }ifProcessInfo.processInfo.arguments.contains("-albums-core"), finished, let feed { AlbumsMeasure.exportCore(feed) } #endif } running = false refresh() }/// Looks at a batch, `atOnce` at a time; each picture asked of the phone with the network off. nonisolated staticfunc look(_ assets: [LibraryAsset], faces: Bool, network: Bool = false) async -> [(id: String, state: AlbumsItem.State, look: AlbumsLook?)] {let model = faces ? AlbumsFaces.model : nilreturnawait withTaskGroup(of: (String, AlbumsItem.State, AlbumsLook?).self) { group invar out: [(id: String, state: AlbumsItem.State, look: AlbumsLook?)] = []var iterator = assets.makeIterator()func next() -> Bool {guardlet asset = iterator.next() else { returnfalse } group.addTask {let picture = awaitAlbumsLibrary.shared.localPicture(asset.id, side: AlbumsAnalysis.side, network: network)switch picture {case .picture(let image, let degraded), .small(let image, let degraded):var state = AlbumsItem.State.lookedifcase .small = picture { state = .small }var look = awaitAlbumsAnalysis.look(image, degraded: degraded, asset: asset, faces: faces, model: model)// Faces too small in the small picture but large enough in the original: once more, closer,// from what the phone holds (never the network). The time counts in the look's own.if faces, let side = AlbumsAnalysis.closerSide(look, asset: asset),case .picture(let near, _) = awaitAlbumsLibrary.shared.localPicture(asset.id, side: side), max(near.width, near.height) > look.side {let started = ContinuousClock.nowlet closer = awaitAlbumsAnalysis.closer(near, asset: asset, model: model)if closer.count >= look.faces.count { look.faces = closer }let took = started.duration(to: .now) look.millis += Double(took.components.seconds) * 1000 + Double(took.components.attoseconds) / 1e15 }return (asset.id, state, look)case .onlyInCloud:return (asset.id, .onlyInCloud, nil)case .failed(let why):Log.write("albums: no picture for one asset (\(why))")return (asset.id, .failed, nil) } }returntrue }for _ in0..<atOnce where next() {}whilelet done = await group.next() { out.append((id: done.0, state: done.1, look: done.2)) _ = next() }return out } }// MARK: Time, heat, memory, people and what the phone reports (LOOK-ONLY, coordinator 27 Nov)/// This build never asks iCloud for anything (LOOK-ONLY: "NO network fetch of originals in this build ... so it/// cannot eat his data"): a photo with no adequate picture on the phone is counted, owed a closer look, and the pass/// goes on. The Wi-Fi pass for what is owed comes in a later build by turning this on. nonisolated staticlet asksICloud = false/// Seconds the pass has run, all runs and launches together (time asleep or in the background never counts).var seconds: Double { Double(store.meta("pass.seconds") ?? "") ?? 0 }/// Photos a minute for the report: the whole look's average (looked over the time it ran) once a minute has run;/// before that, the recent rate. A look whose time was not kept (a pass from before the time was counted) has only/// the recent rate. nonisolated staticfunc perMinute(_ c: AlbumsStore.Counts, seconds: Double) -> Double? {let looked = c.looked + c.smallif seconds >= 60, looked > 0 { returnDouble(looked) / seconds * 60 }return c.perMinute }privatefunc tick(_ since: inoutContinuousClock.Instant) {let now = ContinuousClock.nowlet d = since.duration(to: now) store.setMeta("pass.seconds", String(seconds + Double(d.components.seconds) + Double(d.components.attoseconds) / 1e18)) since = now }/// What throttles the pass besides iOS itself: the phone's heat and Low Power Mode. Serious heat or Low Power/// Mode: a 5-second rest after each batch of 200; critical heat: 30 seconds. iOS ends a background task under/// memory pressure or heat on its own (the expiration handler stops at the next checkpoint).privatefunc coolDown() async {let heat = ProcessInfo.processInfo.thermalStatelet rest: Double = heat == .critical ? 30 : (heat == .serious || ProcessInfo.processInfo.isLowPowerModeEnabled) ? 5 : 0guard rest > 0else { return }Self.throttled += 1try? awaitTask.sleep(for: .seconds(rest)) }/// Rests taken for heat or Low Power Mode. nonisolated(unsafe) staticprivate(set) var throttled = 0/// The most memory Albums held at once (its footprint, as iOS counts it against the app), in MB; and memory/// warnings iOS gave it. nonisolated(unsafe) staticprivate(set) var peakFootprintMB: Int = 0 nonisolated(unsafe) staticprivate(set) var memoryWarnings = 0privatestaticlet warningsWatched: NSObjectProtocol = NotificationCenter.default.addObserver( forName: UIApplication.didReceiveMemoryWarningNotification, object: nil, queue: nil) { _ inAlbumsPass.memoryWarnings += 1 } nonisolated staticfunc footprintMB() -> Int? {var info = task_vm_info_data_t()var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<natural_t>.size)let result = withUnsafeMutablePointer(to: &info) { $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count) } }return result == KERN_SUCCESS ? Int(info.phys_footprint / 1_048_576) : nil }staticfunc sampleMemory() { _ = warningsWatchediflet mb = footprintMB(), mb > peakFootprintMB { peakFootprintMB = mb } }/// People: the core's GROUPING 1 over every face with a vector, in the core's queue (never on a screen's way)./// During the pass only when the faces have grown by a quarter (at least 500) and five minutes have passed, since a/// whole library's faces take seconds; always at the end of a run and after he names someone. @ObservationIgnored privatevar grouped: (faces: Int, at: Date) = (0, .distantPast) @ObservationIgnored private(set) var shownGroups = 0func regroup(force: Bool) {guard faces, let feed else { return }let n = store.faceCount()if !force {guard n - grouped.faces >= max(500, grouped.faces / 4), Date.now.timeIntervalSince(grouped.at) >= 300else { return } } elseif n == grouped.faces, grouped.at != .distantPast, !regroupAsked {return } regroupAsked = false grouped = (n, .now)let store = self.store feed.later { feed inlet shown = await feed.group(store)awaitMainActor.run {iflet shown { AlbumsPass.shared.shownGroups = shown }AlbumsPass.shared.revision += 1 } } } @ObservationIgnored privatevar regroupAsked = false/// He named or renamed a group: group again with his names as must-links.func namesChanged() { regroupAsked = true regroup(force: true) }/// The counts the coordinator reads from his phone (the device's reported state, `albums`): counts and timings only./// Said every 2,000 photos looked and at the end of each run, because each change is a synced write. @ObservationIgnored privatevar saidAt = -1func sayFirstLook(force: Bool) {guardlet feed else { return }let c = countslet looked = c.looked + c.smallguard force || saidAt < 0 || looked - saidAt >= 2_000else { return } saidAt = lookedLog.write("albums: looked \(looked) of \(c.photos), \(Int(seconds)) s, \(Self.perMinute(c, seconds: seconds).map { Int($0.rounded()) } ?? 0) a minute, peak \(Self.peakFootprintMB) MB, \(Self.memoryWarnings) warnings, \(Self.throttled) rests, \(c.faces) faces, \(feed.pending) waiting for the core, core busy \(feed.busySeconds) s")var albums: [String: Any] = ["photos": c.photos, "videos": c.videos, "looked": looked, "small": c.small, "noLocalPicture": c.onlyInCloud,"owed": c.small + c.onlyInCloud, "failed": c.failed, "seconds": Int(seconds), "faces": c.faces, "vectors": c.vectors,"shownGroups": shownGroups, "warnings": Self.memoryWarnings, ]iflet rate = Self.perMinute(c, seconds: seconds) { albums["perMinute"] = Int(rate.rounded()) }ifSelf.peakFootprintMB > 0 { albums["peakFootprintMb"] = Self.peakFootprintMB } nonisolated(unsafe) let said = albums // numbers only, built here and never touched again feed.later { _ = await $0.answer("diagnostics.say", ["albums": said]) } }// MARK: The background nonisolated staticlet processing = "com.cottondb.albums.pass" nonisolated staticvar continuedID: String { (Bundle.main.bundleIdentifier ?? "com.cottondb.albums") + ".pass.first" } nonisolated privatestaticvar permitted: [String] {Bundle.main.object(forInfoDictionaryKey: "BGTaskSchedulerPermittedIdentifiers") as? [String] ?? [] }/// Before launch ends (`CottonAppDelegate`), and only in Albums: no other app's plist permits these. nonisolated staticfunc registerTasks() {guard (Bundle.main.object(forInfoDictionaryKey: "BGTaskSchedulerPermittedIdentifiers") as? [String] ?? []).contains(processing) else { return } BGTaskScheduler.shared.register(forTaskWithIdentifier: processing, using: nil) { task inlet held = HeldTask(task) task.expirationHandler = { Task { @MainActor inAlbumsPass.shared.stop() } }Task { @MainActor inawaitAlbumsPass.shared.loop(reason: "processing") held.task.setTaskCompleted(success: AlbumsPass.shared.counts.waiting == 0)AlbumsPass.shared.scheduleProcessing() } } BGTaskScheduler.shared.register(forTaskWithIdentifier: continuedID, using: nil) { task inlet held = HeldTask(task)Task { @MainActor inawaitAlbumsPass.shared.runContinued(held.task) } } }privatefunc runContinued(_ task: BGTask) async { continued = task task.expirationHandler = { Task { @MainActor inAlbumsPass.shared.stop()AlbumsPass.shared.pause = .away } }let progress = (task as? BGContinuedProcessingTask)?.progress progress?.totalUnitCount = Int64(max(1, counts.photos)) progress?.completedUnitCount = Int64(counts.photos - counts.waiting)await loop(reason: "continued", progress: progress) task.setTaskCompleted(success: counts.waiting == 0) continued = nil }privatefunc submitContinued() {guardSelf.permitted.contains(where: { $0.hasSuffix(".pass.*") }) else { return }let request = BGContinuedProcessingTaskRequest(identifier: Self.continuedID, title: AlbumsWords.looking(counts.photos), subtitle: AlbumsWords.fillIn) request.strategy = .queuedo { try BGTaskScheduler.shared.submit(request) } catch { Log.write("albums: continued task not taken (\(error.localizedDescription))") } }/// The rest, on the charger, when the phone has time.func scheduleProcessing() {guard counts.waiting > 0 || (Self.asksICloud && counts.small + counts.onlyInCloud > 0), Self.permitted.contains(Self.processing) else { return }let request = BGProcessingTaskRequest(identifier: Self.processing) request.requiresExternalPower = true request.requiresNetworkConnectivity = falsedo { try BGTaskScheduler.shared.submit(request) } catch { Log.write("albums: processing task not taken (\(error.localizedDescription))") } }/// Albums went to the background: unless the continued task carries it, the pass pauses, and says why. #if COTTON_DEV/// Dev `-albums-faces-mac` (the owner's sheet on a simulator): Documents/albums-faces-mac.json, {file: [face]}, from/// the Mac harness's real Vision over the same synthetic library, replaces the simulator's own face rows once the/// pass is done (a look made later would write its own again). See AlbumsStore.setFacesFromMac. nonisolated staticfunc facesFromMac() {let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("albums-faces-mac.json")guardlet data = try? Data(contentsOf: url),let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],let files = root["files"] as? [String: [[String: Any]]] else {Log.write("albums: -albums-faces-mac: no Documents/albums-faces-mac.json")return }let took = AlbumsStore.shared.setFacesFromMac(files, looks: root["looks"] as? [String: [String: Any]] ?? [:], model: root["model"] as? String ?? "hyperface-50k-stylegan-pal8")Log.write("albums: faces from the Mac for \(took) items") } #endif/// Wi-Fi (or Ethernet), not a metered or Low Data path: where the pass may ask iCloud for what it is owed. nonisolated(unsafe) privatestaticvar path: NWPath? nonisolated privatestaticlet pathMonitor: NWPathMonitor = {let monitor = NWPathMonitor() monitor.pathUpdateHandler = { AlbumsPass.path = $0 } monitor.start(queue: DispatchQueue(label: "albums.path"))return monitor }()/// The network as the core's drain hears it (`media.network`): wifi, mobile, constrained or none. nonisolated staticvar pathWord: String { _ = pathMonitorguardlet path, path.status == .satisfied else { return"none" }if path.isConstrained { return"constrained" }return path.isExpensive ? "mobile" : "wifi" }/// Read from any thread: Keep's PhotoKit reads ask it as each piece arrives. nonisolated staticvar onWiFi: Bool { _ = pathMonitorguardlet path else { returnfalse }return path.status == .satisfied && !path.isExpensive && !path.isConstrained }staticvar charging: Bool { UIDevice.current.isBatteryMonitoringEnabled = truereturn [.charging, .full].contains(UIDevice.current.batteryState) }func wentAway() {guard running, continued == nilelse { scheduleProcessing(); return } stop()let charging = Self.charging pause = charging ? .away : .batterylet feed = self.feed feed?.later { await $0.lines(charging ? .pausedClosed : .pausedBattery, charging: charging) } sayFirstLook(force: true) scheduleProcessing() }func cameBack() { pause = .noneTask {await readLibrary() run() } }/// Faces turned off: every face and vector goes from this phone; the pass looks without them from now on.func turnOffFaces() { faces = false store.forgetFaces() refresh() }}#endif