This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

RawCull Tech Documentation

RawCull Developer Notes

These pages explain RawCull from a developer’s point of view. They are intended for readers who already understand Swift and SwiftUI and now need to learn where behavior lives, how data moves through the app, and which invariants must survive a change.

Source paths in these pages are relative to the named repository. App paths such as RawCull/Model/ViewModels/RawCullViewModel.swift belong to the RawCull repository. Package paths belong to the separately versioned Swift packages referenced by RawCull.xcodeproj; this documentation repository does not contain or compile source snapshots.

Start Here

Read these pages in this order when learning the project:

  1. Thumbnails and Scan Pipeline follows a selected catalog from directory discovery to visible images.
  2. Viewer Architecture and Keyboard Ownership follows screen sessions, task identity, overlays and keyboard routing.
  3. Concurrency explains @MainActor, actor ownership, cancellation, and bounded parallelism across that pipeline.
  4. Cache System explains why grid, preview, disk, full-size, and analysis caches are separate.
  5. Focus Mask and Sharpness follows scoring and focus evidence into persisted culling data.
  6. Burst Groups combines sharpness, similarity artifacts, grouping, ranking, and the burst-review UI.
  7. Artificial Intelligence covers Review presets, model requirements and saved evidence. RawCull Packages explains the reusable package boundaries behind the app.

Use File Read and Write and Security-Scoped URLs whenever a change touches persistence, caches, user-selected folders, export, or copying.

Repository And Target Map

AreaPrimary sourceResponsibility
App compositionRawCull/Main/RawCullApp.swiftUses RawCullApplicationState.live() to assemble stable models/features, inject environment state, and define windows and commands
Main presentationRawCull/Main/RawCullMainView.swiftSwitches between loupe, grid, similarity, rated, comparison, and Review modes and owns top-level sheets and overlays
App orchestrationRawCull/Model/ViewModels/RawCullViewModel.swiftAssembles catalog, culling, burst, presentation and AI owners for environment injection
Background ownershipRawCull/Actors/Serializes scans, thumbnail requests, caches, persistence, extraction, and contention gates
App services and adaptersRawCull/Model/Connects the UI model to RAW parsing, sharpness analysis, AI providers, persistence, diagnostics, and rsync
Reusable domain logicRawCullCore packageValue models and pure algorithms such as burst grouping and ranking
RAW decodingRawParserKit packageDedicated ARW/NEF/DNG and generic macOS-backed RAW dispatch, metadata normalization, MakerNote parsing, thumbnail extraction, and preview creation
Image analysisPhotoAnalysisKit packageSharpness, saliency, focus evidence, masks, and analysis descriptors
AI contracts and workflowsPhotoAIKit package productsTyped similarity artifacts, Vision/CLIP backends, semantic search, segmentation, and storage contracts
TestsRawCullTests/ and package test targetsExecutable behavior contracts, concurrency checks, cache identity checks, and integration coverage

Architectural Shape

flowchart TD
    App["RawCullApp: composition root"] --> Main["RawCullMainView: presentation router"]
    App --> VM["RawCullViewModel: workspace composition"]
    VM --> Owners["Observable state and workflow controllers"]
    Main --> Owners
    Owners --> Feature["Feature models: culling, sharpness, similarity, Review, settings"]
    Owners --> Actors["Actors: scan, thumbnail, cache, persistence, export"]
    Feature --> Analysis["PhotoAnalysisKit"]
    Feature --> AI["PhotoAIKit services and typed artifacts"]
    Actors --> Parser["RawParserKit"]
    Owners --> Core["RawCullCore pure models and algorithms"]
    Actors --> Storage["Application Support, Caches, selected folders"]

The boundaries are based on ownership:

  • SwiftUI views render observable state and translate gestures, commands, and bindings into model actions.
  • RawCullViewModel and feature view models are @MainActor because their state drives presentation.
  • Actors own shared mutable background state and serialize work such as cache access, thumbnail coalescing, and writes.
  • RawCullCore contains reusable value models and pure decisions that do not need UI isolation.
  • RawParserKit, PhotoAnalysisKit, and PhotoAIKit hide specialized parsing and analysis implementations behind typed boundaries.
  • Security-scoped access remains alive at the app or operation boundary for as long as user-selected files are used.

Workspace owners in 3.4.9

RawCullViewModel.swift wires the long-lived workspace objects together. workspaceEnvironment(_:) supplies those objects to SwiftUI. Views read the state and operations they use through the environment or explicit inputs.

OwnerState or actions
CatalogWorkspaceOpen source, scanned and filtered files, scan progress, focus-point lookup
CatalogControllerCatalog loading, sorting and filtering, grid and zoom projections, sharpness and AI input
CatalogLifecycleCoordinatorCatalog transitions, load tasks and security grant
SelectionModel and RatingsModelFocus, selection and comparison IDs, plus culling store and rating revision
CullingControllerRating changes, selection advance and culling-store recovery
BurstWorkflowControllerAnalysis coordination, review queue, keep-best, undo and review state
WorkspaceNavigationModel, ZoomOverlayModel and LoupeViewportModelView mode, overlay lifecycle and result metadata, and persistent loupe pan/zoom
WorkspacePresentationModel and FileOperationsModelWindow chrome, sheets and banners, plus JPG work and progress

See Internal Swift API for call sites and Viewer Architecture for presentation lifetimes.

Follow One Feature Through The Code

When investigating a behavior, read it in this direction:

  1. Find the SwiftUI control or lifecycle trigger.
  2. Find the environment model or controller that handles the action.
  3. Identify which actor, adapter, or package owns the expensive or mutable work.
  4. Follow the value returned to main-actor state.
  5. Read the tests named after the actor, model, or feature before changing the invariant.

This approach is more reliable than starting with an individual utility type because it shows both ownership and the complete lifetime of the operation.

Focused References

PageUse it when changing
Memory PressureCache limits, pressure events, or diagnostics
Detailed Sharpness ScoringFormula-level sharpness behavior and score-impacting factors
Detailed Focus Mask ComputationFocus-mask rendering, region selection, and visual thresholds
Synchronous CodeBlocking ImageIO, RAW parsing, or explicit executor bridges
Sony/Nikon MakerNote ParserFocus-point metadata and vendor-specific parsing
AI Model DownloadsModel installation, validation, signing, and activation
Repository Git WorkflowThe documentation repository’s linear-history workflow

Reviewed source baseline

Reviewed on 23 November 2026 against RawCull 3.4.9 build 466, commit 0513a30e. The commit is present on both version-3.4.9 and main. The Xcode workspace resolves 24 remote pins. See the package snapshot and review record. Historical audits and measurements retain their original source revisions.

Read Viewer Architecture and Keyboard Ownership for the October viewer refactor and RAW Formats and Exposure Inspection for generic RAW admission, temporary EV rendering, histogram and clipping. The review record lists every page’s disposition and validation limits. The developer guide provides the application tour; its detailed method reference is now separate.

State ownership and historical catalog performance

BurstWorkflowController retains BurstReviewSessionModel.swift for review decisions, independently of viewport/image sessions. SimilarityScoringModel retains RawCullSemanticSearchModel.swift for semantic evidence, provider configuration and queries, while keeping its existing forwarding API. Combined Review still has one mutable feature/run owner, with orchestration, work support and comparison in separate extensions.

Preload workers await disk saves before releasing worker slots, but release each file’s grid gate before the save. See Performance Measurement for the historical October 25 catalog reference, coalesced progress, cache-state limits and deferred validation. The phase 3–6 encoder, grid and source-load candidates were deferred; reduced sampled main-thread work does not establish faster loading or smoother frames. The build 466 smoke manifest expects 384 unique test identifiers. Test targets

ZoomView preview update in build 428

Fit-to-window RAW viewing can now render bounded, eagerly completed pixels while retaining native geometry. Native zoom preserves the developed-JPEG path; temporary inspection stays native. Read RAW viewing policy and performance results for the selected policy and its measured camera/file scope. The next documentation update starts from the full commit recorded in the review record.

RAW preview status in build 429

ZoomView identifies reduced previews and full-detail RAW results, displays preparation progress, and reports the latest RAW request duration including cache retrieval. The current image stays visible while a replacement loads. See RAW status semantics and the internal API.

Close Up in the 3.4.5 development branch

The burst workspace now embeds PhotoEvidenceKit’s manual Close-ups panel, including comparison membership, retained references, source-labeled crops, saved regions and orientation-corrected AF assistance. The same workspace also serves Single Images; the current source has no separate group restriction on the panel. Read Burst Groups and Viewer Architecture for host ownership.

Build 436 adds a detected crop strip above the manual cards. It shows human faces and a Vision animal head and eye pilot from the current embedded preview. Human face geometry and detail can be reused from the on-disk cache. The detected crops are inspection evidence. Build 466 also offers People Ranking as a temporary comparison order. See Close Up.

1 - Thumbnails and Scan Pipeline

Thumbnails and Scan Pipeline

RawCull separates catalog scanning, thumbnail preloading, UI-driven thumbnail requests, and full-size preview extraction. They share RawParserKit and disk-cache infrastructure, but they have deliberately different memory-admission rules.

The key current invariant is: catalog preloading warms the 200 px grid cache and disk cache, but only UI demand may admit an image to the preview-size RAM cache. This keeps scan order from displacing the images the user is actively viewing. Cache reuse is also replacement-safe: a file written over the same path is a different source when its size or modification date changes.

Source Map

AreaMain files
Catalog lifecycleCatalogController+Loading.swift, RawCullMainView.swift
App/package loading boundaryModel/RawImageLoading.swift, RawParserKit/Sources/RawParserKit/RawImageLoader.swift
File discovery and metadata scanActors/DiscoverFiles.swift, Actors/ScanFiles.swift
Catalog thumbnail preloadActors/ScanAndCreateThumbnails.swift, Model/Handlers/CreateFileHandlers.swift
Preload/UI contention gateActors/ThumbnailPreloadGate.swift
UI-driven thumbnailsActors/ThumbnailLoader.swift, Actors/RequestThumbnail.swift, Views/ThumbnailComponents/ThumbnailImageView.swift
Thumbnail identity and cachesModel/Cache/ThumbnailCacheKey.swift, Actors/SharedMemoryCache.swift, Actors/DiskCacheManager.swift, Model/Cache/CachedThumbnail.swift
Full-size preview loadingModel/FullSizePreviewLoader.swift, Model/Handlers/ZoomPreviewHandler.swift, Actors/FullSizeJPGDiskCache.swift
Vendor dispatchRawParserKit/Sources/RawParserKit/RawFormat.swift, RawFormatRegistry.swift, SonyRawFormat.swift, NikonRawFormat.swift
Behavior testsRawCullTests/ThumbnailLoaderConcurrencyTests.swift, ThumbnailProviderTests.swift, DiskCacheAndScanAdmissionTests.swift, ThumbnailCacheIdentityTests.swift, RawCullVerifyTestsConcurrencyTests.swift

Catalog Load Flow

flowchart TD
    A["User selects catalog folder"] --> B["startCatalogLoad"]
    B --> C["Acquire security-scoped access"]
    C --> D["ScanFiles.scanFiles"]
    D --> E["RawImageLoading.fileMetadata per file"]
    E --> F["Sort and filter on MainActor"]
    F --> G["Load ratings and valid saved scores"]
    G --> H["ScanAndCreateThumbnails.preloadCatalog"]
    H --> Gate["ThumbnailPreloadGate: active catalog"]
    Gate --> I["200 px grid RAM cache"]
    Gate --> J["JPEG thumbnail disk cache"]
    F --> K["SwiftUI grid and detail views"]
    K --> L["ThumbnailLoader / RequestThumbnail"]
    L -. "grid miss waits during preload" .-> Gate
    L --> M["Preview RAM cache"]
    L --> J

Catalog Load Ownership

CatalogController.startCatalogLoad(for:) delegates the transition to CatalogLifecycleCoordinator. It flushes the previous culling store before replacing the catalog. A failed flush restores the previous selection. Once admitted, beginCatalogLoad(for:) cancels old work, resets catalog state, starts access, and asks the coordinator to own a background-priority loadTask running handleSourceChange(url:). The task retains the catalog grant until it exits.

handleSourceChange(url:) is main-actor orchestration. File I/O, metadata work, decoding, and cache I/O are awaited through actors or detached work. After every significant suspension, isActiveCatalogLoad(_:) and cancellation checks prevent an old catalog from publishing into the current UI.

Changing catalogs also cancels thumbnail/full-preview work, clears burst analysis state, stops the old security scope, and releases the current scanning actors.

File Discovery

DiscoverFiles enumerates a directory off the main actor and filters extensions through RawFormatRegistry.allExtensions. Its recursive parameter controls whether subdirectories are traversed.

The RawParserKit 1.3.2 registry contains:

FormatExtensionConformer
Sony ARW.arwSonyRawFormat
Nikon NEF.nefNikonRawFormat
Adobe DNG.dngDNGRawFormat
Other registered RAW formatsCanon, Fujifilm, Olympus, Panasonic and other extensionsGenericRawFormat

ScanFiles performs its own non-recursive directory listing and asks RawFormatRegistry.format(for:) whether each item is supported. Discovery and scan therefore share registry policy rather than maintaining separate hard-coded extension lists.

Metadata Scan

ScanFiles.scanFiles(url:onProgress:) starts its own security-scoped access and uses a sliding task-group window rather than admitting the whole directory at once. maximumConcurrentReads defaults to min(8, max(1, activeProcessorCount)) and is injectable for tests. Each child:

  1. reads URL resource values for name, byte size, content type, and modification date;
  2. calls the injected RawImageLoading.fileMetadata(for:) abstraction;
  3. builds a FileItem with EXIF metadata and the normalized AF point;
  4. records the package focus-location string when available.

The production adapter, RawParserKitImageLoader, maps RawParserKit.RawImageLoader.metadata(for:) into the app’s ExifMetadata. RawParserKit reads ImageIO EXIF/TIFF data, dispatches format-specific details through RawFormatRegistry, and resolves MakerNote or EXIF subject-area focus evidence. DNG preview discovery classifies TIFF IFDs with NewSubFileType and Compression before using its legacy positional fallback, so a JPEG-compressed raw strip is not mistaken for a rendered preview.

Progress reports the first admitted file, every 32 admissions, and the final non-multiple of 32. This is discovery/admission progress, not a count of finished decodes. Cancellation returns an empty scan result. See RawCullTests/ScanAdmissionTests.swift for the bound and progress contract.

This is a single metadata pass per file. The app no longer runs separate EXIF and MakerNote extraction passes.

If no native focus-location strings are found for the catalog, ScanFiles falls back to focuspoints.json. This is catalog-wide fallback behavior; it does not merge JSON entries into a partly populated native result.

FileItem is an app typealias for RawCullCore.RawCullFileItem, keeping scan output usable by the pure package engines and tests.

Thumbnail Preload

After scan, sort, ratings, and valid saved scores are applied, ScanAndCreateThumbnails.preloadCatalog(at:targetSize:) walks the catalog again to warm browsing caches. A catalog URL already recorded in processedURLs is not preloaded again during the same app session. The actor registers the catalog with ThumbnailPreloadGate for exactly the lifetime of this preload and always ends the gate after the task returns or is cancelled.

The outer task group admits at most:

RawImageLoadingConcurrency.thumbnailPreloadLimit

The app-level limit bounds catalog work. RawParserKit adds its own thumbnail decode limiter and coalesces identical URL/size requests, preventing simultaneous RAW decodes from growing without bound at the package boundary.

Before any lookup, preload resolves a preview ThumbnailCacheKey from current file metadata and derives its 200 px grid representation. For each file, preload then uses this path:

flowchart LR
    A["RAW URL"] --> B{"Preview RAM hit?"}
    B -->|"yes"| C["Reuse preview thumbnail"]
    B -->|"no"| D{"Disk JPEG hit?"}
    D -->|"yes"| E["Decode oriented JPEG"]
    D -->|"no"| F["RawImageLoading.thumbnailImage"]
    C --> G["Populate 200 px grid cache"]
    E --> G
    F --> G
    F --> H["Encode JPEG data"]
    H --> I["Background atomic disk save"]

All three branches populate the dedicated grid cache when needed. Disk and source branches do not insert into the preview-size RAM cache. RequestThumbnail is its only admitter, so preview RAM admission follows user demand instead of scan order. NSCache controls eviction; RawCull does not implement an explicit LRU ordering. After a cold decode, preload resolves the key again before caching; if the source changed while decoding, the result is discarded rather than being stored under stale identity.

On a cache-miss extraction, processSingleFile encodes the actor-owned image and returns an optional (data: Data, key: ThumbnailCacheKey) payload. The worker calls ThumbnailPreloadGate.finished before awaiting its disk save, then returns its task-group slot only after saving completes. Pending saves and encoded payloads share the existing per-group worker bound: min(4, max(1, activeProcessorCount / 2)). This is not a global write limit.

DiskCacheManager.save already awaits its detached atomic writer. Preload no longer wraps it in another detached task. The boundary carries Data and a cache key, not image references. Interactive RequestThumbnail retains its asynchronous save behavior. Cancellation is checked after waiting for a slot and before encoding/saving. Already-started atomic writes are awaited, not interrupted. The catalog grant remains retained until the group drains. Progress counters mark image processing, not a durable-write receipt. Slow storage can lengthen total preload time while pending write work stays bounded.

The Two Memory Caches

SharedMemoryCache exposes two synchronous TrackedThumbnailCache wrappers. Each owns a private NSCache and serializes storage with count/cost accounting under one recursive lock:

CacheContentAdmission policy
Preview cache (memoryCache)Preview-size images used for detail/list demandOnly RequestThumbnail inserts; lookup uses NSCache
Grid cache (gridThumbnailCache)Downscaled 200 px imagesPreload populates it; grid requests can return immediately

Each wrapper owns its eviction delegate, and entry UUIDs prevent a callback for a replaced thumbnail from subtracting its replacement’s cost. Clears and limit changes use the same lock. See Synchronizing Cache Storage and Accounting for the callback ordering and concurrency tests.

Both caches are cost-limited. The preview item count limit is intentionally high so byte cost is the normal binding constraint. Under warning memory pressure both limits shrink to 60%; under critical pressure both caches are cleared and the preview cache is temporarily capped at 50 MiB.

UI-Driven Thumbnail Loading

ThumbnailImageView has two routes:

  • .grid calls the shared ThumbnailLoader actor;
  • .list calls RequestThumbnail directly.

For grid targets of 200 px or less, ThumbnailLoader first checks the grid cache without acquiring a concurrency slot. A miss joins its FIFO-like slot queue, which allows at most six active requests and removes cancelled waiters safely.

There is one step before that queue: a grid miss for the catalog currently being preloaded waits on ThumbnailPreloadGate, then checks the grid cache again. The gate tracks completion per file and preload session: finished(sourceURL:sessionID:) releases that file after processing, including a failed read the interactive path can retry. For a newly encoded thumbnail this is before awaiting its disk save, not before JPEG encoding. Other unfinished files remain gated. end(_:) releases the session remainder; overlapping sessions must all stop blocking a file before it is eligible. This avoids waiting for an entire large catalog when the requested file is already ready. This prevents the visible grid from launching a duplicate cold decode while preload is already producing the same catalog. Only grid misses in that catalog wait; AI indexing, semantic search, Review, model downloads, non-grid requests, and other catalogs are independent of this gate. Cancellation removes and resumes the gate waiter safely.

After a slot is acquired, the loader reads saved settings and asks RequestThumbnail for settings.thumbnailSizePreview. The passed grid target controls the grid-cache fast path; the slower preview request uses the configured preview size.

RequestThumbnail resolves a request in this order:

  1. preview RAM cache;
  2. oriented JPEG disk cache;
  3. RawImageLoading.thumbnailCGImage source decode.

A disk hit is promoted into preview RAM. A source decode is inserted into preview RAM, encoded to JPEG within the owning actor, then asynchronously saved to the thumbnail disk cache. The cache accounting records current entry count and cost. The current implementation has no separate eviction-history, hit-rate or “boomerang” diagnostics store; use targeted profiling to measure those behaviors.

Requests with the same complete ThumbnailCacheKey share one producer in RequestThumbnail. Each caller has its own continuation. Cancelling one waiter does not cancel work needed by other waiters; the producer is cancelled only when its last waiter leaves.

Replacement-Safe Thumbnail Identity

ThumbnailCacheKey is the identity shared by grid RAM, preview RAM, in-flight request coalescing, and the disk cache. It has two layers:

ThumbnailSourceFingerprint
  standardized file URL
  file size
  modification date

ThumbnailCacheKey
  source fingerprint
  purpose: grid or preview
  requested pixel size
  orientation policy
  schema version

The source fingerprint is optional. If filesystem size or modification date cannot be read, RawCull still decodes the image but does not reuse it through a potentially unsafe key. Purpose and requested size prevent a 200 px grid representation from satisfying a larger preview request. The schema version invalidates all older representation semantics without coupling thumbnail invalidation to PhotoAIKit artifacts.

Disk Thumbnail Cache

DiskCacheManager stores quality-0.7 JPEGs under a directory named for ThumbnailCacheKey.schemaVersion. The filename is an MD5 hash of the complete, locale-independent cacheIdentifier: schema, source path bytes, size, modification-date bits, purpose, requested pixels, and orientation policy. MD5 is used only as a compact filesystem name, not for security.

Older root-level JPEG entries are removed when the current representation-aware cache is initialized. Loads use OrientationNormalizedImageLoader; a corrupt or partial JPEG is deleted and treated as a recoverable miss. Writes accept pre-encoded Data and are atomic, so CGImage does not cross an actor/task boundary.

Full-Size And Zoom Preview Paths

Full-size inspection does not use the normal thumbnail disk cache.

flowchart TD
    A["Zoom / comparison source"] --> B{"Source choice"}
    B -->|"Thumbnail"| C["RequestThumbnail"]
    B -->|"Embedded JPEG"| D["FullSizePreviewLoader"]
    B -->|"Developed RAW"| E["ZoomPreviewHandler"]
    D --> F{"Sidecar JPEG exists?"}
    F -->|"yes"| G["Load oriented sidecar"]
    F -->|"no"| H{"Full-size disk cache hit?"}
    H -->|"yes"| I["Load cached embedded preview"]
    H -->|"no"| J["RawImageLoading.previewCGImage"]
    J --> K["Save embeddedJPG variant"]
    E --> L{"developedRAW cache hit?"}
    L -->|"no"| M["SonyRawFormat.createFullSizeJPEG"]

FullSizePreviewLoader prefers a same-basename .jpg sidecar, then the full-size disk cache, then RawParserKit extraction. RawParserKit itself coalesces duplicate preview requests and limits expensive full-size decode work to two concurrent operations.

The normal developed-RAW route calls the Sony-named development helper and uses its own cache variant. The separate exposure-inspection renderer bypasses that cache. The actual decoder capability remains input- and OS-dependent. The full-size cache stores quality-0.85 JPEG data and has a versioned orientation-aware key. Keeping these larger images on disk prevents a few pixel-peeping previews from evicting many browsing thumbnails from RAM.

App Loading Abstraction

The app depends on the RawImageLoading protocol rather than calling vendor conformers directly:

RequirementUse
fileMetadataScan metadata and normalized focus evidence
thumbnailCGImage / thumbnailImageOn-demand and preload thumbnail generation
previewCGImageEmbedded/sidecar full-size preview loading

RawParserKitImageLoader is the production adapter. Tests can inject alternate loaders without performing real RAW decoding.

Within RawParserKit, RawFormat provides vendor policy:

RequirementUse
extensions, displayNameDedicated and generic RAW registry lookup and diagnostics
extractThumbnailVendor thumbnail fallback
extractEmbeddedPreviewLargest usable embedded preview
focusLocationMakerNote AF location
rawFileTypeStringCompression labels
sizeClassThresholds, rawSizeClassBody-specific S/M/L size labels

extractFullJPEG remains only as a deprecated compatibility requirement; new code uses extractEmbeddedPreview.

What To Check When Changing This Area

  • Preserve the rule that scan/preload does not admit disk or source results to preview RAM.
  • Keep ThumbnailPreloadGate scoped only to grid misses for the actively preloading catalog.
  • Build memory, disk, and coalescing identity from the same complete ThumbnailCacheKey.
  • Do not fall back to path-only reuse when source metadata is unavailable.
  • Check both the grid-cache fast path and configured preview-size path when changing thumbnail settings.
  • Keep RawFormatRegistry.allExtensions and RawFormatRegistry.all aligned when adding a format.
  • Keep expensive decode limits and cancellation behavior covered by concurrency tests.
  • Convert actor-owned images to Data before detached cache writes.
  • Version cache keys when orientation or encoded-image semantics change.
  • Run cache-identity, scan-admission, contention, cancellation, and replacement-at-same-path tests together after changing this pipeline.
  • Inspect isActiveCatalogLoad(_:) guards if stale results appear after switching folders.

Presentation identity after an asynchronous load

ThumbnailImageView constructs a ThumbnailRequest from URL, target size, style, file size and modification date. ThumbnailPresentationModel owns the visible image and a generation UUID. A new URL clears the previous image; a late completion can publish only if its generation is still current and the task is not cancelled. This is a UI publication guard in addition to cache-key identity and producer coalescing. See RawCullTests/ThumbnailPresentationModelTests.swift and RawCullTests/ThumbnailPreloadGateTests.swift.

The loading bounds are deliberately separate: metadata reads use at most eight workers, preload uses min(4, max(1, activeProcessorCount / 2)), and explicit batch extraction uses max(1, activeProcessorCount * 2). Their shared policy is Model/RawImageLoadingConcurrency.swift; changing one limit does not change all other workloads.

Format admission and viewer ownership

Registry admission now includes GenericRawFormat; it does not guarantee that the installed macOS decoder supports a particular camera. Generic formats have no vendor MakerNote or binary embedded-JPEG fallback. See RAW Formats and Exposure Inspection for the exact extension list and why generic display support does not enable the ARW/NEF/DNG byte-export path.

The pipeline ends at a presentation owner, not directly in a large view body. Loupe, zoom, burst and comparison compose focused sections, with task and keyboard lifetimes described in Viewer Architecture.

Verify ownership separately from throughput

ThumbnailPreloadSaveOwnershipTests.swift stalls saves to check worker admission, gate release, completion ownership, cancellation, preview-RAM admission and disk-backed warm reload. These are fixture contracts. A cached catalog may produce no writes and cannot establish backpressure savings; see Performance Measurement.

Catalog progress publication and measurement

Since October 24, each catalog load owns separate main-actor CatalogProgressCoalescer instances for metadata counts and thumbnail completed/total/ETA state. Intermediate UI publication is coalesced at 100 ms; initial values, thumbnail total and terminal completion publish immediately. Metadata still reports admission counts, not completed decodes. The final thumbnail state comes from progressCounts() with ETA zero before progress is hidden. Cancellation cancels pending ticks, rejects queued callbacks and checks catalog/coalescer identity before publication.

This changes presentation cadence, not per-file accounting, gate readiness, preview-RAM admission or save ownership. ProgressCount animates only its ring for 100 ms, disables that animation for Reduce Motion, and updates counts immediately. The grid bitmap helper is GridThumbnailResizer (200 px cap); the later grid investigation retained its production resize policy. See Performance Measurement for the October 25 reference and the distinction between readiness and first painted frames.

Current decoder execution boundary

RawParserKit 1.3.3 moves the thumbnail decode body to a private @concurrent helper inside its existing six-slot limiter. RawCull’s preload worker bound remains separate; this dependency update does not increase it. Decode ordering, coalescing and cancellation checks are retained. See the package delta for evidence and limits.

Close-ups does not change preload admission

The November integration leaves scan/preload worker limits and thumbnail identity unchanged. Close-ups loads full-size preview/developed sources through its own host renderer, separately from the main stage’s three-frame working set and the grid/preview thumbnail caches. A small displayed crop is not proof that only a small source bitmap was decoded. See viewer ownership and cache lifetimes.

2 - Viewer Architecture and Keyboard Ownership

Trace loupe, zoom, burst, comparison and AI presentation through sessions, task owners, shared geometry and keyboard routing.

Viewer Architecture and Keyboard Ownership

The October 22 refactor separates screen composition, session state, transient analysis, and event routing. Read this guide after Thumbnails and Scan Pipeline. The original walkthrough used build 436. The Review screen and outline paths below follow build 466. The historical source-level design note is ViewComposition.md.

Find the owner before changing a screen

Screen entryPersistent screen/session ownerWork and presentation helpers
LoupeMainImageView.swiftLoupeSessionModel owns selected source and loaded source imagesLoupeFocusPresentationModel, SubjectOutlinePresentationModel, LoupeKeyboardController
ZoomOverlayView.swiftZoomSessionModel owns viewport, source, overlays and exposure inspectionZoomNavigationPresentation, ZoomOverlayAnalysisCoordinator, ZoomKeyboardController
BurstCullingWorkspaceView.swiftBurstWorkspaceSessionModel owns viewport and bounded frame cacheBurstWorkspaceImageCoordinator, BurstKeyboardController
ComparisonGridView.swiftComparisonSessionModel owns image loading and display scopeComparisonPager, ComparisonPane, ComparisonKeyboardController
CullingGridView.swiftExisting projection and selection coordinatorCullingQueueHeader, CullingBurstGroupCard, CullingGridThumbnail
ObjectPhotoDetailView.swiftLocal selected object plus ObjectPhotoPreviewModelObjectOverviewImage, ObjectInstanceList, ObjectPhotoAssessmentSection

The main actor owns these observable models. A separate view type limits which properties a section reads: zoom controls observe their session viewport; changing unrelated loupe zoom must not invalidate those controls. This is an ownership and observation boundary, not just a file-size convention.

flowchart TD
    Screen["Screen: lifecycle and task identity"] --> Session["Session: viewport, selected source, transient state"]
    Screen --> Coordinator["Coordinator: decode and analysis orchestration"]
    Coordinator --> Loader["App loader / package / cache"]
    Loader --> Publish["Cancellation and identity checks"]
    Publish --> Session
    Session --> Sections["Focused rendering views"]
    Event["Key event"] --> Scope["Window and native-control scope"]
    Scope --> Controller["Screen keyboard controller"]
    Controller --> Session
    Controller --> Actions["SelectionModel and CullingController actions"]

Rendering sections receive values, bindings and actions. They do not independently decode files or make culling decisions. For example, ZoomImageCanvas draws images and overlays while ZoomOverlayChrome and ZoomOverlayControls compose navigation, source and rating controls. Loupe has matching stage/content/controls and metadata sections; burst has a stage, header, filmstrip and evidence shelf.

Trace an asynchronous zoom request

  1. ZoomOverlayView.reload() cancels zoomOverlay.extractionTask and replaces it with the task returned by ZoomPreviewHandler.swift.
  2. The handler chooses thumbnail, embedded JPEG or developed RAW. It keeps a dedicated thumbnail analysis image distinct from the display render.
  3. A FocusMaskTaskID combines analysis-image object identity, selected source and file ID. SwiftUI replaces its task when those inputs change; it waits 300 ms before analysis. Focus-configuration edits use a separate stored task with a 400 ms debounce.
  4. ZoomOverlayAnalysisCoordinator.swift checks cancellation, file ID, analysis-image identity and source both before and after the awaited focus computation. Only the current request publishes the mask, breakdown and saliency.
  5. Subject-outline loading uses the selected file, mask prompt and visibility in its task identity. Disappearance calls session cleanup, which cancels session tasks, removes its monitor and releases overlays.

An analysis image can intentionally differ from the displayed full-size image. ZoomOverlayImagePolicy prefers the dedicated analysis image. Selecting a developed render therefore does not by itself prove that every focus-mask pixel was measured from that full-resolution render. Follow the actual image passed to the analysis coordinator when diagnosing a surprising overlay.

Loupe results have their own lifetime

LoupeFocusPresentationModel.swift owns a task and generation counter. cancel() increments the generation and cancels work; reset() also clears image/source identity. Publication requires the same generation and a noncancelled task. A completed URL/source pair can reuse its image, and a pending debounce can be cancelled before expensive work begins.

On a source change within the same photograph, the loupe cancels old focus work but keeps the normalized mask visible until replacement work completes. On a new URL or changed configuration, it resets the presentation. Do not replace these different transitions with one unconditional clear.

SubjectOutlinePresentationModel.swift applies the same generation principle to outline publication. The shared ImageReviewSubjectOutlineLoader.swift loads a retained subject mask from Review and uses the original mask if outline rendering cannot produce a contour.

Burst decoding is a bounded working set

BurstWorkspaceImageCoordinator.swift derives the window from BurstFrameCachePolicy: selected index plus at most one neighbor on each side, for capacity three. It prunes other keys, decodes the selected frame first, then neighbors. BurstFrameCacheKey.swift combines file ID and image source; a thumbnail cannot satisfy a developed-RAW key. An edge selection can have only two cached frames.

Thumbnail and embedded paths reuse comparison decoding. Developed RAW uses ZoomPreviewHandler.loadDevelopedRAWPreview; a selected-frame failure marks that source unavailable. Focus work runs only when a decoded selected image exists and lacks a mask. Configuration changes invalidate focus analysis without discarding all decoded images. This small session cache is separate from the global thumbnail caches described in Cache System.

Shared geometry keeps overlays registered

ImageReviewGeometry.swift returns one centered aspect-fit rectangle, or zero for nonfinite/nonpositive dimensions. Review records the source-space bounds and encoder geometry for each inspected crop. Selecting a finding in the inspector highlights its associated region on the photo. Region details expose the retained rectangle and its provenance. CombinedReviewInspectorPane

ImageReviewRasterOverlay shares raster drawing; OverlayControlCapsule shares control chrome. Neither chooses the analysis source or changes mask semantics. ZoomViewportMath handles fit, actual-pixel scale and focus-centered offsets; its offset clamp keeps the transformed image within the viewport bounds.

Keyboard registration and keyboard policy are separate

ReviewKeyMonitor.swift owns one AppKit local monitor token. Installing removes the previous monitor; removal is idempotent. The supplied handler returns .handled to consume the event and .ignored to let it continue. The helper does not decide which screen owns a key.

ReviewKeyboardScope.swift accepts an event only when it belongs to the anchored key window, no attached sheet or modal window owns input, Command/Control/Option are absent, and a native text/control responder does not own the keys. The representable anchor updates its weak window and detaches on teardown. Screens additionally check their mode and overlay state.

Each keyboard controller translates an already admitted action into session changes or app commands. Loupe’s local monitor handles only the subject-outline shortcut; its focused SwiftUI handler handles other viewer keys. Burst’s local monitor accepts only focus/outline keys. Comparison routes events through its own controller. Avoid copying one screen’s accepted-key list into every screen.

During RAW exposure inspection, ZoomKeyboardController consumes recognized navigation, rating and source/overlay actions without performing them. Escape ends inspection; zoom in/out remain available. ZoomSessionModel.navigate also refuses movement during inspection. See RAW Formats and Exposure Inspection.

Tests to read with the implementation

ContractExecutable reference
Cancelled focus/outline completions cannot replace newer stateOverlayPresentationModelTests.swift
Section observation and narrow/desktop renderingReviewViewBoundaryTests.swift
Window, sheet and native-control routingReviewKeyboardScopeTests.swift
Inspection key suppression and outline availabilityZoomKeyboardControllerTests.swift
Inspection snapshot, restore and navigationZoomSessionModelTests.swift

These tests document intended behavior. This documentation review read the fixtures; it did not run the application tests or qualify visual performance.

Review decisions are separate from the viewport

BurstWorkspaceSessionModel still owns viewport state and its bounded image cache. The view model retains BurstReviewSessionModel.swift for decisions, explicit states, queue filter, comparison group and undo entry. Its identity survives reset while its data is cleared. Facade observation still works, but result/state writes use session commands.

CullingGridProjectionKey.reviewRevision tracks session contentRevision so changed results invalidate cached group presentation. The workspace also requests missing AF-center evidence without replacing blended scores or reranking the winner as a side effect.

Reused navigation and progress presentation

Zoom navigation now reuses a projection containing ordered files, an ID-to-index map and catalog membership. Its key includes catalog, grid and navigation-context revisions, source URL, rating filter and analysis-order mode. Selection changes reuse the projection; relevant content/context changes invalidate it. Cache reads still read observable inputs, while memoization storage does not publish changes. Sharpness control labels use sharpnessScoringTargetCount to count membership without constructing and sorting the execution array; execution preserves target ordering.

Catalog progress is published at a coalesced 100 ms cadence with immediate initial/terminal states. Only the progress ring animates, respecting Reduce Motion. These changes do not establish first-painted-frame smoothness; see the October 25 findings.

Resolution changes retain native geometry

Build 428 adds ZoomSessionModel.beginPreviewLoad(preservingImage:) and finishPreviewLoad(_:) operation identity. Fit size follows viewport backing pixels in 256-pixel buckets; resizing during a RAW load follows the latest size after completion. rawPreviewMaximumDimension becomes nil for native zoom or exposure inspection. The current image stays visible during upgrades.

zoomOverlayNativeSize carries native geometry independently of bounded display pixels. ZoomImageCanvas uses it for actual-pixel framing, and chrome uses it for the dimensions label. ZoomPreviewHandler publishes display pixels before awaiting analysis. See RAW source policy.

Loupe metadata describes the displayed preview

ZoomMetadataPanel labels its histogram “Displayed Preview” and shows the selected source plus the available bitmap dimensions. “Original Dimensions” remains a separate EXIF value. Camera settings precede file attributes. The panel’s Open Zoom View action explicitly opens the embedded JPEG source; Show in Finder remains a quick action. LoupeMainImageView supplies the actual selected-source image, avoiding a thumbnail fallback for an unavailable non-thumbnail source.

RAW decode status belongs to the displayed result

RAWPreviewRenderer.Preview carries isReducedResolution (default false) beside image and nativeSize. Direct rendering sets it from the chosen scale, so the chrome does not infer decode quality from zoom state or bitmap/native geometry. ZoomPreviewHandler measures the awaited renderRAW request with ContinuousClock and publishes ZoomOverlayModel.rawIsReduced and rawRenderSeconds alongside the display pixels on the main actor, before awaiting analysis.

ZoomOverlayChrome receives those values and the session’s loading state. rawPreviewMaximumDimension != nil selects the preparing-preview wording; nil selects preparing-full-detail wording. Completion uses the displayed result’s flag. Preserved-image reloads retain its metadata until replacement publication. Nonpreserved loads, thumbnail transitions and closeZoomOverlay() clear both optional values. An embedded-JPEG completion publishes nil RAW metadata.

The November 2 fixture in RAWPreviewRendererTests.swift checks a reduced preview held during a gated native replacement, the completed native flag and clearing after a failed nonpreserved request. The test was inspected, not rerun in this documentation pass.

Close-ups: a second inspection working set

BurstCullingWorkspaceView.swift owns showCloseUps, URL-based comparison membership, a CloseUpModel with an injected store, and a BurstCloseUpRenderer. These are separate from the main stage’s BurstWorkspaceSessionModel and three-frame image cache. The panel is available in the shared workspace, including Single Images (group ID −1).

Filmstrip clicks first update comparison membership, then set the active frame. Command toggles membership; Shift selects a displayed-order range using the previous active frame as anchor; Command-Shift adds that range. Checkboxes change membership without activating a frame. If explicit membership is empty, the panel falls back to the active frame. A pinned reference can remain outside membership; it is not a manual winner.

The JPG/RAW picker shares sourceSelection with the main stage. Its support check includes comparison frames, the active frame and a retained reference. It says RAW 9 only if every relevant URL supports it; individual crop labels retain the actual source/decoder attribution. This does not force the main stage and every crop to share an identical decoded buffer or resolution.

BurstCloseUpsView.swift builds file/render identities, retains access during loading, updates pinned metadata independently of selection and maps AF metadata through EXIF orientation. Group changes clear explicit membership and create a new close-up model. The main viewport resets while preserving its AF-overlay preference; the new model inherits that preference. Saved regions can restore when file revisions match.

CloseUpModel.usesAFPoint and viewportState.showFocusPoints are synchronized. This session preference reapplies available AF centers and removes displaced pan offsets; it differs from the one-time per-frame AF placement action. Neither behavior measures focus quality. The host’s AF callback also selects that file and enables its AF overlay. Show image opens ZoomView using the group’s navigation and selected source; a retained reference absent from the current workspace cannot activate a missing file.

Burst’s focused SwiftUI arrow, Escape and character handlers now check ReviewKeyboardScope.controlOwnsKeys before acting, so native controls retain their keys. This supplements the existing window-scoped local-monitor rules. See BurstCloseUpTests.swift and BurstWorkspaceSessionModelTests.swift for inspected fixtures; no new execution result is claimed here.

Detected crop strip and stage navigation

The strip is keyed by the active file URL and pauses during similarity indexing. The host keeps detections separate from the manual model and renderer. Card Show image still opens the zoom overlay. Double-clicking a thumbnail on a burst group card now opens at that frame, and successful navigation clears single-frame comparison membership so the manual panel follows the active file.

Workspace state and interaction lifetimes

WorkspaceNavigationModel owns view mode and opens or closes the overlay. ZoomOverlayModel carries the launch context, request task, images and metadata. LoupeViewportModel survives mode changes. The loupe image session belongs to LoupeMainImageView. Keyboard handlers use the selected file, navigation and rating owners directly. CatalogController maintains the grid and zoom projections used for navigation, while SelectionModel stores focus and selection.

3 - RAW Formats and Exposure Inspection

Distinguish extension admission, macOS decoding, embedded export, RAW development and display-referred exposure inspection.

RAW Formats and Exposure Inspection

RawCull 3.4.0 resolves RawParserKit 1.3.3 at 26df4abc2178d5c07d08f3883d84d0648f5141d3. This adds a generic macOS-backed format route alongside the dedicated Sony, Nikon and DNG parsers. The app also has a temporary zoom exposure-inspection mode. These capabilities have separate contracts: discovering a file is not proof of camera-specific decoding, AF metadata, embedded-byte export or RAW 9.

Extension admission and camera support

RawFormatRegistry.swift registers SonyRawFormat, NikonRawFormat, DNGRawFormat, then GenericRawFormat. format(for:) lowercases the extension; allExtensions is their union. App discovery and scan admission consume that registry.

RouteExtensionsImplementation boundary
Dedicated SonyarwMakerNote/embedded ranges plus ImageIO and development helpers
Dedicated NikonnefNikon MakerNote/embedded ranges plus ImageIO
Dedicated DNGdngTIFF/SubIFD parsing plus ImageIO
Genericcr2 cr3 crw raf orf rw2 pef ptx srw x3f iiq 3fr fff dcr kdc mrw erf mef mos nrw rwl bay sr2 srfSystem ImageIO/Core Image decoding; no dedicated vendor binary fallback

The exact generic list is defined in GenericRawFormat.swift. The extension set admits a file for an attempt. Actual camera support depends on the installed macOS decoder and the file. A recognized extension can still fail to decode; do not describe the list as a tested camera matrix.

GenericRawFormat.focusLocation returns nil. RawImageLoader.metadata can still obtain an AF point from standard EXIF SubjectArea. It does not invent vendor MakerNote evidence. Generic size thresholds are 25/10 megapixels and compression labels cover the small standardized TIFF subset; unknown codes remain explicitly unknown.

Follow a generic thumbnail and preview

GenericRawThumbnailExtractor.swift uses CancellableImageIOWork at user-initiated QoS. It asks ImageIO for a bounded, transformed thumbnail, then redraws it to 8-bit sRGB RGBA with the requested interpolation quality. Source creation, generation and context failures stay typed thumbnail errors. There is no manual search through an unknown vendor container when ImageIO fails.

GenericEmbeddedPreviewExtractor.swift has a default two-operation limiter and a utility-QoS blocking bridge. It scans ImageIO subimages, accepts JFIF or TIFF compression 6/7 as JPEG candidates and chooses the greatest reported width. The target cap is 4320 px normally or 8640 px for fullSize. Wider candidates use native downsampling. The extractor leaves preview orientation unapplied so the facade can apply source orientation once. Missing candidates return nil; cancellation checkpoints and cache cleanup surround the synchronous ImageIO work.

The generic heuristic has no vendor-specific TIFF classifier. Keep dedicated DNG parsing rules distinct from this ImageIO-only candidate search. Package fixtures in GenericEmbeddedPreviewExtractorTests.swift protect the implemented behavior, not every real camera container.

Display, inspection and export are different paths

OperationCurrent input and behavior
Browsing thumbnailRegistry and RawImageLoader facade; may decode a generic RAW
Embedded display previewFullSizePreviewLoader can use a sidecar, display cache or package preview
Embedded JPEG exportEmbeddedJPGExportLoader reads ARW/NEF/DNG byte ranges; other extensions return nil
Normal developed-RAW displayZoomPreviewHandler uses the helper named SonyRawFormat.createFullSizeJPEG, requests RAW 9 and caches .developedRAW
Exposure inspectionSeparate serialized CIRAWFilter renderer with temporary EV/tone settings; no export/cache write

The helper name is a concrete call boundary, not a guarantee that every registry extension supports full development. The system filter determines whether an attempted input can be developed. In particular, generic browsing support does not extend the export loader’s explicit three-format switch. See EmbeddedJPGExportLoader.swift and ZoomPreviewHandler.swift.

Enter and leave exposure inspection

ZoomSessionModel.swift snapshots source selection, current/committed EV and clipping visibility before selecting .developedRAW and enabling inspection. Ending inspection restores that snapshot. A selected-file reset ends inspection and resets EV to zero. No editing sidecar is written by this mode.

RAWExposureInspectionControls.swift keeps a local slider draft from −5 to +5 EV in 0.1 steps. Dragging updates the small control view; release updates committed EV and triggers rendering. Reset commits zero. Closing inspection or pressing Escape restores the earlier session state; Escape during inspection does not close the entire zoom overlay. Navigation is blocked by session policy, and the keyboard controller suppresses recognized navigation/rating/source actions. These adjustments are temporary inspection state and are not saved edits.

Rendering and resource ownership

The RAWPreviewRenderer actor in RAWPreviewRenderer.swift serializes fit and inspection renders and lazily constructs its CIContext on its own executor. ZoomPreviewHandler.loadOverlayRAWPreview owns the display-source policy. The operation retains catalog access through completion and checks cancellation before and after expensive phases. Its synchronous Core Image portion cannot be interrupted in the middle of a native render.

The current sequence is:

  1. Create or reuse the source CIRAWFilter; prefer RAW 9 when available and retain the system fallback. Inspection uses native resolution. Recreate the filter on entering/leaving inspection so settings cannot leak into normal viewing.
  2. Apply requested exposure; set boostShadowAmount = 2.
  3. On macOS 26 or later, enable highlight recovery when the filter supports it.
  4. Apply CIHighlightShadowAdjust with highlight amount 0.25 and shadow amount 0.
  5. Render through a half-float working context to an 8-bit sRGB display image.

These adjustments change the inspected render. The result bypasses the normal developed-JPEG cache and export pipeline. Serialization bounds simultaneous inspection work; it does not make a full-resolution render inexpensive or establish a free-memory admission budget.

Histogram and clipping have different predicates

Both products sample the completed display render, after its EV and tone adjustments. They cannot establish sensor saturation or recoverable RAW detail.

ProductSample capNear-white ruleNear-black rule
Raster warning overlayLongest side 2048 pxAll RGB channels ≥254All RGB channels ≤1
RGB histogram and percentagesLongest side 512 pxAny RGB channel ≥254Any RGB channel ≤1

The overlay draws near-white pixels red and near-black pixels blue with alpha 180. The histogram has 256 bins per channel, normalized against the largest bin across channels. Its fractions count a pixel once when any channel meets the threshold. A saturated red pixel can contribute to the near-white percentage without a white-clipping overlay pixel. That difference follows the current code; the two displays must not be described as identical tests.

Both calculations run through explicit concurrent functions and check cancellation. Their view tasks key off image object identity; the clipping task also includes whether the warning is enabled for a developed source.

Read and verify the boundaries

Start with registry tests, then generic preview tests in RawParserKit. In RawCull, read RawImageLoadingIntegrationTests.swift for display/export separation, ZoomSessionModelTests.swift for snapshot/restore, and ZoomKeyboardControllerTests.swift for suppressed inspection actions. Those tests do not qualify camera coverage, exposure recovery accuracy or the current histogram predicates on real files. Record OS/decoder, camera, render source and actual pixels when validating those photographic behaviors.

ZoomView fit previews — 31 October 2026

Normal developed-RAW fit viewing first checks completed preview pixels, then an existing persistent developed JPEG. On a miss, RAWPreviewRenderer scales the RAW filter to the longest viewport edge in backing pixels, rounded up to a 256-pixel bucket, and eagerly completes an 8-bit sRGB CGImage. It does not upscale. Native dimensions are captured before scaling and kept separately for the dimensions label, actual-pixel framing and focus positioning.

Zoom above fit or an actual-pixels launch requests native resolution through the established developed-JPEG loader and disk cache. Returning to fit requests the bounded size again. Loupe and burst keep their existing full-size policy. Exposure inspection always requests native pixels and bypasses the persistent JPEG cache. Its filter can be reused between EV changes; entering/leaving inspection recreates it.

Window resizing coalesces while a RAW load is active, then follows the latest size. Operation IDs reject stale load-state completion, and cancellation blocks obsolete image/analysis publication. Resolution upgrades keep the current image visible. Display publication precedes the awaited analysis thumbnail; the two images still have distinct roles.

See viewer ownership, preview memory, and measured results.

RAW status and request timing — November 2–3

Zoom chrome shows “Preparing RAW preview…” for a bounded request and “Preparing full-detail RAW…” for a native request, with a small progress indicator. After completion it shows “RAW Preview” or “RAW Full detail” and the latest successful request duration in seconds, rounded to one decimal place.

The completed label follows RAWPreviewRenderer.Preview.isReducedResolution, which is set from the renderer’s actual scale < 1 decision. It is independent of the native-dimensions label and the current zoom selection. A bounded request can reuse a native developed JPEG and therefore display “RAW Full detail”. During a preserved-image upgrade, the previous image and its decode metadata remain until replacement pixels publish; the preparing label describes the pending request.

Timing wraps the awaited RAW preview loader, including cache retrieval. It is not isolated decoder CPU time or time to the first painted frame. Thumbnail and embedded-JPEG display have no completed RAW status. See viewer ownership for state and cleanup.

Close-ups source selection in build 434

The shared burst/Single Images workspace now offers a JPG/RAW source picker while Close-ups is visible. It updates the source state used by both the main stage and the panel. RAW 9 wording is used only when all relevant selected/current/reference URLs support it; otherwise the label is RAW, and individual crops describe their actual decoder/source. Availability of a registered extension alone does not prove RAW 9 support.

The close-up renderer requests full-size preview pixels or a developed RAW JPEG through the host loaders. These are separate from ZoomView’s bounded fit-render policy and temporary EV/clipping inspection. Cards distinguish sidecar JPG, embedded preview and developed full-size JPEG; they are not sensor-domain RAW measurements or a persistent editing/export adjustment. See Viewer Architecture.

Missing JPG preview in build 436

The burst stage offers Try RAW when its embedded JPG path has no preview. Choosing it switches the shared source preference to developed RAW. The manual cards follow that preference. The automatic detection strip still uses the embedded preview.

4 - Memory Cache

Cache System

RawCull uses several caches because RAW decoding is expensive and because different UI surfaces need different representations and lifetimes. The normal thumbnail path is layered RAM -> disk -> RAW extraction. The zoom path has its own disk cache for larger embedded JPEGs. Similarity has reusable per-file artifacts plus a separate catalog-wide burst snapshot. These layers must not share keys merely because they originate from the same RAW file.

Source Map

CacheMain filesStores
Thumbnail identityModel/Cache/ThumbnailCacheKey.swiftSource fingerprint plus representation purpose, size, orientation, and schema
Preview memory cacheActors/SharedMemoryCache.swift, Model/Cache/CachedThumbnail.swiftLarger NSImage thumbnails admitted by UI demand
Grid memory cacheActors/SharedMemoryCache.swiftSmall 200 px thumbnails populated by preload
Thumbnail disk cacheActors/DiskCacheManager.swiftRepresentation-aware JPEG thumbnail files under the app cache directory
Full-size JPEG disk cacheActors/FullSizeJPGDiskCache.swift, Model/Handlers/ZoomPreviewHandler.swiftLarger embedded JPEG previews for zoom
Per-file similarity artifactsIntelligence/Persistence/PerFileAnalysisArtifactStore.swiftIndividually validated Vision/CLIP SimilarityArtifact records
Burst analysis cacheIntelligence/Persistence/BurstAnalysisCache.swiftDerived catalog snapshots of artifacts, scores, groups, rankings, and review state
Cache accountingModel/Cache/TrackedThumbnailCache.swift, Actors/SharedMemoryCache.swiftLock-backed preview/grid item counts and byte costs kept correct across eviction

Thumbnail Lookup

flowchart TD
    A["Request a purpose and pixel size"] --> Key["Resolve ThumbnailCacheKey"]
    Key --> B{"Matching memory representation?"}
    B -->|"hit"| C["Return NSImage"]
    B -->|"miss"| D{"Matching disk representation?"}
    D -->|"hit"| E["Decode JPEG and refill memory"]
    D -->|"miss"| F["RawParserKit extractThumbnail"]
    F --> G["Create NSImage"]
    G --> H["Store preview memory for UI demand"]
    G --> I["Store grid memory copy for preload"]
    G --> J["Save disk JPEG"]

The same lookup order is used by preload and on-demand requests, but admission differs. ScanAndCreateThumbnails warms disk and the 200 px grid cache after a catalog opens. ThumbnailLoader and RequestThumbnail resolve UI demand; only RequestThumbnail admits disk or source results into preview RAM. ThumbnailPreloadGate prevents a grid miss from duplicating cold work already being performed by preload for the active catalog.

Cache Identity

ThumbnailCacheKey is the single identity used by memory lookup, disk lookup, and exact-key request coalescing. It contains:

  • a standardized source URL;
  • source byte size and modification date;
  • representation purpose (grid or preview);
  • requested pixel size;
  • orientation policy;
  • thumbnail schema version.

This answers two separate questions: “Are these still the same source bytes?” and “Is this the representation the caller requested?” A path-only key fails the first question when a file is replaced in place. A key without purpose or size fails the second by allowing a small grid image to satisfy a preview request.

If source metadata cannot be resolved, the key initializer returns nil. The image may still be decoded for the caller, but RawCull avoids persistent or coalesced reuse rather than assigning unsafe identity. ThumbnailCacheIdentityTests covers file replacement, requested-size separation, purpose separation, orientation policy, and schema participation.

CachedThumbnail

CachedThumbnail wraps an immutable NSImage, its cache cost, and the standardized source URL associated with the representation.

The cost is calculated from image representations:

cost = sum(rep.pixelsWide * rep.pixelsHigh * 4) * 1.1

The 4 is SharedMemoryCache.costPerPixel, fixed for RGBA. The 1.1 multiplier gives a small overhead buffer for the wrapper and image metadata.

CachedThumbnail is @unchecked Sendable. The project invariant is: construct the NSImage fully before caching it, then treat it as immutable.

The class intentionally does not conform to NSDiscardableContent. Earlier versions did, but diagnostics showed NSCache discarded entries too aggressively and destroyed the RAM hit rate. Eviction is now controlled by explicit cache limits and memory-pressure handling.

SharedMemoryCache

SharedMemoryCache is an actor singleton:

actor SharedMemoryCache {
    nonisolated static let shared = SharedMemoryCache()
}

It is still an actor because it owns configuration, pressure monitoring, disk-cache references, and statistics. Its two TrackedThumbnailCache wrappers are exposed as nonisolated let properties because the app needs synchronous lookup APIs. Each wrapper protects its private NSCache and count/cost metadata with one recursive lock.

That gives RawCull both:

  • actor isolation for mutable app-owned state,
  • fast synchronous cache reads for hot thumbnail paths.

Both memory caches are keyed by the complete ThumbnailCacheKey. The preview and grid APIs remain separate even though they use the same identity type, making admission policy visible at the call site.

Adaptive Limits

CacheRecommendationPolicy chooses cache caps from physical memory, current used memory, user maximums, and memory pressure.

Baseline limits:

Machine memoryPreview baselineGrid baseline
64 GB or more8000 MB2000 MB
32 GB or more4096 MB1024 MB
Less than 32 GB2048 MB768 MB

At normal pressure, RawCull calculates available headroom:

freeMB = physicalMB - usedMB
expandableMB = max(0, freeMB - 3072)
extraBudgetMB = expandableMB * 0.5
previewMB = baselinePreview + extraBudgetMB * 0.65
gridMB = baselineGrid + extraBudgetMB * 0.35

Values are rounded up to 256 MB steps and capped by both the machine tier and user settings.

At warning or critical pressure, the policy falls back toward 60 percent of the baseline, again respecting user limits and minimum settings.

Eviction Accounting

Each TrackedThumbnailCache owns its eviction delegate and serializes storage mutations with count/cost accounting. Metadata is registered before insertion, and a unique entry ID prevents a callback for a replaced value from subtracting the new value’s cost. Metadata retains no thumbnail references, so it does not keep evicted image memory alive. Clears and limit changes use the same lock.

See Synchronizing Cache Storage and Accounting for the replacement sequence, recursive-lock rationale, delegate lifetime, and concurrency regression tests. NSCache does not expose current cost or item count; the wrapper supplies those values. The current tree does not maintain a separate eviction-history or hit-rate diagnostics store.

Memory Pressure

SharedMemoryCache owns a DispatchSourceMemoryPressure.

Kernel eventRawCull response
.normalRestore cache configuration from settings/adaptive policy
.warningReduce preview and grid cache cost limits to 60 percent of their current limits
.criticalClear both memory caches, reset accounting, set preview cache limit to 50 MiB until recovery

The current pressure level is stored behind an OSAllocatedUnfairLock and exposed as a synchronous nonisolated property. This lets MemoryViewModel read pressure state without an actor hop.

Disk Caches

DiskCacheManager stores generated quality-0.7 thumbnail JPEGs in a schema-specific directory. Its filename is an MD5 hash of the complete cache identifier. MD5 is a fixed-width filesystem key here, not a security primitive. A corrupt JPEG is removed and treated as a cache miss, and writes are atomic. Callers encode to Sendable Data before crossing the actor/task boundary.

FullSizeJPGDiskCache stores larger embedded previews for the zoom overlay. It is deliberately separate from the normal thumbnail cache because zoom images are larger and should not compete with grid scrolling for memory.

Similarity And Burst Analysis Caches

Similarity persistence has two levels under Application Support:

LevelOwnerReuse unit
Per-file artifact storePerFileAnalysisArtifactStoreOne source fingerprint and backend descriptor
Burst analysis snapshotBurstAnalysisCacheOne compatible catalog analysis context

The per-file store lets RawCull reuse valid SimilarityArtifact values when a catalog-wide snapshot is stale or incomplete. Records include their own schema, source identity, backend/model descriptor, and pipeline signature. Invalid records are ignored or removed individually.

BurstAnalysisCache is not an image cache. Its current schema is 9. It stores:

  • typed Vision or CLIP similarity artifacts,
  • sharpness scores and saliency info,
  • burst groups and boundary evidence,
  • ranking results,
  • review states,
  • a digest of the descriptor-and-payload artifact set.

A snapshot is accepted only when the catalog, file count, every file’s size/modification date, thumbnail size, sharpness descriptor, grouping configuration, backend and artifact descriptors, artifact schema, pipeline version, artifact digest, cache schema, and grouping algorithm version still match. File UUIDs are remapped by path after a new scan. A legacy schema may supply migration candidates, but it is not accepted as a current snapshot.

What To Check When Changing This Area

  • Keep CachedThumbnail immutable after insertion.
  • Use ThumbnailCacheKey consistently for RAM, disk, and in-flight coalescing; never fall back to path-only reuse.
  • Keep grid and preview purposes separate and bump the thumbnail schema when representation semantics change.
  • Route memory-cache mutations through TrackedThumbnailCache so storage and accounting stay synchronized.
  • Use Instruments or temporary signposts to distinguish eviction churn from decoding or I/O regressions; the production tree does not export hit-rate logs.
  • Do not feed zoom-preview images into the normal thumbnail RAM cache unless you intentionally want them competing with grid thumbnails.
  • Keep per-file AI artifact persistence separate from the catalog-wide derived snapshot.
  • When changing scoring, similarity, or burst algorithms, update descriptors, signatures, digests, and schema/algorithm versions so stale analysis data is rejected.

Settings deletion includes durable review evidence

CacheSettingsTab.swift now presents a combined cache total: preview/grid RAM, thumbnail/full-size disk data, similarity artifacts, burst snapshots and saved Combined Reviews. Its Delete Cache action first calls CombinedReviewFeature.clearAllReviews(), then clears shared caches, per-file analysis artifacts and burst snapshots. A held Combined lease disables the button; review deletion also checks the lease at the operation boundary.

Saved Combined reports, masks, retained inputs and history are user-visible evidence, even though this action groups them under cache cleanup. They are deleted by the confirmed action. Do not describe every Settings cache entry as losslessly regenerable: rerunning inference need not reproduce the same report. Original photos, settings and downloaded model packs are outside this purge.

Saved Files has its own confirmed deletion action and size accounting. Read File Read and Write before changing either path. The burst workspace’s three-frame session cache is a separate working set described in Viewer Architecture.

Preload write lifetime and whole-process memory

Preload releases a file’s grid gate before awaiting its disk save, and retains the worker slot until saving returns. The per-group concurrency limit covers pending saves and encoded JPEGs. The background atomic writer and interactive thumbnail-save behavior are unchanged. A started write may finish during cancellation.

Thumbnail-cache limits are not a whole-process memory cap. Loupe, zoom, comparison, full-size sources and framework scratch allocations have separate lifetimes. See Performance Measurement for the October 25 reference, unresolved resource signals and the historical October 23 workload. These workloads are not interchangeable memory comparisons.

Completed ZoomView RAW previews

RAWPreviewRenderer.shared owns a separate 256 MiB byte-bounded LRU of completed pixels. Cost is bytesPerRow × height; this is not a total-process memory cap. Keys include standardized source URL, size, modification date, requested dimension and optional inspection EV. Fit/native and normal/inspection variants are distinct; obsolete revisions and prior inspection exposures at the same size are replaced. Oversized images can be returned without being retained.

Closing ZoomView releases the source filter and Core Image context while retaining bounded completed previews. Warning/critical memory pressure and clearCaches() clear both previews and source/context. Normal native previews retain the existing persistent developed-JPEG policy. These caches are independent of thumbnail budgets, export output and burst’s three-frame working set.

Close-up artifacts and source identity

Close-ups adds a separate inspection working set. Its renderer retains no decoded source cache of its own, although the host preview/developed loaders can reuse their existing caches. PhotoEvidenceKit redraws crop and overview into owned, bounded raster buffers, and card disappearance releases those artifacts. A crop must not accidentally retain the whole source through a shared image backing.

This does not extend the burst stage’s three-frame cache budget to every card. Source decoding can allocate full-size transient images; serialization applies within the close-up renderer, not across every image consumer. Thumbnail budgets and the RAWPreviewRenderer LRU are not a cap on the complete panel/process.

Frame identity includes the RAW file revision; render identity separately includes preview sidecar or development settings. A sidecar change rerenders pixels while preserving a valid RAW-bound manual region. The UserDefaults region store is a preference store and is not included in the existing Settings cache byte total or explicit purge paths. See file storage.

Disposable human face evidence

FaceEvidenceCache writes JSON atomically under the app cache directory, using a hash of the standardized file URL. The signature checks the source revision, preview configuration, algorithm version, Vision revision and OS. The saved preview dimensions must also match. Cache hits reuse human face geometry and detail, while RawCull renders new crop pixels from the decoded preview. Animal landmarks are evaluated separately and remain transient. Manual region records are stored separately.

Unreadable similarity artifacts

An artifact read error preserves the stored record. Forced re-indexing can replace it when a new artifact is generated successfully. See PerFileAnalysisArtifactStore.swift and the tests for PerFileAnalysisArtifactStore before changing read or refresh behavior.

Review masks after upgrading

The runtime attempts to remove the obsolete Objects mask directory during initialization. Current Review outlines resolve a retained input key from a displayed result and recheck the source fingerprint before loading the image. Clearing retained inputs can remove the outline while leaving its measurements and report readable. RawCullAIModelRuntime · ReviewSubjectMasks

5 - Synchronizing Cache Storage and Accounting

Synchronizing Cache Storage and Accounting

RawCull keeps preview and grid thumbnails in memory so that scrolling and selection do not repeatedly decode the same RAW files. Settings also reports how many thumbnails are cached and their estimated byte cost. Those numbers must follow insertions, replacements, clears, and automatic eviction.

This document explains Thomas Evensen’s change, “Synchronize cache storage and accounting with owned eviction delegates”. The commit changes five files: 194 insertions and 101 deletions. The implementation is a worked example of keeping a thread-safe container and its external bookkeeping consistent. See the Memory Cache overview for the surrounding thumbnail pipeline.

The Problem: Safe Operations Can Still Form an Unsafe Sequence

NSCache supports concurrent access, but does not expose its current item count or total stored cost. RawCull therefore maintains its own accounting.

Previously, SharedMemoryCache held bare NSCache instances and separate lock-protected count and cost counters. Replacing a thumbnail involved looking up the previous object, subtracting its cost and count, inserting the new object, and adding the new cost and count. Each individual counter access was protected; the whole sequence was not.

Two writers replacing the same key could both observe the same previous value and both adjust the counters. A clear could also interleave with insertion so that storage and counters ended up describing different states. Clamping a counter to zero did not restore the missing relationship between these operations.

There was a second ownership problem. The old shared CacheDelegate identified caches by comparing them against SharedMemoryCache.shared. A separately constructed cache owner, such as a test fixture, could not use that delegate to update its own accounting. Test fixtures consequently disabled eviction tracking.

One Wrapper Owns Storage, Metadata, and Callbacks

The new TrackedThumbnailCache.swift combines these responsibilities:

private let lock = NSRecursiveLock()
private let storage = NSCache<NSString, Entry>()
private var entries: [String: (id: UUID, cost: Int)] = [:]
private var storedCost = 0

Every storage lookup, insertion, clear, limit access, accounting read, and accounting change uses the same lock. The wrapper sets storage.delegate = self, so an eviction updates the wrapper that owns the evicted entry. No singleton lookup or cache-identity comparison is needed.

Entry contains a unique UUID, the string key, the thumbnail, and its insertion cost. The metadata dictionary stores only the UUID and cost, without retaining the thumbnail. If metadata retained thumbnails, eviction could remove them from NSCache while the bookkeeping still kept their image memory alive.

The accounting rule is simple: currentCount is entries.count, and currentCost is the sum of the registered costs. The stored cost is normalized with max(0, cost). It is the caller-supplied cache cost, not a measurement of the process’s actual resident memory.

Replacement and Immediate Eviction

Insertion runs as one locked operation:

let entry = Entry(key: key as String, thumbnail: thumbnail, cost: max(0, cost))
if let previous = entries[entry.key] {
    storedCost -= previous.cost
}
entries[entry.key] = (entry.id, entry.cost)
storedCost += entry.cost
storage.setObject(entry, forKey: key, cost: entry.cost)

The new metadata is registered before calling NSCache.setObject. An insertion can trigger an eviction callback immediately; that callback must be able to find and remove the new entry’s accounting.

Replacement also needs to distinguish two entries that use the same key. The delegate checks the entry UUID before subtracting anything:

guard entries[entry.key]?.id == entry.id else { return }
entries.removeValue(forKey: entry.key)
storedCost -= entry.cost

For example, suppose key photo holds entry A with cost 400, then receives entry B with cost 1600. Replacement subtracts 400 and registers B’s 1600. If a callback arrives for A, its UUID no longer matches the metadata and the callback is ignored. A callback for B removes B and subtracts 1600. Matching only the key would allow A’s callback to corrupt B’s accounting.

Why the Lock Is Recursive

NSCache can call its delegate during insertion or a limit change, while the wrapper already holds the lock. The callback enters the same locked helper. NSRecursiveLock allows that reentry on the calling thread; a nonrecursive lock would deadlock in that case. A callback on another thread is serialized by the same lock.

All wrapper operations are synchronous. No lock is held across await. @unchecked Sendable expresses the wrapper’s manually maintained concurrency contract: its mutable state is private and lock-protected. It does not itself make mutable data safe. Cached thumbnails must continue to follow RawCull’s invariant that an image is fully constructed before caching and treated as immutable afterwards.

Clearing, Limits, and Lifetime

removeAllObjects() first clears metadata and sets storedCost to zero, then clears NSCache, all under the lock. Any resulting callback finds no matching metadata and does nothing. A concurrent insertion happens before or after that operation, so it cannot leave an empty cache with an insertion’s counter update.

totalCostLimit and countLimit also go through the wrapper. Evictions caused by limit changes use the same accounting callback. These are cache policy limits; the implementation does not assume a particular eviction order or assert an exact number of survivors after changing a limit.

The wrapper detaches storage.delegate in deinit. This prevents cache teardown from calling back into the wrapper after its metadata or lock has been destroyed.

Each accounting property is read under the lock, but separate calls to currentCount, currentCost, and object(forKey:) are separate observations. They are not a combined snapshot while other tasks are mutating the cache.

Integration with SharedMemoryCache

SharedMemoryCache.swift remains an actor for configuration and memory-pressure handling. Its two synchronous cache endpoints become:

nonisolated let memoryCache = TrackedThumbnailCache()
nonisolated let gridThumbnailCache = TrackedThumbnailCache()

Thumbnail reads and writes still work without an actor hop. The preview and grid wrappers independently own their storage and accounting. The actor’s public count/cost methods forward to the corresponding wrapper; the four separate counters and the old CacheDelegate.swift are removed.

Critical memory pressure calls removeAllObjects() and removeAllGridObjects(), using the same synchronized clear path as other callers. The test helper no longer needs tracksEvictions: false: isolated owners now track their own evictions exactly like the production owner.

Tests That Protect the Contract

CacheAccountingConcurrencyTests.swift contains three Swift Testing tests, each parameterized for preview and grid:

TestWorkloadChecked result
Concurrent replacements16 tasks each replace one key 200 times, alternating thumbnail sizesOne live entry; recorded cost matches the surviving thumbnail
Concurrent clear and insert12 tasks each perform 200 clears or insertionsCount and cost match final storage; a subsequent clear and insert reset correctly
Owned eviction accountingInsert 50 keys with count limit 2, then set cost limit 1Count and cost match the entries actually found in that isolated cache

The task-group tests wait for all workers to finish before comparing storage with accounting. The eviction test measures actual survivors instead of relying on NSCache’s eviction order. These are regression tests for the identified races and ownership issue, rather than proof of every possible interleaving.

The reusable principle is to synchronize the container operation and its bookkeeping as one operation, give callbacks an owning instance, and use an entry identity when callbacks can refer to a replaced value.

6 - Memory Pressure

How RawCull measures memory and reacts to macOS pressure events

Memory Pressure

RawCull can hold many images in memory while scanning and culling. The memory-pressure code exists to keep the app responsive when macOS reports pressure and to make cache behavior visible during development.

Source Map

FileRole
Actors/SharedMemoryCache.swiftOwns cache limits, memory-pressure dispatch source, pressure state, and cache clearing
Model/ViewModels/MemoryViewModel.swiftSamples total system memory, used system memory, app memory, and pressure threshold for the UI
Model/Cache/TrackedThumbnailCache.swiftSerializes thumbnail storage, count/cost accounting, limit changes, and owned eviction callbacks
Model/Cache/CacheConfig.swiftContains CacheRecommendationPolicy and cache-limit calculation
Views/Settings/MemoryTab.swiftDisplays memory stats, cache limits, and pressure status
Views/RawCullSidebarMainView/MemoryWarningLabelView.swiftShows the sidebar warning during pressure

Runtime Flow

flowchart TD
    A["SharedMemoryCache.ensureReady"] --> B["startMemoryPressureMonitoring"]
    B --> C["DispatchSourceMemoryPressure"]
    C --> D{"event"}
    D -->|"normal"| E["refreshConfig from settings/adaptive policy"]
    D -->|"warning"| F["shrink cache limits to 60 percent"]
    D -->|"critical"| G["clear memory caches and set 50 MiB preview cap"]
    F --> H["Notify file handler warning"]
    G --> H
    E --> I["Clear warning"]

SharedMemoryCache starts monitoring lazily during ensureReady(). That is called before thumbnail cache use, so the memory-pressure handler is active before large thumbnail work begins.

Measuring System Memory

MemoryViewModel.getUsedSystemMemory() uses Mach VM statistics:

usedMemory = min((wired + active + compressed) * pageSize, physicalMemory)

The model intentionally uses a simple definition of “used”:

VM fieldMeaning
wire_countWired pages that cannot be paged out
active_countPages currently active
compressor_page_countPages held by the VM compressor

The result is clamped to physical memory so the UI cannot show impossible totals.

Measuring App Memory

RawCull measures its own process footprint with:

task_info(... TASK_VM_INFO ...).phys_footprint

That is the value displayed as app memory usage. It is a better signal than simply adding image sizes because it reflects what the kernel says the process currently costs.

Percentages In The UI

MemoryViewModel exposes:

memoryPressurePercentage = memoryPressureThreshold / totalMemory * 100
usedMemoryPercentage = usedMemory / totalMemory * 100
appMemoryPercentage = appMemory / usedMemory * 100

The default pressure threshold is 85 percent of physical memory:

memoryPressureThreshold = totalMemory * 0.85

This UI threshold is informational. The actual pressure response is driven by macOS DispatchSourceMemoryPressure events.

Cache Limit Policy

CacheRecommendationPolicy.adaptiveLimits(...) is the first place to inspect when tuning memory behavior.

RawCull has two independent RAM budgets:

CacheTrackedThumbnailCachePrimary contentSettings maximum
PreviewmemoryCachePreview and loupe thumbnailsmemoryCacheSizeMB
GridgridThumbnailCacheGrid-size thumbnailsgridCacheSizeMB

Both use byte cost as the binding constraint. The preview count limit is 10,000 and the grid count limit is 3,000, so normal eviction should be driven by pixel cost rather than item count.

At normal pressure:

  1. Choose a baseline from physical RAM.
  2. Estimate free memory from Mach stats.
  3. Keep a 3 GB reserve.
  4. Use half of the remaining expandable memory as extra cache budget.
  5. Split that extra budget 65 percent preview cache and 35 percent grid cache.
  6. Round to 256 MB steps.
  7. Clamp by machine tier and user maximums.

The current tiers are:

Physical RAMPreview baselineGrid baselinePreview tier capGrid tier capDefault user maxima
Less than 32 GB2,048 MB768 MB4,096 MB1,024 MB4,096 / 1,024 MB
32 GB to less than 64 GB4,096 MB1,024 MB8,000 MB2,000 MB4,096 / 1,024 MB
64 GB or more8,000 MB2,000 MB8,000 MB2,000 MB8,000 / 2,000 MB

The policy never treats a user maximum as a target. It calculates an adaptive recommendation and then clamps preview and grid independently to their saved maxima. At warning or critical state, calculateConfig(from:) uses 60 percent of the tier baseline, rounded up to 256 MB and bounded by the configured minimum and user maximum.

At non-normal pressure, RawCull returns reduced baseline limits and then the live pressure handler may shrink or clear active caches immediately.

Pressure Responses

EventCode pathEffect
NormalhandleMemoryPressureEvent, .normalSet pressure level to normal, refresh config, clear warning
Warning.warningSet pressure level to warning, reduce the current preview and grid cost limits to 60 percent, retain entries for NSCache to evict, show warning
Critical.criticalSet pressure level to critical, clear preview and grid RAM caches, reset their accounting through the wrappers, and set the preview limit to 50 MiB

The grid cache is cleared on critical pressure too. The disk caches are not deleted; only RAM is released.

The 50 MiB critical cap applies to the preview cache. Critical handling clears the grid cache but does not rewrite its live cost limit. A later .normal event calls refreshConfig(), re-runs the adaptive calculation using current memory and saved settings, restores both live limits, and clears the UI warning. Recovery does not repopulate either cache; normal demand and preload work warm them again.

Why Pressure State Is Lock-Backed

currentPressureLevel is read by the UI without await. The value is stored in an OSAllocatedUnfairLock, which makes the read/write contract explicit while avoiding a main-actor or cache-actor hop during frequent sampling.

Cache accounting uses a different lock: each TrackedThumbnailCache owns one NSRecursiveLock covering its private NSCache, metadata, and stored cost. Insertion, replacement, clearing, limit changes, and eviction callbacks are serialized together. Recursive locking permits a synchronous eviction callback to reenter while an insertion or limit change holds the lock. No lock is held across await.

The synchronous surface is deliberately narrow: pressure snapshots and the wrapper’s thumbnail and accounting APIs. Configuration, disk-cache access, monitoring setup, and handler ownership remain actor-isolated or explicitly run in detached tasks. NSCache’s thread safety alone would not protect a sequence of storage mutations and separate accounting updates.

Runtime Observability

MemoryTab refreshes MemoryViewModel once per second while the settings view is active. It displays total physical memory, the app’s definition of used system memory, the RawCull process footprint, the informational 85-percent threshold, and the kernel-reported pressure level.

SharedMemoryCache forwards current cost and item-count reads to the preview and grid TrackedThumbnailCache wrappers. Each wrapper owns its eviction delegate and subtracts an evicted entry only when its UUID matches the currently registered entry. This protects a replacement from an older entry’s callback. Clearing storage also clears accounting in the same locked operation.

These byte costs estimate cached image storage; they are not the process footprint measured above. Separate count and cost reads are separate observations while writers are active. There are no pressure-event counters, eviction-history ring, or memory-diagnostics TSV export in the current implementation. See Synchronizing Cache Storage and Accounting for the implementation walkthrough.

Validation When Limits Change

Run the cache-policy tests in RawCullTests/ThumbnailProviderTests.swift. They currently cover the production/testing relationship, explicit CacheConfig values, the 16 GB baseline, expansion and tier caps, user maxima, and warning-state rounding. Add fixtures for every new RAM tier, clamp, rounding rule, or pressure branch.

Retain RawCullTests/CacheAccountingConcurrencyTests.swift for concurrent replacement, clear/insert races, and eviction accounting in an isolated owner. Each test covers both preview and grid caches. The eviction test compares accounting with actual surviving entries rather than assuming a particular NSCache eviction order.

Also retain the concurrency test in RawCullVerifyTestsDataRaceDetectionTests.swift, which samples currentPressureLevel concurrently.

For an operational limit change, capture a diagnostics session with the same representative catalog and workflow before and after the change:

  1. Record idle, initial grid population, sustained scrolling, loupe/preview use, and recovery after induced or observed pressure.
  2. Compare peak process footprint, preview/grid cost and item counts, live limits, and time to first usable grid using Instruments or temporary development instrumentation.
  3. Confirm warning shrinks both live caches without deleting disk data.
  4. Confirm critical clears both RAM caches, preview falls to the 50 MiB cap, and .normal restores adaptive limits. Observe the pressure state directly; there is no production pressure-event counter.
  5. Reject a larger limit if it only raises footprint without improving reuse; reject a smaller limit if it creates repeated cold extraction or visible grid/preview churn.

What To Check When Changing This Area

  • Memory sampling should stay off the main actor; Mach calls run in Task.detached.
  • Do not rely only on the 85 percent UI threshold; the real emergency signal is the kernel pressure event.
  • If cache limits look strange, inspect both user settings and the adaptive tier caps.
  • Treat preview and grid limits separately; a healthy total can hide churn in one cache.
  • The settings display samples state; use Instruments or signposts when a change needs event-level evidence.
  • Critical pressure should free RAM quickly and should not delete disk caches.
  • After recovery, verify both live limits were recalculated from current settings and memory, not merely reset to hard-coded values.

Interpret samples in workload context

The October 23 cache-preserved source-switch/reload session fell from a 4,836.9 MiB footprint peak to 692.9 MiB. A separate fresh-process load peaked near 990 MiB and ended near its peak. Neither establishes a leak, long-term stability or a speedup over a different workload. The fresh load recorded zero process disk writes, so it did not stress bounded preload saves. See Performance Measurement for trace failures, source-build identity and measurement limits.

October 31 integration

Warning/critical events now also clear RAWPreviewRenderer.shared, releasing its completed-pixel LRU and active source/context. Its 256 MiB cache budget excludes the active RAW graph, Core Image/framework allocations and other app caches. Closing ZoomView releases the graph but retains completed previews; see cache ownership.

Close-ups is outside the thumbnail cache budget

Manual Close-ups retains bounded crop/overview artifacts while cards are visible; its host can still decode a full-size source transiently. Its renderer serializes its own requests but does not impose a process-wide limit on the main burst stage, ZoomView or other loaders. Existing thumbnail pressure actions and RAW preview cache clearing do not explicitly clear PhotoEvidenceKit’s card state.

Do not infer a new memory measurement from these ownership rules. Qualify several visible cards, source toggles, retained references and rapid navigation as a separate workload. No Close-ups memory-pressure benchmark was run in this pass.

7 - Concurrency

Concurrency

This page describes the current RawCull runtime in the RawCull repository. The app uses Swift 6 with default main-actor isolation: presentation state begins on @MainActor, shared mutable background state lives in actors, and CPU, decode, or file work leaves inherited UI isolation explicitly.

A Swift task is not a thread. await is a suspension point, not an automatic hop to a background thread. RawCull reasons about actor, executor, queue, and task ownership; it never uses worker-thread identity as an application invariant.

Composition And Presentation Boundaries

RawCullApp retains the two roots returned by RawCullApplicationState.live(): one RawCullViewModel and one RawCullIntelligenceRuntime. The application state assembles one integration, one shared similarity model, focused similarity and semantic-search features, the Review feature, settings/model-management models, and the main view model. Settings publishes a complete revisioned configuration to the runtime rather than invoking independent callbacks on the view model.

RawCullMainView is the presentation boundary. It binds the main-actor view model to SwiftUI scenes, sheets, alerts, commands, and child views. It does not own catalog decoding, thumbnail admission, analysis, or persistence work.

RawCullViewModel assembles main-actor state and controllers. CatalogController coordinates loads and publication using CatalogWorkspace and CatalogLifecycleCoordinator. FileOperationsModel owns export and cache warming. BurstWorkflowController owns application burst actions and uses BurstAnalysisCoordinator for the worker task, generation, progress, cache preparation and save. Background actors own mutable storage and provider state.

flowchart LR
    APP["RawCullApp<br/>stable @State roots"] --> STATE["RawCullApplicationState<br/>object-graph assembly"]
    STATE --> VM["@MainActor RawCullViewModel<br/>workspace composition"]
    STATE --> RT["@MainActor RawCullIntelligenceRuntime<br/>AI lifetime and configuration"]
    RT --> AIS["RawCullAISettingsModel"]
    RT --> FEATURES["Focused similarity, semantic, and Review surfaces"]
    VM --> VIEW["RawCullMainView and SwiftUI presentation"]
    VM --> WORKFLOW["BurstWorkflowController"]
    WORKFLOW --> BURST["BurstAnalysisCoordinator"]
    FEATURES --> ACTORS["Background actors and package services"]
    BURST --> ACTORS
    ACTORS --> VALUES["Sendable results"]
    VALUES --> FEATURES
    VALUES --> BURST

Four Runtime Paths And Their Hops

flowchart TB
    subgraph CATALOG["Catalog load"]
        C1["SwiftUI selection<br/>MainActor"] --> C2["flushPersistence<br/>CullingModel"]
        C2 --> C3["start catalog security scope<br/>CatalogLifecycleCoordinator"]
        C3 --> C4["CatalogLifecycleCoordinator.loadTask + retained grant"]
        C4 -->|"await actor"| C5["ScanFiles actor"]
        C5 -->|"bounded task group"| C6["metadata and focus-point reads"]
        C6 --> C7["MainActor publication<br/>only if catalog is still active"]
    end

    subgraph THUMBS["Visible thumbnail demand"]
        T1["SwiftUI task"] -->|"await actor"| T2["ThumbnailLoader"]
        T2 -->|"grid miss only"| T3["ThumbnailPreloadGate"]
        T2 --> T4["six-slot admission"]
        T4 --> T5["RequestThumbnail exact-key single flight"]
        T5 --> T6["RAM / disk / RawParserKit decode"]
        T6 --> T7["CGImage result; caller rechecks cancellation"]
    end

    subgraph BURST["Burst indexing"]
        B1["BurstWorkflowController builds immutable request"] --> B2["BurstAnalysisCoordinator generation + task"]
        B2 --> B3["cache prepare / bounded scoring and indexing"]
        B3 --> B4["provider and artifact-store actors"]
        B4 --> B5["grouping and ranking"]
        B5 --> B6["callback publishes only if generation + catalog match"]
        B6 --> B7["repository-backed cache commit"]
    end

    subgraph TERM["Application termination"]
        A1["AppDelegate.applicationShouldTerminate<br/>MainActor"] --> A2["terminateLater"]
        A2 --> A3["terminationTask"]
        A3 --> A4["await CullingModel.flushPersistence"]
        A4 -->|"success"| A5["release session catalog grant"]
        A4 -->|"failure"| A6["Retry / Cancel Quit / explicit discard"]
        A5 --> A7["reply true"]
    end

    C7 ~~~ T1
    T7 ~~~ B1
    B7 ~~~ A1

The invisible ordering links (~~~) make Mermaid place the four runtime paths below one another. They describe layout only; they are not runtime hops.

The catalog path is latest-wins. startCatalogLoad first flushes pending culling data, then checks cancellation and the selected source before starting the new load. cancelCatalogLoad cancels catalog, preload, hydration, and cache-warming tasks; asks batch actors to cancel their inner tasks; resets dependent analysis; and stops the active catalog scope. Publication repeatedly checks isActiveCatalogLoad(url) and task cancellation.

The termination path deliberately delays AppKit termination. AppDelegate stores one termination task, flushes persistence, and releases the catalog security scope only after a successful save. A failed flush presents Retry, Cancel Quit, or Quit Without Saving. Retry continues in the same termination task; Cancel Quit replies false and retains state/access; explicit discard releases session access and replies true. isTerminationPending suppresses the ordinary persistence alert while quitting.

Concurrency Mechanisms

Main-Actor Isolation

Use the main actor for observable UI state and workflow coordination, not for expensive work.

OwnerState and lifetime owned
RawCullViewModelAssembles catalog, selection, ratings, navigation and workflow owners
CullingModelIn-memory culling records, debounced save task, persistence revision and errors
SharpnessScoringModelScoring request/generation, options, progress, scores and breakdowns
SimilarityScoringModelImage artifacts, indexing/ranking/grouping generations and forwarding semantic API
RawCullSemanticSearchModelSemantic service, evidence, hydration/query tasks and generations, progress and result selection
BurstReviewSessionModelReview results, explicit states, queue filter, comparison group, undo entry and review revision
RawCullSimilarityFeature / RawCullSemanticSearchFeatureFocused operation surfaces, application bindings, and projections over the one shared scoring model
BurstAnalysisCoordinatorBurst worker task, generation, progress, cache preparation, missing compute, grouping, ranking, and cache save
CombinedReviewFeatureRun admission and cancellation, manifest, saved history and presentation of evidence
RawCullIntelligenceRuntimeStable AI feature lifetimes and last accepted configuration revision/identity
RawCullAISettingsModelCapability-refresh generation, preferences, and complete configuration publication

A task created in one of these main-actor contexts inherits that isolation. That is useful for its stateful prefix and final publication. Heavy work must then be reached through an actor, a package async API, or an explicit @concurrent boundary.

Actor Serialization

Actors protect shared asynchronous state.

ActorSerialized invariant
ThumbnailPreloadGateActive preload catalogs and parked grid-demand waiters
ThumbnailLoaderSix decode slots, FIFO continuations, and cached settings
RequestThumbnailSetup single flight and one producer per exact ThumbnailCacheKey
ScanFiles, ScanAndCreateThumbnails, ExtractAndSaveJPGsBatch task, progress, cancellation, and result accumulation
DiskCacheManager, BurstAnalysisCache, WriteSavedFilesJSONFile-backed cache or persistence transactions
PhotoAIKit provider/store actorsModel runtime, artifact, index, and mask-store state

Actor serialization does not make independent work parallel. Where file work can overlap, owners use a bounded task group and keep only a sliding window of children active.

Synchronous Cache Storage and Accounting

SharedMemoryCache remains an actor for configuration, monitoring, and pressure handling. Its nonisolated let preview and grid properties expose independent TrackedThumbnailCache wrappers, so thumbnail access does not require an actor hop.

Each wrapper owns its private NSCache, metadata, stored cost, and eviction delegate. One NSRecursiveLock serializes reads, mutations, limit changes, and callback accounting. Registering metadata before insertion handles immediate eviction; an entry UUID makes callbacks for replaced values harmless. The lock is recursive because NSCache can call its delegate during an operation that already holds it. No locked operation suspends with await.

The wrapper’s @unchecked Sendable conformance relies on this private, lock-protected state and the immutability contract of cached thumbnails. It does not make NSImage mutation safe. Separate accounting reads are not a combined snapshot during concurrent writes. See Synchronizing Cache Storage and Accounting for the source walkthrough and delegate teardown rule.

Bounded Structured Parallelism

OperationBound
Visible thumbnail loading6 slots in ThumbnailLoader
Metadata scanmetadataScanLimit: CPU count clamped to 1…8
Thumbnail preloadthumbnailPreloadLimit: half CPU count clamped to 1…4
Explicit extraction batchesbatchExtractionLimit: twice CPU count, minimum 1
Sharpness scoringFast 6, Balanced 4, High Precision 3; RAW demosaic capped at 2
PhotoAnalysisKit batch and calibrationCaller supplied; RawCull passes the scoring bound
PhotoAIKit indexingmaximumConcurrentTasks sliding window

Structured child tasks inherit cancellation and finish before the task-group scope returns. Completion order can drive progress, but final arrays are restored to request order where order is part of the API. Cancellation calls cancelAll() and partial results are not committed as a successful run.

Explicit Concurrent Work

A task closure marked @concurrent, or an @concurrent function, explicitly leaves inherited actor isolation. That does not make Task { ... } structured: its owner must still retain/await it and arrange cancellation. Task-group children, by contrast, remain scoped to their group. Examples include RawCull’s RAW demosaic helper, sorting and ranking helpers, diagnostics, and PhotoAnalysisKit’s Core Image/Vision worker. The audited PhotoAnalysisKit 1.3.1 implementation uses an explicit concurrent child and a cancellation handler; it does not use a detached task for the focus engine.

Detached And Queue-Backed Work

Task.detached is reserved for operations that deliberately must not inherit actor isolation, including selected cache/file operations and conversion of blocking image representations. Cancellation does not automatically propagate from the caller. When completion or access lifetime matters, the caller must explicitly await/control the task and arrange cancellation. Preload now does so; interactive thumbnail requests still launch a separate asynchronous cache save.

Blocking ImageIO work is stronger than ordinary CPU work. RawParserKit bridges it to a GCD queue with a checked continuation and lock-backed cancellation state so it does not occupy Swift’s cooperative executor. Framework pipe and PTY callbacks similarly arrive outside main-actor isolation and explicitly return through a main-actor task.

Thumbnail Contention Invariants

Thumbnail concurrency has three separate layers:

  1. ThumbnailPreloadGate blocks only grid misses whose parent directory is the catalog currently being preloaded. Other catalogs, preview requests, AI workflows, semantic search, and Review bypass the gate.
  2. ThumbnailLoader admits at most six active loads. A released slot is transferred directly to the next waiter; cancellation removes and resumes a queued continuation exactly once.
  3. RequestThumbnail coalesces only an exact ThumbnailCacheKey. Each waiter owns its continuation. Cancelling one waiter preserves the shared producer; cancelling the final waiter removes the table entry and cancels the producer.

ThumbnailCacheKey is replacement-safe and representation-aware. It includes the standardized path, source file size, modification-date bit pattern, purpose (grid or preview), requested pixel size, orientation policy, and thumbnail schema. If source metadata cannot be resolved, reusable coalescing and caching are skipped: a path alone cannot identify bytes replaced in place.

Every in-flight request also has a generation UUID. A producer may finish after its final waiter was cancelled and a new request for the same key began; the generation check prevents that old completion from removing or resuming the new request’s waiters.

Latest-Wins And Stale-Result Prevention

Cancellation is cooperative and is not enough by itself. A callback or framework operation may complete after cancellation, so owners pair task cancellation with identity checks.

WorkflowCommit guard
Catalog loadActive catalog URL, selected source, and cancellation
Catalog sort/searchRequested text, sort order, file IDs, and cancellation
Sharpness scoringScoringRequest, scoring-generation UUID, and cancellation
Similarity hydrate/index/rank/search/groupPer-workflow generation plus catalog/query snapshots
Burst analysisBurst generation plus catalog URL
ReviewShared lease, frozen source and model snapshots, cancellation and compatibility checks
Raw diagnosticsGeneration UUID plus cancellation
Thumbnail single flightExact cache key plus producer-generation UUID

Progress callbacks use the same guard as final publication. An older run must not update a newer run’s progress, clear its task property, or publish a stale result.

Continuation Ownership And Cleanup

OwnerNormal resumeCancellation cleanup
ThumbnailPreloadGateFile finishes in all blocking sessions, or sessions endRemove waiter, record cancellation, resume false
ThumbnailLoaderA real slot is transferredRemove queued waiter and resume cancelled
RequestThumbnailExact-key producer finishesRemove waiter and resume nil; cancel producer when none remain
RawParserKit decode limiterA decode permit becomes freeRemove cancelled admission waiter and resume cancellation
RawParserKit ImageIO bridgeGCD operation completesLock-backed state guarantees exactly one completion

The collection owner is responsible for exactly one continuation resume. Never hold a lock across await, invoke arbitrary client code while holding a lock, or use a continuation without a cancellation path.

Security-Scope And Persistence Lifetimes

OperationOwnerStartStop / failure cleanup
Active catalogCatalogLifecycleCoordinator / retained grantsBefore CatalogLifecycleCoordinator.loadTask, after the previous catalog is flushedSession release on cancellation, empty/failed load, replacement or termination; actual stop after final worker grant release
Selected JPG exportFileOperationsModelBefore constructing ExtractAndSaveJPGsMain-actor completion path after success, failure, or cancellation
Rsync copyExecuteCopyFilesActive catalog URL for source; destBookmark for destinationOne idempotent cleanup() on startup failure, completion, close, or deinit; it also removes the operation’s include-list file
App terminationAppDelegate and CullingModelNo new scope; uses the active catalog scopeFlush first; release scope only on successful flush

Every successful security-scope start has one owner that records the URL and one idempotent cleanup path.

Source-To-Test Map

Runtime ruleProtecting tests
Exact-key thumbnail coalescing and independent waiter cancellationRawCullTests/ThumbnailProviderTests.swift
Preload-gate drain and cancellation racesRawCullTests/RawCullVerifyTestsConcurrencyTests.swift
Six-slot limit, FIFO transfer, queued cancellation, and cancel-allRawCullTests/ThumbnailLoaderConcurrencyTests.swift
Replacement-safe source/representation identityRawCullTests/ThumbnailCacheIdentityTests.swift
Synchronized cache replacement, clear/insert races, and eviction accounting in isolated ownersRawCullTests/CacheAccountingConcurrencyTests.swift
Scoring request coalescing and generation-safe completionRawCullTests/SharpnessScoringTests.swift
Persistence debounce, failed-save dirty state, retry, atomic backup/write, and legacy decodeRawCullTests/CullingModelTests.swift
Catalog scope idempotence, replacement, failed start, cancellation, and empty catalogRawCullTests/RawCullVerifyViewModelSecurityScopeTests.swift
Export selection and denied destination scopeRawCullTests/ExtractJPGsSelectionTests.swift
Rsync source/destination cleanup and operation-local include filesRawCullTests/ExecuteCopyFilesStartupTests.swift
Package batch ordering, bounds, progress, and cancellationPhotoAnalysisKit/Tests/PhotoAnalysisKitTests/PhotoAnalysisBatchTests.swift

Review Checklist

  1. Which actor or task owns the mutable state and lifetime?
  2. Does the synchronous prefix require that actor?
  3. Is independent work bounded and structured?
  4. Is the work CPU-bound, blocking, or callback-based, and which executor or queue boundary is appropriate?
  5. What Sendable value crosses the boundary?
  6. How is every continuation resumed on success and cancellation?
  7. Which generation, catalog, query, key, or request identity prevents a stale commit?
  8. Who stops each successfully started security scope?
  9. What test makes the invariant executable?

“await moves this to a background thread” is not a valid concurrency model. Name the actual actor, task, executor, queue, cancellation owner, and commit guard.

Catalog grants outlive selection when workers still need them

CatalogLifecycleCoordinator owns transition and load tasks plus the session’s RawCullCatalogGrant. RawCullCatalogAccess registers grants weakly and returns strong references covering requested URLs, choosing the longest matching root by path components. Decoder adapters and batches retain those references until their asynchronous operation exits, using withExtendedLifetime in cleanup.

Cancelling a catalog releases the session reference; the actual security-scope stop occurs in the grant’s isolated deinitializer after the final worker also releases it. Cancellation cannot instantly interrupt synchronous image rendering. A generation/catalog guard still prevents those workers from publishing stale results. See RawCullTests/CatalogLifecycleCoordinatorTests.swift and RawCullTests/CatalogConcurrencyTests.swift.

Viewer task and event ownership

The October 22 refactor makes the presentation boundary explicit: LoupeFocusPresentationModel owns its focus task/generation, SubjectOutlinePresentationModel rejects obsolete outline results, and ZoomOverlayAnalysisCoordinator checks selected file, source and analysis-image identity around awaited computation. SwiftUI task IDs remain on their screen owners; extracting a rendering section must not start a duplicate worker.

BurstWorkspaceImageCoordinator retains only a three-frame source-keyed working set. ReviewKeyMonitor owns registration/removal only; screen scope and keyboard controllers decide whether an event is accepted and what it does.

Read Viewer Architecture for the complete lifecycle and tests. The private RAW exposure renderer is a separate actor with synchronous native render work; its serialization does not make rendering preemptible. See RAW Formats and Exposure Inspection.

Bounded preload saves and separate observable owners

ScanAndCreateThumbnails.swift keeps saving inside each bounded worker: process and encode, release the file’s grid gate, await DiskCacheManager.save, then release the slot. A cancellation check after group.next() prevents new admission when a cancelled producer gets a slot. Already-started writes are awaited and the retained catalog grant covers the drain. Interactive saves are unchanged; each preload group has its own bound.

Review results/states use explicit session commands. The session’s contentRevision is part of CullingGridProjectionKey. Semantic configuration replacement advances hydration generation and rejects stale publication. Similarity’s grid revision combines image and semantic changes. These owners remain observable main-actor models, not new background actors.

Read ThumbnailPreloadSaveOwnershipTests.swift, CullingGridCoordinatorTests.swift and RawCullSemanticSearchTests.swift for the contracts.

Catalog progress lifetime — October 2026

CatalogProgressCoalescer is main-actor presentation state. Each catalog load creates independent metadata and thumbnail instances. A cancellable 100 ms scheduling task weakly references the coalescer; scheduled identifiers and an accepting flag reject obsolete ticks. Initial and terminal publication bypass the cadence. Catalog cancellation cancels both coalescers, and callbacks check current catalog or instance identity. Internal accounting and thumbnail availability do not wait for a UI tick.

Catalog instrumentation pairs CatalogOpen, CatalogMetadataScan and CatalogThumbnailPreload intervals. Optional source-load stage diagnostics are opt-in measurement support; ordinary loading continues through the production adapter. No parser concurrency or save-lifetime rewrite was retained in Phases 3–6. The current findings establish reduced sampled main-thread progress work, not that every expensive path avoids the main thread or that interaction is hitch-free.

October 31 integration

RAWPreviewRenderer serializes synchronous Core Image work on its actor. Cancellation checks surround native calls; they cannot preempt them. Zoom load operation IDs guard completion state, while cancelled tasks cannot publish obsolete pixels or analysis. RawParserKit 1.3.3 separately places thumbnail decoding in an @concurrent helper under the existing six-slot limiter.

RAW status publication — November 2–3

The handler publishes decode status and request duration on the main actor with the completed display pixels, before waiting for the analysis thumbnail. A preserved-image replacement keeps the previous result metadata until publication. Session loading state independently drives the preparing indicator; the completed quality label follows renderer metadata. Cancellation and existing load IDs keep the same publication/completion responsibilities. See viewer ownership.

Close-up rendering and publication

BurstCloseUpRenderer is an actor with an explicit tail-task chain. Actor isolation alone would allow reentrancy across awaits; waiting for the preceding task prevents overlapping native decodes within this renderer instance. A cancellation handler cancels the queued task, which checks cancellation after waiting and around decoding. Synchronous native calls still cannot be preempted arbitrarily.

Its @concurrent worker retains catalog access, validates file and render-source revisions before and after image loading, and returns bounded raster artifacts. The PhotoEvidenceKit card model separately checks cancellation, request generation, render descriptor, dimensions and transform before publication. These protect different boundaries: a valid current descriptor does not replace a host file revision check, and cancellation does not replace result-generation checks.

The main burst stage retains its separate cache and loading coordinator. This renderer serializes its own work; it is not a global cap shared by all image pipelines. See cache ownership and security-scope lifetime.

Automatic detection scheduling

The current URL scopes the detection task. The view delays starting work briefly, removes the detection strip during similarity indexing and cancels obsolete loads when the current URL changes. The loader retains catalog access and checks cancellation and source revision before saving or returning results. Manual card metadata loads off the main actor and is published after a cancellation check.

Vision request scheduling

PhotoAnalysisKit schedules saliency, classification, face and animal detection, and feature-print requests on VisionRequestGate.shared. RawCull injects RawCullVisionWorkSerializer into PhotoAIKit’s Vision similarity backend, so feature prints from similarity indexing use the same queue. The indexer can keep up to four decodes in flight while Vision executes one request body at a time. This leaves the cooperative thread pool available to other tasks.

A waiting caller suspends. Cancelling before its turn skips the body. Once a request has started, it finishes on the serial queue and returns its result or error. Construct the non-Sendable Vision request and handler inside that body and return Sendable data. Sharpness still bounds concurrent images by quality and source, allowing six Fast, four Balanced or three High Precision preview jobs and at most two RAW demosaics. VisionRequestGate · VisionWorkSerializing · RawCullVisionSimilarityService · SharpnessScoringModel

8 - Focus Mask and Sharpness

Focus Mask And Sharpness

RawCull exposes four related results, but they are not interchangeable:

ResultMeaningMain consumer
Scalar sharpnessA package-computed ranking value based on full-frame, salient-subject, AF, and local-patch detailSorting, burst ranking, persistence
Saliency evidenceVision candidates and an optional classification label/confidenceSubject selection and diagnostics
Focus-point evidenceCamera AF position plus AF-center, neighborhood, and local scoresRegion selection and diagnostics
Rendered focus maskA thresholded, colorized overlay clipped to selected evidence patchesVisual inspection only

The scalar score and the overlay share edge-energy and evidence machinery in PhotoAnalysisKit, but showing more red pixels does not increase a stored score. Mask presentation does not change scalar analysis. A weak or unfocused image is allowed to produce an empty overlay; the renderer does not lower its threshold merely to manufacture visible evidence.

The formula walkthrough uses PhotoAnalysisKit 1.3.1, revision 2a1466e04d821fa2628d6985296643e0d0c7e465. Build 466 resolves 1.4.1, which shares the focus engine’s Core Image context and includes the Vision request gate. See the package snapshot. The package owns sharpness, saliency, calibration, focus evidence, and mask algorithms. RawCull owns UI settings, file decoding/source selection, workflow lifetime, normalization, and persistence.

Ownership From Controls To Package

flowchart TD
    CONTROLS["SharpnessControlsView<br/>start, cancel, photo type"] --> VM["@MainActor CatalogController<br/>target files and persistence"]
    SHEET["ScoringParametersSheetView<br/>quality, source, size, config"] --> MODEL["@MainActor SharpnessScoringModel<br/>request, generation, progress, results"]
    SETTINGS["FocusSettingsTab and FocusMaskControlsView"] --> FM["@MainActor FocusMaskModel<br/>presentation bridge"]
    VM --> MODEL
    MODEL --> ADAPTER["RawCullPhotoAnalysisAdapter<br/>host file/source adapter"]
    ADAPTER --> LOAD{"RawCull-owned input source"}
    LOAD -->|"embeddedPreview"| RPK["RawParserKitImageLoader"]
    LOAD -->|"rawDemosaic"| RAW["CIRAWFilter concurrent worker"]
    RPK --> INPUT["PhotoAnalysisInput<br/>CGImage + ISO + aperture + AF"]
    RAW --> INPUT
    INPUT --> ANALYZER["PhotoAnalysisKit.PhotoAnalyzer"]
    ANALYZER --> RESULTS["PhotoAnalysisResult / batch result<br/>score, saliency, breakdown"]
    ANALYZER --> MASK["CGImage focus mask"]
    RESULTS --> MODEL
    MASK --> FM
    MODEL --> PERSIST["CullingModel and savedfiles.json"]

SharpnessScoringModel and FocusMaskModel are @Observable @MainActor because they publish UI state. Their PhotoAnalyzer and adapter values are immutable, nonisolated boundaries. PhotoAnalysisKit’s internal FocusMaskEngine is @unchecked Sendable only because Core Image does not declare CIContext Sendable; the documented invariant is an immutable engine with value snapshots for every operation.

Configuration Resolution

A scoring run snapshots one effective SharpnessConfiguration:

focusMaskModel.config
  -> SharpnessPhotoType.packagePreset.applying
  -> SharpnessScoringQuality.packageQuality.applying
  -> PhotoAnalyzer applies each input's ISO and aperture hint

RawCull’s default focus configuration is .birdsInFlight. Photo type maps to PhotoAnalysisKit presets: Automatic, Birds and Wildlife, Portrait, Landscape, or General Action. Quality maps to Fast, Balanced, or High Precision. Automatic preserves the shared config rather than selecting a preset from image classification; the default .birdsInFlight has no explicit weight override, unlike the explicit Birds and Wildlife preset.

The selected thumbnail setting is normalized before decode:

effective size = min(max(user value, quality minimum), 2048)

quality minimum:
  Fast           512
  Balanced       768
  High Precision 1024

The UI currently offers 1024, 1536, and 2048 px choices. The quality minimum still matters for old settings and programmatic values. Embedded previews use RawParserKit’s thumbnail loader. RAW demosaic uses CIRAWFilter, disables added sharpness, and sets detail 0.6, contrast 1.0, and exposure 0 before scaling the longest side to the effective size.

Analysis Descriptor And Cache Identity

PhotoAnalyzer.sharpnessDescriptor(for:) produces SharpnessAnalysisDescriptor, the package-owned identity for non-mask scalar analysis. At the pinned PhotoAnalysisKit 1.3.1 revision it has:

  • descriptor schema version 1;
  • scalar algorithm version 4;
  • ISO-scaling policy version 1;
  • aperture-hint policy version 1;
  • the scoring-affecting configuration values and the stable scoring gain 7.62.

It deliberately excludes per-image ISO and aperture, decoded image size, input source, source-file identity, and mask-only presentation settings. RawCull adds the missing host identity in SharpnessScoringSignature:

Identity layerFields
Package descriptorAlgorithm/policy versions, scoring configuration, stable gain
RawCull signatureDescriptor + embedded-preview/RAW source + effective maximum pixel size
Per-file persistence validationSignature + source file size + modification date

Legacy signatures without a package descriptor still decode, but compare stale to every current signature. On catalog load, RawCull restores a score only when the full signature matches and the current file size and modification date match (date tolerance is 0.001 seconds). A change to scalar-affecting config, quality, source, size, algorithm identity, or source-file metadata therefore forces recomputation.

Calibration Lifetime

Calibration is a visual-threshold operation, not catalog normalization of the scalar score. Before scoring, RawCull asks FocusMaskModel to load inputs and call PhotoAnalyzer.calibrate, using a dedicated 1616 px maximum rather than the scoring thumbnail size. PhotoAnalysisKit:

  1. loads inputs with the same bounded concurrency and source choice as scoring;
  2. applies each file’s ISO and aperture;
  3. disables classification;
  4. samples up to about 4096 positive Laplacian energies per successful image;
  5. requires at least five successful images;
  6. chooses the requested percentile (RawCull uses 0.90) and clamps the threshold to 0.01…0.95.

Only focusMaskModel.config.threshold is updated. Scalar scoring uses the stable gain and package descriptor; it does not depend on the catalog’s calibration distribution. The calibrated threshold remains in the shared focus model until settings, later calibration, or model reset changes it.

Scoring, Progress, Cancellation, And Publication

SharpnessScoringModel.scoreFiles builds a request identity from ordered file IDs, the scoring signature, and the concurrency limit.

  • An identical request already in flight is coalesced and awaited.
  • A different request cancels the old task and installs a new generation UUID.
  • Fast, Balanced, and High Precision admit 6, 4, and 3 package tasks respectively; RAW demosaic is capped at 2.
  • PhotoAnalysisKit keeps a sliding task-group window, reports completion-order progress, and restores final results to request order.
  • RawCull publishes progress only while the generation matches.
  • Cancellation makes the package return nil and partial results are discarded.
  • Final score, saliency, and breakdown dictionaries are replaced only if the task is not cancelled and the generation still matches.
  • A successful run enables sharpness sorting, then CatalogController merges the results into CullingModel.

This is latest-wins state management. Cancelling work alone is insufficient; every progress and final commit also checks the generation.

Mask tasks have the same presentation rule. SwiftUI views own stored mask tasks, cancel them on image/config replacement, and check cancellation before assigning the returned overlay or diagnostics.

Raw Score Versus UI Label

PhotoAnalysisKit does not promise that the raw scalar is a percentage or clamp the final value to 0…1. It is a relative detail metric whose scale is kept stable by the package gain and descriptor.

RawCull computes an O(1) UI denominator when the score dictionary changes:

fewer than 2 scores -> lone score, or 1
2 through 9         -> maximum
10 or more          -> element at floor((n - 1) * 0.90) in sorted scores
denominator floor   -> 1e-6

Badge consumers clamp score / maxScore to 0…1 before mapping it to presentation labels. A lone score above the denominator floor therefore displays as 100%, and an all-soft catalog can still produce Sharp labels. The labels are relative to the current score set and do not establish absolute focus quality. That UI normalization is not persisted as the package score.

Focus Mask Presentation

FocusMaskModel offers two package-backed paths:

PathPackage callUse
Existing image, optional saved evidencePhotoAnalyzer.focusMaskRender without repeating classification and, when evidence includes a winning saliency rectangle, without repeating saliency selection
Image plus fresh diagnosticsPhotoAnalyzer.analyzeWithFocusMaskCompute scalar/saliency/evidence and render one aligned mask

Views pass a CGImage, ISO, aperture, normalized AF point, scale, and a configuration snapshot. RawCull adapts the package breakdown only to add SharpnessScoringSource; it does not reinterpret the numeric fields.

Presentation-only controls include threshold, dilation, erosion, feathering, raw-Laplacian display, and subject isolation. The legacy guaranteeVisibleFocusEvidence and minimumEvidenceCoverage properties remain source-compatible but no longer relax rendering. Some shared values such as pre-blur, border inset, AF radii, ISO, and aperture affect the evidence image or regions used by both paths. See Detailed Focus Mask Computation for the exact stage classification.

Read These Files In Order

  1. RawCull/Views/GridView/SharpnessControlsView.swift and ScoringParametersSheetView.swift — user entry and settings.
  2. RawCull/Model/ViewModels/CatalogController+Sharpness.swift — target scope, persistence handoff, and sort.
  3. RawCull/Model/ViewModels/FocusandSharpness/SharpnessScoringModel.swift — request identity, generation, bounds, progress, and publication.
  4. RawCull/Model/ViewModels/FocusandSharpness/SharpnessScoringOptions.swift — RawCull-to-package preset, quality, source, and size mapping.
  5. RawCull/Model/ViewModels/FocusandSharpness/RawCullPhotoAnalysisAdapter.swift — decode ownership and PhotoAnalysisInput construction.
  6. RawCull/Model/ViewModels/FocusandSharpness/FocusMaskModel.swift and FocusMaskTypes.swift — mask bridge and result adaptation.
  7. PhotoAnalysisKit/Sources/PhotoAnalysisKit/PhotoAnalyzer.swift and PhotoAnalysisBatch.swift — public package facade and bounded batch.
  8. SharpnessConfiguration.swift, SharpnessPresets.swift, and SharpnessAnalysisDescriptor.swift — defaults, policy, and identity.
  9. FocusMaskEngine+Scoring.swift, FocusMaskEngine+MaskGeneration.swift, and Resources/Kernels.ci.metal — algorithm implementation.

Continue with Detailed Sharpness Scoring for the numeric algorithm, or Detailed Focus Mask Computation for overlay rendering.

Protecting Tests

Boundary or invariantTests
RawCull/package Metal integration and scoring-source adaptationRawCullTests/PhotoAnalysisKitIntegrationTests.swift
Preset/quality mapping, descriptor signatures, legacy invalidation, coalesced runs, UI normalizationRawCullTests/SharpnessScoringTests.swift
Persistence merge and file/signature validation behaviorRawCullTests/CullingModelTests.swift
Batch bounds, ordering, progress, decode failure, cancellationPhotoAnalysisKitTests/PhotoAnalysisBatchTests.swift
Descriptor inclusions/exclusions and policy versionsPhotoAnalysisKitTests/SharpnessAnalysisDescriptorTests.swift
Numeric score helpers, aperture policy, ISO curve, focus-failure classificationPhotoAnalysisKitTests/SharpnessMetricsTests.swift
Analyze, mask, calibration, and cancellation facadePhotoAnalysisKitTests/PhotoAnalyzerTests.swift

Restoring scores without repeated normalization

CatalogController+Sharpness.swift restores persisted scores by building one filename index and validating the scoring signature, source byte size and modification date (within 0.001 seconds). It collects the valid values before publishing dictionaries, so normalization runs once per restoration. AF-center scores additionally require a valid current AF point, finite value and value above 1e-6. Empty restoration clears stale evidence. Store recovery invokes this same path before refreshing filters and selection; see RawCullTests/ReviewPersistenceTests.swift.

Current presentation owners

Loupe mask task/generation state now lives in LoupeFocusPresentationModel.swift; zoom mask coordination lives in ZoomOverlayAnalysisCoordinator.swift. The PhotoAnalysisKit pin and scalar algorithm are unchanged by these view extractions. A mask may remain visible during a same-photo source transition, while new-file/config transitions reset presentation. See Viewer Architecture for guards, task IDs and regression tests. The displayed zoom source and dedicated analysis image can differ; follow the coordinator’s actual input when evaluating detail.

Hydrate missing AF evidence without reranking

Older burst caches can contain blended scores without AF-center scores. loadMissingAFPointScores(for:) in SharpnessScoringModel.swift analyzes valid AF points with missing evidence unless ordinary scoring is active. It retains access, checks cancellation and the scoring signature, and publishes only AF-center values. Existing blended scores and winners remain intact. The workspace requests this when its file set changes; package formulas are unchanged.

Close-up AF assistance is independent of scoring

The burst workspace synchronizes its AF-overlay preference with CloseUpModel.usesAFPoint. The model centers available manual regions on current, orientation-corrected camera AF targets and removes displaced viewport pan. Group changes preserve that preference while resetting the inspection session. This does not call PhotoAnalyzer, rerank candidates or replace AF-center scores. Moving a manual region is not a request to recompute the focus mask or score. See viewer ownership.

Calibration source and display scale

The visual mask cutoff is calibrated on embedded previews at a 1616-pixel target even when scalar scoring uses RAW demosaic. The overlay analysis can rescale its input to match that calibration scale. A late burst calibration result is applied only while its run is still active. FocusMaskTypes.swift

9 - Detailed Sharpness Scoring

Detailed Sharpness Scoring

This is the algorithm-level reference for scalar sharpness at PhotoAnalysisKit 1.3.1, revision 2a1466e04d821fa2628d6985296643e0d0c7e465. RawCull chooses files and image sources, maps UI settings, bounds work, publishes progress, normalizes badges, and persists results. PhotoAnalysisKit owns the analysis formula.

For ownership, cancellation, calibration, and UI flow, start with Focus Mask And Sharpness. This page concentrates on the package algorithm and names RawCull policy only where it changes package input or consumes package output.

Compact Worked Example

Consider a wildlife frame after Laplacian sampling:

full-frame robust score                 0.18
AF broad score                          0.30
Vision salient broad score              0.24
best AF-local patch                     0.34
best salient-interior patch             0.28
wildlife salient weight                 0.85
subject saliency area                   ignored because AF exists
subject border fraction                 0.50 (below silhouette trigger)
subject micro-contrast                  0.020
aperture                                f/5.6 -> wide gate 0.010...0.025

The actual pipeline combines the evidence in stages:

broad subject = 0.6 * 0.30 + 0.4 * 0.24 = 0.276

local detail  = 0.6 * 0.34 + 0.4 * 0.28 = 0.316
subject       = 0.75 * 0.276 + 0.25 * 0.316 = 0.286

base          = 0.15 * 0.18 + 0.85 * 0.286 = 0.2701

blur t        = (0.020 - 0.010) / (0.025 - 0.010) = 0.6667
attenuation   = 0.20 + 0.80 * 0.6667 = 0.7333

final         = 0.2701 * 0.7333 = about 0.198

There is no silhouette penalty because 50% is below 62%, and no subject-size bonus because an AF region exists. The final value is a raw relative score, not a percentage. RawCull later normalizes it against the catalog denominator for a badge.

The numeric values above are illustrative inputs to the current formulas; they are not fixture output from a particular image.

End-To-End Boundary

flowchart TD
    UI["RawCull controls"] --> RVM["CatalogController target files"]
    RVM --> SM["SharpnessScoringModel<br/>preset + quality + source + size"]
    SM --> ADAPTER["RawCullPhotoAnalysisAdapter"]
    ADAPTER --> DECODE{"Host-owned decode"}
    DECODE -->|"embedded"| RPK["RawParserKitImageLoader"]
    DECODE -->|"RAW"| CIRAW["CIRAWFilter"]
    RPK --> INPUT["PhotoAnalysisInput"]
    CIRAW --> INPUT
    INPUT --> BATCH["PhotoAnalyzer.analyzeBatch"]
    BATCH --> ANALYZE["PhotoAnalyzer.analyze"]
    ANALYZE --> VISION["Vision saliency/classification"]
    ANALYZE --> LAPLACIAN["Metal Laplacian + robust region metrics"]
    VISION --> BLEND["subject/full blend, adjustments, blur gate"]
    LAPLACIAN --> BLEND
    BLEND --> RESULT["PhotoAnalysisResult / SharpnessBreakdown"]
    RESULT --> SM
    SM --> PERSIST["RawCull normalization, sorting, persistence"]

1. RawCull-Owned Input Policy

Target Files

CatalogController.sharpnessScoringTargetFiles chooses, in order:

  1. explicitly selected files, keeping visible selected files first and appending selected files hidden by the current projection;
  2. the exact active star-rating set;
  3. otherwise the active catalog set, including semantic-search scope, sorted by filename.

Calibration uses embedded previews capped at 1616 px. Scoring uses the selected source and effective size. Calibration adjusts only the visual mask threshold; it does not calibrate the scalar score. After a non-cancelled, nonempty result, RawCull merges scores and subject labels into CullingModel and reapplies catalog sorting.

Protected by: RawCullTests/CullingModelTests.swift target-scope and calibrateAndScoreCurrentCatalog tests.

Preset And Quality

RawCull starts from the shared focus config, initially .birdsInFlight, then applies the selected PhotoAnalysisKit preset and quality. Auto preserves that config; it does not infer a photo type from classification. Unlike the explicit Birds/Wildlife preset, .birdsInFlight leaves the explicit salient override nil, so the f/8 aperture fallback can reduce Auto’s subject weight to 0.55.

RawCull photo typePackage changes from the input config
AutoNo preset change
Birds/Wildlifepre-blur 2.2; border 0.05; salient weight and explicit override 0.85; size factor 0.05; silhouette strength 0.55; AF radius 0.06; classify and isolate
Portraitpre-blur at most 1.7; salient weight/override 0.80; size factor 0.08; silhouette 0.25; AF radius 0.10; classify and isolate
Landscapepre-blur at most 1.55; salient weight 0.35 with explicit override 0.35; size factor 0; silhouette 0.15; AF radius 0; do not isolate mask
Actionpre-blur 2.0; salient weight/override 0.65; size factor 0.05; silhouette 0.40; AF radius 0.09; classify and isolate
QualityPackage fine-detail weightRawCull minimum sizeRequested concurrency
Fast05126
Balancedat least 0.257684
High Precisionat least 0.45 and classification enabled10243

The effective maximum pixel size is clamped between the quality minimum and 2048; a nonpositive setting resolves to 2048. RAW demosaic further caps concurrency at two. Embedded-preview scoring uses the quality limit in the table. The shared Vision gate serializes blocking request bodies across these jobs. SharpnessScoringModel

Protected by: RawCullTests/SharpnessScoringTests.swift preset, quality, size, and concurrency assertions; package policy also has PhotoAnalysisKitTests/SharpnessMetricsTests.swift.

Image Source

SourceRawCull implementation
Embedded PreviewRawParserKitImageLoader.shared.thumbnailCGImage at the effective size
RAW DemosaicConcurrent CIRAWFilter decode; sharpness 0, detail 0.6, contrast 1.0, exposure 0; scale longest side to effective size

The adapter returns PhotoAnalysisInput(image:iso:aperture:normalizedAFPoint:). PhotoAnalysisKit never opens RawCull files and does not choose a source.

Protected by: RawCullTests/PhotoAnalysisKitIntegrationTests.swift and adapter overrides in RawCullTests/SharpnessScoringTests.swift.

2. Package Defaults And Per-Image Resolution

The default SharpnessConfiguration values at the pinned revision are:

ValueDefaultRole
preBlurRadius1.92Shared edge-energy input
iso400Replaced from each input
threshold0.46Mask presentation only
energyMultiplier7.62Stable scoring and shared edge gain
borderInsetFraction0.04Scalar full-frame border exclusion; also blackens mask border
salientWeight0.75Scalar subject/full blend
subjectSizeFactor0.10Scalar saliency-only size bonus
silhouettePenaltyStrength0.55Scalar penalty maximum
fineDetailBlendWeight0Scalar second pass
enableSubjectClassificationtrueLabel only; saliency candidates are still analysis evidence
afRegionRadius0.12Broad AF scoring region
afCenterRegionRadius0.025Evidence diagnostic/local region
afNeighborhoodRegionRadius0.075Evidence diagnostic/local-patch region
apertureHintmidReplaced from each input

PhotoAnalyzer.analyze copies the config, sets the input ISO, and derives:

ApertureHintBlur gate low/highBlur dampFallback salient override
f/5.6 or widerwide0.010 / 0.0251.0none
between f/5.6 and f/8mid0.008 / 0.0221.0none
f/8 or narrowerlandscape0.006 / 0.0180.80.55
missingmid0.008 / 0.0221.0none

An explicit preset override wins over the aperture fallback.

Protected by: PhotoAnalysisKitTests/SharpnessMetricsTests.swift and RawCullTests/SharpnessScoringTests.swift.

3. Normalization And Vision

PhotoAnalysisKit normalizes the decoded CGImage to sRGB RGBA before analysis. Vision produces attention-based saliency candidates. Classification, when enabled, is additional metadata; it is not itself a score.

Candidates are retained when normalized area is greater than 0.03 or Vision confidence is at least 0.9. For each retained candidate, the engine computes a broad region detail score when it has at least 64 finite samples. Candidate selection favors AF containment/alignment when an AF point exists, then uses Vision confidence, detail, and area as tie-break evidence. Vision rectangles use a bottom-origin coordinate convention; the rendered bitmap is sampled with the Y coordinate inverted so the intended pixels are measured.

Checked against FocusMaskEngine+Scoring.swift. The package facade and RawCull integration tests check that analysis is available; they do not directly test candidate filtering, selection tie-breaks, or asymmetric Y-coordinate fixtures.

4. Edge-Energy Image

The package applies:

isoFactor:
  ISO < 800          -> 1.0
  800 <= ISO < 3200  -> 1.0 + (ISO - 800) / 2400 * 0.6
  ISO >= 3200        -> min(1.6 + (ISO - 3200) / 6400 * 0.6, 2.2)

resolutionFactor =
  clamp(sqrt(max(longestSide, 512) / 512), 1, 3)

effective blur radius =
  min(preBlurRadius * isoFactor * resolutionFactor * apertureBlurDamp, 100)

After Gaussian pre-blur, the Metal focusLaplacian kernel computes:

laplace = 8 * center - sum(the 8 neighboring pixels)
energy  = dot(abs(laplace.rgb), [0.299, 0.587, 0.114])

A color matrix multiplies that energy by 7.62. The scoring image is cropped back to the source extent because Gaussian blur expands its extent.

Balanced and High Precision additionally build a fine pass with:

fine pre-blur = max(0.35, primary pre-blur * 0.58)
combined      = primary * (1 - w) + fine * w
w             = clamped to 0...0.65

Protected by: PhotoAnalysisKitTests/SharpnessMetricsTests.swift ISO and numeric helper tests, and PhotoAnalysisKitTests/PhotoAnalyzerTests.swift end-to-end tests.

5. Region Samples And Robust Tail Score

The engine creates these sample sets:

  • full frame, excluding borderInsetFraction on every edge;
  • each Vision candidate;
  • a broad AF square with half-size afRegionRadius;
  • AF-center and AF-neighborhood squares for evidence;
  • best local patches within the AF neighborhood and winning saliency region.

Broad AF, saliency, and AF-neighborhood regions need at least 64 finite samples; the tighter AF center needs 16. Full-frame scoring accepts any nonempty finite sample set. Local patches use a separate patch sampling/ranking path.

For any nonempty sample array:

p20 = sample at floor((n - 1) * 0.20)
p90 = sample at floor((n - 1) * 0.90)
p97 = sample at floor((n - 1) * 0.97)

band mean = mean(max(0, value - p20))
            for original samples where p90 <= value <= p97

density = min(1, (bandCount / n) / 0.06)
robust tail score = band mean * density

If p97 is not greater than p90, or the band is unexpectedly empty, the fallback is max(0, p90 - p20). The density factor is a band-occupancy multiplier, not an independent measure of spatial edge density. With distinct continuous samples, the p90…p97 band contains about 7% of samples, so the multiplier usually saturates at 1. Sparse outliers can still score low because the top 3% is excluded and the band mean is small; dense residual noise is not ruled out by this factor. Micro-contrast is the standard deviation of finite Laplacian samples.

Protected by: PhotoAnalysisKitTests/SharpnessMetricsTests.swift and the forwarding checks in RawCullTests/SharpnessScoringTests.swift.

6. Subject Construction

The broad subject score is:

AF and saliency present -> 0.6 * AF + 0.4 * saliency
only one present        -> that score
neither present         -> nil

The local detail score uses the same 0.6/0.4 blend for the best AF-local and salient-interior patches. The effective subject is conservative:

broad and local present -> 0.75 * broad + 0.25 * local
only one present        -> that score

This prevents one tiny high-energy patch from replacing the broad subject measurement while still rewarding localized detail.

Checked against conservativeSubjectScore and computeSharpnessAnalysis in FocusMaskEngine+Scoring.swift. The pinned tests do not directly assert this blend or its missing-evidence branches.

How A Local Patch Is Chosen

“Best” means first selected by composite patch ranking, not necessarily the patch with the largest robust-tail score. The scoring path reuses patchRankings and selectEvidencePatches from FocusMaskEngine+MaskGeneration.swift, applied to the scoring energy image.

Patch dimensions are 34% of the search region, bounded to 3.5%…14% of the full image dimension, with 50% overlap. Ranking combines robust-tail score, micro-contrast, adaptive-threshold coverage, AF proximity, an interior bonus, silhouette penalties, and ring/compact/linear shape heuristics. AF-anchored patches also receive a penalty for being below the AF point. A nearest-to-AF patch is preferred when the strongest composite score is less than 1.15 times its score. The first selected patch contributes its robust-tail value to the scalar blend.

A salient-interior patch is favored by an interior bonus; it is not required to exclude the region border. Landscape sets the broad AF radius to zero, but it retains the AF-neighborhood radius. An AF-local patch can therefore still contribute to Landscape scoring. Changes to shared patch-ranking helpers can change scalar scores even when made in the mask-generation source file.

7. Full/Subject Blend And Adjustments

When both full and subject scores exist:

weight = explicit preset override
         ?? aperture hint override
         ?? config.salientWeight

base = full * (1 - weight) + subject * weight

Two adjustments occur before the blur gate:

  1. Silhouette penalty. The package compares average energy in the outer rim of the effective subject region with its interior. Rim thickness is max(1, floor(0.12 * min(regionWidth, regionHeight))) pixels, and the comparison is borderMean / max(borderMean + interiorMean, 1e-6), rather than the fraction of total energy located in the rim. If the derived border fraction exceeds 0.62:

    over = min(1, (borderFraction - 0.62) / 0.38)
    base *= 1 - silhouettePenaltyStrength * over
    
  2. Subject-size bonus. Only when no AF region exists and Vision supplied the subject:

    base *= 1 + saliencyArea * subjectSizeFactor
    

Fallbacks are intentionally asymmetric:

full only    -> full * (1 - weight)^3
subject only -> subject
neither      -> no analysis

Checked against computeSharpnessAnalysis. Existing tests cover preset values and the analysis facade; the pinned suite has no direct regression assertions for the cubic fallback, silhouette multiplier, or subject-size bonus.

8. Aperture-Aware Blur Gate

The effective AF analysis is preferred over saliency for subject micro-contrast. With at least 64 samples:

t = clamp((sigma - blurGateLow) / (blurGateHigh - blurGateLow), 0, 1)
attenuation = 0.20 + 0.80 * t
final score = base * attenuation

Without a valid subject sample set, attenuation is 1.0.

Focus-failure classification is diagnostic. Here subject means the broad saliency score, falling back to broad AF; it is not the conservative blended subject score described above. Missing scores count as zero in the motion-blur branch, so these labels are heuristic indicators rather than a reliable diagnosis of the physical cause of blur:

  • motion blur when global, subject, and AF-or-subject are all below 0.08 and sigma is below 0.012;
  • missed focus when global is at least 0.12 and subject/global is below 0.55;
  • otherwise none.

Protected by: PhotoAnalysisKitTests/SharpnessMetricsTests.swift focus-failure and aperture tests.

9. Score Range, UI Normalization, And Persistence

The package score is nonnegative for valid finite inputs, but the implementation does not clamp the final score to 1.0. The subject-size multiplier can also raise the blended value. Treat the output as a stable relative metric, not a percentage or probability.

RawCull stores the raw value. It computes a badge denominator from the lone score, small-set maximum, or large-set 90th-percentile element and clamps the UI ratio to 0…1. That presentation normalization does not change the stored score or burst-ranking input.

SharpnessAnalysisDescriptor schema 1 / algorithm 4 identifies package behavior. It includes scoring-affecting config and policy versions, excludes mask-only settings and per-image values, and fixes the scoring gain at 7.62. RawCull adds source and effective pixel size, then validates source file size and modification date on reload. Legacy descriptors decode but are stale.

Protected by:

Assessment And Validation Priorities

Source review on 2026-09-28 confirms the principal formulas match the pinned implementation. The metric is a practical relative-detail heuristic, but the existing numeric and facade tests do not establish that its ranking is optimal for real photographs.

Before tuning coefficients, validate these specific policies:

  • Missing subject evidence: the full-only multiplier is 0.003375 for an explicit wildlife weight of 0.85, 0.015625 for the generic default weight of 0.75, and 0.274625 for Landscape’s 0.35. Detection failure can dominate detail. Compare a confidence-aware fallback and expose unavailable subject evidence separately from measured softness.
  • Texture and noise: band occupancy generally saturates. Evaluate sharp low-contrast subjects, sparse real detail, blurred textured backgrounds, and high-ISO residual noise before adding an independently measured noise or edge-support term.
  • Local subject intent: test Landscape with and without AF metadata and test small wildlife subjects against sharper neighboring/background detail. Decide explicitly whether AF-local scoring belongs in Landscape.
  • Blur gate and scale: test ISO, aperture, thumbnail size, preview processing, and RAW decode independently. The fixed sigma thresholds and pre-blur are heuristics; larger thumbnails and a higher quality setting do not by themselves prove better rankings.
  • Presentation: a lone score above the denominator floor normalizes to 100%, and an all-soft catalog can still produce Sharp labels. These are relative labels, not absolute focus-quality judgments.

Use expert-ranked pairs from representative bursts and report pairwise ordering, top-choice agreement, and severe subject/background mistakes by condition. Keep evaluation images separate from coefficient tuning. Add deterministic regressions for the confirmed failure cases, then compare proposed changes with the current algorithm before replacing it.

Change Checklist

When changing scoring:

  1. change package code and package tests first, including shared patch-ranking helpers used by scalar scoring;
  2. decide whether the scalar algorithm or ISO/aperture policy version must increase;
  3. verify descriptor tests include every scalar-affecting setting and exclude mask-only presentation;
  4. verify RawCull preset, quality, source, and size mapping;
  5. test batch cancellation and latest-generation publication;
  6. inspect raw score distributions separately from normalized badge labels;
  7. update this reference and the overview together.

Validate AF-center ordering separately

The app can backfill missing AF-center scores without replacing blended scores or recommended winners. This hydrates evidence; it does not change the formula.

make releaseafcomparison RELEASE_CATALOG="/path/to/photos" exports the fixed Wildlife / Balanced / 1024 px / embedded-preview recipe. CompareAFSharpness.py compares exported AF scores against Laplacian variance and mean Sobel magnitude on matching crops. Production filtering retains full-frame context; baselines use crop-local OpenCV boundaries. Compare pair ordering, never absolute scores or units. Keep intended-subject pairs and blinded photographer labels fixed; track unavailable evidence, photographer ties, model ties and uncertain labels alongside agreement.

Follow the optional NumPy/OpenCV setup and labeling protocol in Release test guide. The report does not claim statistical significance or change app scoring. This documentation pass did not run this opt-in comparison or qualify photographic accuracy.

Target count and execution order

Control labels now read sharpnessScoringTargetCount, which computes membership without sorting sharpnessScoringTargetFiles. Execution still uses the ordered array: visible selections first, hidden selected files in filename order; a star filter uses visible matching files when available, otherwise matching active files in filename order; the unfiltered active scope is filename-sorted. This avoids presentation-only sorting without changing scoring options or package throughput. See Viewer Architecture.

10 - Close Up

Compare detail across frames using manual regions, pinned references, recorded autofocus points and detected crops.

Close Up is the inspection panel in the burst and Single Images workspace. Use it to compare the same part of a subject across frames before choosing a keeper. The manual cards give you control over the region and pixel source. A strip above them shows automatic detections for the current frame.

Compare two or more frames

  1. Click a filmstrip frame to make it current. Command-click to toggle other frames into the comparison. Shift-click selects a displayed range, and Command-Shift-click adds a range to the selection. The inclusion checkboxes change comparison membership without activating another frame.
  2. Open Close-ups in the workspace toolbar. With no explicit selection, the panel inspects the current frame.
  3. Click the overview in each card to choose the region to inspect. Set the crop extent with Region size. Drag the crop or focus it and use the arrow keys to pan. Use Zoom to inspect the result more closely.
  4. Click Pin reference on a strong frame. It stays visible while you change the comparison selection in that inspection session. Use Replace reference to switch baselines or Unpin reference to clear it. Show image activates the frame and opens the zoom overlay with group navigation and the current source.

Double-click a thumbnail on a burst card to open the workspace at that frame. When comparing at most one frame, workspace navigation makes Close Up follow the active frame. An explicit multi-frame comparison keeps its membership.

A new group starts a new inspection session. Manual regions are saved for their source revisions, so revisiting a frame can restore its region. Reset region resets that frame’s chosen area. Reset view and Reset views reset inspection pan and zoom.

Choose a scale and pixel source

  • Fit region fits each chosen area inside its card. Use it to compare framing, expression or the placement of detail.
  • Source pixels uses one source pixel per physical display pixel at 1×, including on Retina displays. Check the source label and dimensions under the crop when judging fine detail across frames.
  • JPG uses the preview path. The source label identifies which preview supplied the pixels, such as a sidecar JPG or an embedded preview.
  • RAW uses a developed RAW render, with RAW 9 where supported and the system decoder otherwise. The picker displays RAW 9 when all relevant frames support it. This picker controls the main stage and manual cards together. The automatic strip uses the embedded preview. If the main stage cannot show a JPG preview, Try RAW switches sources.

Turn on Link pan/zoom to move and zoom the cards together around their independent regions. First place each region on the part you want to compare. If a bird shifts between frames, center each region on its head before linking the views.

Inspect the recorded autofocus point

Use AF point uses the recorded autofocus location where supported. RawCull maps the camera coordinates to the upright image and shares this setting with the main stage. The recorded point tells you where the camera reported focusing. Check the crop itself for sharpness. If the point is unavailable or on a different part of the subject, select a manual region in the overview.

Read the automatic detection strip

Detected faces and animal landmarks uses the current frame’s upright embedded preview, capped at 1,600 pixels on its longest side. It refreshes when you activate another frame and resumes after indexing. Detection and manual comparison use separate regions.

TileWhat you seeHow to use it
Human faceA face crop and, when available, a local preview detail valueCompare similar captures of the same face at comparable preview scales.
Animal headA crop around usable head landmarksCheck head framing and visible detail.
Animal eyeA tighter crop around each usable eye landmarkInspect the visible eye and use a manual RAW crop when more source detail is needed.

RawCull calls PhotoAnalysisKit’s animal body pose adapter. A head crop needs enough landmarks to establish a crop size. Eyes below the confidence threshold are omitted, so a profile may show a single eye, and a head may appear without eye tiles. Apple documents cat and dog support. Coverage for birds, deer and other wildlife needs validation. Use the manual overview for distant subjects, occlusions or missed detections. Apple Vision animal pose

Animal tiles are for visual inspection. The human tile’s detail value measures local luminance gradients and is separate from ratings and burst ranking. If the strip reports that detection is unavailable, use Retry. A manual card with a render failure offers Retry image.

The automatic strip awaits PhotoAnalysisKit’s face and animal requests. Those requests use the same serial Vision queue as sharpness and feature-print indexing. RawCull also bounds work in the detected-evidence loader. A manual crop uses PhotoEvidenceKit’s renderer and can be inspected independently of detection. BurstDetectedFacesView

Example workflow for a wildlife burst

Start with the best-looking pose and pin it. Select two nearby frames. Use any animal tiles as a quick check, then choose each subject’s eye or head in the manual overviews. Switch to RAW and Source pixels to judge fine detail from the developed render. Link pan and zoom after aligning the regions. Use the workspace’s rating or winner controls to record your decision.

For implementation details, see PhotoEvidenceKit, PhotoAnalysisKit, and burst review.

11 - Detailed Focus Mask Computation

Detailed Focus Mask Computation

This page follows visible focus-mask rendering at PhotoAnalysisKit 1.3.1, revision 2a1466e04d821fa2628d6985296643e0d0c7e465.

The focus mask is not the camera’s AF-point marker. The marker reports where the camera attempted focus. The mask is a package-generated bitmap of selected edge-detail evidence. The AF point can guide selection, but it is never painted as the mask by itself.

RawCull owns the SwiftUI trigger, image and metadata supplied to the package, task lifetime, and overlay presentation. PhotoAnalysisKit owns normalization, saliency, evidence selection, Laplacian generation, patch ranking, thresholding, morphology, colorization, clipping, and mask diagnostics.

For shared ownership, persistence, calibration, and scalar score behavior, see Focus Mask And Sharpness.

Data Shapes And The Overlay Boundary

flowchart LR
    VIEW["SwiftUI view<br/>NSImage or CGImage"] --> FM["@MainActor FocusMaskModel"]
    FM --> INPUT["PhotoAnalysisInput<br/>CGImage<br/>ISO, aperture, AF CGPoint?"]
    INPUT --> PA["PhotoAnalyzer"]
    PA --> NORM["normalized sRGB CGImage"]
    NORM --> CI["CIImage RGBAf analysis"]
    CI --> VALUES["Float edge samples<br/>saliency rectangles<br/>FocusPatchRanking[]"]
    VALUES --> EVIDENCE["FocusEvidence<br/>regions, confidence, threshold, coverage"]
    VALUES --> MASKCI["thresholded/colorized CIImage"]
    MASKCI --> OUT["CGImage focus mask"]
    OUT --> ADAPT["NSImage when required"]
    ADAPT --> OVERLAY["SwiftUI Image overlay<br/>presentation boundary"]
    EVIDENCE --> BREAKDOWN["SharpnessBreakdown diagnostics"]

CGImage is the public decoded-image boundary. Package internals create CIImage values and render RGBAf edge-energy samples with a reusable CIContext. The returned CGImage contains only the overlay bitmap; RawCull positions it over the displayed image. The package does not retain a SwiftUI view, app model, URL, or persistence object.

Call Paths

RawCull contextModel callPackage facadeEvidence behavior
Main thumbnail/detailgenerateFocusMaskPhotoAnalyzer.focusMaskCan reuse existing FocusEvidence; classification is skipped and a saved winning saliency rectangle avoids a new saliency pass
Zoom overlaygenerateFocusMaskWithBreakdownPhotoAnalyzer.analyzeWithFocusMaskRecomputes saliency, scalar breakdown, evidence, and mask together
Comparison gridgenerateFocusMaskWithBreakdownPhotoAnalyzer.analyzeWithFocusMaskSame aligned diagnostic path per comparison image

The RawCull entry files are:

Views snapshot the effective config, inject ISO, aperture, and normalized AF point, cancel a previous mask task when image or config identity changes, and check cancellation before publishing the result.

Which Values Affect What

The categories below are important when tuning the mask.

Scalar Score Values

These change package scalar analysis and therefore belong in SharpnessAnalysisDescriptor:

  • pre-blur radius;
  • border inset;
  • salient weight and explicit override;
  • subject-size factor;
  • silhouette-penalty strength;
  • broad/center/neighborhood AF radii used by scoring evidence;
  • fine-detail blend;
  • classification policy;
  • the stable scoring gain and algorithm/policy versions.

ISO and aperture also change scalar analysis, but are per-image inputs rather than descriptor configuration. Photo type and quality change scalar output indirectly by applying the values above.

Mask Presentation Values

These change only the rendered overlay or its visibility:

ValueCurrent defaultEffect
threshold0.46Fallback/floor reference for adaptive visual threshold
dilationRadius0.0Optionally connects thresholded edge pixels
erosionRadius0.0Optionally removes isolated/small responses
featherRadius0.5Softens the clipped mask alpha
showRawLaplacianfalseDebug early return before threshold, patches, color, and morphology
guaranteeVisibleFocusEvidencefalseCompatibility property; no longer lowers the render threshold
minimumEvidenceCoverage0.001Compatibility property retained with the public configuration
isolateMaskToSubjecttrueChooses subject/AF search regions rather than the whole frame

The final mask uses a single warm red/orange color matrix: red 1.0, green 0.22, blue 0.02, alpha 0.92 before SwiftUI compositing.

Shared Evidence Values

Some values affect both analysis evidence and rendering even though the final mask threshold itself never becomes a scalar multiplier:

  • pre-blur radius, energy gain, ISO, aperture blur damp, and image resolution determine the shared primary Laplacian;
  • border inset excludes scalar border samples and blackens the corresponding mask border;
  • saliency candidates and AF point determine scoring regions and potential mask search regions;
  • AF radii determine scalar evidence regions and which mask region can be selected;
  • existing FocusEvidence can make mask selection follow a previous score.

Calibration Output

Calibration returns FocusCalibrationResult(threshold, sampleCount, p50, p90, p95, p99). RawCull applies only threshold to the active config. The percentiles and sample count are diagnostics. Calibration changes visual threshold policy; it does not rescale stored scalar scores.

Stage 1: Normalize And Resolve Per-Image Configuration

PhotoAnalyzer.focusMask and analyzeWithFocusMask normalize the input CGImage to sRGB. They copy the caller’s SharpnessConfiguration, then replace:

config.iso          = input.iso
config.apertureHint = derived from input.aperture

Aperture at or below f/5.6 is wide, at or above f/8 is landscape, the interval between is mid, and missing metadata defaults to mid.

The package engine runs synchronous Vision/Core Image work in an explicitly @concurrent child task. A cancellation handler cancels that worker. This is not a detached task in the pinned revision.

Stage 2: Obtain Saliency And Score Evidence

The simple facade follows this rule:

saved winningSaliencyRect exists -> reuse it
else isolateMaskToSubject         -> run saliency, without classification
else                              -> no salient region

The diagnostic facade always detects saliency, optionally classifies, computes a SharpnessBreakdown, then gives the resulting evidence to mask rendering. That keeps the displayed patch, score diagnostics, and saliency decision from the same analysis pass.

The evidence can request one of:

  • AF center;
  • AF neighborhood;
  • broad AF point;
  • saliency;
  • mixed AF and saliency;
  • global;
  • none.

If the requested evidence is unavailable, rendering falls back in this order: broad AF, saliency, then global.

Stage 3: Scale And Build The Primary Laplacian

The input CIImage is transformed by the requested mask scale. RawCull’s FocusMaskAnalysisResolutionPolicy.prepare returns every decoded preview pixel, so view code must choose an appropriate decode before this call. The package builds a dedicated native-pixel focus-mask detail image with clamped edges and the following pre-blur:

focus-mask pre-blur = max(0.35, primary preBlurRadius * 0.52)

Native-mask mode disables resolution scaling and preserves the input extent. The scalar scoring path continues to use its resolution-aware primary and optional fine-detail passes.

The underlying scalar edge pipeline is:

ISO factor:
  below 800          1.0
  800...3199         linear 1.0 -> 1.6
  3200 and above     linear tail capped at 2.2

resolution factor =
  clamp(sqrt(max(longestSide, 512) / 512), 1, 3)

blur radius =
  min(preBlurRadius * ISO factor * resolution factor * aperture damp, 100)

Laplacian =
  abs(8 * center - 8 neighbors)
  collapsed with [0.299, 0.587, 0.114]
  multiplied by energyMultiplier

Landscape aperture damp is 0.8; wide and mid are 1.0. The package then blackens the configured border inset so expanded Gaussian edges are not visual evidence.

Raw Laplacian Debug Mode

When showRawLaplacian is true, the package crops the boosted Laplacian to the scaled image extent and returns it immediately. It records the saliency/AF region source, but does not:

  • build or select patches;
  • calculate an adaptive visual threshold;
  • threshold or colorize edges;
  • erode, dilate, thin, clip, or feather the mask.

Use this mode to inspect the edge-energy input, not the final overlay.

Stage 4: Resolve Search Regions

With subject isolation enabled, the package converts normalized Vision and AF coordinates into pixel rectangles. AF Y is inverted when moving between the view/AF convention and Core Image pixel space.

It also creates two tighter AF rectangles from defaults:

AF center half-radius       0.025 of image dimensions
AF neighborhood half-radius 0.075
broad AF half-radius         config.afRegionRadius

Search regions are selected from the requested evidence. Mixed evidence searches AF and saliency separately. Global/none searches the whole image. With subject isolation disabled, the whole image becomes the saliency-shaped selection and the search is effectively global.

Every focus-mask region uses the same native-pixel detail source described in Stage 3. The mask is not center-weighted around the AF point. This 0.52 factor is mask selection and rendering policy; scalar quality’s second pass uses a different 0.58 factor and blend.

Stage 5: Generate Candidate Patches

For each bounded search region:

patch width =
  min(max(region width * 0.34, image width * 0.035), image width * 0.14)

patch height =
  min(max(region height * 0.34, image height * 0.035), image height * 0.14)

grid step = patch dimension * 0.50

If the AF-centered patch overlaps at least 75% of its intended size, it is added. The renderer also appends a separate 6%-of-image AF patch when an AF point exists.

Each patch records:

  • robust p90…p97 tail detail relative to p20;
  • micro-contrast standard deviation;
  • coverage above an adaptive patch threshold;
  • normalized distance to AF and whether it contains AF;
  • interior versus silhouette fraction;
  • ring, compact-detail, and linear-edge shape evidence;
  • a below-AF penalty and eye/head heuristic adjustment.

Stage 6: Rank Patches

The current composite is:

robust tail
+ micro contrast * 0.35
+ coverage * 0.08
+ AF proximity * 0.12
+ interior bonus (0.03 when not touching search border)
- silhouette * (0.18 for AF-anchored regions, otherwise 0.45)
+ eye/head adjustment

eye/head adjustment =
  ring detail * 0.10
+ compact detail * 0.08
- linear edge * 0.10
- below-AF penalty

below-AF penalty =
  clamp((distance below AF - 0.025) / 0.15, 0, 1) * 0.18

AF proximity falls linearly to zero at normalized distance 0.20. Composite scores are floored at zero.

For AF-anchored evidence, the nearest patch is promoted ahead of the strongest only when it is not already strongest and the strongest is less than 1.15 times the nearest. Selection then walks descending composite score, rejects patches with overlap ratio 0.55 or greater, and keeps at most three.

These rankings are visual-evidence selection and diagnostics. Scalar scoring does use the best AF-local and salient-interior patch’s robust tail score as a conservative 25% refinement of broad subject evidence, but it does not use the rendered mask threshold, morphology, color, or rendered coverage.

Stage 7: Choose The Visual Threshold

Samples are collected from the full selected search regions. Ranked patches summarize and order local evidence, but no longer truncate the visible focus map. The adaptive threshold is:

EvidencePercentileFloor from config thresholdMay exceed fallback?
AF center/neighborhood/point0.820.32 times fallbackNo
Saliency, mixed, or global0.900.55 times fallbackYes

The floor is at least 0.01 and the final threshold is at most 0.95.

The threshold is not relaxed for visibility. relaxedForVisibility is always false in the current renderer, and weak images may return an empty mask.

Stage 8: Render And Clip

The package performs this sequence:

  1. copy the Laplacian red channel into grayscale;
  2. apply CIColorThreshold;
  3. apply morphology minimum with erosionRadius, when positive;
  4. apply morphology maximum with dilationRadius, when positive;
  5. colorize to warm red/orange with alpha 0.92;
  6. clip the result to the union of the selected search regions;
  7. Gaussian-feather with featherRadius, when positive;
  8. crop to the scaled image extent and create the output CGImage.

After morphology and feathering, GPU area reductions compute visible-alpha coverage within the selected regions. This final rendered coverage—not a pre-render sample estimate—is stored in the evidence.

Stage 9: Return Diagnostics

The mask result updates FocusEvidence with:

  • visualized region and overlay style;
  • all sorted patch rankings;
  • effective threshold, coverage, and relaxation flag;
  • visualized centroid distance from AF;
  • spatial-alignment score and best/second-best dominance;
  • silhouette indication;
  • high, medium, or low evidence confidence plus a reason.

Confidence rules are intentionally readable:

  • no viable patch -> low;
  • rendered coverage below 0.001, robust-tail below 0.01, micro-contrast below 0.005, or patch coverage below 0.001 -> low;
  • AF anchored within normalized distance 0.05 with strong detail -> high;
  • AF aligned with measurable but weaker detail -> medium;
  • AF farther than 0.05 -> low;
  • global with composite at least 0.10 -> medium, otherwise low;
  • non-AF subject with strong detail, silhouette below 0.20, and dominance at least 1.08 -> high;
  • other usable subject evidence -> medium.

The diagnostic facade also records FocusMaskRegionSource and the visual threshold in SharpnessBreakdown. RawCull adapts that package breakdown only to add the selected scoring source.

SwiftUI Publication And Cancellation

RawCull views own their mask tasks:

  • a new image, config, source, or explicit regeneration cancels the old task;
  • view disappearance/toggle-off cancels and clears mask state;
  • package workers check cancellation before and after Vision, Laplacian, patch, and render stages;
  • views check cancellation before assigning the returned mask and breakdown.

The package result is a value. It cannot publish into an old view on its own; the owning SwiftUI task is the final stale-result boundary.

Debugging A Surprising Mask

  1. Confirm the input image, mask scale, ISO, aperture, and normalized AF point.
  2. Inspect winningRegion, winning saliency rectangle, and region source.
  3. Compare AF-center, AF-neighborhood, broad AF, saliency, and global scores.
  4. Inspect sorted patch composite components, especially AF distance, silhouette, linear-edge, and below-AF penalties.
  5. Check effective visual threshold and final rendered coverage.
  6. Enable raw Laplacian mode to separate edge-energy input from threshold and morphology.
  7. Remember that a strong scalar score and a sparse mask are compatible: the mask is permitted to be empty when the evidence gates are not met.

Protecting Tests

StageTests
RawCull facade, Metal resource, returned breakdown, scoring-source adaptationRawCullTests/PhotoAnalysisKitIntegrationTests.swift
Public analyze/mask/calibration behavior and cancellationPhotoAnalysisKitTests/PhotoAnalyzerTests.swift
Native-pixel mask detail, full-region rendering, empty weak masks, and final coveragePhotoAnalysisKitTests/FocusMaskAccuracyTests.swift
Robust tail, micro-contrast, ISO curve, aperture gates, failure classification, presetsPhotoAnalysisKitTests/SharpnessMetricsTests.swift
Descriptor excludes mask-only presentation and includes scalar policyPhotoAnalysisKitTests/SharpnessAnalysisDescriptorTests.swift
Bounded input loading and analysis cancellationPhotoAnalysisKitTests/PhotoAnalysisBatchTests.swift

Change Checklist

When changing the mask:

  1. classify the value as scalar-affecting, mask-only, shared evidence, or calibration output;
  2. update the descriptor only for scalar-affecting behavior;
  3. verify simple rendering can reuse score evidence without repeating Vision;
  4. verify AF and Vision coordinate conversion;
  5. test cancellation at the package worker and SwiftUI publication boundaries;
  6. inspect raw Laplacian, patch diagnostics, threshold coverage, and final overlay as separate stages;
  7. update this page and the overview together.

Presentation after the October viewer refactor

The formula walkthrough above uses the dated package revision. The app’s publication boundary now includes LoupeFocusPresentationModel and ZoomOverlayAnalysisCoordinator, with focused raster/canvas views for rendering. The zoom coordinator snapshots selected file, image identity and source and rechecks them after analysis. Follow Viewer Architecture for the current task owners; the small raster view is not an analysis engine.

Focus overlay and Review subject outline

The host calibrates the focus overlay on embedded previews at a fixed scale. A Review subject outline comes from a retained segmentation mask. Focus check or Full must first produce a usable subject for that photo. The viewer checks the file fingerprint before drawing the retained mask. Review presets and subject masks

12 - Burst Groups

Burst Groups

Burst analysis turns a flat catalog into groups of adjacent, visually similar frames. It ranks each multi-frame group, presents review queues, and supports culling decisions such as keeping the best frame, keeping the top two, deferring a group, or setting a manual pick.

The implementation separates application commands in BurstWorkflowController, worker orchestration in BurstAnalysisCoordinator, backend-selectable similarity indexing behind RawCullSimilarityFeature, pure grouping and ranking engines, two levels of artifact persistence, and the review UI. Vision feature prints are the safe default. A validated CLIP model can become the active burst-similarity backend when the user enables it; the rest of the burst pipeline works with typed SimilarityArtifact values rather than assuming one representation.

Source Map

AreaMain files
Application commands and result publicationRawCull/Model/ViewModels/BurstWorkflowController+Grouping.swift
Worker orchestration and cache compatibilityRawCull/Intelligence/BurstAnalysis/BurstAnalysisCoordinator.swift and coordinator extensions
Similarity feature and shared stateRawCull/Intelligence/Similarity/RawCullSimilarityFeature.swift, SimilarityScoringModel.swift
Backend composition and adaptersRawCull/Intelligence/Composition/RawCullAIModelRuntime.swift, RawCull/Intelligence/Similarity/RawCullVisionSimilarityService.swift
Per-file durable artifactsRawCull/Intelligence/Persistence/PerFileAnalysisArtifactStore.swift
Pure grouping and rankingRawCullCore Sources/RawCullCore/BurstGroupingEngine.swift, BurstRankingEngine.swift
Shared modelsRawCullCore Sources/RawCullCore/BurstAnalysisModels.swift; app BurstAnalysisModels.swift, BurstReviewQueueModels.swift
Cache and repository boundaryRawCull/Intelligence/Persistence/BurstAnalysisCache.swift, RawCull/Intelligence/BurstAnalysis/BurstAnalysisCacheRepository.swift
Ratings and manual overridesCullingModel.swift, SavedFiles.swift
Burst home and review listBurstGroupsHomeView.swift, SimilarityGridSelectionView.swift, CullingGridView.swift
Single-burst workspace and comparisonBurstCullingWorkspaceView.swift, ComparisonGridView.swift
Batch badge selection and ratingCullingGridSelectionCoordinator.swift, CullingGridView.swift
Review subject outlinesReviewSubjectMasks · SubjectMaskOutlineRenderer
TestsRawCullCore/Tests/RawCullCoreTests/BurstGroupingEngineTests.swift, BurstRankingEngineTests.swift, app burst/culling tests

End-to-End Flow

flowchart TD
    A["Analyze Bursts"] --> B["BurstWorkflowController builds immutable request"]
    B --> C["BurstAnalysisCoordinator owns generation and task"]
    C --> H0["Hydrate valid per-file similarity artifacts"]
    H0 --> D{"Valid BurstAnalysisCache and matching artifact digest?"}
    D -->|"yes"| E["Remap cached IDs and apply snapshot"]
    D -->|"no"| F{"Sharpness scores missing?"}
    F -->|"yes"| G["Calibrate and score target files"]
    F -->|"no"| H["Reuse scores"]
    G --> I{"Similarity artifacts missing?"}
    H --> I
    I -->|"yes"| J["Index with active Vision or CLIP service"]
    I -->|"no"| K["Reuse descriptor-valid artifacts"]
    J --> L["Commit per-file artifacts"]
    K --> M["Group adjacent frames"]
    L --> M
    M --> N["Rank multi-frame groups"]
    N --> O["Apply manual winner overrides"]
    O --> P["Save derived snapshot and review states"]
    P --> Q["Show dashboard, queues, and workspace"]

The coordinator owns the worker generation, task, progress, cache preparation, missing sharpness/similarity work, grouping, ranking, and the primary cache save. It receives callbacks for the application-owned catalog validity check and final result publication. Every awaited phase is therefore protected by both the coordinator generation and selected catalog; a cancelled or superseded run cannot publish late results into a newer catalog.

The target is normally every catalog file sorted by localized filename, which acts as shot order. If files are selected, visible selected files are followed by hidden selected files. If no selection exists and a star filter is active, only files with that rating are analyzed.

Similarity Artifacts And Backend Selection

SimilarityScoringModel depends on the RawCullSimilarityServicing protocol. The active service supplies a backend descriptor, the descriptors it can produce, an indexing operation, and a distance operation. This keeps grouping independent of whether the payload is a Vision feature print or a CLIP image embedding.

RawCullAIModelRuntime owns provider selection and model resources; RawCullIntelligenceRuntime owns stable feature surfaces:

  • RawCullVisionSimilarityService is always available and is the startup/default service.
  • RawCullCLIPSimilarityService is selected only when CLIP is enabled and the chosen model bundle has validated and produced a provider.
  • A selected CLIP pass uses fallbackPolicy: .none. Failed files are retried once with the loaded provider, then once with a newly constructed provider. Successful CLIP artifacts survive; remaining failures are recorded and excluded from grouping. Vision is the startup/service-selection fallback, not an automatic whole-batch replacement for a partially failed CLIP pass. The concrete CLIP service lives in RawCullVisionSimilarityService.swift.
SettingCurrent value
Input thumbnail maximum512 px
Similarity pipeline version3
Artifact schemaSimilarityArtifactDescriptor.currentSchemaVersion
Default backendVision feature print
Optional backendsValidated OpenAI or DataComp CLIP provider

Each SimilarityArtifact contains a descriptor and encoded payload. The descriptor records backend identity, model fingerprint, representation, preprocessing, normalization, configuration, and schema version. RawCullSimilarityArtifactValidation compares that descriptor and the source fingerprint before an artifact is admitted.

PerFileAnalysisArtifactStore persists individually valid artifacts independently of the catalog-wide burst snapshot. On a later run, hydrateArtifacts(_:) loads only artifacts allowed by the current service and pipeline signature. This makes a partial index reusable and lets invalid entries be removed without discarding every other file.

The same model can rank a catalog by distance from an anchor image. Burst grouping calculates distances only between adjacent files. Those distances are cached in memory under the current artifact/backend signature and reused when regrouping remains compatible.

Grouping Rules

BurstGroupingEngine.group(...) makes one sequential pass. It starts a new group when any boundary rule fires.

Boundary reasonTrigger
Visual distance changedAdjacent active-backend distance is at or above visualDistanceThreshold
Similarity evidence missingNo adjacent distance is available
Capture gapAbsolute capture-date gap exceeds maxTimeGapSeconds; modification-date fallback uses maxFallbackTimeGapSeconds
Camera changedNormalized camera value changed and requireSameCamera is enabled
Focal length changedParsed focal-length delta exceeds maxFocalLengthDeltaMM
Exposure changedShutter, aperture or ISO delta exceeds 0.5 EV, or exposure compensation exceeds 0.34 EV; unparseable values use conservative text fallback

Lens changes are recorded as evidence but do not independently split a group. They do make group metadata unstable during ranking.

Default configuration:

visualDistanceThreshold = 0.25
maxTimeGapSeconds = 2.0
maxFallbackTimeGapSeconds = 10.0
requireSameCamera = true
requireSimilarFocalLength = true
maxFocalLengthDeltaMM = 3.0
algorithmVersion = 4

The burst sensitivity control changes only the visual threshold. reGroupBursts() cancels older grouping work, reuses similarity artifacts and adjacent-distance data, rebuilds rankings, and saves a new cache. The current home/category presentation is preserved instead of being forced into the grouped grid.

Ranking Formula

BurstRankingEngine computes:

overall =
    rankingSharpness * 0.62
  + focusPoint      * 0.12
  + saliency        * 0.10
  + metadata        * 0.16

Sharpness is normalized by SharpnessScoringModel.maxScore. When at least two group members have scores and their normalized spread is at least 0.03, global and burst-relative sharpness are blended:

rankingSharpness = normalizedSharpness * 0.65
                 + burstRelativeSharpness * 0.35

The other components are heuristic evidence:

  • Focus is 0.70 when camera AF data exists and 0.45 otherwise.
  • Saliency is 0.75 when the subject label matches the group’s dominant label, 0.25 on a mismatch, and 0.45–0.60 when evidence is incomplete.
  • Metadata starts at 0.70 for stable groups or 0.40 otherwise and gains 0.15 for tight similarity. Above ISO 1600 it loses 0.05 per stop, capped at 0.15, and gains 0.05 at f/5.6 or wider. Lower motion risk adds 0.05; elevated motion risk subtracts a stop-based penalty capped at 0.15. The final component is clamped to 0…1. High ISO (3200+) is also a candidate caution.

Ties in overall score retain original shot order.

Confidence And One-Click Safety

ConfidenceConditions
HighScores exist, group has at least 3 files, best leads second by at least 0.12, best normalized sharpness is at least 0.65, metadata is stable, all members have parsed capture times, and all internal visual distances are below 0.22
MediumBest leads by at least 0.05 and metadata is stable
LowScores are absent, candidates are close, or evidence is unstable

isSafeForOneClickCulling is true only for high-confidence results. keepBestInGroup and keepTopTwoInGroup also require the current sharpness score table to be non-empty; otherwise they return without changing ratings.

Home Dashboard And Review Queues

After analysis, BurstGroupsHomeView composes BurstGroupsHomeHeader, BurstNextUpCard, BurstQueueActionCard, BurstRecentGroupsCard and BurstGroupsSidebar to build the dashboard. They present coverage, group counts, threshold, suggested picks and these queue categories:

CategorySelection rule
AllEvery computed group, including singleton groups
Single ImagesGroups containing exactly one file
Needs ReviewMulti-frame groups with explicit review-needed state or unsafe/uncertain ranking evidence
DeferredMulti-frame groups explicitly deferred
Marked ReviewedMulti-frame groups explicitly marked .reviewed
ReviewedEffective reviewed results, decisions already applied, and manual-winner groups

The grouped culling grid can collapse a burst to its top three ranked frames. A group header opens the dedicated workspace and toggles Reviewed or Deferred state.

The grid can also derive batch selectors from visible burst-rank, saliency, and sharpness badges. A normal badge action replaces the selection with every visible match, Command toggles the matching set, and Shift extends/replaces according to the coordinator’s modifier policy. Batch rating applies one rating to the resulting selected files. The coordinator is a pure value transformation so these semantics are testable without SwiftUI.

BurstCullingWorkspaceView displays one large selected frame plus a bounded three-frame image window around the current selection and a filmstrip of ranked candidates. It reuses ComparisonImagePaneView, ComparisonViewportInteractionState, ImageSourceSelectionState, and ZoomMetadataPanel rather than creating a second image-inspection implementation. The cache key combines file identity and selected image source.

P/N and the arrow keys move between frames, G advances to the next eligible multi-frame group, and E toggles the metadata panel. The workspace also exposes zoom, thumbnail/embedded-JPEG source selection, focus evidence, rating, pick/reject, reviewed state, and the detailed comparison grid. Escape returns to the active burst list.

Focus check and Full can produce a subject outline. Press S on a reviewed frame to show it. RawCull looks up a retained mask in the displayed Review results by standardized file URL and checks the fingerprint before loading it. Review presets and subject masks

Assess the ranked pair in each burst

Once the burst lists are ready, open the AI assessment card and choose Assess All Bursts. RawCull needs an open catalog, at least 16 GB of unified memory, an available Qwen model, and a free AI lease. The button stays disabled during catalog preparation or competing AI work.

The plan snapshots the active catalog and burst-analysis generation. It skips Single Images, groups without matching analysis membership and groups with missing files. For each eligible group, it takes the recommendation and distinct alternate when available. The worker reads previews up to 2048 pixels and asks Qwen about composition, exposure and subject visibility. It counts unreadable photos and failed assessments separately from successful findings. A model change stops the run.

Cancel stops further work. Between bursts the worker checks that the catalog and analysis generation still match. A completed burst with at least one successful assessment gets an entry in AI Assessments. Choose View Results to inspect the pair. These entries last for the app session and starting another batch clears the previous session entries. The burst ranking and ratings change only through explicit culling actions. MCP follow-ups have a separate shared store and retention policy. BurstBatchAssessment · BurstGroupsHomeView · BurstBatchAssessmentTests

Review States

RawCullCore.BurstReviewState currently defines:

  • .none
  • .needsReview
  • .reviewed
  • .deferred
  • .algorithmReviewed
  • .manualWinnerOverride
  • .decisionApplied

The app and package enum are now aligned. algorithmReviewed remains for cache compatibility.

BurstReviewQueuePolicy.effectiveState(for:) preserves explicit modern states. For .none or legacy .algorithmReviewed, it derives Needs Review when confidence is not high, cautions exist, no recommendation exists, or one-click culling is unsafe; otherwise it treats the group as reviewed.

Toggling Reviewed or Deferred a second time resets the result to .none and removes that group from the explicit state dictionary. Review states are persisted using a catalog-and-membership BurstGroupSignature, so they can be restored after a threshold change even if numeric group IDs change.

Manual Winner Overrides

A manual winner is stored in savedfiles.json as BurstWinnerOverride:

FieldMeaning
winnerFileNameUser-selected winner
memberFileNamesGroup membership snapshot

Overrides use filenames because saved-file persistence is filename-based. CullingModel canonicalizes member names so lookup is order-independent and prunes overrides whose files no longer exist. Applying an override promotes the selected file, recalculates second place, and sets .manualWinnerOverride.

User Actions

ActionMethodEffect
Keep bestkeepBestInGroupOn a safe result, rate the winner 3 stars and reject the rest
Keep top twokeepTopTwoInGroupOn a safe result, rate first place 3 stars, second place 2 stars, and reject the rest
Set manual picksetManualBurstWinnerPersist the winner override and rate the selected frame 3 stars
Open groupcompareBurstGroupOpen the workspace with up to four ranked comparison IDs
Next groupadvanceToNextBurstGroupOpen the next eligible multi-frame group in the active queue
Toggle reviewed/deferredtoggleBurstGroupReviewed, toggleBurstGroupDeferredPersist or clear the explicit review state
Undo last burst actionundoLastBurstActionRestore the previous ratings captured for the last one-click action
ReindexreindexBurstAnalysisClear loaded analysis, delete the catalog cache, and recompute

One-click rating actions capture a BurstUndoEntry before writing ratings. Only the most recent burst action is retained for undo.

Cache Validity

BurstAnalysisCache stores similarity artifacts, scores, saliency, groups, boundary evidence, ranked results, and review-state snapshots. It is a derived catalog snapshot; PerFileAnalysisArtifactStore is the reusable per-image artifact layer. The current burst-cache schema is 9. A snapshot is accepted only when all of these still match:

  • cache schema version,
  • grouping algorithm version,
  • catalog path,
  • effective sharpness thumbnail size and complete sharpness signature,
  • grouping configuration and active backend descriptor,
  • all allowed artifact backend descriptors, artifact schema, input size, and pipeline version,
  • file count,
  • every file path, size, and modification date,
  • a digest of the current descriptor-and-payload artifact set.

On load, every embedded artifact is revalidated against its source and allowed backend descriptors. Cached UUIDs are then remapped to the current scan’s UUIDs by file path because FileItem.id values are recreated. Cache saves are guarded by the completed analysis context, generation, catalog, artifact digest, and similarity signature so stale asynchronous work cannot overwrite a newer result. Schema 8 can be read only as a migration candidate; individually valid artifacts and stable review-state signatures may be imported, but the old snapshot is not treated as a current cache hit.

What To Check When Changing This Area

  • Bump BurstGroupingConfig.algorithmVersion when grouping semantics change.
  • Update the similarity pipeline version or descriptor/signature when artifact inputs or meaning change.
  • Preserve descriptor validation and the separation between per-file artifacts and the derived burst snapshot.
  • Test both the always-available Vision path and validated CLIP selection/fallback behavior.
  • Update the sharpness scoring signature when score meaning changes.
  • Keep review-state decoding backward compatible and preserve signature-based restoration across regrouping.
  • Keep manual winner overrides durable across cache invalidation and UUID remapping.
  • Treat high confidence plus available sharpness scores as the one-click culling gate.
  • Keep the workspace’s bounded image window and source-aware cache identity when changing image navigation.

Grid projection and keyboard ownership

CullingGridProjection.swift memoizes visible files, burst ordering, selection IDs and badge data. Its key combines content/similarity/saliency mutation revisions, source URL, rating and review filters, grouped mode and score availability. Cache hits avoid rebuilding membership sets during view updates. The cache itself is observation-ignored; mutation sites must advance the corresponding revision. RawCullTests/CullingGridProjectionTests.swift checks reuse and invalidation.

ReviewKeyboardScope restricts local event monitors to the anchored key window, with no sheet/modal and no focused native text/control. Command, Control and Option combinations are left to their owners. In grouped grid mode, ThumbnailKeyboardRouting consumes Return, Escape, B, 2 and U as burst commands before ordinary rating dispatch, including reserved commands that cannot act. This prevents an unavailable burst command from becoming a rating edit. See RawCullTests/ReviewKeyboardScopeTests.swift and RawCullTests/ThumbnailKeyboardRoutingTests.swift.

Single Images is a synthetic review workspace

Singletons remain real one-file groups in the analysis result. In the Single Images grid projection, CullingGridProjection.swift flattens visible singleton files into one presentation group with ID −1. compareBurstGroup uses that ID when opening this queue. The workspace obtains singleImageReviewFiles from singleton membership in active catalog order, so it can traverse all single images rather than opening a separate workspace for each. That workspace scope can be broader than the visible rating-filtered grid projection.

ID −1 has no ranking or winner. burstGroupReviewState(groupID:) returns a shared explicit state only when all active singleton groups agree; a mixed set returns .none. Setting Reviewed or Deferred fans out to the constituent singleton groups with per-group persistence suppressed, then saves once. Persistence therefore uses real group signatures; −1 is not a stored domain group and must not become input to the ranking engine.

Read BurstWorkflowController+Grouping.swift, BurstCullingWorkspaceView.swift and CullingGridCoordinatorTests.swift together. The tests cover the combined singleton workspace and review-state behavior.

Workspace components and work ownership

The burst screen now composes BurstWorkspaceHeader, BurstImageStage, BurstWorkspaceFilmstrip and BurstEvidenceShelf. Image-window decoding lives in BurstWorkspaceImageCoordinator, keyboard actions in BurstKeyboardController, and cleanup in BurstWorkspaceSessionModel. Viewer Architecture explains the three-frame cache, source identity, focus invalidation and monitor lifetime. These presentation extractions do not change RawCullCore’s ranking formula.

Review session and membership-based persistence

BurstReviewSessionModel.swift owns results, explicit states, queue filter, comparison group and undo entry. BurstWorkflowController keeps its facade and coordinates ratings, navigation, persistence and admission. Reset clears the same session object rather than replacing it.

Results/states are externally read-only. Commands apply analysis, replace rankings, restore states, set manual winners and synchronize result state after undo. Explicit restored workflow state may differ from a ranking’s embedded state. Manual overrides retain precedence when decisions are applied, without redundant persistence. Rating undo consumes its entry without reverting the established workflow state. contentRevision is in the grid-projection cache key.

BurstReviewStateMapping.swift shares snapshot/restore rules across the coordinator and live review. Membership signatures map decisions onto current group IDs; .none and invalid signatures are omitted. Missing file references are filtered. The persisted schema is unchanged. Read CullingGridCoordinatorTests.swift and BurstAnalysisCoordinatorTests.swift for the contracts.

Missing AF evidence in older burst caches

Opening a workspace requests loadMissingAFPointScores(for:) on the sharpness model. It analyzes only files with valid AF points and missing AF-center scores, retains access, and checks cancellation/scoring identity before publication. It does not start while ordinary scoring is active. Existing blended scores and recommended winners are not replaced. Read SharpnessScoringModel.swift and SharpnessScoringTests.swift.

Manual Close-ups in the current workspace

The Close Up guide walks through frame selection, pinned references, pixel sources and the automatic detection strip.

The Close-ups button opens a right-side manual comparison panel in the same workspace used by bursts and Single Images. Comparison membership is a separate URL set: plain click selects one frame, Command-click toggles, Shift-click selects a displayed-order range, and Command-Shift-click adds a range. Filmstrip clicks also activate the clicked frame; inclusion checkboxes only change membership. With no explicit members, the current frame is inspected.

Each frame has an independent region. A pinned reference survives selection changes, while changing groups creates a new inspection session. Regions persist in source-revision-bound UserDefaults records. Linked pan/zoom works around each frame’s own region and does not track the same subject across photos.

JPG/RAW selection is shared with the main stage; RAW 9 wording requires support across the relevant frames. AF assistance is synchronized with the stage’s AF preference and respects EXIF orientation. A recorded location is not evidence of sharpness. Pinning, region editing and comparison membership do not write a rating, override a winner, rerank a burst or submit Combined Review automatically.

The manual cards receive no ranking-evidence projection. A separate automatic strip shows current-frame face crops and preview detail where available, plus animal head and eye crops when Vision returns usable landmarks. Double-clicking a burst card thumbnail opens the workspace at that frame. Navigation follows the active frame for single-frame inspection and preserves explicit multi-frame membership. See viewer ownership and remaining unified evidence work.

People Ranking in the comparison workspace

Apply People Ranking checks a group of at least two frames using face evidence. Use it with a consistent subject. It changes the comparison order while the candidate order matches the current group and its source frames. Restore Best Frame Order clears that order. Persisted burst recommendations and ratings remain independent. BurstCullingWorkspaceView.swift

13 - Model Context Protocol (MCP)

The RawCull MCP architecture, Swift source map, and a walkthrough from a Codex prompt to ranked burst results.

RawCull’s Model Context Protocol (MCP) integration lets a client such as Codex read an authorized catalog, request burst analysis, and review the resulting recommendations. You can follow up in the same chat to compare a burst’s recommended frame and alternate, or ask for a Qwen assessment of specific photos. RawCull runs the image processing on your Mac. Codex uses the returned data to explain the results.

How the integration is built

ComponentResponsibility
CodexInterprets the prompt, discovers the helper’s tools and their argument schemas, constructs tool calls, waits for work to finish, and explains the returned results.
Bundled Swift helperRuns as the rawcull-mcp executable at RawCull.app/Contents/MacOS/rawcull-mcp. It uses the MCP Swift SDK and exchanges JSON-RPC messages with Codex over standard input and output. It validates tool arguments, reads shared records, submits requests, and returns structured data with a JSON text fallback. Diagnostics go to standard error.
Shared macOS app groupCarries the saved catalog grant and metadata, setup requests and receipts, the current analysis job, and separate follow-up records. Atomic file writes and a cross-process storage lock protect updates. A worker lock coordinates burst and follow-up work and helps recover jobs after a process exits.
RawCull appOwns the folder picker, approval dialogs, security-scoped file access, job execution, and settings. Its MCP controller calls the same full-catalog burst analysis used by the app and publishes progress and rankings to the shared store. Follow-up photo assessment uses the app’s local Qwen runtime and the saved source job.

The callable RawCull API here is the set of MCP tools such as request_catalog_setup and list_bursts. Codex interprets the natural-language request and sends only the selected tool name and arguments. RawCull acts on those arguments through its controller and Swift services. The helper and app communicate through shared storage, and this workflow requires no HTTP endpoint.

The saved grant describes what metadata and analysis the client may access. RawCull keeps the security-scoped folder bookmark in its own preferences and resolves it when opening photos. An absolute path in a tool call is a folder hint. Permission comes from existing authorized access or your approval in the app.

sequenceDiagram
    actor User as Photographer
    participant Client as Codex
    participant Helper as rawcull-mcp
    participant Store as Shared app group
    participant App as RawCull
    User->>Client: Analyze my Saturday Shoot folder
    Client->>Helper: tools/list
    Helper-->>Client: Tool names and argument schemas
    Client->>Helper: request_catalog_setup
    Helper->>Store: Save setup request
    Helper->>App: Open RawCull if needed
    App->>Store: Read setup request
    opt Folder access or approval needed
        App->>User: Choose folder and approve analysis
        User->>App: Approve This Job
    end
    App->>Store: Queue burst job and save job IDs
    Client->>Helper: get_catalog_setup_status
    Helper-->>Client: Catalog ID and job ID
    App->>Store: Publish progress and ranked bursts
    Client->>Helper: get_analysis_status and list_bursts
    Helper->>Store: Read progress or rankings
    Helper-->>Client: Coverage and ranked frames
    Client-->>User: Explain the results

Connect the installed helper

In Codex CLI, register the executable bundled with the app you intend to use. Adjust the path if RawCull is installed elsewhere.

helper=/Applications/RawCull.app/Contents/MacOS/rawcull-mcp
codesign --verify --strict --verbose=2 "$helper"
codex mcp add rawcull -- "$helper"

Start a fresh Codex chat and paste this read-only check.

Use the rawcull MCP server. Check the helper version, bundled app build, transport, and available tools. Tell me whether photo assessments are enabled if the helper reports the setting, and whether a saved catalog grant exists.

This uses rawcull_status and list_catalogs. Check the reported build and expect stdio transport. If you have multiple RawCull registrations, name the one you want Codex to use.

Walkthrough from prompt to ranked bursts

Use a folder that contains a few bursts. Substitute your folder’s exact path and send the prompt in Codex.

Use RawCull MCP to analyze the photos in /Users/you/Pictures/Saturday Shoot for bursts. If RawCull asks for approval, tell me and wait. When it finishes, show the recommended frame and alternate for each burst and flag any low-confidence picks.

The calls and responses below show an illustrative successful run. IDs and counts are examples, and response excerpts omit fields unrelated to the walkthrough.

1. Codex decides what to call

Codex recognizes the folder path, the request for a new burst job, and the desired report. It chooses request_catalog_setup because that tool can handle a folder that has yet to be authorized. The report instructions stay in Codex. There are no setup arguments for “show alternates” or “flag low confidence”. Codex applies those instructions when it formats the rankings.

The client sends an MCP tools/call request like this.

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "request_catalog_setup",
    "arguments": {
      "requestId": "11111111-1111-4111-8111-111111111111",
      "catalogHint": "/Users/you/Pictures/Saturday Shoot",
      "jobType": "burstAnalysis"
    }
  }
}

The JSON-RPC id correlates one protocol request with its reply. The UUID in requestId identifies the setup operation across calls. Reuse that UUID with the same arguments for a retry. Generate a new UUID for a new operation.

2. The helper validates the call and RawCull gets approval

The helper checks the required keys, UUID, job type, and catalog hint. It saves the request and asks macOS to open the bundled app. RawCull examines the hint against the folders it can resolve. An eligible saved grant can queue the work automatically. A known folder that needs permission can go straight to the approval sheet. RawCull asks you to choose a folder when it cannot resolve an accessible match.

For this example, choose Approve This Job. It authorizes work and sharing for the current job. Approve and Remember also saves authorization for later eligible runs and replaces any previous saved grant.

While RawCull waits, Codex calls get_catalog_setup_status with the original setup UUID. An approval can return this structured response.

{
  "requestId": "11111111-1111-4111-8111-111111111111",
  "state": "queued",
  "catalogId": "22222222-2222-4222-8222-222222222222",
  "jobId": "33333333-3333-4333-8333-333333333333"
}

At this point RawCull has already queued the analysis. The client switches from polling the setup UUID to polling the returned catalog and job IDs. It can stop if setup is denied or fails.

3. RawCull runs the existing burst pipeline

MCPAnalysisController claims the queued job, checks authorization and workspace availability, and loads the selected catalog as needed. It calls startBurstAnalysis through MCPAnalysisWorkspace, which delegates to BurstWorkflowController with the full catalog input. The pipeline uses sharpness and the app’s configured similarity backend, Vision or CLIP, to group and rank frames. The catalog setup schema has no backend override.

Codex calls get_analysis_status with the returned IDs as RawCull publishes progress. A terminal reply can look like this.

{
  "catalogId": "22222222-2222-4222-8222-222222222222",
  "jobId": "33333333-3333-4333-8333-333333333333",
  "state": "completed",
  "filesScanned": 8,
  "filesAnalyzed": 8,
  "coverage": {
    "photoCount": 8,
    "burstCount": 2,
    "singletonCount": 2,
    "unevaluatedCount": 0,
    "skippedByReason": {},
    "similarityBackends": {"vision-feature-print": 8}
  }
}

4. Codex fetches the rankings and explains them

Codex calls list_bursts with the same catalog and job IDs. It passes any non-null nextCursor as cursor on the next call. Burst pages default to 10 entries and allow up to 25. Each entry can include saved picks, confidence, reasons, cautions, and evidence for up to five candidate frames. The full burst may contain more frames.

For the example above, Codex might say that RawCull analyzed all eight photos and found two bursts and two singletons. It might report DSC_1203.ARW as the recommendation for the first burst and DSC_1204.ARW as the alternate. If the source labels the burst low confidence, Codex can put that pair first for visual review and cite the recorded reasons. You apply keeper choices and ratings in RawCull.

5. Use the same job for a visual follow-up

When Qwen3-VL-2B is available in Settings → AI, and Enable MCP photo assessments is on in Settings → MCP, continue in the same chat.

Use the completed job to compare the recommendation and alternate in the first low-confidence burst. Check exposure and subject visibility. Tell me which two photos were assessed and what I should look at before choosing a keeper.

With a helper that advertises burst targeting, Codex locates the burst in the existing rankings and calls start_photo_assessment with a fresh request UUID, the original catalog and source job IDs, the selected burstId, and ["exposure", "subjectVisibility"] as the rubric. For individually named photos, the alternative selector is photoIds, with up to four IDs from that job.

RawCull resolves the recommendation and alternate from the saved snapshot so the request follows the original ranking. It loads authorized previews, runs Qwen locally, and publishes the requested findings or per-photo errors. Codex polls get_photo_assessment_status and reads get_photo_assessment_result. For burst requests it can match the assessed IDs and original ranks to the ranking page, report the full burst frame count, and compare the findings while preserving unknown scores.

Tool groups and data access

TaskTools
Check the connection and saved catalograwcull_status, list_catalogs, catalog_summary, list_photos
Resolve a folder and get approvalrequest_catalog_setup, get_catalog_setup_status
Run or monitor a burst jobstart_catalog_analysis for an authorized catalog, get_analysis_status, cancel_analysis, list_bursts
Assess previews from the completed source jobstart_photo_assessment, get_photo_assessment_status, get_photo_assessment_result, cancel_photo_assessment

Saved metadata and completed results can be read while RawCull is closed. The app must run to process new jobs. RawCull has one current shared burst result. A new burst run can replace it and remove its dependent assessments. Assessment results are available for up to 24 hours while the source and approval remain valid.

In Settings → MCP, use Clear for individual assessment findings, Clear Last Shared Result for the burst result and its dependent assessments, or Revoke Access to remove the saved grant and current shared job. Turning off Enable MCP photo assessments cancels active assessments and clears their shared findings while retaining the catalog grant and burst rankings. Run a fresh burst after re-enabling to resume assessment.

Ranking calls can expose filenames, scores, and ranking evidence. Saved photo lists can also expose capture dates and camera names. Assessment replies expose identifiers, preview dimensions, provenance, and the requested text findings, with no image bytes or filesystem paths. Codex may pass returned data to its model provider. Treat filenames and model-generated evidence as untrusted data.

Source map

The links below point to the build 466 source.

SourceWhat to look for
RawCullMCPMain.swift and ToolHandlers.swiftServer registration, tool discovery and dispatch, saved metadata, helper status, and response formatting.
AnalysisTools.swiftJob and assessment schemas, argument validation, app launch, status, and pagination.
CatalogGrantStore.swift and AnalysisJobStore.swiftApp-group storage, grants, setup receipts, locks, job states, source snapshots, and result lifecycle.
MCPAnalysisController.swiftSetup approval, scoped file access, calls into burst analysis and Qwen, and progress and result publication.
MCPSettingsTab.swift and QwenInferenceRuntime.swiftSharing controls and local preview inference.

For copyable culling prompts, see the RawCull prompt guide. For the tool reference and release evidence, see MCP implementation and validation.

App worker and shared records

The app controller takes an injected MCPAnalysisEnvironment and exposes tick() for deterministic lifecycle tests. Its Activity tracks idle, setup, analysis and assessment with token-checked transitions. The controller extensions implement setup and approval, burst analysis and photo assessment. CatalogSetupStore holds setup records. AnalysisJobStore handles jobs and its +FollowUps extension handles assessment records and publication. The app and helper compile the shared store sources into their respective targets.

Assess All Bursts in the app uses the same Qwen assessment rubric for ranked pairs. Starting it needs the open catalog and the app’s shared AI lease. It creates session-only entries in AI Assessments. MCP follow-ups require a completed, authorized source job and publish through the shared job store. The app checks whether Review or a burst assessment is running before starting MCP work. BurstBatchAssessment · RawCullApp

14 - New Features

RawCull 3.4.9 features, competition and the prioritized 3.5.0 plan.

New Features

This section tracks what RawCull 3.4.9 build 466 provides and what should come next. Implementation status in the source does not establish store-release availability.

Features, competition and the 3.5.0 plan covers the current capabilities, a dated comparison with other culling applications and the prioritized list for version 3.5.0, including the scope of XMP exchange and unified burst evidence. Those two scopes replace the earlier separate P0 plan pages.

For implemented behavior, see Close Up, Burst Groups and RawCull MCP.

14.1 - RawCull 3.4.9: Features, Competition and the 3.5.0 Plan

RawCull 3.4.9 features, a cross-platform photo-culling comparison, and a prioritized plan for version 3.5.0.

RawCull 3.4.9: Features, Competition and the 3.5.0 Plan

RawCull’s strongest position is local, evidence-based selection for RAW photographers who want to understand and control the decision. Version 3.4.9 combines fast preview review, camera autofocus evidence, burst ranking, face and animal close-ups, semantic search, a single AI Review with three presets, and an MCP server for desktop AI clients. The next gains should come from getting decisions into an editor and from making the existing evidence easier to act on, not from adding more models.

Baseline and evidence

ItemValue
Application source0513a30e on main, 3.4.9 build 466, checked 23 November 2026
Release statusThe local v3.4.9 tag points to 3c8e7aba. App Store availability was outside this source review.
PlatformApple silicon, macOS 27
Competitor evidenceVendor documentation checked 5 November 2026, not requalified for this revision

Competitor facts describe advertised capabilities, not independently measured accuracy, latency, market share or customer satisfaction. Recommendations are product judgments based on those capabilities and RawCull’s implementation. No hands-on comparative benchmark was performed. Availability can vary by plan, platform and release. Check prices and minimum OS versions before purchase.

What RawCull 3.4.9 provides

AreaImplemented capabilityBoundary that matters
RAW browsingDedicated ARW, NEF and DNG paths, embedded previews, cached thumbnails, viewport-sized and full-resolution developed-RAW displayGeneric formats use macOS decoding; extension recognition is not a tested camera-support guarantee
Broader format admissionCanon CR2/CR3/CRW, Fujifilm RAF, Olympus ORF, Panasonic RW2, Pentax PEF and other registered RAW extensionsCamera, compression and OS support still need qualification; generic admission adds no vendor AF parsing
Focus inspectionSony and Nikon AF points rotated into the upright frame, focus masks, full-frame, salient-subject and AF-region sharpnessA recorded AF location is not proof that the intended subject is sharp; scores depend on the analyzed render
Burst reviewSimilarity grouping, ranked candidates with confidence and cautions, comparison, manual winners, review/defer stateGrouping and ranking assist the photographer; they do not establish a universally best photograph
Close UpManual crop comparison across frames with pinned references, saved regions, linked pan/zoom, JPG or developed-RAW source and Use AF pointLinked pan/zoom copies inspection state; it does not track the same subject across frames
Faces and animalsAutomatic strip with human face crops and a local preview detail value, plus animal head and eye crops from Vision landmarks; People Ranking reorders a group by face evidenceNo eye-open/closed assessment. Apple documents cat and dog support; birds and other wildlife are unvalidated
Similarity and searchOptional DataComp CLIP similarity and natural-language search; Vision similarity fallbackText search requires CLIP; the Vision fallback is not semantic search
Review (single AI entry point)Focus check (SAM 3 masks, subject focus measurement, CLIP; no Qwen), Describe (one Qwen assessment) and Full (all stages, per-object crops, written report) for 1–8 selected or tagged images. Results offer Tag and Rate for eligible catalog files, plus Mark Reviewed for an unambiguous burstBounded shortlist review, not whole-catalog culling. Qwen output is advisory. Describe and Full need 16 GB of unified memory, 32 GB recommended
Burst AI assessmentLocal Qwen assessment of the recommended and alternate frame of every burst, with progress and cancel; results in the AI Assessments windowUp to two distinct ranked frames per eligible burst. Results last for the app session
MCP serverBundled local helper: catalog queries while RawCull is closed, approved catalog setup, burst analysis, ranked recommendations and optional Qwen photo assessments from a desktop AI clientAuthorization can be one-time or remembered. The AI client may send returned results to its own model provider
Decisions and handoffBatch tag/reject/rating, saved decisions, JPEG export and rsync copying of tagged or minimum-rated RAW files with live progressRatings are RawCull JSON, not XMP. Embedded-JPEG export is ARW/NEF/DNG-specific
Exposure inspectionTemporary EV/tone inspection, histogram and clipping overlays in zoomDisplay-referred; not a sensor-domain RAW histogram, persistent edit or export adjustment
Model managementOptional download, validation, licence presentation and resource controls for CLIP, SAM 3 and Qwen3-VL-2BLocal analysis still costs setup time, storage and memory

The macOS 27 and Apple silicon baseline is an adoption constraint compared with most competitors. Communicate it clearly rather than treating every Mac owner as an eligible user.

Detailed behavior: RAW Formats and Exposure Inspection, Close Up, Burst Groups, RawCull MCP and AI Models in RawCull. Source boundaries: model choices, decision persistence, Review and build settings.

What changed between 3.4.0 and 3.4.9

ChangeEffect on the competitive picture
Close Up gained automatic human face crops and animal head/eye crops (3.4.5)Narrows the close-inspection gap to Narrative and Aftershoot. Eye-state assessment is still missing
People Ranking in the comparison workspaceFirst face-informed ordering. It is a session reorder, not a persisted recommendation
MCP server with approval, recovery and shared resultsNo direct competitor documents an equivalent. It is an integration differentiator, not a culling-quality claim
Deep AI Review, Qwen Vision and Objects tabs replaced by one Review with three presetsOne place to ask “what is wrong with this photo?”, with culling controls alongside eligible results
Burst AI assessment of the top two framesA first step toward a whole-shoot first pass
Vision concurrency work, AF orientation fix, resolution/ISO-normalized subject detail, safer burst cachesImproves trust in the numbers; none of it is visible as a new feature
Large view-model refactoring into workspace modelsLowers the cost of the 3.5.0 work; automated workspace tests cover part of the refactor and the release checklist adds manual UI checks

EfficientSAM assets in a linked package do not make a selectable feature: the segmentation enum exposes SAM 3 only. XMP exchange and eye-state assessment remain the two largest functional gaps.

Competitive landscape across operating systems

The comparison covers direct AI cullers, fast manual review tools and editors that can absorb the culling step. Linux alternatives show how much local functionality is available without a commercial cloud workflow. Do not assume that desktop capability exists in a vendor’s mobile app.

ApplicationDesktop platformsMain reason to choose itImplication for RawCull
AftershootmacOS, WindowsAutomated/assisted/manual culling, duplicate groups, blur and closed-eye checks, target yield and editor handoffWorkflow completeness and automation are strong competition; offline culling is already offered [A]
NarrativemacOS, WindowsFace close-ups, focus/eye assessments, scene grouping and sharpness rankingRawCull now has face and animal crops; Narrative still leads on eye assessment and fewer zoom actions [N]
Lightroom ClassicmacOS, WindowsAssisted Culling inside the editor/catalog, with subject/eye criteria and face scoresRawCull must save enough time or give enough evidence to justify another app, and must hand decisions back [L]
Capture OnemacOS, WindowsIntegrated Cull view plus Assisted Review for technical portrait issuesCompare against its assisted workflow, not an obsolete manual-only baseline [C]
ImagenmacOS, WindowsBest-of-group or requested-count culling connected to editingLocal analysis is a real alternative to its upload-based workflow; its editing integration remains a strength [I]
FilterPixel DeepCullmacOS, WindowsGenre-based criteria, explanations, burst grouping and target countsExplanations and wildlife/sports criteria alone are not unique; DeepCull documents cloud AI scoring [F]
Photo MechanicmacOS, WindowsFast manual review, multi-card ingest, renaming and metadata workflowsResponsiveness and dependable ingest can matter more than another AI score [P]
FastRawViewermacOS, WindowsRAW rendering, RAW histogram/statistics, exposure and focus inspectionTechnical RAW evaluation is established; keep RawCull’s render semantics explicit [R]
Excire Foto 2027macOS, WindowsLocal search, people/content organization, grouping and quality-assisted selectionLocal semantic search and privacy are shared strengths, not exclusive advantages [E]
digiKammacOS, Windows, LinuxOpen-source DAM, optional local AI, face recognition, duplicates and quality labelsFree local AI is a credible alternative; a focused, efficient review must earn adoption [D]
darktablemacOS, Windows, LinuxOpen-source RAW editor with side-by-side culling and synchronized inspectionManual culling plus editing is available without buying a specialist culler [T]

Where RawCull 3.4.9 stands

A condensed view of the capabilities that decide adoption. “Common” means several of the products above document it.

CapabilityRawCull 3.4.9CompetitorsAssessment
Decisions reach the editor (XMP or catalog)NoCommonLargest gap
Closed-eye / eye-sharpness assessmentNo (face crops only)Aftershoot, Narrative, Lightroom, Capture OneGap for portrait and event work
Burst grouping and best-frame rankingYes, with confidence and cautionsCommonParity
Camera AF point shown with sharpness evidenceYes (Sony, Nikon)Rare among cullers; FastRawViewer for inspectionDifferentiator
Subject-mask focus measurementYes (Focus check)Subject sharpness criteria in Lightroom, NarrativeParity on intent, stronger on inspectability
Explained, inspectable AI findingsYes (Review drill-down with regions and provenance)Explanations in FilterPixel, reasons in LightroomDifferentiator in depth, not in kind
Local, offline analysisYesAftershoot, Excire, digiKam; not Imagen or DeepCull scoringShared strength
Natural-language searchYes (CLIP)Excire, digiKamShared strength
AI-agent access (MCP)YesNone documentedUnique, niche audience
Whole-shoot first pass / target yieldPartial (burst AI assessment of two frames)Aftershoot, Imagen, FilterPixelGap
Ingest, renaming, metadata templatesNo (rsync copy only)Photo MechanicGap, lower priority
Windows / LinuxNoMostStructural; XMP helps mixed-OS users sooner

Direct AI culling competitors

Aftershoot offers automatic, assisted and manual modes. Its documentation describes blur and closed-eye checks, duplicate grouping, key faces, configurable ratings and Cull to Target. RawCull’s opportunity is a more inspectable technical comparison for difficult bursts, not another automatic score. Its larger gap is the complete journey from first pass to editor. Aftershoot guide, offline/platform FAQ [A].

Narrative reduces close inspection effort with face crops, eye and focus assessments and scene-based ranking. It also documents non-face close-ups and wildlife sharpness ranking, so non-portrait subjects are contested too. RawCull’s 3.4.5 face and animal tiles follow the same design lesson: fewer manual zoom and pan actions. Windows is documented alongside macOS. Narrative Select, platform support [N].

Imagen selects the best photographs in a group or a requested number, lets the user review the choices and continues into editing. Its FAQ describes uploading low-resolution files for culling and editing. RawCull can appeal to users with unreliable connectivity or who keep analysis on their own machine. That does not establish better selection quality. Culling workflow, upload behavior, desktop requirements [I].

FilterPixel DeepCull advertises genre-dependent criteria, explanations, best-of-burst selection and target counts. Its specification says cloud AI scoring while original RAWs stay local, so keeping RAWs on disk does not mean offline analysis. RawCull’s possible advantage is local, inspectable region evidence. The page gives inconsistent genre counts, so this review does not treat an exact count as a qualified capability. DeepCull specifications [F].

Editors that reduce the need for a separate culler

Lightroom Classic documents subject sharpness, eye sharpness and eye-open criteria, per-face scores, reviewable selection reasons and batch actions. Its customers already have an AI first pass in their catalog. RawCull needs a demonstrable benefit on difficult shortlists and a reliable return path for decisions. Adobe Assisted Culling [L].

Capture One offers grouped review and introduced Assisted Review for closed eyes, missed focus and exposure problems in May 2026. On 5 November the vendor release page still labelled it Beta. This makes studio and portrait displacement a hard initial target; RawCull can instead complement the editor for difficult technical comparisons. Cull workflow, Assisted Review introduction, current release overview [C].

Manual review, RAW inspection and local library tools

Photo Mechanic is the benchmark for working while ingest continues, multi-card copying, metadata templates, renaming and fast preview review. Measure RawCull’s basic browsing and handoff against it before adding analysis to every image. FastRawViewer emphasizes RAW-based exposure statistics, focus inspection and converter handoff. RawCull must keep its temporary rendered exposure view distinct from those RAW-data measurements. Photo Mechanic tour, platform requirements [P]; FastRawViewer features and platforms [R].

Excire Foto 2027 combines local semantic search, people and content organization, scene grouping and image-quality selection. That overlaps directly with RawCull’s CLIP search and local AI pitch. RawCull’s better opportunity is focused selection with camera and region evidence, not a general photo library. Excire Foto, platforms and current products [E].

digiKam documents optional on-device models, face recognition, similarity search and quality-based pick labels. Face recognition identifies people; it is not blink or eye-sharpness assessment. darktable offers side-by-side culling with zoom and pan, integrated with RAW editing. Both are real choices on Linux, Mac and Windows, but neither documents the automatic best-of-burst workflow of the specialist products. digiKam features, platform documentation [D]; darktable culling, downloads/platforms [T].

Where RawCull can gain momentum

1. Get decisions into the editor

XMP interoperability is still the largest adoption blocker, and nothing changed here between 3.4.0 and 3.4.9. Copying selected RAWs is useful, but decisions must survive in Lightroom Classic, Capture One and other editors without being rebuilt by hand. Every other improvement is worth less while the photographer has to redo the cull in the editor.

2. Explain difficult wildlife and sports burst decisions

RawCull has camera AF evidence, subject masks, normalized detail scoring, Close Up, manual winners and Review. The missing piece is bringing them together on the frames being compared: which subject was measured, on which render, where the AF point falls and why the result is uncertain.

A bird burst where the background is sharp but the bird is soft is the test case. Show comparable subject crops, mask coverage and detail values, and distinguish a missing eye assessment from an actual eye result. Keep the photographer’s preferred gesture even when another frame scores higher. Narrative ranks wildlife sharpness and FilterPixel markets wildlife and sports criteria, so the claim to make is a faster, verifiable decision on difficult bursts, backed by photographer trials.

3. Make the first pass simple; keep deep analysis for shortlists

Use the existing burst ranking and burst AI assessment to fill conservative Keep, Review and Likely Reject queues with explicit reasons and easy overrides. Keep uncertain cases visible. Review’s 1–8-image limit should stay an escalation path; running a VLM on every photograph needs its own throughput and quality justification. Target yield can follow once the queues are trusted, and must not silently drop unique moments.

4. Add eye-state assessment for portraits and groups

Face crops exist; eye state does not. Narrative, Aftershoot, Adobe and Capture One make closed-eye detection a baseline requirement for weddings and events. Add a calibrated open/closed/unknown result per face, handle glasses, small faces, profiles, occlusion and low light, and show each face in a group rather than one average. Qwen observations are not a blink detector.

5. Earn trust through supported cameras and predictable performance

Publish a tested camera and format table that separates browsing, embedded preview, RAW development, AF metadata and JPEG extraction. A long extension list is less useful than knowing a specific camera workflow works. Keep browsing responsive while models load or run, and show model size, setup progress, cancellation and recovery. A Windows or Linux port would be far larger than any item here because the app depends on Apple frameworks; XMP serves mixed-OS workflows much sooner.

Prioritized plan for RawCull 3.5.0

These are recommendations, not release commitments. Order reflects adoption value first, then the risk carried over from the 3.4.9 refactoring. Effort is relative and includes qualification, not only implementation.

RankWorkWhy nowEffortDone when
1XMP sidecar export and import of decisionsLargest adoption gap; unchanged since 3.4.0LargeLightroom Classic and Capture One round-trip; no loss of unrelated XMP; conflicts and failed writes visible per file
2Qualify the 3.4.9 consolidation: CI, lint baseline, Vision hang regression test, Review preset comparisonThe Vision gate has measured catalog results. CI and a photographic comparison of the new Review presets with the retired tabs are separate qualification workMediumCI runs lint and smoke tests on pull requests; Focus check/Describe/Full compared with the old tabs on 20 real photos and every difference decided
3Evidence on Close Up cards and an explained burst recommendationTurns existing measurements into the burst-decision differentiatorMediumEach card shows AF and detail values with source, region and availability; incompatible values are withheld with a reason; the recommended frame explains itself
4Eye open/closed/unknown per detected faceCloses the main portrait gap on top of the existing face strip and People RankingMedium–largePer-face results across glasses, profiles, small faces and low light, with a measured false-closed rate
5Camera qualification table and performance baselineMakes product claims dependable before wider promotionOngoing, start smallPublished per-camera matrix; cold/warm latency and peak memory for 500, 2,000 and 10,000 images
6Conservative Keep / Review / Likely Reject queuesMakes analysis usable at shoot scale; builds on burst AI assessmentMedium–largeLower total review time; every Likely Reject audited in a labelled sample; manual decisions never overwritten
7Wildlife animal-eye validation (birds, deer) and subject proposals in Close UpCurrent animal support is documented for cats and dogs onlyMediumMeasured detection rate on real bird and wildlife bursts; manual fallback stays authoritative
8Review presets over MCP; shared MCP IPC moduleExtends the unique integration once the in-app presets are qualifiedSmall–mediumMCP clients can request Focus check; one shared module replaces duplicated helper sources

Recommended 3.5.0 scope: items 1–3, with 4 if time allows. Items 5–8 can run alongside or move to 3.5.x.

Scope for item 1: XMP exchange

The detailed P0 pages were retired; this is the scope to carry forward.

In 3.5.0Deferred
Export chosen ratings and reject state to XMP sidecars beside the originals, with a preview of every file and valueWriting metadata into RAW files
Read existing sidecars on catalog open or on request, with an import previewBackground two-way sync and folder watching
Preserve unrelated XMP, including editor adjustmentsRAW development settings exchange
Detect changes since the last exchange and show conflicts; never resolve by newest timestampUniversal pick flags or colour labels
Copy RAW plus sidecar together in the rsync handoffBurst winners, AI findings and caches in XMP
Qualified Lightroom Classic and Capture One proceduresEditing editor databases directly

No AI recommendation becomes a rating because export was opened. A failed write stays retryable and is never reported as handed off. A written sidecar does not mean an open editor catalog has re-read it; document each editor’s read step.

Scope for item 3: unified burst evidence

  1. Project existing AF and detail measurements onto the selected Close Up frames with region, render and algorithm revision, and show missing, loading, failed and stale states.
  2. Define when two values are comparable (metric version, preprocessing, source class, region). Withhold incomparable values from ranking and say why.
  3. Offer a subject-derived region from existing segmentation that the photographer can confirm or correct. A correction invalidates dependent evidence.
  4. Only then send a Close Up shortlist to Review with frozen inputs, and mark the report stale when those inputs change.

Not in 3.5.0

Full RAW editing, retouching, cloud delivery, a model marketplace and new or alternative segmentation models. A new model is worth adding only for a measured gain in quality, latency or memory over the current SAM 3 and non-model baselines. Ingest backups, renaming and metadata templates remain a later professional-workflow item.

How to test the opportunity

Use the same labelled shoots in RawCull and selected competitors: birds and wildlife, sports, portraits and groups, landscapes and low light. Test supported camera and compression combinations, embedded versus developed renders, difficult subjects and intentional creative blur. Let photographers record acceptable alternatives rather than forcing one winner.

Measure end-to-end time from opening a shoot to accepted editor handoff, including setup, uploads where applicable, review and corrections. Report first-use model preparation separately from warm use. Run 500-, 2,000- and 10,000-image catalogs and record hardware, storage, app versions, settings, failures, peak memory and tail latency.

For selection quality, measure missed keepers, preferred-frame agreement, manual overrides and time spent inspecting faces or subject crops. Audit every Likely Reject in the labelled sample. For Review, separate valid structured output from visually correct observations and useful comparisons. For handoff, check ratings and unrelated metadata after a round trip through each target editor.

The commercial hypothesis is that photographers will adopt RawCull when it reduces difficult review time while preserving control and dependable editor handoff. Local processing supports that promise; it does not replace measured workflow value.

15 - Artificial Intelligence

Review, burst assessments, semantic search and the boundaries between RawCull and its model providers.

Artificial intelligence in RawCull

Use Review to inspect selected or tagged photos. Use the burst list to assess ranked pairs across a catalog. Both workflows run inference locally. Each exposes different evidence and stores its results for a different lifetime.

TaskInput and resultGuide
Inspect focus, describe a photo or run all Review stagesOne to eight selected or tagged images. Review saves a run record and can retain the exact inputs behind a finding.Review presets and findings
Compare a burst’s top candidates across the catalogThe recommended and distinct alternate from each eligible ranked group. AI Assessments displays session results.Burst groups
Request an assessment from a desktop AI clientAn authorized MCP source job. The consumer reads structured findings under the shared job’s consent and retention rules.RawCull MCP
Find similar frames or search by descriptionVision or CLIP image artifacts support visual similarity. Text queries require compatible CLIP embeddings.CLIP indexing and search

Model and application boundaries

SAM 3 produces candidate masks for prompted subjects. Review uses registered masks for subject-detail measurements. DataComp CLIP encodes images and text for comparison. Qwen3-VL supplies whole-photo descriptions, crop observations and report text where the preset calls for them. Qwen also supplies the structured findings for burst and MCP assessments. A stored model finding is advisory. Tagging, rating and marking a burst reviewed require an explicit action.

PhotoAIKit owns provider contracts, model validation, inference backends and reusable indexing workflows. RawCull owns the catalog, file access, model activation, run budgets, evidence presentation and culling decisions. PhotoAnalysisKit owns sharpness and Vision measurement facilities. Its Vision queue is also used by the app’s PhotoAIKit feature-print backend.

The earlier AI Analysis tabs appeared in development builds. Their source-level replacement and rationale are recorded in the AI feature decision.

15.1 - RawCull AI models

Download and prepare the three AI model packs

Recipe scope (16 October 2026): Preserve the dated source/exporter pins below when reproducing the original packs. The current RawCull lockfile uses PhotoAIKit 3.1.0 (26647c62d9933968d92bd00b162290cdd7c78fee) and coreai-models 1.0.0 (5de95c6cd29e5e390fb36d87e13b2396668f7974). An older recipe pin is not the current app dependency. Compare exporter options and model provenance before building new candidates. This documentation review did not run model conversion, download packs or qualify their output.

This is a terminal workbook for rebuilding RawCull’s DataComp CLIP, Meta SAM 3, and Qwen3-VL-2B-Instruct model packs from source and finishing with three Apple Managed Background Assets .aar files. It was assembled on September 26, 2026 from the local PhotoAIKit exporters, the RawCull release runbook, and the existing layout in /Users/thomas/ModelAssets/Release.

Run each numbered block in zsh and inspect the indicated output before the next block. The workbook builds in a fresh directory below /Users/thomas/ModelAssets; it does not overwrite the three existing Release/Output/*.aar files. Conversion is CPU and memory intensive and the source downloads are several gigabytes. Keep ample free space for source weights, intermediate models, three converted bundles, and three archives.

These commands produce local release candidates, not App Store approval. After packaging, compare the new hashes with the application catalog and follow the publishing runbook to update RawCull, upload the packs, and test a signed TestFlight build. A fresh conversion may produce different archive bytes even when the same source model was used.

0. What will be produced

ModelPermanent pack IDSelected installed model pathOutput archive
DataComp CLIPrawcull-clip-datacompModels/CLIP-DataCompclip-datacomp.aar
Meta SAM 3rawcull-sam3Models/SAM3sam3.aar
Qwen3-VL-2B-Instructrawcull-qwen3-vl-2bModels/Qwen/qwen3_vl_2bqwen3-vl-2b.aar

The starting evidence is the RawCull repository at /Users/thomas/GitHub/RawCull/RawCull, its sibling /Users/thomas/GitHub/RawCull/PhotoAIKit, and the notices in RawCull/ModelAssets/Notices. The old archive sizes and SHA-256 values in the application catalog describe the September 17, 2026 artifacts, not expected values for this rebuild. OpenAI CLIP and EfficientSAM are outside this three-pack release.

1. Check the Mac and select tools

Install Xcode 27 with the Core AI and Background Assets tools and select it in Xcode Settings or with xcode-select. Install git and uv if needed. The commands below merely check the selected tools:

set -e
set -o pipefail
RAWCULL_REPO='/Users/thomas/GitHub/RawCull/RawCull'
PHOTOAIKIT_REPO='/Users/thomas/GitHub/RawCull/PhotoAIKit'
MODEL_ASSETS='/Users/thomas/ModelAssets'

test -d "$RAWCULL_REPO/.git"
test -d "$PHOTOAIKIT_REPO/.git"
test -d "$MODEL_ASSETS"
command -v uv
command -v git
command -v python3
xcode-select -p
xcodebuild -version
xcrun ba-package --version

If uv is missing and Homebrew is available, install it with brew install uv, then rerun the checks. Record the exact tool versions with the eventual archive hashes. At the time this workbook was written the local Mac selected Xcode 27.0 (27A266a) and ba-package 2.0; a later toolchain can produce different output. The PhotoAIKit exporter scripts declare their Python dependencies in their own # /// script blocks, so uv run creates the appropriate isolated environments automatically. Do not combine the CLIP and SAM dependency sets by hand: their transformers requirements differ.

2. Start a clean build directory

Paste this block into the same Terminal window that will run later blocks. If you open a new window, rerun the variable definitions in this block and set BUILD_ROOT to the directory printed by echo.

set -e
set -o pipefail
RAWCULL_REPO='/Users/thomas/GitHub/RawCull/RawCull'
PHOTOAIKIT_REPO='/Users/thomas/GitHub/RawCull/PhotoAIKit'
MODEL_ASSETS='/Users/thomas/ModelAssets'
BUILD_ROOT="$(mktemp -d "$MODEL_ASSETS/Build-2026-09-26.XXXXXX")"
HF_HOME="$BUILD_ROOT/HuggingFace"
HF_HUB_CACHE="$HF_HOME/hub"
export HF_HOME HF_HUB_CACHE
mkdir -p "$BUILD_ROOT/Release/Models/Qwen" \
  "$BUILD_ROOT/Release/Notices" \
  "$BUILD_ROOT/Release/Packaging" \
  "$BUILD_ROOT/Release/Output" \
  "$BUILD_ROOT/Release/Evidence" \
  "$BUILD_ROOT/Tools"
echo "BUILD_ROOT=$BUILD_ROOT"
df -h "$MODEL_ASSETS"

This layout isolates the Hugging Face cache and the new release candidates. Never run rm -rf against the existing ModelAssets/Release tree to make room. For a later run, change the date in the mktemp template or leave it: the random suffix still creates a separate directory.

3. Freeze source and exporter revisions

The model revisions recorded in the existing RawCull catalog are:

CLIP_REV='4afec35ffe57a943d569ff7ee888061830164da8'
SAM_REV='3c879f39826c281e95690f02c7821c4de09afae7'
QWEN_REV='78448d793a7eb2f7a987a1da76d464384aa1becd'
CLIP_TOKENIZER_REV='3d74acf9a28c67741b2f4f2ea7635f0aaf6f0268'
COREAI_MODELS_REV='475c585fdb0fe82a83c8f777f259e9414bd44c98'

COREAI_MODELS_REV is the revision pinned by the local PhotoAIKit package in the September 2026 RawCull work. These revision labels are a starting recipe. The old DataComp and Qwen provenance explicitly does not prove which exact weight bytes their exporters consumed. This rebuild records the actual source inventory so its evidence is stronger.

First save the repository states. If either repository has local changes to the exporter, review them before proceeding:

git -C "$RAWCULL_REPO" rev-parse HEAD | tee "$BUILD_ROOT/Release/Evidence/rawcull-commit.txt"
git -C "$PHOTOAIKIT_REPO" rev-parse HEAD | tee "$BUILD_ROOT/Release/Evidence/photoaikit-commit.txt"
git -C "$RAWCULL_REPO" status --short
git -C "$PHOTOAIKIT_REPO" status --short
shasum -a 256 "$PHOTOAIKIT_REPO/Tools/export_clip.py" \
  "$PHOTOAIKIT_REPO/Tools/export_sam3.py" \
  "$PHOTOAIKIT_REPO/Tools/select_sam3_asset.py" \
  | tee "$BUILD_ROOT/Release/Evidence/photoaikit-exporters-sha256.txt"

Get Apple’s converter at the selected revision in the build directory. A normal git clone also preserves its licence and Python project configuration. If the pinned revision is unavailable, stop and choose a reviewed revision; do not silently use the current main branch.

git clone https://github.com/apple/coreai-models.git "$BUILD_ROOT/Tools/coreai-models"
git -C "$BUILD_ROOT/Tools/coreai-models" checkout --detach "$COREAI_MODELS_REV"
git -C "$BUILD_ROOT/Tools/coreai-models" rev-parse HEAD \
  | tee "$BUILD_ROOT/Release/Evidence/coreai-models-commit.txt"

4. Download immutable Hugging Face snapshots

SAM 3 is gated: sign in to Hugging Face in a browser, request/receive access to facebook/sam3, accept its terms, and authenticate the terminal with uvx --from huggingface-hub hf auth login. Do not paste your access token into this workbook or a shell command. Qwen and DataComp are public, but checking their model cards and current redistribution terms is still part of release review. These downloads use Hugging Face’s CLI.

uvx --from huggingface-hub hf auth whoami
uvx --from huggingface-hub hf download \
  laion/CLIP-ViT-B-32-256x256-DataComp-s34B-b86K \
  --revision "$CLIP_REV" \
  --local-dir "$BUILD_ROOT/Source/CLIP-DataComp"
uvx --from huggingface-hub hf download facebook/sam3 \
  --revision "$SAM_REV" \
  --local-dir "$BUILD_ROOT/Source/SAM3"
uvx --from huggingface-hub hf download Qwen/Qwen3-VL-2B-Instruct \
  --revision "$QWEN_REV" \
  --local-dir "$BUILD_ROOT/Source/Qwen"

The exporters do not all take a --revision or --source-dir flag. To make their ordinary model-ID lookups use the selected snapshots, populate the isolated Hugging Face cache at the same revisions and bind its main refs to those revisions. This is explicit, local to BUILD_ROOT, and leaves your ordinary Hugging Face cache alone. The CLIP exporter also obtains the OpenAI CLIP tokenizer, so cache it separately.

uvx --from huggingface-hub hf download \
  laion/CLIP-ViT-B-32-256x256-DataComp-s34B-b86K \
  --revision "$CLIP_REV"
uvx --from huggingface-hub hf download facebook/sam3 --revision "$SAM_REV"
uvx --from huggingface-hub hf download Qwen/Qwen3-VL-2B-Instruct \
  --revision "$QWEN_REV"
uvx --from huggingface-hub hf download openai/clip-vit-base-patch32 \
  --revision "$CLIP_TOKENIZER_REV"

mkdir -p "$HF_HUB_CACHE/models--laion--CLIP-ViT-B-32-256x256-DataComp-s34B-b86K/refs" \
  "$HF_HUB_CACHE/models--facebook--sam3/refs" \
  "$HF_HUB_CACHE/models--Qwen--Qwen3-VL-2B-Instruct/refs" \
  "$HF_HUB_CACHE/models--openai--clip-vit-base-patch32/refs"
printf '%s' "$CLIP_REV" > "$HF_HUB_CACHE/models--laion--CLIP-ViT-B-32-256x256-DataComp-s34B-b86K/refs/main"
printf '%s' "$SAM_REV" > "$HF_HUB_CACHE/models--facebook--sam3/refs/main"
printf '%s' "$QWEN_REV" > "$HF_HUB_CACHE/models--Qwen--Qwen3-VL-2B-Instruct/refs/main"
printf '%s' "$CLIP_TOKENIZER_REV" > "$HF_HUB_CACHE/models--openai--clip-vit-base-patch32/refs/main"

The first --local-dir downloads are the inspectable evidence copies; the second downloads populate the cache actually used by the model-ID loaders. Record source hashes, including every Qwen weight shard:

find "$BUILD_ROOT/Source" -type f ! -name '.DS_Store' -print0 \
  | xargs -0 shasum -a 256 \
  | sort > "$BUILD_ROOT/Release/Evidence/source-files-sha256.txt"
rg 'safetensors|tokenizer.json|LICENSE' \
  "$BUILD_ROOT/Release/Evidence/source-files-sha256.txt" | head -80

Check that the expected source files exist before converting:

test -f "$BUILD_ROOT/Source/SAM3/model.safetensors"
test -f "$BUILD_ROOT/Source/Qwen/config.json"
find "$BUILD_ROOT/Source/Qwen" -maxdepth 1 -name '*.safetensors' -print
find "$BUILD_ROOT/Source/CLIP-DataComp" -maxdepth 1 -type f -print

DataComp binding limitation: open_clip.create_model_and_transforms uses the datacomp_s34b_b86k preset and may resolve its checkpoint through an OpenCLIP configuration rather than the checked-out LAION directory. Run it with the isolated cache and inspect the export log and cache entries. Do not claim that the LAION file was consumed solely because it was downloaded. If the resolved source differs, capture that actual source file, revision and SHA-256, or adapt the exporter to accept an explicit local weight path before release.

5. Convert DataComp CLIP

The PhotoAIKit exporter creates one two-function .aimodel plus tokenizer and bundle metadata. Its default DataComp options use ViT-B/32 at 256 px, datacomp_s34b_b86k, float16, and static shapes. The script itself pins the Python packages, including coreai-core==1.0.0b2 and coreai-torch==0.4.1.

cd "$PHOTOAIKIT_REPO"
export HF_HUB_OFFLINE=1
uv run Tools/export_clip.py \
  --model openclip-datacomp \
  --architecture ViT-B-32-256 \
  --pretrained datacomp_s34b_b86k \
  --dtype float16 \
  --output-dir "$BUILD_ROOT/Release/Models" \
  --bundle-name CLIP-DataComp \
  2>&1 | tee "$BUILD_ROOT/Release/Evidence/clip-export.log"

The exporter checks parity between the OpenCLIP tokenizer IDs and the saved PhotoAIKit tokenizer. Stop if that check fails. HF_HUB_OFFLINE=1 intentionally prevents a network fallback to an unpinned source. If OpenCLIP needs a different checkpoint repository, find its actual configured repository, pin and download it, then rerun this block in a new build directory. Do not use --overwrite until you have saved and reviewed the first result.

test -f "$BUILD_ROOT/Release/Models/CLIP-DataComp/metadata.json"
test -f "$BUILD_ROOT/Release/Models/CLIP-DataComp/tokenizer/tokenizer.json"
test -f "$BUILD_ROOT/Release/Models/CLIP-DataComp/ViT-B-32-256-datacomp_s34b_b86k_float16_static.aimodel/main.mlirb"
cat "$BUILD_ROOT/Release/Models/CLIP-DataComp/metadata.json"

6. Convert Meta SAM 3

The SAM exporter downloads the gated checkpoint by model ID, exports a source asset and an optimized runtime asset, and writes tokenizer and metadata. Select the optimized sam3_float16.aimodel so the package contains the runtime asset only. The selector refreshes the bundle fingerprint metadata.

cd "$PHOTOAIKIT_REPO"
export HF_HUB_OFFLINE=1
uv run Tools/export_sam3.py \
  --model facebook/sam3 \
  --dtype float16 \
  --output-dir "$BUILD_ROOT/Release/Models" \
  --bundle-name SAM3 \
  2>&1 | tee "$BUILD_ROOT/Release/Evidence/sam3-export.log"

python3 Tools/select_sam3_asset.py sam3_float16.aimodel \
  --bundle-dir "$BUILD_ROOT/Release/Models/SAM3"

Inspect the result. The package selector below includes only the optimized asset, tokenizer and metadata; it does not include any remaining *_source.aimodel directory.

test -f "$BUILD_ROOT/Release/Models/SAM3/metadata.json"
test -f "$BUILD_ROOT/Release/Models/SAM3/tokenizer/tokenizer.json"
test -f "$BUILD_ROOT/Release/Models/SAM3/sam3_float16.aimodel/main.mlirb"
cat "$BUILD_ROOT/Release/Models/SAM3/metadata.json"

7. Convert Qwen3-VL-2B-Instruct

Apple’s VLM exporter creates the text decoder, embedding lookup, vision encoder, tokenizer, and metadata.json in a qwen3_vl_2b directory. Use the full model: do not set --num-layers or --skip-vision. The existing RawCull bundle records a 4096 token context. The exporter has no --revision option, so the isolated cache and offline mode from section 4 matter here. Its output directory is the parent of qwen3_vl_2b.

cd "$BUILD_ROOT/Tools/coreai-models"
export HF_HUB_OFFLINE=1
uv run coreai.vlm.export --list-models
uv run coreai.vlm.export qwen3-vl \
  --max-context-length 4096 \
  --compression none \
  --output-dir "$BUILD_ROOT/Release/Models/Qwen" \
  2>&1 | tee "$BUILD_ROOT/Release/Evidence/qwen-export.log"

If the pinned converter revision does not offer qwen3-vl or one of these options, stop and inspect that revision’s --help; record and review any converter revision change. Qwen export can take a long time and use substantial memory. A process killed by macOS needs a fresh build directory or a carefully inspected incomplete-output cleanup before retrying.

QWEN_BUNDLE="$BUILD_ROOT/Release/Models/Qwen/qwen3_vl_2b"
test -f "$QWEN_BUNDLE/metadata.json"
test -f "$QWEN_BUNDLE/tokenizer/tokenizer.json"
test -f "$QWEN_BUNDLE/qwen3_vl_2b.aimodel/main.mlirb"
test -f "$QWEN_BUNDLE/embed.aimodel/main.mlirb"
test -f "$QWEN_BUNDLE/vision.aimodel/main.mlirb"
python3 -m json.tool "$QWEN_BUNDLE/metadata.json"

Check that the metadata still names Qwen/Qwen3-VL-2B-Instruct, the three assets, 448 px vision input, and 4096 context. This is a format check, not an inference test. RawCull’s Qwen provider must also load and run the bundle.

8. Stage licences, notices and build provenance

Copy the reviewed notice catalog from RawCull. These files include the complete model, tokenizer, and Apple conversion-recipe notices used by the existing release. Review their terms and dates against the newly downloaded sources before redistribution. SAM 3’s licence acceptance is required in RawCull.

for name in CLIP-DataComp SAM3 Qwen; do
  ditto "$RAWCULL_REPO/ModelAssets/Notices/$name" \
    "$BUILD_ROOT/Release/Notices/$name"
done
find "$BUILD_ROOT/Release/Notices" -type f -maxdepth 2 -print | sort

Those checked-in NOTICE.md files describe earlier published versions. Mark the staging copies as new candidates without changing their licence text:

python3 - "$BUILD_ROOT" <<'PY'
from pathlib import Path
import sys
base = Path(sys.argv[1]) / 'Release/Notices'
replacements = {
    'CLIP-DataComp': (
        'RawCull publishes this pack in the v2 model release. The release catalog\n'
        'records its download size and version, while the release host records the\n'
        'archive checksum. This notice catalog records the upstream reference revision,\n'
        'runtime fingerprint, and complete accompanying licence notices.',
        'This converted bundle is a new local release candidate. Its final archive\n'
        'size, SHA-256, Apple-assigned version, and review status must be recorded\n'
        'after packaging and upload.'),
    'SAM3': (
        'The Apple-hosted asset pack is enabled for download at the project owner\'s\n'
        'direction. Its archive byte size and SHA-256 are recorded in the external\n'
        'release evidence after packaging, while the host-correct in-pack release record\n'
        'is in `PROVENANCE.json`. This release decision does not claim an independent\n'
        'legal review. Verified licence acceptance remains required.',
        'This converted bundle is a new local release candidate. Record its archive\n'
        'size, SHA-256, Apple-assigned version, and review status after packaging\n'
        'and upload. Verified SAM licence acceptance remains required.'),
    'Qwen': (
        'RawCull publishes this pack in the v3 model release. The release catalog\n'
        'records its download size and version, while the release host records the\n'
        'archive checksum.',
        'This converted bundle is a new local release candidate. Record its final\n'
        'archive size, SHA-256, Apple-assigned version, and review status after\n'
        'packaging and upload.'),
}
for name, (old, new) in replacements.items():
    path = base / name / 'NOTICE.md'
    content = path.read_text()
    if content.count(old) != 1:
        raise RuntimeError(f'Expected release paragraph not found: {path}')
    path.write_text(content.replace(old, new))
PY

The copied PROVENANCE.json files describe the old release. Replace only the staging copies with a clearly identified record of this build. The script below preserves the licence inventory, writes the actual converted-component hashes, and points to the source inventory. It intentionally has no final .aar hash because that hash cannot be embedded inside its own archive.

python3 - "$BUILD_ROOT" "$CLIP_REV" "$SAM_REV" "$QWEN_REV" <<'PY'
import datetime, hashlib, json, pathlib, sys
root = pathlib.Path(sys.argv[1])
revisions = dict(zip(('CLIP-DataComp', 'SAM3', 'Qwen'), sys.argv[2:]))
models = {
    'CLIP-DataComp': root / 'Release/Models/CLIP-DataComp',
    'SAM3': root / 'Release/Models/SAM3',
    'Qwen': root / 'Release/Models/Qwen/qwen3_vl_2b',
}
for name, model_dir in models.items():
    notice_dir = root / 'Release/Notices' / name
    old = json.loads((notice_dir / 'PROVENANCE.json').read_text())
    components = {}
    for path in sorted(model_dir.rglob('main.mlirb')):
        digest = hashlib.sha256()
        with path.open('rb') as stream:
            for chunk in iter(lambda: stream.read(4 * 1024 * 1024), b''):
                digest.update(chunk)
        components[str(path.relative_to(model_dir))] = digest.hexdigest()
    record = {
        'catalog_version': 2,
        'release_status': 'candidate',
        'release': {
            'hosting': 'apple',
            'app_bundle_id': 'no.blogspot.RawCull',
            'asset_pack_id': {
                'CLIP-DataComp': 'rawcull-clip-datacomp',
                'SAM3': 'rawcull-sam3',
                'Qwen': 'rawcull-qwen3-vl-2b',
            }[name],
            'packaging_date': datetime.date.today().isoformat(),
            'processing_status': 'not-uploaded',
            'review_state': 'not-submitted',
        },
        'model': {
            'bundle': old.get('model', {}).get('bundle', name),
            'converted_main_mlirb_sha256': components,
        },
        'upstream': {
            'project': old.get('upstream', {}).get('project'),
            'selected_revision': revisions[name],
            'source_inventory': 'Release/Evidence/source-files-sha256.txt',
            'exporter_binding_note': 'Verify exporter log and isolated cache before claiming exact source binding.',
        },
        'conversion': {
            'photoaikit_commit_file': 'Release/Evidence/photoaikit-commit.txt',
            'coreai_models_commit_file': 'Release/Evidence/coreai-models-commit.txt',
        },
        'licences': old.get('licences', []),
    }
    (notice_dir / 'PROVENANCE.json').write_text(json.dumps(record, indent=2) + '\n')
PY

The staging provenance format is release-candidate evidence; it is not a drop-in replacement for RawCull’s checked-in PROVENANCE.json. After packaging, update the repository record using its full validated schema and the final archive hash, size, App Store Connect pack version, and processing state.

9. Create the three packaging manifests

These selector paths are relative to the current directory used by ba-package, which must be BUILD_ROOT/Release. Keep the permanent IDs and installed paths identical to RawCull’s catalog.

cat > "$BUILD_ROOT/Release/Packaging/clip-datacomp.json" <<'JSON'
{
  "assetPackID": "rawcull-clip-datacomp",
  "downloadPolicy": { "onDemand": {} },
  "fileSelectors": [
    { "file": "Models/CLIP-DataComp/metadata.json" },
    { "directory": "Models/CLIP-DataComp/tokenizer" },
    { "directory": "Models/CLIP-DataComp/ViT-B-32-256-datacomp_s34b_b86k_float16_static.aimodel" },
    { "directory": "Notices/CLIP-DataComp" }
  ],
  "platforms": ["macOS"]
}
JSON

cat > "$BUILD_ROOT/Release/Packaging/sam3.json" <<'JSON'
{
  "assetPackID": "rawcull-sam3",
  "downloadPolicy": { "onDemand": {} },
  "fileSelectors": [
    { "file": "Models/SAM3/metadata.json" },
    { "directory": "Models/SAM3/tokenizer" },
    { "directory": "Models/SAM3/sam3_float16.aimodel" },
    { "directory": "Notices/SAM3" }
  ],
  "platforms": ["macOS"]
}
JSON

cat > "$BUILD_ROOT/Release/Packaging/qwen3-vl-2b.json" <<'JSON'
{
  "assetPackID": "rawcull-qwen3-vl-2b",
  "downloadPolicy": { "onDemand": {} },
  "fileSelectors": [
    { "file": "Models/Qwen/qwen3_vl_2b/metadata.json" },
    { "directory": "Models/Qwen/qwen3_vl_2b/tokenizer" },
    { "directory": "Models/Qwen/qwen3_vl_2b/embed.aimodel" },
    { "directory": "Models/Qwen/qwen3_vl_2b/qwen3_vl_2b.aimodel" },
    { "directory": "Models/Qwen/qwen3_vl_2b/vision.aimodel" },
    { "directory": "Notices/Qwen" }
  ],
  "platforms": ["macOS"]
}
JSON

for slug in clip-datacomp sam3 qwen3-vl-2b; do
  python3 -m json.tool "$BUILD_ROOT/Release/Packaging/$slug.json" >/dev/null
done

10. Inspect and freeze the selected input files

.DS_Store files are present in the older ModelAssets/Release directories; the new candidate should not include them. Do not delete anything from the old release. Check the fresh selected directories and resolve any unexpected symlink or secret before packaging.

cd "$BUILD_ROOT/Release"
find Models/CLIP-DataComp Models/SAM3 Models/Qwen/qwen3_vl_2b \
  Notices/CLIP-DataComp Notices/SAM3 Notices/Qwen \
  \( -name '.DS_Store' -o -type l \) -print

find Models/CLIP-DataComp Models/SAM3 Models/Qwen/qwen3_vl_2b \
  Notices/CLIP-DataComp Notices/SAM3 Notices/Qwen \
  -type f -print0 | xargs -0 shasum -a 256 | sort \
  > Evidence/selected-inputs-sha256.txt

for slug in clip-datacomp sam3 qwen3-vl-2b; do
  xcrun ba-package evaluate "Packaging/$slug.json" \
    | tee "Evidence/$slug-evaluate.txt"
done

Read all three Evidence/*-evaluate.txt files. Each list should contain only its model bundle, tokenizer, metadata, and matching notice directory. The Qwen pack needs all three .aimodel directories. No source weight files, download cache, old archive, or other model should be selected. If the evaluation output is wrong, fix the manifest and rerun evaluation and the input inventory before packaging.

11. Build the three .aar files

ba-package creates Background Assets archives; .aar is not a ZIP file. Run it from BUILD_ROOT/Release so the relative file selectors resolve.

cd "$BUILD_ROOT/Release"
xcrun ba-package package Packaging/clip-datacomp.json \
  --output-path Output/clip-datacomp.aar --verbose \
  2>&1 | tee Evidence/clip-datacomp-package.log

xcrun ba-package package Packaging/sam3.json \
  --output-path Output/sam3.aar --verbose \
  2>&1 | tee Evidence/sam3-package.log

xcrun ba-package package Packaging/qwen3-vl-2b.json \
  --output-path Output/qwen3-vl-2b.aar --verbose \
  2>&1 | tee Evidence/qwen3-vl-2b-package.log

Do not edit an archive after this point. Any changed model, metadata, notice, or manifest requires another ba-package package run and a new hash. For the three existing App Store Connect pack records, a changed archive will become a new pack version under the same permanent ID.

12. Verify and record the result

cd "$BUILD_ROOT/Release"
for slug in clip-datacomp sam3 qwen3-vl-2b; do
  test -s "Output/$slug.aar"
  stat -f '%N|%z bytes' "Output/$slug.aar"
  shasum -a 256 "Output/$slug.aar"
  shasum -a 256 "Packaging/$slug.json"
done | tee Evidence/archive-and-manifest-sha256.txt

find Output -maxdepth 1 -type f -name '*.aar' -print | sort

The last command must print exactly these three paths:

Output/clip-datacomp.aar
Output/qwen3-vl-2b.aar
Output/sam3.aar

Compare the final selected-inputs-sha256.txt with a fresh hash pass to catch any source mutation while the archives were built:

find Models/CLIP-DataComp Models/SAM3 Models/Qwen/qwen3_vl_2b \
  Notices/CLIP-DataComp Notices/SAM3 Notices/Qwen \
  -type f -print0 | xargs -0 shasum -a 256 | sort \
  > Evidence/selected-inputs-after-sha256.txt
diff -u Evidence/selected-inputs-sha256.txt \
  Evidence/selected-inputs-after-sha256.txt

An empty diff and exit status 0 confirm that the selected inputs remained unchanged during packaging. Record the BUILD_ROOT path, Xcode version, exporter commits, source hashes, and all three archive hashes with the release candidate. The files are at:

<BUILD_ROOT>/Release/Output/clip-datacomp.aar
<BUILD_ROOT>/Release/Output/sam3.aar
<BUILD_ROOT>/Release/Output/qwen3-vl-2b.aar

13. Before uploading or calling these release files

  1. Verify that the DataComp exporter actually consumed the pinned checkpoint; the downloaded LAION snapshot alone does not prove it. For all three packs, retain actual source-weight hashes and exporter logs.
  2. Review the current model licences and all copied notice files. Keep the correct notice directory inside each .aar.
  3. Run RawCull’s make verify-model-provenance, catalog and release-metadata tests, and release preflight after updating its manifest template, Swift catalog, and checked-in provenance to the new archive values. Never leave the old archive SHA-256 in the app catalog for new .aar files.
  4. If uploading, use the existing rawcull-clip-datacomp, rawcull-sam3, and rawcull-qwen3-vl-2b App Store Connect records. Follow RawCull/Docs/newmodels.md for xcrun altool, API-key handling, processing checks, and TestFlight verification. The AppStore build must use Apple hosting and the matching App Group. A successful local .aar build does not test runtime inference.

If a step fails

SymptomCheck
401/403 downloading SAM 3Hugging Face approval and hf auth whoami; accept the gated model terms.
Offline source missingCheck the isolated HF_HUB_CACHE and the model’s refs/main; download the exact revision before re-exporting.
CLIP tokenizer parity failureDo not package; inspect the tokenizer source and OpenCLIP configuration.
SAM export leaves source assetPackage only the optimized asset selected by select_sam3_asset.py.
Qwen bundle lacks vision.aimodelRebuild with a converter that supports Qwen VLM and without --skip-vision.
ba-package evaluate lists extra filesCorrect its fileSelectors; evaluate again before packaging.
Archive hash differs from the old releaseExpected for a new conversion; update catalog and provenance before upload.

The source commands and pack layout come from PhotoAIKit’s export tools, Apple’s Core AI model recipes, Apple’s managed pack documentation, and the RawCull release runbook linked above. Verify the exact checkout used for a release: repository main branches and tool versions can change.

October 13: verify an installed candidate before interpreting success

The conversion workbook above preserves its September build procedure. The October application snapshot was the version-3.3.0 working tree with PhotoAIKit 7f9adfcd69661c6bae4a640c16a4056dfc7393df and Core AI models 1953c4f90ba0214c1abc7bebcb9be5107e329a46. Recheck exporter command-line options at the revisions actually used for a new conversion; application dependency pins do not silently update an already exported model or its provenance.

There are independent gates:

  1. Archive integrity: recorded bytes, SHA-256, selected files and notices.
  2. Installation/provider admission: required assets, metadata and modality.
  3. Inference: finite vectors, usable masks, or nonempty generated responses.
  4. Contract acceptance: IDs, enums, evidence ownership and response limits.
  5. Visual qualification: annotations, source comparisons and useful judgments.

A successful archive or model load does not imply the later gates passed. The app’s catalog hash describes a specific release archive, not every future conversion of the same upstream weights.

For build 466, use make combinedinputstest for installed-model input contracts or make combinedselectiontest for the six-file selection probe. The October tab runner was retired with AI Analysis. Keep request images and model responses private when collecting photographic evidence. Verify Apple-hosted installation separately on a TestFlight or App Store build. Makefile

Relationship to the current application

This is a pinned model-preparation recipe. Its exporter revisions, source-weight snapshots and historical tool versions are retained deliberately; the October 22 application review did not rebuild or publish model packs. Do not substitute a new source revision into the commands merely because the app version changed. Current download/installation UI ownership is described in AI Runtime, and evaluation entry points in the RawCull test plans (RawCull.xctestplan, ReleaseObjects.xctestplan, ReleaseSharpness.xctestplan). Earlier links to RawCull/Docs/newmodels.md open historical commits because that report has been removed from the current application tree.

To trace an installed bundle from its resolved directory into a provider and an inference request, see Full Review execution.

15.2 - Full Review Execution

A source-level trace from the Full preset through installed model URLs, prompts, local inference, and saved evidence.

Trace a Full Review from SwiftUI to saved evidence

Open the Review workspace, select Full in the preset control, then click Review to start. This walkthrough follows RawCull 3.5.0 build 468 and its resolved PhotoAIKit 3.1.0 and Core AI Models 1.0.0 dependencies. The links point to the source revisions used for the trace. Build 466 has the same Review implementation and package pins. Application lockfile

1. Follow the installed model URLs into PhotoAIKit

Settings activates the models before Review runs. The model download service asks Background Assets for each installed bundle directory using AssetPackManager.shared.url(for: FilePath(descriptor.assetPackModelPath)) and checks that the returned URL names an existing directory. The production catalog paths are Models/Qwen/qwen3_vl_2b, Models/SAM3 and Models/CLIP-DataComp. These are asset-pack-relative paths. At a breakpoint, inspect the returned file URL to see the location on that Mac. The download coordinator collects installed locations into a snapshot, which RawCullAISettingsModel applies to RawCullAIModelRuntime. Download catalog · Download service · Settings model

ModelRawCull handoffPhotoAIKit receives and keeps
QwenapplyManagedModelLocations calls the Qwen actor’s validate(url:) with the installed directory. The actor standardizes it and calls CoreAIQwenProvider.factory.capability(in: [standardizedURL]), then makeProvider(from:).CoreAIQwenProvider(modelBundleURL:) validates the directory and reads metadata.json. It checks Qwen tokenizer/source identifiers, positive vocabulary and context sizes and, for a VLM, vision metadata plus the embedding and vision asset files. RawCull requires vision modality. The provider retains the bundle URL. On first inference, makeVisionLanguageModel() passes it to CoreAIVisionLanguageModel(resourcesAt:).
SAM 3The model runtime updates its SAM resource manager’s candidate URL. load() asks CoreAISAM3Provider.factory to resolve and construct a provider.The provider records the identity of the validated bundle. On first inference, loadModel() opens the tokenizer and constructs CoreAISegmentationEngine using the resolved main asset. For a flat exporter tokenizer layout, the provider can stage metadata and tokenizer files in a temporary directory with a symlink to the model asset.
CLIPSeparate resource managers validate DataComp and OpenAI candidates with CoreAICLIPProvider.factory. The model runtime keeps validated providers and their resolved locations.The provider stores the resolved model URL, bundle identity and preprocessing configuration. Its lazy load opens the model functions and tokenizer using the bundle metadata and model descriptors.

The PhotoAIKit factory boundary is capability(in: [URL]) → ModelResource → makeProvider(from:) → concrete provider. The package resolves metadata, required paths and asset identity from the candidate directories RawCull supplies. RawCull’s SAM and CLIP resource managers can reuse a capability/provider pair while their recursive filesystem snapshot still matches. Qwen validation instead cancels active generation, increments its generation counter and resets the loaded model. Resource manager · Package resource contracts · Qwen provider · SAM provider · CLIP provider

When Review requests a live backend, the factory in RawCullIntelligenceRuntime captures the shared Qwen actor and its available URL, the SAM 3 object-instance service and serialized SAM identity, and the CLIP provider and location. It prefers DataComp, with OpenAI CLIP as the fallback when DataComp is absent. The Review backend uses the captured Qwen and CLIP URLs to check bundle identity. Actual inference uses the configured actor or provider. SAM’s URL is already inside its provider. The current configuration refresh coordinates with Review through the shared lease before replacing model state. Runtime factory · Model runtime · Live backend

2. Follow the Review action to the saved run snapshot

  1. The toolbar opens the Review workspace. CombinedReviewWorkspaceView passes either the grid selection (the default) or the tagged images from CatalogController.aiAnalysisFiles(for:) into CombinedReviewView. The thumbnail selection controls which photo is displayed. The input picker controls the files passed to the run. Workspace input
  2. In CombinedReviewRunBar, the segmented picker binds to feature.preset. Selecting Full writes .full. In CombinedReviewRunActions, the Review action projects the workspace files into ReviewSelectedFile values with catalog ID, photo URL, display name, normalized AF point and ISO, then calls CombinedReviewFeature.analyze. SwiftUI controls
  3. The feature evaluates selection, criteria, source availability and model readiness. The criteria must be nonblank and at most 512 UTF-8 bytes after trimming. The Qwen presets require a Mac with at least 16 GB of unified memory. A new run requests the shared Review lease, constructs the backend and captures the chosen preset, depth, source and retention settings. The worker freezes one to eight files with fingerprints and retains security-scoped access through ReviewCatalogSession. A user region is captured for a single selected image. Feature admission · File admission
  4. backend.models(for: .full) checks Qwen’s 448 × 448 stretch input, 196 image tokens, 4096-token context and exact bundle tree hash. The tree hash combines sorted relative paths and SHA-256 digests of the visible regular files. CLIP admission recognizes two bundle hashes with 224- or 256-pixel geometry. The SAM snapshot records provider identity and the source-normalized mask contract. Full requires Qwen. Missing SAM or unrecognized CLIP can leave individual stages unavailable while the run continues. Model admission · Preset contract
  5. ReviewRunSnapshot freezes the file and model identities, trimmed criteria, depth, source preference, retention flags, stage versions, pipeline version and 768-token response limit. The feature validates it and saves the initial work manifest before calling execute. Follow manifest.snapshot.id through progress, result and storage breakpoints. Snapshot and worker · Initial manifest

3. Locate the Qwen prompt boundary

RawCull builds a separate instruction for each Qwen stage. CombinedReviewLiveBackend.respond(instruction:image:tokens:) copies the instruction string, CGImage and output limit into a RawCull QwenVisionRequest. Inside QwenInferenceRuntime.respond(to:), the request waits on the generation gate and verifies that the model generation still matches. The first request uses the PhotoAIKit provider to construct the vision-language runtime. Later requests reuse the loaded runtime. The actor creates a fresh Foundation Models session per request and supplies the image first and the instruction second. Live backend · Generation code

let session = LanguageModelSession(model: model)
let response = try await session.respond(
    options: GenerationOptions(maximumResponseTokens: request.maximumResponseTokens),
) {
    Attachment(request.image)
    request.instruction
}

There are two boundaries to inspect. PhotoAIKit’s Qwen provider takes the model directory and constructs the Core AI model. The session takes the request text and pixels and invokes that model locally. Each request has its own prompt and attachment. Earlier stage data reaches later calls only where RawCull explicitly interpolates it into instructions or uses it to choose pixels. After generation, the actor checks cancellation and generation again, trims response.content and rejects an empty response. The stage parser then validates the text against that stage’s schema. Provider constructor · Runtime request and response

Before dispatch, CombinedReviewResponse.admitted checks instruction.utf8.count + imageTokens + outputTokens + 256 <= contextTokens. This conservatively charges one unit per UTF-8 byte and reserves framing space. With the accepted Qwen model and the normal 768-token response limit, the instruction allowance is 2,876 bytes. validatedResponse can append a bounded correction and retry a rejected response with the same image, subject to prompt admission and the repair budget. Inspect the original instruction, the validation issue and the repaired instruction separately. Prompt admission · Stage validation and repair

4. Step through a single photo

execute sorts files by stable review ID, allocates crop slots round robin across the selection, and calls prepare → plan → inspect → finish for each photo. The source, overview, subject identity and report have stable work IDs. Dynamic work IDs describe the concept, subject or region being processed. Execution

Prepare the source and ask Qwen for an overview

prepare opens the frozen photo URL with the chosen source preference and the appearance policy. Inspect source.metadata, source.image and source.overview to distinguish the rendered source from its overview raster, whose default maximum side is 2,048 pixels. The source loader records identity, fidelity and render settings. The Qwen attachment is the overview raster. The admitted model subsequently applies its 448 × 448 stretch preprocessing. Source loader · Prepare

CombinedReviewResponse.overviewInstruction asks for JSON with observations, uncertainty and up to three object concepts. Each concept has query, displayName and reason. The queries should be short singular object noun phrases. This initial discovery instruction is fixed. The user’s Review criteria are used later in CLIP relevance and in the synthesis and comparison goals. The overview parser’s validated concepts are what the next stage sees. Overview instruction and parser

Plan subjects and regions with SAM 3

For each admitted overview concept, plan calls backend.segment(image: source.image, file: file, concept: concept). The live backend constructs a SegmentationConcept and supplies an AIImageSource with the file ID, photo URL and display name to ObjectSegmentationService. The service reads source identity from the URL and bounds the supplied raster to 4,320 pixels on the long side. Review constructs this service with an eight-instance limit and an empty package store list. Planning · Service construction · Package workflow

In CoreAISAM3Provider.infer, the provider tokenizes the concept using the model’s tokenizer context length and calls engine.segment(image:textQuery:parameters:) with .tokens([tokens]). For example, a validated overview concept of bird becomes a tokenized SAM query. The provider decodes instance outputs and the service resizes masks back to the dimensions of the supplied source image. RawCull registers each mask against the appearance source, deduplicates overlapping candidates across concepts and assigns subject priority. With retained subjects, a separate head query can propose a generic child region subject to spatial checks. RawCull then plans bounded crops from retained subjects and the optional user region. Check omissions and the identity work item when a proposed region is missing. SAM inference · Registration and planning

Measure focus, score relevance and inspect crops

  • Focus measurement. inspect may load the technical render of the photo. Where sources are compatible, it maps the registered subject mask to the measurement raster and calls SubjectMaskFocusScorer for subject-local detail evidence. Inspect the recorded source, foreground bounds, mask contract and measurement availability. This work has no generative instruction. Measurement execution · Focus scorer
  • CLIP relevance. The backend calls provider.embedding(for: image) and provider.embedding(for: snapshot.criteria) for the overview and eligible crops. The provider preprocesses the image for its configured encoder and runs the image function. It tokenizes the criteria to the text input shape, builds the token batch and any required attention mask, and runs the text function. RawCull checks vector shape and finiteness, computes cosine relevance from the two embeddings, and records the visual embedding and encoder geometry. Inspect the criteria literally as typed, after admission trimming. CLIP returns vectors and relevance rather than prose. CLIP call site · CLIP provider
  • Qwen crop observation. The attachment is the registered crop. RawCull interpolates the generic target, exact region ID and purpose into the instruction. It requests JSON containing that region ID, four criterion strings or nulls (composition, exposure, visibility, detail), uncertainty and targetIdentified. The parser validates the ID and target support and can preserve valid criteria while recording abstentions for others. A crop’s detail text must describe resolved texture of the intended target. The run records its provenance and any limitation separately from focus measurements. Crop prompt and result

The depth setting caps crops per photo and across the selection. Standard allows 3 and 16, Deep 8 and 32, and Exhaustive 16 and 64. A slot permits a crop attempt when qualified input exists. The manifest budget also tracks SAM, CLIP, overview, reconciliation, reporting, comparison and repair attempts. Depth contract · Attempt accounting

Reconcile and assemble the per-image report

With both measurements and available crop observations, finish may request reconciliation. The final synthesize call attaches the overview and builds a new instruction from the user’s goal, source information and admitted observation rows. It excludes reconciliation prose from the synthesis inputs. Each row has a short alias such as o1, scope information and supported text. RawCull prioritizes rows and omits optional rows that exceed the context allowance. It computes the eligible row IDs for each criterion before asking Qwen to select one ID or null per criterion. Synthesis implementation · Evidence grounding

The report parser resolves aliases to the original evidence IDs and copies the selected criterion text. Measurements remain available as numeric evidence in the UI. Missing categories and uninspected regions become limitations. If report synthesis fails validation, RawCull saves an evidence-only summary and an incomplete report with no accepted generated claims. This lets the developer distinguish a report-generation failure from the loss of earlier observations. Report fallback and row selection · Response validation

5. Follow the multi-photo branch and saved results

For more than one photo, compare runs after per-image work. It assembles a 2,048 × 2,048 labeled overview board and an instruction referencing evidence from the reviewed photos. The Qwen request attaches that single board. The comparison validates its references and can abstain while leaving per-image reports available. A comparable tie can schedule optional pair boards. Both images must have one candidate subject with the same concept, and their qualified whole-subject crops must match in source policy and fidelity and be within the scale tolerance. Deep allows up to two such pairs and Exhaustive up to four. Comparison calls validate their responses directly through the comparison parser. Comparison execution · Board renderer

perform is the breakpoint for stage transitions, budget consumption, artifact reuse and failure diagnostics. The manifest tracks stage state, dependencies, compatibility and artifact keys. The store writes per-run JSON under runs/ and stage artifacts under stages/ under RawCull/AnalysisArtifacts/CombinedReview in the app’s user Application Support directory. Exact input retention can save the request rasters as PNGs under inputs/ for inspection. Compact retention can still keep masks needed for later processing. Cancel preserves completed work. Resume checks saved compatibility, file and model identities and artifact validity before reusing work. The Review Record window reads the same feature state and links findings to retained inputs and diagnostics. Work execution · Artifact store · Record window

6. Inspect an actual request in Xcode

Start with one photo, Standard depth and Retain exact inputs if you want to compare the UI’s evidence with the request raster after execution. Use a second run with multiple photos to reach the comparison branch.

Stop hereInspect
RawCullManagedBackgroundAssetsModelDownloadService.modelURL(for:), resource manager load(), or QwenInferenceRuntime.validate(url:)Installed URL, resolved bundle URL, package capability, constructed provider and model metadata.
CombinedReviewFeature.analyze and CombinedReviewLiveBackend.models(for:)Selected preset, frozen file URLs and fingerprints, qwen/sam/clip entries, and bundle hash or capability mismatch.
CombinedReviewFeature.validatedResponse and QwenInferenceRuntime.generateExact instruction, attachment dimensions, response token limit, trimmed raw response and validation or repair outcome. The methods in the execution file extend CombinedReviewFeature.
ObjectSegmentationService.segment and CoreAISAM3Provider.inferConcept, image and output sizes, tokenizer output, instance limit, scores and masks.
CoreAICLIPProvider.embedding(for:) and CombinedReviewLiveBackend.clipCriteria tokens, preprocessing configuration, embedding dimensions and cosine result.
CombinedReviewFeature.synthesize and ReviewArtifactStore.saveManifestIncluded evidence rows, allowed IDs, stored evidence references, limitations and terminal stage states.

For a concrete trace, set Review criteria to “judge how clearly the bird stands out.” If the overview returns a valid bird concept, follow it into SAM’s query tokenizer and inspect the returned instance. Follow the resulting subject and region IDs into the crop’s Qwen instruction. At the CLIP breakpoint the original criteria sentence goes into the text encoder. At synthesis, the same sentence is the goal and Qwen chooses among the admitted observation aliases. In the Review Record, trace the selected report claim back through its stored observation ID to the crop input.

The existing CombinedReviewFeatureTests use an injected backend to drive Full, comparison, preset admission and saved-run behavior without installed model packs. For app orchestration debugging, start with ReviewFakeBackend.respond and the test “full preset keeps every stage and saved runs without a preset load as full.” The live breakpoints above cover package inference. Review feature tests

The app also has opt-in Qwen capture via the RAWCULL_AI_CAPTURE_DIR environment variable. Point it to a private directory with no group or other permission bits. For each captured response it writes a PNG of the request raster and JSON with bounded instruction and response text, dimensions, response-token limit and input capabilities. The PNG is taken before backend preprocessing. Compare it with the retained Review input when debugging crop geometry, and inspect the backend separately for encoder tensors. The capture contains photo pixels and request text. Diagnostic capture

For the surrounding lifecycle, see AI Runtime. For the record UI and retention controls, see AI Models in RawCull. For the provider contracts, see PhotoAIKit Architecture.

15.3 - AI Models in RawCull

Review presets, model requirements, findings, saved evidence, decision controls and CLIP indexing in RawCull.

AI models in RawCull

Open Review from the toolbar to inspect a shortlist. Choose Selected or Tagged, select a preset, then click Review. The selected input must contain one to eight photos. If no grid items are explicitly selected, the focused visible photo can supply the input. Tagged input uses ratings of two or more in the active scope. To assess the top frames across the catalog’s ranked bursts, use Assess All Bursts on the burst list. Burst Groups

Choose a Review preset

PresetRequired modelWhat the run produces
Focus checkSAM 3Segments the generic subject prompt, registers available masks against the source and measures detail within usable foreground. CLIP can add relevance to the review criteria when available. This preset runs without Qwen.
DescribeQwen3-VLOne whole-photo overview per image. The run finishes after the overview, so expect no region crops or masked measurements.
FullQwen3-VLStarts with the overview, uses its concepts for SAM 3 when available, measures registered subjects and inspects crops within the depth budget. Reconciliation and report stages preserve evidence, omissions and conflicts. Multiple images also schedule a selection comparison. Missing optional models limit what the report can establish.

Describe and Full require at least 16 GB of unified memory. Below 32 GB the app displays a memory advisory. Review starts with Full on eligible machines and switches to Focus check when Qwen presets are disabled for memory. Enter nonblank criteria of at most 512 UTF-8 bytes. Review checks that the chosen preview or RAW-detail source works across the selection. Model availability is checked for the chosen preset when the run starts. ReviewRunContract · CombinedReviewFeature · CombinedReviewLiveBackend

Select Full, then click Review to start. For the call path and model inputs, see Full Review execution.

Read a result

The photo stays in place as you inspect the findings. During a run, the card on the photo shows the current step and progress. Select a finding to see its crop and highlight its region when region evidence exists. Region details shows the subject, crop geometry and provenance. The up and down arrows move between findings and Escape goes back one level. The layer controls below the photo show regions, subject masks and crop geometry.

Open Coverage & limits to see what the run could establish. For example, a mask touching the image edge may represent only part of a subject. A head-shaped region alone cannot establish eye sharpness. A crop omitted because the depth budget ran out has no crop observation. If synthesis fails, read the surviving observations as individual findings. The separate Review Record window follows the selected result and also exposes the technical record, JSON copy action and task history. CombinedReviewView · CombinedReviewInspectorPane · CombinedReviewRecordWindow · CombinedReviewLimitDigest

Follow a finding back to its pixels

A Full run records whether it used an embedded camera preview, a developed RAW or an ordinary raster. The overview is bounded to 2048 pixels on the long side by default. Review records the dimensions and orientation of the source used to cut a crop. It keeps the requested, padded, source and encoder-retained rectangles separately. Inspect exact crop can open the retained input when available. This matters on a small subject near the frame edge, where a source region, the visible foreground and the pixels supplied to the encoder can cover different areas. ReviewImageSource · CombinedReviewInspectorPane

For masked detail, Review loads the technical render, checks alignment against the appearance render, and requires the mask dimensions to match. A valid camera AF point can add evidence about the focus location. If alignment fails or the foreground is unusable, read the resulting limitation before interpreting a focus claim. The detail value depends on the render, with no calibrated sharp/blur threshold. A high CLIP relevance score describes a match to the criteria and cannot qualify an eye as sharp. CombinedReviewExecution

Apply a decision

Reading or reopening a result leaves culling decisions untouched. Tag sets two stars. Untag removes a two-star record. A photo with three to five stars shows a disabled Tagged button so using it cannot erase those stars. Use the rating controls to change them. Mark Reviewed applies to the burst containing the photo and appears when the photo maps to exactly one burst in the active scope.

The decision bar resolves the saved photo against the open, editable catalog and checks its on-disk fingerprint at the time of the action. Scanning, pending shutdown, an unavailable ratings store, duplicate filenames or a changed file can prevent an edit. Ratings use filenames as keys, so duplicate names make the target ambiguous. ReviewDecisionActions · CombinedReviewDecisionBar

Rating keys

With the result active, X rejects, P or 0 marks a keeper, 1 or 2 assigns two stars, 3 or T assigns three, and 4 or 5 assigns the corresponding stars. A text field or other control that owns the keystroke keeps it. The action targets the displayed result after the same live-file checks as the buttons. ImageReviewPolicies · CombinedReviewView

Where the subject outline comes from

Focus check and Full can supply the thumbnail mask badge and the S outline in loupe, zoom and the burst workspace. For the last displayed result matching the standardized photo URL, RawCull prefers an available primary-candidate mask with a retained input key, then the highest-confidence usable mask. Loading the image checks the file fingerprint again. Clearing retained inputs can leave a readable report with no drawable mask. Describe supplies no subject masks. ReviewSubjectMasks · ImageReviewSubjectOutlineLoader

Saved runs and repeatability

The snapshot freezes the preset, files, source preference, criteria, depth, model identities, stage versions and retention choices. The manifest tracks work and dependencies. Focus check starts with source and identity work, Describe with source and overview, and Full adds report work and, for a selection, comparison. Discovered subjects and crop regions add work as the run progresses.

An interrupted run can retain completed evidence. Resume revalidates the saved source fingerprints, model snapshots, pipeline contract and stored artifacts. A historical run without a preset decodes as Full and uses the earlier Full compatibility keys. After relaunch, RawCull restores the latest manifest and task history. The photo picker draws from results held in memory. Resume reconstructs results for a compatible run and reuses valid stage artifacts. If the original photo has changed, the saved task history remains available. When there is no displayed photo result, open Run history & diagnostics in the Review workspace. Clear retained inputs removes stored images. Clear rejected responses removes optional response diagnostics. CombinedReviewFeature+Manifest · CombinedReviewExecution · ReviewRunContract

When resuming, the store checks the stage’s compatibility and that any mask inputs referenced by a segmentation artifact still exist. Evicting a referenced mask makes that stage ineligible for reuse. The historical report can still explain what the earlier run observed. ReviewArtifactStore · ReviewRunContractTests

How CLIP Works in RawCull

CLIP places images and text in a shared vector space. RawCull uses that property in three ways: image-to-image distance, text-to-image semantic search, and a small closed-set subject-label pass that helps choose SAM prompts.

Provider construction and identity

PhotoAIKit’s CoreAICLIPProvider is an actor implementing image embedding, artifact generation/comparison, text embedding, and image/text comparison. During initialization it:

  1. validates the supplied model bundle;
  2. derives a ModelIdentity and asset fingerprint;
  3. decodes model-specific preprocessing, tokenizer, function-name, normalization, and configuration metadata; and
  4. exposes a SimilarityBackendDescriptor containing all compatibility-critical versions.

The descriptor is effectively the type identity of an embedding on disk. It records backend, model fingerprint, representation, preprocessing, normalization, and configuration versions. Image artifacts additionally record vector dimensions, schema version, and a source fingerprint. Consequently, RawCull does not compare a DataComp vector with an OpenAI vector, reuse an artifact after preprocessing changes, or silently treat an edited source file as unchanged.

Image preprocessing and inference

RawCullSimilarityImageDecoder first asks RawParserKitImageLoader for a bounded thumbnail. If that fails it attempts an ImageIO thumbnail without requesting a full fallback decode. The resulting CGImage is passed through the model-specific preprocessing declared by the CLIP bundle. Current metadata supports either the legacy stretch/bilinear path or shortest-side resize plus square center crop with bicubic interpolation and configured RGB mean/standard deviation.

The provider lazily loads Core AI functions and tokenizer resources. The image function receives the prepared image tensor and, if required by the exported graph, dummy text inputs. Its output is flattened, checked against the expected dimension, wrapped in an ImageEmbedding, JSON-encoded, and stored in a SimilarityArtifact. The backend descriptor records the bundle’s declared normalization version; image/text comparison later verifies that the image vector actually has approximately unit magnitude.

Indexing and recovery

RawCullCLIPSimilarityService uses PhotoAIKit’s bounded SimilarityArtifactIndexer with concurrency limit 1. CLIP inference is kept serial because the provider is actor-owned and model execution is resource intensive. There is no per-file or whole-batch Vision substitution during a CLIP pass.

For a non-finite vector, RawCullRecoveringCLIPArtifactProvider performs a targeted sequence:

  1. reject the invalid output;
  2. retry once with the already-loaded provider;
  3. construct a fresh provider from the same validated model location;
  4. verify that the replacement descriptor is exactly the same; and
  5. retry once with the replacement.

Successful CLIP artifacts from other files are retained. A file that still fails is reported and remains unindexed; it is not given a Vision artifact that would make the batch heterogeneous. Decode failures and inference failures are recorded separately for diagnostics.

Image similarity and burst grouping

For compatible normalized image embeddings, PhotoAIKit returns cosine distance. SimilarityScoringModel owns the artifact dictionary and computes distances from an anchor. It can apply a small RawCull-owned subject-label mismatch penalty, then uses those distances as input to ranking and burst grouping.

This responsibility split is deliberate:

  • CLIP defines the vector and mathematical comparison;
  • PhotoAIKit defines artifact compatibility and indexing mechanics; and
  • RawCull defines catalog admission, grouping thresholds, ordering, progress, persistence, and culling policy.

Vision remains the runtime fallback when CLIP is disabled or cannot be validated. Vision and CLIP artifacts are both descriptor-bearing, so switching backends causes incompatible state to be rejected or rehydrated rather than misinterpreted.

Semantic search never indexes missing images as a side effect. It operates only on already-persisted, descriptor-compatible CLIP image artifacts:

flowchart LR
    Query["Text query"] --> Tokens["CLIP tokenizer"]
    Tokens --> TextModel["CLIP text function"]
    TextModel --> TextVector["Validated normalized text vector"]
    Images["Compatible cached image artifacts"] --> Compare["Dot product / cosine similarity"]
    TextVector --> Compare
    Compare --> Sort["Descending score with deterministic tie breaks"]

RawCullCLIPSemanticSearchService trims and validates the query, filters image artifacts by the complete backend descriptor, generates one transient text embedding, and scores each compatible image. Because both vectors are normalized, their dot product is cosine similarity. Valid scores lie in -1...1; they are relative ranking values, not confidence percentages.

Sorting is deterministic: score descending, then original catalog order, localized filename, and UUID. Individual malformed artifacts become per-file failures rather than aborting every valid result. Text embeddings are scoped to one search and are not persisted.

Earlier model evaluations

The September puffin tests exercised the former Objects workflow. All 16 runs produced the expected board IDs, yet visual inspection found swapped bird descriptions and a wrong bird count. Those observations explain why a valid structured response still needs photographic review. The archived guide preserves the fixtures, timings and evidence limits for that workflow. September evaluation

15.4 - The RawCull AI Runtime

Runtime ownership, model activation, preset admission, inference sharing and Vision scheduling in RawCull.

The RawCull AI runtime

RawCullApplicationState.live() assembles the catalog workspace and long-lived intelligence services. RawCullApp holds the view model and intelligence runtime in SwiftUI state. The main view receives the similarity, semantic search, settings and Review features explicitly. The executable still uses the name CombinedReviewFeature for the feature behind the Review toolbar item. RawCullApp · RawCullIntelligenceRuntime

LifetimeOwnerWhat it owns
AppRawCullAIModelRuntimeValidated CLIP and SAM providers, Vision similarity, subject-mask stores and the Qwen inference actor
AppRawCullIntelligenceRuntimeSimilarity and semantic search features, Review, settings and downloads, configuration revision, and Review Record navigation
App sessionBurstBatchAssessment and AIAssessmentNavigationQwen batch task, its progress and the burst entries shown in AI Assessments
Review runCombinedReviewFeatureFrozen inputs, model snapshots, task and lease, evidence, manifest and optional retained inputs
Displayed Review resultsReviewSubjectMasksLookup of a primary or highest-confidence retained mask for a catalog photo. Image loads verify the photo fingerprint.

From settings to a running Review

  1. Settings validates installed model locations and publishes a complete configuration. The runtime compares its revision with the last accepted revision. Equal or older revisions leave the active services in place.
  2. A newer revision with identical descriptors advances the revision alone. Changes to similarity or semantic identity replace those services independently. A segmentation change selects the provider through the model runtime.
  3. The Review backend factory reads the currently available Qwen URL, the SAM object-instance segmenter, and the CLIP provider and location. The preset determines which model snapshots the run requests. Qwen validation checks encoder capability and bundle identity for a Qwen preset. Focus check can construct a backend with no Qwen URL.
  4. After admission, the feature holds the shared lease, retains access to selected files, freezes their fingerprints and persists the initial work manifest. Resume uses the original snapshot. A provider or file change can make work incompatible.
  5. The record window reads the same feature and navigation selection as the main workspace. Opening it does not create another run. The old SAM/CLIP, Qwen and Objects tab controllers have been removed. At startup the model runtime attempts to remove the obsolete Objects mask directory.

RawCullAIModelRuntime · CombinedReviewLiveBackend · CombinedReviewFeature · CombinedReviewRecordWindow

For a debugger walkthrough of Full, including the precise instruction and pixel inputs at each provider boundary, see Full Review execution.

Startup Refresh and Installed-Model Activation

The graph is usable immediately with Vision while disk checks happen later. The main window attaches the settings refresh to its root view:

.task {
    await intelligenceRuntime.settingsModel.refresh()
}

The call path is:

sequenceDiagram
    participant View as RawCullMainView
    participant Settings as RawCullAISettingsModel
    participant Downloads as RawCullAIModelDownloadsModel
    participant Models as RawCullAIModelRuntime
    participant Resource as Resource-manager actors
    participant Runtime as RawCullIntelligenceRuntime

    View->>Settings: refresh()
    Settings->>Downloads: refresh()
    Downloads-->>Settings: applyManagedModelLocations(snapshot)
    Settings->>Models: applyManagedModelLocations(snapshot)
    Models->>Models: validate or clear Qwen
    Models-->>Settings: Qwen status
    par model validation
        Settings->>Models: refreshCapabilities()
        Models->>Resource: load SAM 3 and both CLIP choices
    and saved evidence
        Settings->>Settings: scan burst caches
    end
    Models-->>Settings: capabilities
    Settings->>Runtime: apply(revisioned configuration)
    Runtime-->>Settings: current capabilities

One complete location snapshot

applyManagedModelLocations(_:) is the only activation path for a complete set of installed locations. It gives the current SAM and CLIP URLs to their resource managers. A missing Qwen URL calls qwenInference.clear(); a present URL is standardized and validated.

Using a complete snapshot avoids a transient mixture such as “new CLIP, old SAM, removed Qwen still active.” Every invocation describes one model-install state.

Generation-gated refresh

Settings increments refreshGeneration before beginning work. The generation is checked after Qwen validation and after the concurrent capability/evidence work. A later refresh therefore supersedes an earlier one; the earlier result cannot publish merely because its disk work finished last.

The defer that clears isScanningSavedBurstData also checks the generation, so an obsolete refresh cannot hide the current refresh’s progress indicator.

Concurrent capability validation

RawCullAIModelRuntime.refreshCapabilities() starts SAM 3, DataComp CLIP, and OpenAI CLIP loads with async let. Each resource-manager actor computes a lightweight recursive metadata snapshot. When unchanged, the previous validated capability/provider result is reused. When changed, PhotoAIKit validates the bundle and constructs a provider.

After all three complete, the main-actor runtime atomically replaces its provider dictionaries and resolved location dictionaries, translates package statuses into RawCull statuses, builds semantic-search readiness separately, stores one new capability snapshot, and activates the selected segmentation provider.

Capability State Is More Than “Loaded”

RawCullAICapabilityStatus distinguishes:

StateMeaning
checking(expectedLocations:)Validation is pending.
available(location:)Bundle validation and provider construction succeeded, or an always-available service such as Vision is ready.
missing(expectedLocations:)No candidate bundle was found.
invalid(location:reason:)A candidate exists but validation or provider construction failed.
unavailable(reason:)The runtime cannot offer the capability for another explicit reason.

CLIP model availability and semantic-search readiness are separate. A provider must expose the text/image contracts before semantic search is .ready. Vision remains a valid similarity service but can never satisfy semantic text search.

Qwen uses an internal QwenModelStatus with not-configured, checking, available, missing, and invalid states. Settings translates it to the common capability presentation and retains the validated Qwen status for the Review backend factory.

Resource Managers and Their Cache

RawCullAIModelResourceManager<Provider> is an actor because filesystem inspection, cryptographic bundle validation, and provider initialization must not run on the main actor or race with a managed-location change.

The resource cache has two keys:

  • RawCullAIModelResourceSnapshot, a sorted list of path, file kind, byte count, modification time, and symlink target; and
  • the resulting capability, optional provider, and optional provider-init failure.

setManagedCandidateURL invalidates both when the URL changes. load() also detects modifications within the same directory. The snapshot only decides whether validation may be reused. PhotoAIKit’s resolver remains responsible for metadata, required files, asset extension, fingerprint, and checksum validity.

Bundle validity and provider construction are reported separately. A bundle can be structurally valid yet fail to initialize its concrete runtime; RawCull maps that case to .invalid with the provider error so Settings can explain the actual stage that failed.

Selecting the Similarity Runtime

RawCullAIModelRuntime.similarityService(prefersCLIP:clipModel:) has a strict selection order:

  1. If the user disabled CLIP, return the existing Vision service.
  2. If the selected CLIP provider is absent, log the expected/resolved path and return Vision.
  3. If the provider exists but its resolved location is missing, return Vision.
  4. Otherwise return a new RawCullCLIPSimilarityService around the validated provider and supply a factory that can reconstruct a provider from the exact validated location for finite-vector recovery.

The service value can change while RawCullSimilarityFeature and SimilarityScoringModel retain their identities. Backend descriptors determine whether existing artifacts are still compatible.

Semantic search is constructed only from a currently validated CLIP provider. The provider itself satisfies both TextEmbeddingProviding and ImageTextSimilarityComparing, so RawCullCLIPSemanticSearchService can use the same model identity as the cached image embeddings.

Model identity at Review admission

The live Review backend accepts Qwen when the installed bundle hash and encoder contract match its expected configuration: a 448 × 448 stretch input, 196 image tokens and a 4096-token context. For CLIP it recognizes two bundle hashes and records the corresponding 224- or 256-pixel encoder geometry. An unrecognized CLIP hash leaves Review without CLIP relevance. The SAM entry records the segmenter identity and source-normalized mask preprocessing. A preset requests only its participating models. For example, Focus check skips Qwen bundle hashing entirely. CombinedReviewLiveBackend

The backend also stores a runtime-version string containing historical abbreviated revisions and the OS version. That string participates in saved evidence identity. Use the application lockfile for the actual Swift package revisions in this build.

Qwen model lifetime

Validation cancels active generation, advances the model generation, checks vision modality and retains a provider. The first request lazily constructs the vision-language model. Subsequent requests can reuse that model, each with a fresh session. A generation gate limits responses to one at a time. A request waiting for its turn rechecks its captured generation after admission. After model loading and response generation the actor checks cancellation and generation again before publishing text. QwenInferenceRuntime

Shared inference and Vision scheduling

The app creates one Qwen inference actor. Review uses it through its live backend. The in-app burst batch and MCP follow-ups use the structured assessment interface. The latter binds work to a model generation and validates the requested findings before publication. The shared Review lease coordinates exclusive work within the app. MCP also has a cross-process worker lock and authorization checks for shared jobs. An in-app batch writes session entries using the open catalog’s access. MCP results use the job’s catalog grant. QwenInferenceRuntime · BurstBatchAssessment · MCPAnalysisController+FollowUp

Vision similarity has a different scheduling constraint. RawCull injects RawCullVisionWorkSerializer into its feature-print backend. That adapter forwards Vision request bodies to PhotoAnalysisKit’s process-wide serial queue. Waiting tasks suspend while the queue executes the blocking Vision request. Image decoding can proceed concurrently. Concurrency

For preset requirements, evidence limits and culling actions, see AI Models in RawCull.

16 - RawCull Packages

Pinned package revisions, imported products, dependency direction, and the recommended architecture reading order.

RawCull Packages

Start here: One Package, Three Imports: Understanding Swift Modules explains packages, products, targets and imports using PhotoEvidenceKit before you read the individual package architecture guides.

RawCull is the composition root for five architecture packages and four small rsync/persistence support packages. Package repositories are separately versioned; paths under Sources/ and Tests/ refer to the named repository, not files copied into this documentation site. The app translates between package contracts and owns selection, file access, caches, persistence, and review decisions.

The November 8, 2026 review uses RawCull 3.4.0 build 434. Existing guides retain their explicitly dated architecture audits and add current integration notes. PhotoEvidenceKit has a new guide covering the resolved 1.0.7 implementation. Sibling checkout HEADs do not redefine the application’s resolved baseline.

Build 466 resolved dependencies

The application lockfile records 24 remote pins. Since build 462, PhotoAIKit moved from 1.0.0 to 3.1.0 and PhotoAnalysisKit from 1.3.9 to 1.4.1. PhotoEvidenceKit changed its repository URL from SSH to HTTPS at the same version and revision. The MCP helper has a separate package graph. Application lockfile · MCP helper lockfile

IdentityVersionRevision
coreai-models1.0.05de95c6cd29e5e390fb36d87e13b2396668f7974
decodeencodegeneric1.0.0b5ecbbbe1b244191efec1532a979f6ae342d6617
eventsource1.6.0bb4b61273b5a976bb571859c17f903ebc3439df1
parsersyncoutput1.0.0e079e0c9d34bf07f7f2a4312b40feea79ae14847
photoaikit3.1.026647c62d9933968d92bd00b162290cdd7c78fee
photoanalysiskit1.4.12f41e8b756f006e0218f86b103801ebb47cf8983
photoevidencekit1.1.5e49d34adcfa2e2c43a4240c2e962dbe9defa4cad
rawcullcore1.1.5ea8ac2fc6611949af2b55ec433456bfe502cf886
rawparserkit1.3.326df4abc2178d5c07d08f3883d84d0648f5141d3
rsyncarguments1.0.00ff6518136c208dfbecc1a918f045048ca79853d
rsyncprocessstreaming1.0.0dd86f012b352888fd146e0b6e103740dc237f740
swift-asn11.7.4917b472dbe53ba699cbb0495f9a95a084bc6364d
swift-atomics1.3.10442cb5a3f98ab802acb777929fdb446bda11a34
swift-collections1.7.5f96b909e1a9e469620bc5037c1e24e00153f376f
swift-crypto4.5.2da9d28d69ebe3894b18376c8f2395c2f37b8448f
swift-huggingface1.0.0c30143a4616f3fa994ee3ab3e3464f752845c07c
swift-jinja3.0.0a091d6ae559ee97e904a0f3c2890b21949d0306f
swift-log1.17.0e3da04078777e6a1b72ce19981fbd6539b0847d8
swift-nio2.105.02f58d8ef84438d6517fc78bcea2f8527e3c72936
swift-sdk0.12.1a0ae212ebf6eab5f754c3129608bc5557637e605
swift-system1.8.1869129b7bf4ecc57b97d0193ad29690ca2134750
swift-transformers1.4.0402a8a1105f52038b0949d9596981fc9e32bed17
xgrammar0.2.24d145cc13d878c751ebeed36af1c013074be76bc
yyjson0.13.06447536015f3d600f3d65323b10976103b337ca7

November 9 Close Up Development Build

At the November 9 review, the version-3.4.5 branch used two local package references. Its source baseline is RawCull 3.4.5, build 436, commit a68253b73cbad14a7b1030dba6b439e6bce7d3da. The revisions identify the sibling checkouts used to verify the integration.

PackageXcode pathCheckout revisionClose Up responsibility
PhotoAnalysisKit../PhotoAnalysisKit27d422b100214dd1520f7ca11123f58a86f04e99Human face rectangles and preview detail
PhotoEvidenceKit../PhotoEvidenceKit35e8aca4135ac2151cbce033e4e9baefb8bafabcCrop rendering and manual inspection UI

The animal head and eye pilot lives in RawCull and uses Apple’s Vision framework. It required no package release or dependency update. The November 8 table below is the historical remote snapshot. Build 436 retains the other 17 entries at their recorded revisions. See the Close Up guide for the workflow and the distinction between detected and manual crops.

November 8 Resolved Dependency Snapshot

This table is derived from the local RawCull RawCull.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved, reviewed November 8, 2026 alongside project.pbxproj and source imports. “App” means RawCull directly consumes package products; “transitive” means a package owns the dependency. There are 19 resolved entries.

IdentityRelationshipVersion/branchRevision
DecodeEncodeGenericapp1.0.0b5ecbbbe1b244191efec1532a979f6ae342d6617
ParseRsyncOutputapp1.0.0e079e0c9d34bf07f7f2a4312b40feea79ae14847
PhotoAIKitapp1.0.04b85056e6c2603b5e382987710ca2f16f4c5c155
PhotoAnalysisKitapp1.3.12a1466e04d821fa2628d6985296643e0d0c7e465
PhotoEvidenceKitapp1.0.77614fd1528bb7cf2549799fb937678ea39d90228
RawCullCoreapp1.1.2d25a51e65ad32a82bf82f86fa0ec07d6e14498e9
RawParserKitapp1.3.326df4abc2178d5c07d08f3883d84d0648f5141d3
RsyncArgumentsapp1.0.00ff6518136c208dfbecc1a918f045048ca79853d
RsyncProcessStreamingapp1.0.0dd86f012b352888fd146e0b6e103740dc237f740
coreai-modelstransitive1.0.05de95c6cd29e5e390fb36d87e13b2396668f7974
EventSourcetransitive1.6.0bb4b61273b5a976bb571859c17f903ebc3439df1
swift-asn1transitive1.7.4917b472dbe53ba699cbb0495f9a95a084bc6364d
swift-collectionstransitive1.7.5f96b909e1a9e469620bc5037c1e24e00153f376f
swift-cryptotransitive4.5.2da9d28d69ebe3894b18376c8f2395c2f37b8448f
swift-huggingfacetransitive1.0.0c30143a4616f3fa994ee3ab3e3464f752845c07c
swift-jinjatransitive3.0.0a091d6ae559ee97e904a0f3c2890b21949d0306f
swift-transformerstransitive1.4.0402a8a1105f52038b0949d9596981fc9e32bed17
xgrammartransitive0.2.24d145cc13d878c751ebeed36af1c013074be76bc
yyjsontransitive0.13.06447536015f3d600f3d65323b10976103b337ca7

Do not infer the app boundary from every transitive pin. Xcode product references and source imports define what RawCull actually consumes.

Imported Products And Boundary Types

PackageProducts imported by RawCullValues or protocols crossing the boundary
RawParserKitRawParserKitRawImageLoader, RawImageMetadata, RawFocusPoint, RawFormatRegistry, CGImage results; the app maps them through RawParserKitImageLoader
PhotoAnalysisKitPhotoAnalysisKitPhotoAnalyzer, PhotoAnalysisInput, PhotoAnalysisDescriptor, PhotoAnalysisResult, focus evidence and mask values
RawCullCoreRawCullCoreRawCullFileItem, RawCullSourceCatalog, ExifMetadata, burst inputs/results/configurations, ranking evidence, histograms; the app exposes compatibility typealiases such as FileItem
PhotoAIKitPhotoAIContracts, CoreAICLIPBackend, CoreAIQwenBackend, CoreAISAM3Backend, CoreAIEfficientSAMBackend, VisionFeaturePrintBackend, PhotoAIWorkflows, PhotoAIStorageAIImageSource, model identities/resources, similarity artifacts/descriptors, provider protocols, segmentation requests/results, mask stores and workflows
PhotoEvidenceKitPhotoEvidenceContracts, PhotoEvidenceEngine, PhotoEvidenceUICloseUpFrame, region/viewport/source descriptors, AF availability, renderer and region-store protocols, CloseUpModel, CloseUpPanel
RsyncArgumentsRsyncArgumentsrsync argument builders used by Params and ArgumentsSynchronize
RsyncProcessStreamingRsyncProcessStreamingRsyncProcess and ProcessHandlers used by the copy executor
ParseRsyncOutputParseRsyncOutputparsed transfer progress and totals used by RemoteDataNumbers
DecodeEncodeGenericDecodeEncodeGenericgeneric JSON encode/decode used by saved-file persistence

RawCull owns the translations between these vocabularies. None of the five architecture packages imports another merely to share an app model.

Dependency Direction

flowchart TD
    UI["RawCull SwiftUI"] --> Host["RawCull composition, adapters, policy, persistence"]
    Host --> Parser["RawParserKit\nRAW decode + normalized metadata"]
    Host --> Analysis["PhotoAnalysisKit\nmeasurements + masks"]
    Host --> AI["PhotoAIKit products\nAI contracts + backends + workflows"]
    Host --> Core["RawCullCore\npure grouping + ranking"]
    Host --> Evidence["PhotoEvidenceKit products\nmanual close-up inspection"]
    Host --> Args["RsyncArguments"]
    Host --> Process["RsyncProcessStreaming"]
    Host --> Output["ParseRsyncOutput"]
    Host --> JSON["DecodeEncodeGeneric"]
    Parser -. "app adapter" .-> Core
    Analysis -. "app adapter" .-> Core
    AI -. "app adapter" .-> Core

Solid arrows are compile-time imports by the app. Dotted arrows are value translation performed by RawCull, not package dependencies.

The three rsync support packages do not depend on one another. RawCull connects argument building, process execution and streamed-output parsing in its copy workflow. The runtime sequence is not a package import chain.

  1. RawParserKit — a file becomes an orientation-normalized image and neutral metadata.
  2. PhotoAnalysisKit — a decoded image becomes sharpness, saliency, focus evidence, and masks.
  3. RawCullCore — measurements become burst boundaries, recommendations, and review state.
  4. PhotoAIKit — optional CLIP similarity/semantic search and segmentation run behind typed contracts.
  5. PhotoEvidenceKit — manual regions, retained references, source-labeled crops, and optional recorded AF-point assistance.
  6. Return to the app pages to see RawCull compose those independent boundaries, persist results, and present policy.

When a package pin changes, compare its manifest and public source at the new resolved revision before updating this documentation. A sibling checkout may be ahead of the revision RawCull actually builds.

November 8 Dependency Delta

Compared with the October 31 snapshot, PhotoEvidenceKit is newly resolved at 1.0.7. EventSource moves from 1.5.1 to 1.6.0, swift-asn1 from 1.7.3 to 1.7.4, swift-collections from 1.7.3 to 1.7.5, swift-jinja from 2.5.1 to 3.0.0, swift-transformers from 1.3.5 to 1.4.0, and yyjson from 0.12.0 to 0.13.0. The eight previously direct package pins and the other transitive pins retain the revisions recorded in the October 31 table.

The Xcode project also lists PhotoEvidenceDemo, the package’s executable example, as a product reference. RawCull source imports the three library products above; the demo is not a fourth library API.

End-to-End Ownership

StepPackage outputRawCull responsibility
DecodeRawParserKit image and metadataRetain sandbox access, select preview/development policy, cache decoded work
MeasurePhotoAnalysisKit scores, evidence, masksCombine source identity with analysis descriptor and reject stale results
InferPhotoAIKit embeddings, semantic results, segmentationInstall models, admit requests, choose fallback and publish current results
RecommendRawCullCore grouping and ranking valuesSupply ordered inputs and evidence; preserve photographer decisions
InspectPhotoEvidenceKit crops and session stateSupply truthful source labels, file/settings revisions, AF mapping and region storage

PhotoEvidenceKit consumes host-rendered images through an injected renderer. It does not import the decoder, analysis, AI, or ranking packages. A close-up can help a photographer evaluate a recommendation without becoming new ranking evidence automatically. See the individual guides for invalidation and failure behavior at each boundary.

16.1 - One Package, Three Imports: Understanding Swift Modules

Learn how Swift packages, products, targets, modules, imports, and linking fit together using PhotoEvidenceKit as a concrete example.

One Package, Three Imports: Understanding Swift Modules

PhotoEvidenceKit is one package containing three library modules. That is why RawCull can contain these three imports:

import PhotoEvidenceContracts
import PhotoEvidenceEngine
import PhotoEvidenceUI

Each import names a module. PhotoEvidenceKit is the package name, but this package does not define a module with that name. Consequently, adding the package to Xcode does not make import PhotoEvidenceKit valid.

This guide uses the actual PhotoEvidenceKit manifest at the RawCull-resolved 1.0.7 revision. Alternative designs later in this guide are teaching examples, not changes made to that package.

1. The Names Describe Different Things

TermMeaning in this exampleWhere it appears
RepositoryThe Git repository containing the packageGitHub URL and checkout directory
PackageThe overall SwiftPM definition, named PhotoEvidenceKitPackage(name: ...) in Package.swift
ProductA library or executable offered to consumersThe manifest’s products array and Xcode’s product selection
TargetA build unit with source files, dependencies and settingsThe manifest’s targets array
ModuleThe namespace and access-control boundary compiled from a regular Swift library targetimport PhotoEvidenceContracts, for example
Source fileOne contribution to a target’s moduleSources/PhotoEvidenceContracts/CloseUpContracts.swift

In this package, each library product and its target have the same name. That makes integration convenient, but it can hide the difference between selecting a product and importing a module. SwiftPM’s Product documentation explains that a product is assembled from build artifacts of one or more targets. A product name does not itself create a new module.

Think of the package as the complete distribution, products as the choices offered to its consumer, and targets as the units that actually build the code. They do not have to share a name.

2. Read The Real Manifest From The Outside In

The beginning of the manifest declares the tools version, imports the manifest API, and creates the package description:

// swift-tools-version: 6.2
import PackageDescription

let package = Package(
    name: "PhotoEvidenceKit",
    // products, targets, platform and language settings follow
)

This is a shortened excerpt. import PackageDescription is used while evaluating the manifest. It does not become an application import or add PackageDescription to the photo-inspection runtime.

The package name identifies the whole package. It does not instruct SwiftPM to collect all source files into a PhotoEvidenceKit module.

Products: What Consumers Can Select

The actual library product declarations are:

.library(name: "PhotoEvidenceContracts", targets: ["PhotoEvidenceContracts"]),
.library(name: "PhotoEvidenceEngine", targets: ["PhotoEvidenceEngine"]),
.library(name: "PhotoEvidenceUI", targets: ["PhotoEvidenceUI"]),

Each exposes one same-named target as a library product. There is also an executable product, PhotoEvidenceDemo, for running the synthetic example. The demo is not a fourth library that a host should import to display close-ups.

Targets: What Gets Compiled And What It May Depend On

The three library targets are declared as:

.target(name: "PhotoEvidenceContracts"),
.target(name: "PhotoEvidenceEngine", dependencies: ["PhotoEvidenceContracts"]),
.target(name: "PhotoEvidenceUI", dependencies: ["PhotoEvidenceContracts", "PhotoEvidenceEngine"]),

The first target has no dependencies on another target in this package. Engine can use Contracts, while UI can use both Contracts and Engine. There are no external package dependencies in this manifest. Apple frameworks such as Foundation, CoreGraphics and SwiftUI are SDK modules used by source files, rather than downloaded Swift package dependencies.

These declarations establish the build graph. They are not an instruction to insert import statements into every source file.

3. How Folders Become Importable Modules

For these regular targets, SwiftPM uses the conventional source directories:

PhotoEvidenceKit/
├── Package.swift
├── Sources/
│   ├── PhotoEvidenceContracts/
│   │   ├── CloseUpContracts.swift
│   │   ├── CloseUpRenderSource.swift
│   │   └── CloseUpAFPoint.swift
│   ├── PhotoEvidenceEngine/
│   │   ├── CloseUpCropGeometry.swift
│   │   ├── CloseUpRasterizer.swift
│   │   └── CloseUpRendering.swift
│   └── PhotoEvidenceUI/
│       ├── CloseUpModel.swift
│       ├── CloseUpCardModel.swift
│       └── CloseUpPanel.swift
├── Examples/PhotoEvidenceDemo/
└── Tests/PhotoEvidenceKitTests/

The example executable has an explicit path in the manifest because it lives outside the default Sources/PhotoEvidenceDemo location.

All three files under Sources/PhotoEvidenceContracts contribute declarations to the same PhotoEvidenceContracts module. There is no import CloseUpContracts for the individual file. Source-file names organize the repository; the target determines the module boundary.

Similarly, a nested folder added inside a target does not automatically become another module. A separate target declaration and appropriate source layout are needed to create another regular Swift module. See SwiftPM’s Target documentation for the target’s role in compilation.

4. Follow The Build In Dependency Order

flowchart BT
    Contracts["PhotoEvidenceContracts\nframes, regions, requests, source identity"]
    Engine["PhotoEvidenceEngine\ngeometry, rasterizer, render protocol"]
    UI["PhotoEvidenceUI\nmodel, panel, card loading"]
    App["RawCull\nhost adapters and application policy"]
    Engine --> Contracts
    UI --> Contracts
    UI --> Engine
    App --> Contracts
    App --> Engine
    App --> UI

An arrow means “depends on.” Contracts can be compiled before Engine; UI needs the lower modules’ interfaces. The build system schedules work according to this graph and can reuse outputs when they remain valid.

Conceptually, the build proceeds through these stages:

  1. Resolve the package revision and evaluate its manifest.
  2. Locate source files and establish the required target dependencies.
  3. Compile each required module with its dependencies available.
  4. Produce module information for the compiler and object/library artifacts for linking, according to the build configuration.
  5. Compile the host’s source files against the modules it uses.
  6. Link the required executable code into the final application arrangement.

The exact artifact layout varies between Xcode and command-line builds. Three imports do not imply three separately downloaded packages, three runtime processes, or necessarily three dynamic frameworks. These .library declarations do not explicitly choose a static or dynamic library type.

An import is a compile-time language operation. It does not download the package, run the demo or instantiate a renderer.

5. Why Divide This Particular Package Into Three Modules?

The division follows three different responsibilities in the existing source. It makes those responsibilities enforceable through dependencies rather than relying only on folder names and developer convention.

Contracts: Agree On The Vocabulary

Contracts defines values such as CloseUpFrame, CloseUpRegion, CloseUpRequest, CloseUpRenderSource and CloseUpAFPoint, plus the CloseUpRegionStoring protocol.

For example, a frame identifies a source and its revision, while a request specifies the region and rendering source. A renderer and a view can exchange these values without either defining its own incompatible version.

This module uses Foundation and CoreGraphics, but it does not import SwiftUI or contain decoded image buffers. A client can use the region-record format without adopting the panel. “Contracts” describes a responsibility; it is not a special Swift keyword or a promise of permanent API stability.

Engine: Produce Inspection Pixels

Engine defines CloseUpRendering, CloseUpRender, crop geometry and rasterization. It imports Contracts because it needs the request and coordinate values.

A host can use CloseUpRasterizer with a custom user interface. The engine does not need to know which SwiftUI panel displays the resulting images, which photo is rated, or which RAW loader produced the source.

Notice that not every protocol is in Contracts. CloseUpRendering lives in Engine because it returns the engine’s image-bearing CloseUpRender. The division follows the actual API’s dependencies, rather than placing everything named “protocol” into the lowest module.

UI: Present And Coordinate Inspection

UI defines CloseUpPanel, CloseUpModel and its internal card model. It needs Contracts for frame/region values and Engine for rendering requests and results. It adds SwiftUI and Observation behavior on top of those lower layers.

This direction prevents a change in presentation from requiring the engine to import a view. If Contracts tried to depend on UI while UI already depended on Contracts, that would create a cycle. Shared low-level values must stay in a layer both higher-level components can depend on.

The split also creates access-control boundaries. For example, the actual CloseUpPanel and CloseUpModel are public, while CloseUpCardModel is internal to PhotoEvidenceUI. Moving everything into one module would remove those particular cross-module boundaries. Other access levels still apply within it.

6. Why Does A RawCull File Need All Three Imports?

Look at RawCull’s BurstCloseUpsView.swift. It performs several jobs at once:

Code used by the adapterDefining moduleImport
Frame, request and render-source valuesContractsimport PhotoEvidenceContracts
Rendering protocol, result and rasterizerEngineimport PhotoEvidenceEngine
Panel and session modelUIimport PhotoEvidenceUI

A file that merely handles saved-region values may need only Contracts. A custom renderer may need Contracts and Engine. The composition file uses declarations from all three, so it explicitly imports all three.

Imports apply to the source file containing them. Adding an import to another RawCull file does not provide that import to every file in the app target. Declarations in the app’s own module are a different matter: app files can refer to that module’s accessible declarations without importing each other by filename.

The dependency graph and source imports serve different purposes:

  • Target/product dependencies make required modules available to the build.
  • Source imports state which modules a particular file uses.
  • Access control determines which declarations that file may use across the module boundary.

An ordinary import PhotoEvidenceUI is not a designed umbrella export of all Contracts and Engine names. Do not rely on incidental transitive visibility. Import the modules that define the APIs your file directly uses. The current package provides no explicit PhotoEvidenceKit facade module.

7. Selecting Products In Xcode Or SwiftPM

In Xcode, adding the repository makes its products available for assignment to application targets. Select the library products the app directly consumes. Selecting UI also brings the lower target dependencies required to build UI; you do not separately download Contracts and Engine repositories.

For a Swift package consumer, the same distinction is explicit in its manifest. The following is an illustrative consumer configuration:

// In the consumer Package.swift, within Package(...):
dependencies: [
    .package(url: "https://github.com/rsyncOSX/PhotoEvidenceKit.git", from: "1.0.7")
],
targets: [
    .target(
        name: "MyInspectionFeature",
        dependencies: [
            .product(name: "PhotoEvidenceContracts", package: "PhotoEvidenceKit"),
            .product(name: "PhotoEvidenceEngine", package: "PhotoEvidenceKit"),
            .product(name: "PhotoEvidenceUI", package: "PhotoEvidenceKit")
        ]
    )
]

This excerpt belongs inside a complete manifest, not in a runtime Swift file. The package requirement permits compatible versions starting at 1.0.7; it is not an exact revision pin. The consumer’s resolution records the chosen revision. SwiftPM’s dependency guide describes package requirements and product dependencies separately.

Once configured, that consumer’s source files import the modules they use. Adding a product dependency alone does not create an import in their source text.

8. Why Not Offer Only import PhotoEvidenceKit?

It is possible. There are several designs, with different consequences.

Design A: Put Everything In One Target

The package could define one library product and one target, both named PhotoEvidenceKit, and move the three source groups into that target. Consumers would then use import PhotoEvidenceKit.

This reduces integration choices and can suit a small, cohesive library. However, Contracts, Engine and UI would share a module. A contracts-only consumer would consume that combined module, and the compiler would no longer enforce the current separation between those three internal layers.

Design B: Rename Only The Product

Suppose a maintainer instead changes the product declaration to:

.library(
    name: "PhotoEvidenceKit",
    targets: ["PhotoEvidenceContracts", "PhotoEvidenceEngine", "PhotoEvidenceUI"]
)

That offers one product containing multiple targets. It still does not create a PhotoEvidenceKit module. The module names remain the target names, so a single product selection alone does not deliver the desired single import.

Design C: Add A Facade Target

A fourth library target named PhotoEvidenceKit could depend on the three existing targets and expose a deliberate convenience API. Consumers of that facade could write import PhotoEvidenceKit, while advanced consumers could keep using the smaller modules.

The facade must actually provide the intended public API through wrappers, forwarding functions, public aliases or a consciously chosen export mechanism. An empty target that merely imports three dependencies does not automatically create a supported umbrella API for all their declarations. Export mechanisms also need language/toolchain review; underscored compiler features should not be presented as an ordinary stable-language recommendation.

The benefit is convenience. The cost is another API surface to design, document, test and maintain. A convenience name does not remove the underlying dependency graph or make all three lower layers independently unnecessary.

9. What This Design Buys, And What It Costs

AspectThree-module PhotoEvidenceKit design
ReuseContracts and Engine can be consumed without the SwiftUI panel
Dependency directionThe build graph enforces lower layers’ independence from UI
API boundariesCross-module use requires suitable access control
IntegrationConsumers choose products and write explicit module imports
MaintenanceMore target configuration and public boundary design
Build performanceDependencies can be reused independently, but module count alone guarantees no speedup
VersioningAll targets ship under the same package revision; three modules do not mean independent release versions

For PhotoEvidenceKit, the source demonstrates a useful boundary: describe an inspection, render it, then present it. Those steps can be reused separately. The decision is an architectural tradeoff, not a rule that every Swift package should have three modules.

10. Diagnose Import Problems By Checking The Correct Layer

SymptomCheck
No such module 'PhotoEvidenceKit'The package currently has no module with that name; use the actual module names
No such module 'PhotoEvidenceEngine'Product/target dependency, resolution, platform/toolchain requirements and successful dependency build
A type is unavailable in one fileThat file’s imports, the spelling of the type, its defining module and access level
Adding a folder did not create a new importA folder inside a target is not a new target/module
Linking fails after compilationRequired linked products/artifacts and target configuration; imports alone do not supply executable code

Start with the manifest, then identify the target owning the declaration, then inspect the consuming file’s imports. This follows the same structure the build system uses and avoids confusing a repository name with a module name.

Source Map

TopicPhotoEvidenceKit source
Package, products and targetsPackage.swift
Shared request and region valuesSources/PhotoEvidenceContracts/CloseUpContracts.swift
Engine imports and rendering boundarySources/PhotoEvidenceEngine/CloseUpRendering.swift
UI imports and public panelSources/PhotoEvidenceUI/CloseUpPanel.swift
Internal UI implementationSources/PhotoEvidenceUI/CloseUpCardModel.swift

Continue with How PhotoEvidenceKit Is Constructed for the detailed runtime contracts and RawCull integration, or return to the package catalog.

16.2 - How PhotoAIKit Is Constructed

A detailed guide to PhotoAIKit’s contracts, CLIP image and text inference, semantic comparison, SAM 3 and EfficientSAM, workflows, storage, concurrency, and model identity.

How PhotoAIKit Is Constructed

Revision scope: Updated against the RawCull dependency pin 4b85056e6c2603b5e382987710ca2f16f4c5c155 on 16 October 2026. The original walkthrough used 20e57359603313af7c2d38cae3e8b6e37f8838ef. Current application policy is described in AI Models in RawCull and AI Runtime.

PhotoAIKit is a reusable Swift package extracted from application code. Its most important achievement is not merely that CLIP, SAM 3, and EfficientSAM run. It is that reusable AI behavior has been separated from RawCull’s UI, RAW-file handling, paths, sandbox rules, and culling policy.

This document explains the construction from the bottom up and gives the reason for each boundary.

Build 466 integration

RawCull resolves PhotoAIKit 3.1.0. Its Vision feature-print backend accepts a VisionWorkSerializing instance and defaults to SerialVisionWorkQueue.shared in standalone clients. RawCull supplies an adapter to PhotoAnalysisKit’s Vision gate. This lets feature prints and measurement requests share a queue without adding a dependency between the packages. Review obtains SAM 3 instance segmentation and optional CLIP relevance through its live backend. The detailed walkthrough below describes the earlier audited revision. VisionWorkSerializing · CombinedReviewLiveBackend

For Full Review, CoreAIQwenProvider validates the host-supplied bundle URL and creates the local vision-language model. RawCull builds the instructions, then supplies the text and image attachment through LanguageModelSession. The Full Review execution chapter traces that handoff and the SAM 3 and CLIP request paths against the resolved package.

1. Begin With The Package Boundary

The package owns:

  • typed, Sendable contracts;
  • model-bundle validation and fingerprinted model identity;
  • Core AI CLIP image and text inference plus SAM 3 and EfficientSAM inference;
  • validated image/text semantic comparison;
  • Apple Vision feature-print generation and comparison;
  • bounded similarity indexing and explicit fallback;
  • segmentation, mask selection, geometry, and catalog workflows;
  • optional artifact codecs and mask stores.

The host application owns:

  • model download, installation, candidate URLs, and sandbox bookmarks;
  • RAW decoding and application image models;
  • SwiftUI, Observation state, and display wording;
  • app-specific task staleness such as “latest selection wins”;
  • query admission, result ordering, filtering, and semantic-search presentation;
  • culling, burst ranking, sharpness, saliency, and rating policy;
  • helper-process launch and application restart behavior.

This boundary makes PhotoAIKit reusable. A package that imports FileItem or searches Bundle.main for a RawCull resource might be convenient for one app, but it would silently encode application policy into the AI layer.

2. Read Package.swift As An Architecture Diagram

PhotoAIKit/Package.swift declares Swift tools 6.4, macOS 27, Swift 6 language mode, eight library products and one test target. CoreAIQwenBackend is the eighth library product. The inspected manifest requires apple/coreai-models exactly at 1.0.0; RawCull resolves it to 5de95c6cd29e5e390fb36d87e13b2396668f7974; it declares huggingface/swift-transformers from 1.3.3 and the October app resolved 1.3.5. Build 466 resolves swift-transformers 1.4.0.

flowchart TD
    Contracts["PhotoAIContracts\nvalues + protocols"]
    CLIP["CoreAICLIPBackend"] --> Contracts
    Efficient["CoreAIEfficientSAMBackend"] --> Contracts
    SAM3["CoreAISAM3Backend"] --> Contracts
    Vision["VisionFeaturePrintBackend"] --> Contracts
    Qwen["CoreAIQwenBackend"] --> Contracts
    CoreLM["coreai-models CoreAILM"] --> Qwen
    Workflows["PhotoAIWorkflows"] --> Contracts
    Storage["PhotoAIStorage"] --> Contracts
    CoreAI["apple/coreai-models\nCoreAISegmentation product"] --> CLIP
    CoreAI --> Efficient
    CoreAI --> SAM3
    Transformers["swift-transformers\nTokenizers product"] --> CLIP
    Tests["PhotoAIKitTests"] --> Contracts
    Tests --> CLIP
    Tests --> Efficient
    Tests --> SAM3
    Tests --> Vision
    Tests --> Workflows
    Tests --> Storage

There is intentionally no large umbrella target in which every feature can reach every implementation. Each higher-level product depends on PhotoAIContracts, but the backends, workflows, and storage products do not depend on one another.

Why this shape helps:

  • A host can import only the products it uses.
  • Workflow code is testable with fake providers and decoders.
  • Storage does not need to know which inference backend produced a value.
  • A backend cannot accidentally reach into RawCull or into another backend.
  • Framework-heavy dependencies remain concentrated in concrete backend targets.

3. PhotoAIContracts: The Stable Center

Contracts are the innermost layer. They contain data and protocol definitions, not application decisions.

3.1 Translate Host Photos Into AIImageSource

Sources/PhotoAIContracts/AIImageSource.swift defines the package-owned source value:

public struct AIImageSource: Codable, Hashable, Identifiable, Sendable {
    public let id: UUID
    public let url: URL
    public let displayName: String
}

RawCull maps FileItem into this type at its integration boundary. PhotoAIKit therefore receives only what a reusable indexing or segmentation workflow needs. It never learns ratings, focus data, camera metadata, or view state.

SourceFileIdentity reads size and modification date. SourceFingerprint adds the standardized path. These values let persisted artifacts answer a crucial cache question: “Was this result produced for the current contents of this source file?”

3.2 Invert Image Decoding

PhotoAIKit declares:

public protocol ImageDecoding: Sendable {
    func image(for source: AIImageSource) async throws -> CGImage
}

The package needs a CGImage, but it should not prescribe how one is obtained. A JPEG host can use ImageIO; RawCull can try RawParserKit first; tests can return a generated image. The workflow depends on the capability, not on a camera-format implementation.

This is the dependency-inversion principle in a small, concrete form:

flowchart LR
    Workflow["PhotoAIKit indexer"] --> Protocol["ImageDecoding protocol"]
    Raw["RawCull RAW decoder"] -. conforms .-> Protocol
    Test["Test decoder"] -. conforms .-> Protocol

3.3 Separate Generation From Comparison

Sources/PhotoAIContracts/SimilarityArtifact.swift defines two protocols:

  • ImageSimilarityArtifactProviding creates an artifact from a CGImage and source.
  • ImageSimilarityArtifactComparing computes the distance between two compatible artifacts.

The combined ImageSimilarityBackend type alias requires both.

The split matters because generation can be actor-isolated and expensive, while comparison may be synchronous and nonisolated. It also keeps distance semantics with the backend that understands its payload. RawCull does not decode a VNFeaturePrintObservation, nor does it implement CLIP cosine distance from unverified arbitrary data.

3.4 Keep Text Queries Query-Scoped

Sources/PhotoAIContracts/TextEmbedding.swift defines a second, deliberately different similarity value. TextEmbedding contains a normalized text vector and a TextEmbeddingDescriptor with the complete backend identity, dimensions, tokenizer version, and schema version.

Text embeddings are not file-backed SimilarityArtifact values. They have no source fingerprint and are intended to live for one query. The split public protocols mirror the image API:

  • TextEmbeddingProviding tokenizes and encodes a query.
  • ImageTextSimilarityComparing compares a compatible image artifact with the text embedding.
  • ImageTextSimilarityBackend combines both capabilities.

The comparison returns cosine similarity in -1...1, where a larger value is a closer semantic match. It is a relative retrieval score, not a confidence or a keep/reject decision.

3.5 Make Persisted Artifacts Self-Describing

A SimilarityArtifact has two fields:

SimilarityArtifact
├── descriptor
│   ├── backend
│   ├── model fingerprint
│   ├── dimensions
│   ├── representation
│   ├── preprocessing version
│   ├── normalization version
│   ├── configuration version
│   ├── source fingerprint
│   └── schema version
└── payload (backend-owned Data)

This looks more elaborate than storing [Float], but it prevents subtle cache bugs. A vector is not reusable merely because its dimension matches. Reuse is valid only if the source, model asset, preprocessing, normalization, configuration, representation, and schema are still the same.

SimilarityArtifactDescriptor.isCompatibleForDistance(with:) intentionally compares every backend/configuration field but excludes the source fingerprint. Two different photos must have different source fingerprints, yet their artifacts can still be compared when they were produced by the same backend definition.

3.6 Treat Model Identity As Data

The model types are spread across:

ModelIdentity.cacheIdentifier preserves compatibility with older cache naming. artifactIdentifier adds the selected asset fingerprint for new artifacts. This distinction allows migration without pretending that two different model binaries are the same model.

ModelResourceDescriptor.clip and .sam3 describe package-neutral requirements and version strings. ModelCapabilityStatus reports available, missing, or invalid without user-facing wording. The host translates that status into its own settings UI.

4. Model Bundles Are Supplied, Not Discovered

PhotoAIKit never chooses an application directory. The host supplies one URL or an ordered list of candidates.

A valid bundle has this conceptual layout:

ModelBundle/
├── metadata.json
├── tokenizer/
│   └── tokenizer.json
└── selected-model.aimodel  (or .aimodelc)

metadata.json names the selected model in assets.main. New exports can also provide asset_fingerprints.main.

ModelBundleResolver validates, in order:

  1. the URL exists and is a directory;
  2. metadata.json decodes;
  3. assets.main is present and non-empty;
  4. the asset extension is accepted;
  5. the selected asset exists;
  6. required resources such as tokenizer/tokenizer.json exist;
  7. the model asset can be fingerprinted;
  8. a manifest checksum, when present, matches the actual asset.

For a file asset, the cryptographic algorithm is SHA-256. For a compiled model directory, PhotoAIKit hashes a stable sorted tree representation. Older manifests without a checksum receive a size/modification-time fallback fingerprint. That fallback can detect replacement in place but is marked as not cryptographically verified.

ModelProviderFactory<Provider> connects validation to a backend constructor. A backend supplies “how to make me from a validated URL”; the host supplies “which URLs should be considered, and in what order.”

Candidate order is policy, not just presentation. ModelResourceResolver skips a candidate that is missing, but returns immediately when it finds an invalid candidate. This prevents a damaged higher-priority installation from being silently hidden by a lower-priority fallback.

CLIP has a second validation layer after generic bundle resolution. CLIPRuntimeConfiguration reads the model contract from metadata: source model and revision, architecture, pretrained checkpoint, embedding dimensions, preprocessing dimensions and normalization, tokenizer context and padding, named image/text functions, normalization version, and configuration version. Current bundles use shortest-side resize, a centered square crop, and bicubic interpolation. Older PhotoAIKit bundles remain compatible through the original 224-pixel stretch and bilinear defaults.

This separation prevents a library update from unexpectedly changing an application’s installation or sandbox policy.

5. Concrete Backend Products

5.1 CoreAICLIPBackend

CoreAICLIPProvider is an actor conforming to image embedding, artifact generation/comparison, text embedding, and image/text comparison protocols.

Its responsibilities are deliberately backend-specific:

  • validate the supplied CLIP bundle;
  • lazily load and cache the named image and text Core AI functions;
  • validate tensor names, shapes, scalar types, dimensions, and metadata;
  • create the image, token, and attention-mask NDArrays;
  • apply the model-declared resize/crop policy in sRGB and CLIP channel normalization;
  • L2-normalize image vectors through ImageEmbedding;
  • validate that the exported graph’s text vector is finite, non-empty, correctly shaped, and already L2-normalized;
  • encode the vector as an artifact payload;
  • compute cosine distance only after descriptor and payload validation.

The actor owns loadedModel, so lazy initialization is isolated from concurrent callers.

For a semantic query, the same provider creates a TextEmbedding and similarity(image:text:) rejects every incompatible model, representation, dimension, preprocessing, normalization, configuration, tokenizer, schema, or payload before computing a dot product. Vision artifacts are rejected because they are not in CLIP’s image/text embedding space.

RawCull’s RawCullCLIPSemanticSearchService keeps the product policy outside the backend: it trims and admits a literal query, selects already-persisted compatible image artifacts, isolates per-file failures, reports progress, and orders equal scores deterministically. It never decodes an image or persists a query embedding.

5.2 CoreAIEfficientSAMBackend

CoreAIEfficientSAMProvider is an actor conforming to SubjectSegmenting. It validates the EfficientSAM bundle, lazily owns ImageSegmenter, uses the model’s empty point query (center point or regular grid depending on the export), selects the highest-scoring mask, and adapts it to the same SubjectSegmentationResult contract used by SAM 3. The pinned provider uses a 0.5 mask threshold and at most one segment.

5.3 CoreAISAM3Backend

CoreAISAM3Provider conforms to SubjectSegmenting. It owns tokenizer setup, lazy model loading, request inference, query selection, confidence conversion, mask decoding, resizing, thresholding, feathering, timing, and diagnostics.

The provider creates CoreAIClipTokenizer and asks Core AI for up to five segments. Postprocessing prefers the exhaustive semantic probability map when the exporter supplies one. Otherwise it unions every returned instance mask, rather than selecting only the highest-scoring instance. The resulting SubjectSegmentationResult therefore represents all subjects matching the prompt. SAM3MultiSubjectTests protects both the semantic-map and instance-union paths.

The public contract speaks in SubjectSegmentationRequest and SubjectSegmentationResult, not Core AI tensors. This lets workflows and hosts work at the domain level while the backend handles framework details.

5.4 VisionFeaturePrintBackend

This actor uses VNGenerateImageFeaturePrintRequest. The produced VNFeaturePrintObservation is securely archived into an opaque artifact payload.

Comparison returns to this backend, which unarchives the observations and calls Vision’s native computeDistance. The observation never becomes part of RawCull’s persistence API. This is an example of information hiding: callers can store and route the artifact without learning its private representation.

6. PhotoAIWorkflows: Reusable Orchestration

Backends operate on one image or request. Workflows coordinate many sources and reusable policies.

6.1 Similarity Indexing

EmbeddingIndexer is the vector-specific API. SimilarityArtifactIndexer is the more general API used when the fallback might have an opaque representation such as a Vision feature print.

Both indexers accept:

  • package-owned sources;
  • an injected decoder;
  • a primary provider;
  • an optional fallback provider;
  • an explicit fallback policy;
  • a concurrency limit;
  • an async progress callback.

They use a throwing task group but enqueue only concurrencyLimit children. Each time one finishes, one new source is added. This is bounded concurrency: a catalog with 20,000 files does not create 20,000 live tasks and decoded images.

The fallback policies are:

PolicyBehaviorAppropriate when
.noneKeep primary successes and failuresThere is no compatible fallback
.perItemRetry only a failed itemPrimary and fallback results can safely coexist
.wholeBatchIf any primary item fails, rerun every requested source through fallbackA batch must use one comparable representation

The indexer does not decide which policy is correct for a host. RawCull’s current CLIP service selects .none: it keeps successful CLIP artifacts and reports per-file failures. RawCull selects Vision before indexing when CLIP is disabled or no validated provider exists. The generic .wholeBatch mechanism remains available to other hosts, but is not the current RawCull CLIP path.

6.2 Segmentation Workflows

The SAM 3 side is split into focused units:

TypeResponsibility
SegmentationServiceResize/preprocess coordination, cache lookup, inference, persistence, partitioning, and prefetch
SegmentationBatchPipelineBatch generation, progress events, summary, and versioned JSON-lines transport
SubjectMaskRepositoryCache-only access using explicit prompt/model/size configuration
SubjectMaskSelectorOrdered prompt fallback, quality/confidence thresholds, and best-mask selection
SubjectMaskCatalogIndexIncremental cache inventory without invoking inference
SubjectMaskGeometryAlpha coverage, bounds, centroid, and freshness
SubjectMaskQualityReusable geometry-based quality classification

The package can decide which mask best satisfies a general selection strategy. RawCull still decides which photo is a culling candidate or winner. Reusable mask quality is not the same concern as product ranking policy.

7. PhotoAIStorage: Optional Persistence Mechanics

Storage depends only on contracts.

For similarity data:

  • SimilarityArtifactCodec wraps an artifact in a versioned envelope.
  • EmbeddingCodec writes descriptor-complete CLIP artifacts.
  • decodeMigrating reads current data and two version-1 formats, but legacy values are accepted only against the real current model identity and are marked for immediate rewrite.
  • LegacyCLIPEmbeddingCodec remains a staged migration reader; its identity-incomplete writer is deprecated.

For segmentation:

  • SubjectMaskMemoryStore is an injected actor-backed dictionary.
  • SubjectMaskDiskStore stores PNG mask data plus JSON metadata, validates the storage key, reports disk usage, supports pruning, and rejects stale or corrupt entries.

The host injects the disk directory. PhotoAIKit owns how the record is encoded and validated, while the application owns where records live and when they are removed.

8. Concurrency And Isolation

PhotoAIKit targets Swift 6 and makes boundary values Sendable.

The main patterns are:

  • Actors for mutable runtime state: providers lazily cache loaded models; services and stores protect mutable state.
  • Value types for transport: sources, identities, descriptors, progress, failures, and configuration values cross tasks safely.
  • Bounded task groups: indexers and prefetch workflows limit simultaneous work.
  • Cooperative cancellation: workflow boundaries and expensive stages call Task.checkCancellation().
  • Async progress callbacks: the package reports neutral progress values; a host decides how and where to publish UI state.

Actor isolation does not remove the need for a host policy. RawCull still owns generation tokens and catalog checks that prevent an older task from replacing results for a newer selection.

9. RawCull integration at the October audit

RawCull imports the package products and assembles concrete providers in RawCullAIModelRuntime. RawCullApplicationState binds those providers to stable features owned by RawCullIntelligenceRuntime:

Package contract or implementationRawCull adapter/consumerPolicy that remains in RawCull
CoreAICLIPProvider, ImageSimilarityArtifactProviding, and ImageSimilarityArtifactComparingRawCullCLIPSimilarityService, SimilarityScoringModel, and RawCullSimilarityFeaturemanaged model locations, selected CLIP model, RAW decoding, concurrency 1, retry/replacement recovery, per-file persistence, burst thresholds, and subject-mismatch adjustment
VisionFeaturePrintBackendRawCullVisionSimilarityServicealways-available startup service, concurrency 4, service selection, cache admission, and UI state
TextEmbeddingProviding and ImageTextSimilarityComparingRawCullCLIPSemanticSearchService and RawCullSemanticSearchFeaturequery admission, progress, catalog/rating filters, deterministic ties, result count, selection/navigation binding, and ephemeral query lifetime
SubjectSegmenting, SegmentationService, mask stores, repository, and selectorRawCullAIModelRuntime, DeepAIReviewFeature, and DeepAIReviewControllerSAM 3 versus EfficientSAM selection, application-support paths, saved-evidence status, candidate admission, review presentation, group-signature validation, and culling decisions

The package owns validation, descriptors, backend actors, mathematical comparison, bounded generic workflows, and reusable codecs/stores. The app owns filesystem/security scope, camera decoding, settings, capability wording, generation tokens, catalog identity, cache policy, culling rules, and UI. In particular, PhotoAIKit does not know FileItem, a burst winner, or where RawCull installs a model. RawCullIntelligenceRuntime owns stable feature lifetimes and applies revisioned configuration; views consume the focused features and controller rather than low-level package providers.

10. Testing The Architecture, Not Only The Math

Most of Tests/PhotoAIKitTests/ exercises the products through public APIs. The CLIP text suite also uses @testable import for deterministic tokenizer, batch, tensor-shape, and preprocessing checks that sit below the provider boundary. Together the tests cover architectural promises such as:

  • model bundles are accepted through supplied URLs;
  • manifest fingerprints become artifact identity;
  • provider factories and resource resolvers share validation;
  • CLIP normalization and cosine distance remain stable;
  • model-declared CLIP preprocessing and legacy preprocessing remain compatible;
  • token batches, attention masks, text-output validation, and image/text compatibility checks reject malformed or mismatched data;
  • the generic whole-batch fallback policy produces a homogeneous result set (RawCull currently uses .none for CLIP);
  • Vision artifacts stay opaque and use the native metric;
  • segmentation caches by package-owned source values;
  • disk stores reject stale or corrupt entries;
  • legacy data is a rewrite candidate, not silently current data;
  • batch transport has an explicit versioned schema;
  • cancellation crosses the service boundary.
  • SAM 3 preserves all matching subjects through its semantic-map or union fallback.

Fake decoders, providers, and stores make these tests possible. That testability is a direct consequence of putting protocols in the innermost target.

11. Developer Tools And Model Assets

The package includes tools under Tools/ for exporting CLIP and SAM 3 assets, selecting a SAM 3 asset, generating fingerprints, and producing reference CLIP image/text similarities. Output paths are explicit.

export_clip.py supports the existing OpenAI clip-vit-base-patch32 model and OpenCLIP ViT-B-32-256 with datacomp_s34b_b86k weights. It writes the image and text encoders as named functions in one Core AI asset, verifies tokenizer parity for the OpenCLIP export, and records the runtime metadata consumed by CLIPRuntimeConfiguration.

The Swift package itself declares no model resources. It does not embed .aimodel, .aimodelc, tokenizer, or metadata assets. Model binaries are large deployment inputs with their own lifecycle; keeping them out of the library avoids coupling package source, application installation, and model distribution.

12. How To Add Another Similarity Backend

Use the existing layering as a checklist:

  1. Add or reuse package-neutral contract values in PhotoAIContracts; do not add host types.
  2. Create a separate backend target that depends on contracts.
  3. Conform to artifact providing and comparing protocols.
  4. Give the backend a complete SimilarityBackendDescriptor.
  5. Put framework-specific payload encoding and distance semantics inside that backend.
  6. If the backend supports text, add a query-scoped descriptor and keep image/text compatibility checks with that backend.
  7. Reuse SimilarityArtifactIndexer and inject the host’s decoder.
  8. Decide explicitly whether fallback is none, per-item, or whole-batch.
  9. Add public-API tests with fake sources and model-free inputs where possible.
  10. Let the host choose model URLs, cache locations, settings, and product policy.

If a proposed type needs SwiftUI, FileItem, a RawCull path, or a burst rating, it probably belongs in RawCull’s adapter layer instead.

Source Map

TopicPhotoAIKit source
Products and dependency graphPackage.swift
Host-neutral image and decoder boundarySources/PhotoAIContracts/AIImageSource.swift, ImageEmbedding.swift
Model validation and identitySources/PhotoAIContracts/ModelBundleResolver.swift, ModelResource.swift, ModelIdentity.swift, ModelAssetFingerprint.swift
Similarity descriptors and protocolsSources/PhotoAIContracts/SimilarityArtifact.swift
Text embeddings and image/text comparisonSources/PhotoAIContracts/TextEmbedding.swift
Segmentation contractsSources/PhotoAIContracts/SubjectSegmentation.swift, SubjectMaskStorage.swift
CLIP runtime and backendSources/CoreAICLIPBackend/CLIPRuntimeConfiguration.swift, CoreAICLIPProvider.swift
EfficientSAM backendSources/CoreAIEfficientSAMBackend/CoreAIEfficientSAMProvider.swift
SAM 3 backendSources/CoreAISAM3Backend/CoreAISAM3Provider.swift
Vision backendSources/VisionFeaturePrintBackend/VisionFeaturePrintBackend.swift
Similarity orchestrationSources/PhotoAIWorkflows/EmbeddingIndexer.swift, SimilarityArtifactIndexer.swift
Segmentation orchestrationSources/PhotoAIWorkflows/SegmentationService.swift, SegmentationBatchPipeline.swift, SubjectMask*.swift
Codecs and storesSources/PhotoAIStorage/
Package boundary auditDocumentation/ExtractionMap.md
Public behavior testsTests/PhotoAIKitTests/
RawCull semantic-search policyRawCull/Intelligence/SemanticSearch/RawCullSemanticSearchService.swift, RawCull/Intelligence/SemanticSearch/RawCullSemanticSearchFeature.swift, RawCull/Intelligence/Similarity/SimilarityScoringModel.swift

Next, follow these abstractions into the host application in How RawCull Enables and Uses CLIP.

Historical October 13 package additions and application boundaries

CoreAIQwenBackend validates and configures a local Qwen provider and constructs the model used by the host’s inference runtime. RawCull owns session creation, request caps, criteria, retries and photo/object schemas. A package backend can be correct while an application’s generated response fails its stricter contract.

Objects crosses the package boundary through SegmentationConcept, instance segmentation results and object-mask storage contracts. ObjectSegmentationService coordinates providers/stores; RawCull chooses concept mode, deduplicates retained instances, renders a numbered board and validates Qwen’s descriptions. Subject mask stores for Deep Review and object-mask stores are separate concerns.

The CLIP provider’s descriptor includes model, representation, preprocessing, normalization and configuration versions. In the inspected implementation, center-crop bicubic preprocessing includes a Pillow-compatible implementation version in the effective descriptor. Two embeddings with the same vector length but different preprocessing identities are not automatically compatible.

Reusable geometry and mask contracts can carry source-normalized registration, foreground and scorer semantics. The host must preserve those identities when cropping, measuring, displaying and persisting evidence. A SAM producer box alone is not a substitute for decoding foreground against the declared source raster. Combined’s ReviewMaskRegistration performs that application-owned registration.

Study the layers in order: package values/protocols, backend actors, package workflows/stores, application feature, SwiftUI presentation. Do not place Qwen photo prompt policy into CLIP or segmentation contracts merely because all three use a CGImage. Their outputs and acceptance conditions differ.

Host semantic-state ownership

The semantic-state extraction kept the package pin used at that time. RawCull’s RawCullSemanticSearchModel owns cached evidence, capability, hydration and query presentation, retained behind SimilarityScoringModel’s existing API. The package still owns encoding and comparison of compatible embeddings; this host extraction does not alter its models, artifact compatibility or ranking algorithms.

November 8 Integration Review: Identity Across Workflows

The November 8 application resolved PhotoAIKit 1.0.0 at 4b85056e6c2603b5e382987710ca2f16f4c5c155. The newer transitive versions in the package snapshot do not imply a new PhotoAIKit API revision. Review backend behavior against the resolved source when changing the lockfile; a sibling development checkout can contain later code.

Treat an AI artifact’s identity as more than its file URL. Backend, model asset fingerprint, preprocessing/configuration and representation dimensions establish whether two artifacts can be compared. Source identity determines whether an artifact still belongs to the current photo. Equal vector length alone is not proof that representations share an embedding space.

ChangeHost integration consequence
Replace a model assetResolve its identity again and invalidate artifacts that no longer match
Switch CLIP/Vision backendRebuild or retrieve compatible artifacts and use that backend’s comparator
Change source pixels or preprocessingRevise the corresponding source/configuration identity
Change the active query or selectionSuppress publication from the previous host request generation
Open a manual close-upRender inspection pixels through the host; do not treat the crop as an AI result

Cancellation and artifact validation solve different problems: a cancelled task can finish native work late, while an incompatible persisted artifact can arrive from a perfectly current task. Keep both request-generation checks and descriptor validation at publication boundaries.

Relationship To PhotoEvidenceKit

PhotoEvidenceKit provides manual inspection, including pinned references and independently positioned regions. It neither runs PhotoAIKit providers nor converts segmentation masks into selected subjects. If a host later offers an AI-assisted region action, the host must explicitly translate coordinates, identify the source revision and distinguish that action from a photographer’s existing manual region.

Model-download errors, incompatible artifacts, and unavailable inference should remain observable in the AI workflow. They do not prevent a host from offering manual close-ups when a renderable image is available. Conversely, a close-up render failure says nothing about whether an existing embedding is valid.

16.3 - How PhotoAnalysisKit Is Constructed

A detailed guide to PhotoAnalysisKit’s image-analysis boundary, sharpness pipeline, focus evidence, masks, calibration, batching, feature prints, resources, and concurrency.

How PhotoAnalysisKit Is Constructed

Revision audited: The formula walkthrough uses PhotoAnalysisKit 1.3.1 at 2a1466e04d821fa2628d6985296643e0d0c7e465. The facade, descriptors, presets, batch behavior, calibration, evidence, and mask APIs below describe that revision.

PhotoAnalysisKit is the reusable measurement layer extracted from RawCull. It turns a decoded CGImage plus neutral capture metadata into sharpness, saliency, focus evidence, and an optional focus-mask image. It can also create opaque Apple Vision feature prints.

The package measures a photo; it does not decide whether to keep it. That distinction prevents image-processing code from becoming coupled to RawCull’s files, settings, views, caches, or culling policy.

Build 466 integration

RawCull resolves PhotoAnalysisKit 1.4.1. Version 1.4.0 moved blocking saliency, classification, face, animal and feature-print requests onto the shared Vision gate. Version 1.4.1 also shares a lazily initialized Core Image context across focus engine instances. Treat queue admission and render reuse separately when investigating latency. The real-catalog comparison in the performance guide evaluated the gate change. VisionRequestGate · FocusMaskEngine · Performance measurements

1. Begin With The Package Boundary

PhotoAnalysisKit owns:

  • sRGB normalization for predictable analysis input;
  • Core Image and Metal Laplacian processing;
  • Vision saliency and optional subject classification;
  • scalar sharpness metrics and failure classification;
  • AF-point, subject, local-patch, and global focus evidence;
  • focus-mask selection and rendering;
  • numeric configuration, presets, quality levels, and analysis identity;
  • bounded batch analysis and calibration;
  • Vision feature-print generation and native comparison.

The host application owns:

  • RAW, JPEG, or other source decoding;
  • file URLs, security-scoped access, and sandbox bookmarks;
  • source identity, cache keys, cache directories, and persistence;
  • observable task state, progress presentation, and cancellation policy;
  • settings labels and saved-settings migration;
  • sorting, ratings, burst decisions, and culling actions.

The input boundary is intentionally small:

flowchart LR
    Source["RAW or rendered source"] --> Decoder["Host decoder"]
    Decoder --> Input["PhotoAnalysisInput\nCGImage + ISO + aperture + AF point"]
    Input --> Analyzer["PhotoAnalyzer"]
    Analyzer --> Result["PhotoAnalysisResult\nsaliency + breakdown + optional mask"]
    Result --> Host["Host cache, UI, and culling policy"]

PhotoAnalysisKit does not import RawParserKit or RawCullCore. RawCull provides the adapters between them.

2. Read Package.swift As The First Design Document

The manifest declares Swift tools 6.2, Swift 6 language mode, macOS 26, one library product, and one test target.

PhotoAnalysisKit package
├── PhotoAnalysisKit library
│   ├── public contracts and facade
│   ├── Core Image, Vision, and Accelerate implementation
│   └── packaged default.metallib
└── PhotoAnalysisKitTests

There are no third-party package dependencies. The implementation uses Apple frameworks including Core Graphics, Core Image, Vision, Accelerate, and Foundation.

The target enables InferIsolatedConformances and NonisolatedNonsendingByDefault. The package is therefore built under the same strict Swift 6 concurrency assumptions as the host without adopting UI isolation.

3. PhotoAnalysisInput Is The Decoding Boundary

Sources/PhotoAnalysisKit/PhotoAnalysisInput.swift defines the package’s source value:

public struct PhotoAnalysisInput: Sendable {
    public let image: CGImage
    public let iso: Int
    public let aperture: Double?
    public let normalizedAFPoint: CGPoint?
}

The AF point uses normalized 0...1 coordinates with the origin at the visual top-left. This matches the camera metadata shape used by RawCull. Vision uses a bottom-left coordinate system, so the package performs the vertical conversion internally.

ISO is clamped to at least 1. Aperture and AF point are optional because not every image or camera provides them. The package can still compute a global result when either is absent.

This value has no URL or file identifier. Two consequences follow:

  1. The package cannot reopen a source behind the host’s back.
  2. The host must associate returned results with the correct file and invalidate them when that file or decode policy changes.

RawCull makes that ownership concrete in RawCullPhotoAnalysisAdapter. The adapter chooses an embedded-preview decode through RawParserKit or a host-owned RAW demosaic, bounds the requested pixel size, and then constructs PhotoAnalysisInput. It also translates the returned neutral saliency value into RawCullCore’s SaliencyInfo. Neither package needs to import the other to participate in that flow.

PhotoAnalysisResult returns:

FieldMeaning
saliencyOptional neutral subject label and confidence
breakdownScalar score plus detailed evidence and diagnostics
focusMaskOptional rendered overlay image
scoreConvenience access to breakdown.finalScore

An absent breakdown means analysis could not produce a valid result or was cancelled. It is different from a valid score of zero.

4. PhotoAnalyzer Is The Public Facade

Sources/PhotoAnalysisKit/PhotoAnalyzer.swift keeps the public entry points small:

APIWork performed
analyzeSaliency, classification, scalar scoring, and focus evidence; no overlay rendering
analyzeWithFocusMaskAnalysis plus a mask derived from the same evidence
focusMaskMask rendering, optionally reusing previously computed evidence
calibrateCatalog-sample calibration of the visual edge threshold
sharpnessDescriptorStable identity for cacheable non-mask analysis behavior

The facade contains an immutable FocusMaskEngine. Both types are @unchecked Sendable because CIContext does not declare sendability even though this package holds no mutable model or UI state and reuses the context concurrently.

For each input, PhotoAnalyzer copies the supplied configuration, replaces its ISO with the input ISO, and derives an aperture hint from the input aperture. Callers can safely reuse one base configuration across many files.

When a host already stores SharpnessBreakdown.focusEvidence, passing it to focusMask avoids repeating the saliency selection step. This makes the measurement result useful as an input to later presentation work.

5. Follow The Scalar Sharpness Pipeline

The core implementation is in FocusMaskEngine+Scoring.swift.

flowchart TD
    Image["CGImage"] --> SRGB["8-bit sRGB normalization"]
    SRGB --> Vision["Vision saliency + optional classification"]
    SRGB --> Preblur["ISO- and aperture-aware Gaussian pre-blur"]
    Preblur --> Laplacian["Metal focusLaplacian kernel"]
    Laplacian --> Samples["Global, saliency, AF, and local-patch samples"]
    Vision --> Samples
    Samples --> Tail["Robust p90-p97 tail scores"]
    Tail --> Blend["Subject/global blend"]
    Blend --> Adjust["Silhouette, subject-size, and blur-gate adjustments"]
    Adjust --> Breakdown["SharpnessBreakdown"]

5.1 Normalize Before Measuring

normalizeToSRGB redraws the input into an 8-bit sRGB RGBA bitmap. The Metal pipeline therefore receives a predictable pixel format regardless of the source image’s bit depth or color space.

5.2 Find Candidate Subject Regions

VNGenerateAttentionBasedSaliencyImageRequest supplies salient-object rectangles. Small weak objects are removed, and candidates are ordered using AF overlap or distance, saliency confidence, interior detail, area, and deterministic coordinates.

When classification is enabled, VNClassifyImageRequest supplies a neutral subject label. The package filters out broad environment descriptions and prefers likely subjects such as animals or people. This label is evidence, not a keep/reject decision.

5.3 Build Edge Energy

The packaged focusLaplacian Metal kernel runs after Gaussian pre-blur. The pre-blur grows with ISO so high-frequency sensor noise is less likely to masquerade as detail. Aperture hints damp or strengthen parts of this behavior for wide, middle, and landscape apertures.

The result is rendered as floating-point RGBA data. The red channel carries edge energy.

5.4 Score Several Regions

The engine samples:

  • the full image after excluding a configurable border;
  • the selected salient region;
  • the camera AF region;
  • smaller AF-center and AF-neighborhood regions;
  • ranked local patches within subject or AF regions.

robustTailScore sorts the sample values, measures the p90-p97 energy band relative to a p20 noise floor, and penalizes a band that is too sparse. microContrast computes the standard deviation of finite edge samples.

The normal blend combines full-frame and subject evidence. When both AF and saliency scores exist, AF has the larger share of the subject score. A conservative local-detail component can then refine the broad subject measurement.

The final value may be adjusted for:

  • a silhouette-dominated subject whose strongest energy is mostly at the outer rim;
  • the area of a saliency-only subject;
  • an aperture-aware soft blur gate driven by subject micro-contrast.

SharpnessBreakdown preserves the component scores and selected evidence so a host can explain the result instead of presenting a single unexplained number.

5.5 Distinguish Failure Shapes

FocusFailureKind classifies the evidence as:

  • .motionBlur when global, subject, and AF detail are all weak and micro-contrast is low;
  • .missedFocus when the frame has usable global detail but the subject is much weaker;
  • .none when neither pattern is established.

These are algorithmic classifications, not final user-facing copy or culling actions.

Scalar scoring answers “how much reliable detail is present?” Mask rendering answers “where should the UI draw visible focused edges?” They share evidence but have different configuration needs.

FocusEvidence records the winning region, AF scores, selected patch rankings, spatial alignment, dominance, silhouette handling, visual threshold, coverage, and confidence diagnostics. FocusPatchRanking exposes the detail, coverage, shape, position, and penalty components behind each candidate patch.

The overlay pipeline:

  1. chooses AF-center, AF-neighborhood, AF, saliency, mixed, or global evidence;
  2. builds one native-pixel fine-detail Laplacian with clamped edges for every region;
  3. ranks local patches and selects the best evidence patches;
  4. chooses an adaptive percentile threshold from the complete selected search regions;
  5. applies optional erosion and dilation to the binary edge mask;
  6. colorizes, clips to the full search regions, feathers, and crops the mask;
  7. measures visible coverage after rendering with GPU reductions;
  8. returns updated evidence and render diagnostics with the image.

The renderer deliberately does not lower the threshold to force visible pixels. guaranteeVisibleFocusEvidence remains in the public configuration for source compatibility, but a weak or unfocused image may produce an empty mask.

FocusMaskRegionSource describes whether saliency, AF, both, or neither provided the overlay region. FocusEvidenceOverlayStyle distinguishes subject edges from global edges. RawCull decides how these neutral values appear in its interface.

7. Configuration, Presets, And Cache Identity

SharpnessConfiguration is a value snapshot containing numeric algorithm settings. It separates host-editable behavior from observable settings models.

Notable groups are:

Configuration groupExamples
Edge pipelinepreBlurRadius, threshold, energyMultiplier
Mask morphologydilationRadius, erosionRadius, featherRadius
VisibilityguaranteeVisibleFocusEvidence, minimumEvidenceCoverage
Region selectionAF radii, border inset, saliency weight
Scoring adjustmentssubject-size factor, silhouette strength, fine-detail weight
Capture hintsiso, apertureHint

SharpnessPreset applies high-level subject tuning for automatic, birds and wildlife, portrait, landscape, or general action use. SharpnessQuality selects fast, balanced, or high-precision fine-detail work. The host may persist its own UI enums, but should map them into these package values instead of duplicating constants.

Persisted results need more than a filename. SharpnessAnalysisDescriptor records:

  • descriptor schema version;
  • scalar algorithm version;
  • ISO-scaling policy version;
  • aperture-hint policy version;
  • every host-configurable value that affects non-mask scoring;
  • the stable scoring energy multiplier.

The descriptor deliberately excludes per-image ISO and aperture, mask-only presentation settings, decoded dimensions, source choice, and source-file identity. A host must account for changes in those inputs and decode policy when deciding whether a persisted result is reusable.

RawCull persisted sharpness identity
├── PhotoAnalysisKit SharpnessAnalysisDescriptor
├── selected embedded-preview or RAW source
├── effective maximum pixel size
└── source file size and modification date

RawCull’s signature records requested effective size rather than every actual decoded dimension. Per-image metadata is supplied with each analysis input; source size/modification checks invalidate replaced input files. See Focus Mask and Sharpness for the exact host signature and restoration contract.

8. Bounded Batch Analysis

PhotoAnalysisBatchRequest<Identifier> contains an identifier and an async input provider. The provider inversion is important: PhotoAnalysisKit coordinates work, while the host retains file access and decoding policy.

analyzeBatch starts only up to maximumConcurrentTasks child tasks. When one completes, it enqueues one more request. This prevents a large catalog from creating an unbounded number of decoded bitmaps.

The API has three ordering and failure guarantees:

  • progress is emitted in completion order;
  • the returned results preserve request order;
  • a decode failure is represented by a result whose analysis is nil.

If the parent task is cancelled, the method cancels the group and returns nil, telling the host to discard partial results rather than mistake them for a complete batch.

9. Calibration Changes The Overlay, Not The Score

Calibration samples Laplacian energies from host-provided decoded inputs with bounded concurrency. It downsamples the collected sample set, sorts it, and returns p50, p90, p95, and p99 statistics plus a clamped threshold at the requested percentile.

At least minimumSuccessfulImages inputs must succeed. Cancellation or too few samples returns nil.

Calibration changes only the visual edge threshold. Core sharpness scores keep a stable gain and do not depend on the current catalog. This prevents the same photo from receiving a different scalar score merely because unrelated photos were added or removed.

10. Vision Feature Prints Stay Opaque

VisionFeaturePrintBackend is an actor that creates a VNFeaturePrintObservation using Vision revision 2 by default. The observation is securely archived inside VisionFeaturePrint.payload.

The value also stores its Vision revision and representation version. Before comparison, the backend verifies both values, securely unarchives each observation, and calls Vision’s native computeDistance.

The host can persist the opaque payload, but it must associate it with source-file identity. Incompatible prints return nil; corrupt archives or failed Vision operations throw a typed VisionFeaturePrintError.

PhotoAnalysisKit intentionally does not copy PhotoAIKit’s general similarity artifact descriptors, CLIP fallback, or batch indexing. It supplies only the focused Vision measurement primitive.

11. Metal Resources Are Part Of The Algorithm

Sources/PhotoAnalysisKit/Resources/Kernels.ci.metal is the source for the Core Image kernel. SwiftPM copies Metal source resources but does not compile them for command-line builds, so the package also checks in default.metallib.

Tools/build_metallib.sh regenerates the binary. A kernel change is incomplete until the checked-in library has been rebuilt and tests have been run. The binary resource affects algorithm output and must be treated like source, not an optional deployment file.

12. Concurrency And Cancellation

The package uses four complementary techniques:

  • Immutable facade and engine: callers pass input and configuration snapshots; no app state is retained.
  • Explicit concurrent workers: synchronous Core Image and Vision work runs outside caller UI isolation while retaining task priority and task-local context.
  • Bounded task groups: batch analysis and calibration cap simultaneous inputs.
  • Cooperative checks: expensive stages test cancellation before Vision work, rendering, large loops, and result publication.

@unchecked Sendable is confined to the immutable Core Image facade and engine. Public transport values are Sendable value types.

13. RawCull Call Maps

The app has two deliberate entry paths into the same PhotoAnalyzer facade.

flowchart LR
    Settings["Settings + photo-type preset"] --> Sharp["SharpnessScoringModel"]
    Sharp --> Adapter["RawCullPhotoAnalysisAdapter"]
    Adapter --> Input["PhotoAnalysisInput: decoded CGImage + neutral metadata"]
    Input --> Batch["PhotoAnalyzer.analyzeBatch"]
    Batch --> Results["PhotoAnalysisResult per FileItem"]
    Results --> Core["RawCullCore ranking evidence + BurstAnalysisCache"]

SharpnessScoringModel applies the selected package preset, builds requests through RawCullPhotoAnalysisAdapter, and calls the facade’s bounded batch API. The adapter owns source loading and file-to-identifier mapping; the package owns measurement and its descriptor. BurstAnalysisCache records PhotoAnalyzer.sharpnessDescriptor(for:), so a configuration-identity change invalidates incompatible cached scores.

flowchart LR
    UI["Focus overlay or calibration action"] --> Model["FocusMaskModel"]
    Model --> Analyze["PhotoAnalyzer.analyzeWithFocusMask / focusMask / calibrate"]
    Analyze --> Evidence["FocusEvidence + FocusCalibrationResult + CGImage mask"]
    Evidence --> Presentation["RawCull FocusMaskResult + overlay state"]

FocusMaskTypes.swift aliases neutral package types such as FocusEvidence, FocusFailureKind, and FocusCalibrationResult, then layers RawCull presentation metadata over SharpnessBreakdown. FocusMaskModel consumes the returned mask image on app-owned isolation; scoring and evidence remain package values.

14. Testing The Public Contract

The executable contracts are split by concern:

Package testRequired behavior
Tests/PhotoAnalysisKitTests/SharpnessMetricsTests.swiftScalar metric and normalized sharpness calculations
Tests/PhotoAnalysisKitTests/PhotoAnalysisBatchTests.swiftBounded batch completion, ordering, failure isolation, and cancellation
Tests/PhotoAnalysisKitTests/SharpnessAnalysisDescriptorTests.swiftStable configuration identity and descriptor changes
Tests/PhotoAnalysisKitTests/PhotoAnalyzerTests.swiftFacade behavior, focus evidence, calibration, and mask rendering
Tests/PhotoAnalysisKitTests/VisionFeaturePrintTests.swiftOpaque Vision feature-print creation and comparison

Tests/PhotoAnalysisKitTests/ imports the library through import PhotoAnalysisKit, not @testable import. Tests therefore exercise the public surface used by a host.

The suite covers:

  • end-to-end sharpness analysis with the packaged Metal kernel;
  • focus-mask images, evidence, and diagnostics;
  • calibration from decoded images and neutral metadata;
  • bounded concurrency, order preservation, progress, decode failure, and cancellation;
  • descriptor encoding and changes in identity-affecting settings;
  • robust-tail, micro-contrast, ISO scaling, and focus-failure metrics;
  • configuration presets and aperture behavior;
  • Vision feature-print compatibility, round trips, and malformed payloads.

Synthetic images keep the suite deterministic and independent of RAW files, model downloads, cache directories, and application state.

15. How To Add Another Analysis

Use the existing boundary as a checklist:

  1. Accept CGImage and only the neutral metadata the algorithm needs.
  2. Keep URLs, camera decoding, settings state, and source selection in the host.
  3. Return a Sendable package-owned result with enough evidence to explain it.
  4. Put numeric tuning in a value configuration, not UI preferences.
  5. Define a versioned descriptor when hosts may persist the output.
  6. Make synchronous framework work cancellation-aware and independent of UI isolation.
  7. Bound multi-image work instead of spawning one live task per catalog item.
  8. Test through the public API with synthetic images and values.

If the proposed API needs FileItem, SwiftUI, a cache directory, or a rating, that concern belongs in RawCull’s adapter or policy layer.

Source Map

TopicPhotoAnalysisKit source
Product and resource declarationPackage.swift
Input and result boundarySources/PhotoAnalysisKit/PhotoAnalysisInput.swift
Public analysis facade and metricsSources/PhotoAnalysisKit/PhotoAnalyzer.swift
Batch orchestrationSources/PhotoAnalysisKit/PhotoAnalysisBatch.swift
Configuration and presetsSources/PhotoAnalysisKit/SharpnessConfiguration.swift, SharpnessPresets.swift
Cache descriptorSources/PhotoAnalysisKit/SharpnessAnalysisDescriptor.swift
Public evidence valuesSources/PhotoAnalysisKit/FocusMaskTypes.swift
Engine isolationSources/PhotoAnalysisKit/FocusMaskEngine.swift
Saliency and scalar scoringSources/PhotoAnalysisKit/FocusMaskEngine+Scoring.swift
Overlay generation and patch rankingSources/PhotoAnalysisKit/FocusMaskEngine+MaskGeneration.swift
CalibrationSources/PhotoAnalysisKit/FocusMaskCalibration.swift
Vision feature printsSources/PhotoAnalysisKit/VisionFeaturePrintBackend.swift
Metal source and compiled resourceSources/PhotoAnalysisKit/Resources/
Extraction decisionsDocumentation/ExtractionMap.md
Public behavior testsTests/PhotoAnalysisKitTests/
RawCull decode and result adapterRawCull/Model/ViewModels/FocusandSharpness/RawCullPhotoAnalysisAdapter.swift

Next, see how package-neutral measurements become culling-domain decisions in How RawCullCore Is Constructed.

Current host AF evidence hydration

RawCull’s workspace fills missing AF-center evidence from older cached analysis without replacing blended scores or recommended winners. Cancellation and scoring identity guard publication. The resolved PhotoAnalysisKit 1.3.1 formula is unchanged. The host’s optional releaseafcomparison workflow exports crops for a separately labeled comparison; it is not photographic qualification.

November 8 Integration Review: Measurement And Inspection

RawCull continues to resolve PhotoAnalysisKit 1.3.1 at 2a1466e04d821fa2628d6985296643e0d0c7e465. Its measurement boundary is unchanged by the addition of PhotoEvidenceKit. The latter displays manually chosen regions; it does not call PhotoAnalyzer or recompute a score when a photographer moves or zooms a crop.

Build Cache Identity Around The Actual Analysis Input

SharpnessAnalysisDescriptor describes algorithm/policy versions and configurable non-mask analysis settings. The host must additionally identify the source file, the chosen decoding path and decoded resolution. A score computed from an embedded preview must not silently become the score for a developed RAW image after a source toggle. Per-image ISO and aperture belong to PhotoAnalysisInput and must remain consistent with the metadata used for that cached computation.

A manual inspection’s CloseUpRenderSource is a separate identity. It enables fresh display pixels without overwriting analysis identity or implying that a previous score was computed from the newly displayed crop.

Interpret Batch Outcomes Precisely

Batch outcomeMeaningHost behavior
Empty inputSuccessful empty arrayFinish with no work
Result with analysis == nilThat input provider failed to supply a usable imageRetain the item’s failure state rather than inventing a zero score
Outer result is nilParent task was cancelledDiscard partial publication for that batch
Progress callbackNext completion, not next input positionUpdate progress using the supplied identifier
Final result arrayOriginal request orderAssociate results with their stable identifiers

The default maximumConcurrentTasks is eight; the implementation clamps it to at least one and at most the request count. Input providers execute within that bounded work, so hosts can avoid eagerly decoding a whole catalog. This bounds active batch tasks, not every cache or retained image elsewhere in the app.

Keep AF Evidence And Manual Placement Distinct

Analysis AF evidence contributes to measurement interpretation. PhotoEvidenceKit’s recorded AF point assists region placement in canonical oriented coordinates. Neither the presence of an AF location nor successful region placement establishes that the subject is sharp. Supply metadata appropriate to each API and perform sensor-to-oriented coordinate conversion in the host adapter.

Close Up Integration

Build 466 uses PhotoAnalysisKit 1.4.1. FaceEvidenceAnalyzer runs Vision face rectangle detection on an upright embedded preview and can return a local luminance-gradient measurement for each face. RawCull owns the disposable evidence cache. It keys compatibility on the source revision, preview configuration and dimensions, algorithm version, Vision revision and OS version.

RawCull calls the package’s AnimalCloseUpDetector for animal head and eye crops. Animal tiles are visual crops. The human face detail measurement stays with the human tiles. See the Close Up guide for how these tiles appear beside manual comparisons.

Changes at 1.3.9

The package can reuse supplied focus evidence without repeating Vision. Scoring uses the configured capture fallbacks when metadata is missing, includes those fallbacks in scalar cache identity, and uses the global score when subject evidence is unavailable. Calibration records its decode size alongside the mask cutoff. Historical metric tables above describe their pinned audits.

16.4 - How RawCullCore Is Constructed

A detailed guide to RawCullCore’s package-safe models, capture-time and EV-aware burst grouping, ranking evidence, confidence rules, histograms, concurrency, and tests.

How RawCullCore Is Constructed

Revision audited: The original walkthrough used RawCullCore 1.1.2 at d25a51e65ad32a82bf82f86fa0ec07d6e14498e9.

RawCullCore is the small domain layer at the center of RawCull. It does not decode or analyze photos. Instead, it receives file metadata and measurements already produced elsewhere, groups sequential files into bursts, and ranks the candidates using deterministic culling rules.

Its main architectural value is that a recommendation can be tested without opening a RAW file, running Vision, creating a Metal context, loading application settings, or constructing a view model.

1. Begin With The Package Boundary

RawCullCore owns:

  • package-safe file, EXIF, source-catalog, and saliency values;
  • normalized focus-point parsing;
  • burst group, boundary-evidence, ranking, confidence, and review-state models;
  • pure burst grouping rules;
  • pure burst ranking and one-click-safety rules;
  • a lightweight 256-bin luminance histogram.

RawCullCore deliberately does not own:

  • TIFF, MakerNote, ARW, or NEF parsing;
  • thumbnail, preview, or full RAW decoding;
  • Vision, Core Image, Metal, CLIP, or SAM 3 analysis;
  • caches, settings, security-scoped URLs, and saved-file coordination;
  • observable view models, SwiftUI, selection, sorting, and culling actions.

This produces a clear flow:

flowchart LR
    Parser["RawParserKit\nmetadata + AF location"] --> Adapter["RawCull adapter"]
    Analysis["PhotoAnalysisKit\nsharpness + saliency"] --> Adapter
    AI["PhotoAIKit\nvisual distance"] --> Adapter
    Adapter --> Values["RawCullCore values"]
    Values --> Group["BurstGroupingEngine"]
    Group --> Rank["BurstRankingEngine"]
    Rank --> Decision["RawCull presentation and action"]

The arrows describe how RawCull composes runtime values. RawCullCore imports none of the other packages.

2. The Manifest Optimizes For A Small Domain Library

Package.swift declares Swift tools 6.2, Swift 6 language mode, macOS 26, one RawCullCore library target, and one test target. It has no external package dependencies and no bundled resources.

The target uses:

.defaultIsolation(MainActor.self)
.enableUpcomingFeature("InferIsolatedConformances")
.enableUpcomingFeature("NonisolatedNonsendingByDefault")

Default main-actor isolation matches the surrounding application environment, but the package’s public value types and pure engines are explicitly nonisolated. Background grouping and ranking therefore do not acquire unnecessary main-actor hops.

This is a useful distinction: the build default is conservative, while each proven pure API opts out explicitly.

3. Package-Safe Models Replace Application State

The package uses transport values instead of importing RawCull’s FileItem or view models.

3.1 ExifMetadata

ExifMetadata is a Codable, Hashable, and Sendable snapshot containing display strings and numeric values for shutter speed, focal length, aperture, ISO, exposure compensation, camera, lens, RAW type, size class, and pixel dimensions.

It contains both strings and numbers because they serve different purposes:

  • strings preserve display-ready metadata such as shutter notation and lens names;
  • numeric exposure time, focal length, aperture, ISO, and exposure compensation support deterministic stop-based rules without reparsing display text.

RawCull or an adapter constructs this value from RawParserKit’s RawImageMetadata. RawCullCore does not know where the values came from.

At the app boundary, RawCull/Main/RawCullFileItem.swift deliberately preserves familiar app names:

typealias FileItem = RawCullFileItem
typealias ARWSourceCatalog = RawCullSourceCatalog
typealias ExifMetadata = RawCullCore.ExifMetadata

These aliases are migration conveniences, not permission for the package to import application state. Feature code may say FileItem, while the stored value and package API remain RawCullFileItem.

3.2 RawCullFileItem

RawCullFileItem contains an ID, URL, name, byte size, modification date, optional capture date and capture-time-zone offset, optional EXIF snapshot, and optional normalized AF point.

Equality and hashing use only id. Two snapshots with the same ID are the same logical file item even if another stored field changed. This matches the identity behavior expected by RawCull collections.

effectiveCaptureDate prefers the EXIF capture instant and falls back to the file modification date. usesFileModificationDateForCaptureTime exposes which path was used so grouping and confidence can treat the fallback conservatively. formattedSize is a lightweight Foundation convenience. File access and mutable scan state remain outside the value.

3.3 Catalog And Saliency Summaries

RawCullSourceCatalog identifies a named source URL without adding bookmark or access-lifecycle behavior.

SaliencyInfo stores only an optional subject label and confidence. It deliberately does not import Vision or expose a Vision observation. A PhotoAnalysisKit result can be translated into this small culling-domain value at the host boundary.

4. Focus-Point Parsing Connects Vendor Metadata To Analysis

RawParserKit’s vendor parsers return a focus string in this shape:

imageWidth imageHeight focusX focusY

FocusPointParser.normalizedPoint(from:) splits on arbitrary whitespace, requires exactly four numeric values and positive image dimensions, and returns:

x = focusX / imageWidth
y = focusY / imageHeight

The origin remains at the visual top-left. PhotoAnalysisKit accepts that convention and performs its own Vision coordinate conversion.

The parser does not clamp the returned point. Vendor parsers and host validation are expected to supply meaningful sensor coordinates. Malformed input or non-positive dimensions return nil.

5. Burst Models Preserve Evidence, Not Just A Winner

BurstAnalysisModels.swift defines the values exchanged by the two engines.

BurstGroupingOutput
├── groups: [BurstGroup]
└── boundaryEvidence: [BurstBoundaryEvidence]

BurstAnalysisResult
├── ordered candidate scores
├── recommended and second-best IDs
├── confidence and review state
├── one-click safety flag
├── reasons
└── cautions

This design avoids throwing away intermediate decisions. RawCull can show why a boundary was created, why a file won, and why automation is or is not considered safe.

BurstGroupingConfig.algorithmVersion is currently 4. Its defaults are visual distance 0.25, EXIF gap 2 seconds, modification-date fallback gap 10 seconds, same camera required, similar focal length required within 3 mm, shutter/ aperture/ISO change at most 0.5 EV, and exposure compensation at most 0.34 EV. The version gives hosts an identity marker for persisted grouping output. Custom decoding supplies defaults for fields that are absent from older saved configurations.

BurstReviewState has the current workflow states .none, .needsReview, .reviewed, and .deferred, plus compatibility states .algorithmReviewed, .manualWinnerOverride, and .decisionApplied retained for older caches. Unknown decoded raw values fall back to .none. BurstWinnerOverride likewise migrates older data by generating a missing ID and defaulting missing member filenames to an empty array.

6. BurstGroupingEngine: Decide Where A Burst Splits

The grouping engine expects files in shot order. It starts with the first file and evaluates each adjacent pair.

flowchart TD
    Pair["Previous + current file"] --> Visual{"Visual distance present\nand below threshold?"}
    Visual -- No --> Split["Start new group"]
    Visual -- Yes --> Time{"Time gap allowed?"}
    Time -- No --> Split
    Time -- Yes --> Camera{"Required camera same?"}
    Camera -- No --> Split
    Camera -- Yes --> Focal{"Required focal delta allowed?"}
    Focal -- No --> Split
    Focal -- Yes --> Exposure{"Exposure stable?"}
    Exposure -- No --> Split
    Exposure -- Yes --> Continue["Append to current group"]

A new group begins when any enabled boundary rule fires:

  • similarity evidence is missing;
  • visual distance is greater than or equal to visualDistanceThreshold;
  • the absolute capture gap exceeds maxTimeGapSeconds, or maxFallbackTimeGapSeconds when either file lacks a parsed EXIF capture instant;
  • camera identity changes when requireSameCamera is enabled;
  • numeric or parsed focal length changes by more than maxFocalLengthDeltaMM when similarity is required;
  • shutter speed, aperture, ISO, or exposure compensation changes by more than its configured EV threshold.

The default EXIF capture gap is 2 seconds; the default file-date fallback gap is 10 seconds. Each boundary records captureTimeUsedFallback, allowing later ranking to distinguish precise camera time from filesystem time.

Exposure comparison works in photographic stops:

shutter delta  = |log2(current seconds / previous seconds)|
aperture delta = 2 × |log2(current f-number / previous f-number)|
ISO delta      = |log2(current ISO / previous ISO)|
compensation   = |current EV - previous EV|

The defaults are 0.5 EV for shutter, aperture, and ISO and 0.34 EV for exposure compensation. The engine prefers numeric values. When a numeric shutter, aperture, or ISO comparison is unavailable but both normalized display strings are present and differ, it still treats the exposure as changed. The largest available adjustment is retained as exposureAdjustmentEV.

Focal length similarly prefers focalLengthMM and falls back to the first number in the display string. If either side has no usable value, that rule has no delta to evaluate.

Lens changes are recorded in BurstBoundaryEvidence, but do not by themselves split a group. They later make the group’s ranking metadata unstable. Keeping evidence separate from the grouping decision makes this behavior visible rather than implicit.

Missing similarity is conservative: it creates a boundary instead of assuming two files belong together. BurstPairKey.cacheKey standardizes the ordered adjacent-pair key used to supply those distances.

Each boundary record stores the measured values, boolean changes, final decision, and human-readable reasons. The output assigns stable sequential group IDs beginning at zero for that run.

7. BurstRankingEngine: Turn Evidence Into A Recommendation

Ranking consumes groups, files keyed by ID, sharpness scores, a score normalization maximum, saliency summaries, boundary evidence, and optional review states.

7.1 Determine Group Conditions

For each group, the engine derives:

  • metadata stability: none of its internal boundaries report exposure, camera, or lens changes;
  • capture-time reliability: every member has a parsed EXIF capture date rather than the modification-date fallback;
  • tight similarity: every internal boundary has a visual distance below 0.22;
  • dominant subject: the most frequent non-nil saliency label;
  • burst-relative sharpness: a within-group 0...1 normalization when at least two valid scores exist and their normalized spread is at least 0.03.

The configured grouping threshold decides membership; the fixed tighter 0.22 check contributes to ranking confidence. They answer different questions.

7.2 Score Each Candidate

If burst-relative sharpness is available, the ranking sharpness component is:

ranking sharpness = 0.65 × catalog-normalized sharpness
                  + 0.35 × burst-relative sharpness

The final candidate score is:

overall = 0.62 × ranking sharpness
        + 0.12 × focus-point evidence
        + 0.10 × saliency consistency
        + 0.16 × metadata evidence

The supporting components are deliberately simple and inspectable:

ComponentRule
Focus point0.70 when AF metadata exists, otherwise 0.45
Saliency0.75 for the dominant label, 0.25 for a different label, 0.45 when absent
Metadata base0.70 when stable, otherwise 0.40
Tight-similarity adjustment+0.15
ISO adjustmentAbove ISO 1600, -0.05 per stop, capped at -0.15
Wide-aperture adjustment+0.05 at f/5.6 or wider
Motion-risk adjustment+0.05 for a clearly fast shutter; up to -0.15 for a slower shutter

Every component is clamped or normalized into a predictable range before use. Candidates are sorted by descending overall score; equal scores preserve the group’s original shot order.

Motion risk uses exposureTimeSeconds with focalLengthMM when both are available. A shutter at least twice as fast as the reciprocal focal-length rule gets the positive adjustment; a shutter slower than the reciprocal rule gets a stop-based penalty. Without focal length, 1/500 second or faster is treated as lower risk and 1/60 second or slower as elevated risk.

Each candidate also carries reasons and cautions such as measured sharpness, available AF evidence, classified subject, missing sharpness, changed metadata, fast or slow shutter behavior, and high ISO.

7.3 Assign Confidence Separately

Winning a group does not automatically mean a decision is safe to automate.

High confidence requires:

  • at least one sharpness score;
  • at least three files in the group;
  • a best-versus-second score gap of at least 0.12;
  • best absolute sharpness of at least 0.65 after normalization;
  • stable metadata;
  • tight visual similarity;
  • parsed capture times for every member.

Medium confidence requires a gap of at least 0.05 and stable metadata. Other results are low confidence.

isSafeForOneClickCulling is true only for high confidence. canApplyOneClickCulling(hasSharpnessScores:) adds an explicit host-supplied confirmation that sharpness data is available before an action is enabled. RawCull still owns the action itself.

Reasons and cautions on BurstAnalysisResult are capped to three each so the result remains concise enough for inspection UI and persistence.

A modification-date fallback therefore does not prevent grouping, but it does prevent high-confidence automation and adds a capture-time caution.

8. Histogram Calculation Is Intentionally Lightweight

HistogramCalculator.normalizedLuminanceHistogram(from:) directly reads an 8-bit RGB or RGBA-style CGImage buffer. Each pixel is placed in one of 256 bins using Rec. 601 luminance:

Y = 0.299R + 0.587G + 0.114B

The bins are normalized by the largest bin count, so the peak has value 1. This is shape normalization, not probability normalization; the bins do not necessarily sum to 1.

The implementation requires positive dimensions, provider data, 8 bits per component, and at least three bytes per pixel. Unsupported input returns a zero-filled 256-bin array, preserving a stable return shape for views and callers.

The helper is appropriate for display and lightweight comparisons. Color conversion, RAW development, high-bit-depth analysis, and channel-layout generalization are outside this package.

9. Concurrency Is Achieved Through Purity

RawCullCore contains no actor because it owns no shared mutable runtime state. Models are Sendable values and engines are namespaces of nonisolated static functions.

The package performs no asynchronous I/O. Callers do expensive decoding, Vision work, embeddings, and sharpness analysis on the appropriate tasks, then pass snapshots into RawCullCore.

This design has several practical benefits:

  • grouping and ranking are deterministic for the same inputs;
  • no application singleton can change a result midway through a call;
  • tests do not require async setup or framework assets;
  • background work does not cross the main actor merely because the host uses main-actor default isolation.

10. Testing Rules And Migrations

Tests/RawCullCoreTests/ uses Swift Testing and synthetic values. Coverage includes:

  • model coding, hashing, identity, and source-catalog values;
  • valid, decimal, whitespace-varied, and malformed focus strings;
  • empty and stable groups;
  • boundaries caused by missing distance, time, camera, focal length, and exposure;
  • EXIF capture ordering, time-zone offsets, modification-date fallback, and the different fallback gap;
  • numeric and display-string exposure comparisons in photographic stops;
  • boundary evidence content;
  • absolute and burst-relative sharpness ranking, motion risk, and progressive ISO penalties;
  • missing scores, stable tie order, confidence, review-state propagation, and one-click eligibility;
  • RGB and RGBA histogram bins, peak normalization, and unsupported input.

No test needs an actual catalog, RAW file, Vision model, Metal device, cache directory, or settings store. That is the strongest evidence that the package boundary is doing useful work.

11. How To Extend Culling Logic

Use these constraints when adding a rule:

  1. Pass the required fact into a Sendable package value; do not reach into a view model.
  2. Preserve raw evidence separately from the final boolean or winner.
  3. Keep scoring weights and confidence thresholds deterministic and testable.
  4. Decide whether a rule affects group membership, candidate ranking, confidence, or only a caution.
  5. If evidence changes a grouping boundary or its meaning, bump BurstGroupingConfig.algorithmVersion and add migration/engine tests.
  6. If the app’s persisted result shape, validation, or pipeline identity changes, bump BurstAnalysisCache.schemaVersion (currently 9) and update cache tests.
  7. Maintain decoding fallbacks for existing review and override data.
  8. Leave framework observations and heavy image processing in the producing package.
  9. Leave user actions and presentation state in RawCull.

Source Map

TopicRawCullCore source
Product and concurrency settingsPackage.swift
EXIF transport valueSources/RawCullCore/ExifMetadata.swift
File and source identitySources/RawCullCore/RawCullFileItem.swift, RawCullSourceCatalog.swift
Saliency summarySources/RawCullCore/SaliencyInfo.swift
Focus normalizationSources/RawCullCore/FocusPointParser.swift
Burst contracts and migrationsSources/RawCullCore/BurstAnalysisModels.swift
Boundary decisionsSources/RawCullCore/BurstGroupingEngine.swift
Ranking and confidenceSources/RawCullCore/BurstRankingEngine.swift
HistogramSources/RawCullCore/HistogramCalculator.swift
Behavior testsTests/RawCullCoreTests/
RawCull metadata adapter and burst orchestrationRawCull/Model/RawImageLoading.swift, RawCull/Model/ViewModels/BurstWorkflowController+Grouping.swift

Return to the package overview in RawCull Packages, or continue with the file-decoding layer in How RawParserKit Is Constructed.

The exposure histogram is an app-level display product

RawCull’s temporary exposure-inspection histogram uses three RGB channels and near-black/near-white fractions from the completed sRGB preview. It does not replace or call this package’s single normalized luminance histogram. Keep the two algorithms and their interpretation separate when changing display code. See RAW Formats and Exposure Inspection.

Live review ownership remains in the application

RawCull stores live decisions in BurstReviewSessionModel and maps snapshots through BurstReviewStateMapping. The app restores membership signatures onto current group IDs and coordinates persistence. This extraction does not change RawCullCore’s pure grouping/ranking models or its resolved 1.1.2 pin.

November 8 Integration Review: Recommendations And Close-ups

The resolved RawCullCore baseline remains 1.1.2 at d25a51e65ad32a82bf82f86fa0ec07d6e14498e9. The new PhotoEvidenceKit integration adds a manual inspection surface beside grouping and ranking. It introduces no compile-time dependency into RawCullCore.

Three Kinds Of State Have Different Lifetimes

StateOwnerEffect
Grouping/ranking evidenceRawCullCore values produced from host inputsExplains boundaries, candidate scores and recommendation confidence
Photographer review decisionsRawCull host review/persistence layerRecords explicit choices independently of recomputation
Close-up region/reference/viewportPhotoEvidenceKit session plus injected region storeSupports visual comparison without setting a winner or rating

Pinning a close-up reference does not select a recommended winner. Moving a manual region does not alter the analysis score. Selecting several comparison frames does not regroup the burst. RawCull’s BurstCloseUpSelection keeps comparison membership separate from the active review frame, including command-toggle and shift-range interactions.

Preserve Missing Evidence And Time Provenance

Grouping consumes files in shot order and adjacent-pair similarity evidence. A missing comparison is a reason for a boundary, not a zero-distance match. Capture-time fallback is recorded in boundary evidence and influences the allowed time gap. Keep the distinction between capture metadata and file modification time when constructing the input values.

Ranking also records cautions for missing sharpness or AF evidence. Reliable capture times participate in the high-confidence gate, alongside score separation and metadata conditions. A candidate appearing first in a ranked result does not by itself establish that a one-click action is safe. Preserve the package’s confidence and eligibility fields when adapting results for the UI.

Recompute Without Overwriting Review Intent

When upstream source identity, sharpness configuration or similarity backend changes, regenerate the affected input evidence before ranking again. Publish the new recommendation only for the current host request and preserve separately owned photographer decisions. Refresh a pinned close-up’s source revision through updateReference so manual inspection can stay current without modifying the ranking input or host selection.

Resolved app revision

Build 466 pins RawCullCore 1.1.5 at ea8ac2fc6611949af2b55ec433456bfe502cf886. The app’s burst workflow invokes the package algorithms through app-side adapters. Earlier examples and results retain their original audit revision.

16.5 - How RawParserKit Is Constructed

A detailed guide to RawParserKit’s vendor dispatch, TIFF and MakerNote parsing, embedded previews, structured capture and exposure metadata, orientation, decode limiting, cancellation, compatibility APIs, and tests.

How RawParserKit Is Constructed

Revision scope: This walkthrough was written against RawParserKit 1.3.0 at d2175ed880d39021bdb5f5a2a842b460af0b316c. The current RawCull checkout resolves 1.3.3 at 26df4abc2178d5c07d08f3883d84d0648f5141d3. The earlier audit remains explicitly historical. The 1.3.1 RAW 9 and 1.3.2 generic-format additions below describe the current application boundary.

RawParserKit is RawCull’s camera-file boundary. It knows how Sony ARW, Nikon NEF, and Adobe DNG files are structured, how to locate their embedded JPEGs and AF metadata, and how to turn those sources into orientation-normalized images and display-ready metadata.

The package stops at decoding. It does not score sharpness, generate embeddings, group bursts, cache application results, or decide which photo should be kept.

1. Begin With The Package Boundary

RawParserKit owns:

  • vendor-neutral RAW format dispatch;
  • Sony ARW, Nikon NEF, and Adobe DNG format knowledge;
  • TIFF IFD and vendor MakerNote traversal;
  • focus-location and embedded-JPEG offset parsing;
  • RAW and rendered-image thumbnails and previews;
  • source-orientation normalization;
  • display-ready and numeric EXIF/RAW metadata extraction, including a structured capture instant and time-zone offset;
  • Sony full sensor development to JPEG;
  • decode task deduplication, concurrency limiting, and cooperative cancellation;
  • diagnostics and staged compatibility APIs.

The host application owns:

  • security-scoped URL access and sandbox bookmarks;
  • directory discovery, catalogs, and source selection;
  • memory and disk cache locations and eviction policy;
  • image-analysis inputs and result identity;
  • observable loading state, placeholders, retries, and presentation;
  • ratings, burst grouping, ranking, and saved-file behavior.

RawParserKit supplies inputs to higher layers without importing them:

flowchart LR
    File["ARW, NEF, DNG, JPEG, PNG, or TIFF"] --> Parser["RawParserKit"]
    Parser --> Image["CGImage or NSImage"]
    Parser --> Metadata["RawImageMetadata + RawFocusPoint"]
    Image --> Host["RawCull adapters"]
    Metadata --> Host
    Host --> Analysis["PhotoAnalysisKit / PhotoAIKit"]
    Host --> Core["RawCullCore"]

2. Package Shape And Framework Boundary

Package.swift declares Swift tools 6.2, Swift 6 language mode, macOS 26, one library product, and one test target. There are no third-party package dependencies.

The implementation uses Apple frameworks appropriate to file decoding: Foundation, AppKit, Core Graphics, ImageIO, Core Image, OSLog, and synchronization primitives from os.

Like RawCullCore, the target enables main-actor default isolation plus InferIsolatedConformances and NonisolatedNonsendingByDefault. Pure parsing and static format APIs opt out with nonisolated; the stateful loader and limiter use actors.

The source is arranged in layers:

RawImageLoader                         high-level deduplicated facade
├── RawFormatRegistry + RawFormat      vendor-neutral dispatch
│   ├── SonyRawFormat
│   ├── NikonRawFormat
│   └── DNGRawFormat
├── thumbnail and preview extractors   ImageIO + binary fallback
├── MakerNote parsers                  TIFF byte traversal
├── OrientationNormalizedImageLoader   rendered/embedded image helpers
└── cancellation + decode limiter      concurrency control

Callers can use the facade for normal browser behavior or a lower layer when they need explicit control.

3. RawFormat Makes Vendor Dispatch Explicit

Sources/RawParserKit/RawFormat.swift describes the static capabilities every camera format supplies:

  • supported filename extensions and a display name;
  • thumbnail extraction;
  • embedded-preview extraction;
  • AF focus-location parsing;
  • a readable label for compression codes;
  • camera-specific megapixel thresholds for S, M, and L size classes.

Conformers are stateless enums. RawFormatRegistry.all currently registers:

ConformerExtensionVendor responsibilities
SonyRawFormat.arwSony extractors, MakerNote parser, compression labels, body thresholds, and full sensor JPEG creation
NikonRawFormat.nefNikon extractors, MakerNote parser, compression labels, and body thresholds
DNGRawFormat.dngDNG TIFF/SubIFD parser, extractors, compression labels, and generic/camera-family thresholds

format(for:) lowercases a URL’s extension and returns a format metatype. Callers invoke static protocol requirements on that value without switching on brands.

The default rawSizeClass implementation converts dimensions to megapixels, obtains body-specific L and M thresholds, and returns L, M, or S. Unknown bodies use a generic fallback supplied by the conformer.

This is a simple plugin architecture inside the package. Adding a camera brand means adding a conformer and registering it, not adding vendor switches throughout the loader.

4. RawImageLoader Is The High-Level Facade

RawImageLoader.shared is an actor. It offers four current operations:

APIResult
thumbnail(for:maxPixelSize:)An NSImage suitable for grids and browsers
thumbnailCGImage(for:maxPixelSize:)The same thumbnail as CGImage
previewImage(for:)A larger sidecar or embedded preview
metadata(for:)A neutral RawImageMetadata snapshot

4.1 Deduplicate Equivalent Work

The actor stores in-flight tasks:

  • thumbnails keyed by URL and requested pixel size;
  • previews keyed by URL;
  • metadata keyed by URL.

If another caller requests the same work while it is running, both await the existing task. The entry is removed after completion. This prevents rapid view updates from decoding the same large image repeatedly.

4.2 Bound Expensive Decodes

The facade uses two DecodeConcurrencyLimiter actors:

  • up to six concurrent thumbnail decodes;
  • up to two concurrent full-size preview decodes.

These limits control memory as much as CPU. A few full-resolution bitmaps can consume substantially more memory than the compressed RAW files that produced them.

4.3 Follow The Thumbnail Strategy

For a rendered JPEG, PNG, or TIFF, the loader asks ImageIO for an orientation-aware thumbnail. For RAW input, it tries an embedded ImageIO thumbnail first and then dispatches to the registered vendor extractor. The vendor result is orientation-normalized before it becomes an NSImage.

4.4 Follow The Preview Strategy

The preview path checks for a same-basename .jpg sidecar first. If absent, it tries an orientation-aware embedded preview and then the registered format’s embedded-preview extractor. Vendor output is normalized using the source orientation.

The sidecar-first decision is host-facing convenience, not RAW parsing. A caller that requires only bytes physically embedded in the RAW can call the format or extractor API directly.

5. Metadata Is Normalized Into A Neutral Snapshot

RawImageMetadata contains optional display and numeric values for camera, lens, shutter speed, exposure time in seconds, aperture, focal length in millimeters, ISO, exposure compensation in EV, capture time, dimensions, focus point, RAW compression label, size class, and pixel dimensions.

RawImageLoader.metadata(for:) combines several sources:

  1. ImageIO properties from the source or a sidecar fallback;
  2. TIFF make, model, compression, and display-date fields;
  3. EXIF exposure time, aperture, focal length, ISO, exposure bias, lens, and dimensions;
  4. EXIF DateTimeOriginal, SubsecTimeOriginal, and OffsetTimeOriginal;
  5. the registered vendor MakerNote parser for an AF point;
  6. EXIF subject-area coordinates when vendor focus data is unavailable;
  7. vendor-specific compression labels and size-class thresholds.

captureDate parses the original capture timestamp as a real Date, preserving variable-length fractional seconds. OffsetTimeOriginal accepts Z, +HH:MM, -HH:MM, and compact +HHMM/-HHMM forms; the parsed offset is also retained as captureTimeZoneOffsetSeconds. When the EXIF offset is missing, parsing uses the current time zone. A missing or invalid DateTimeOriginal leaves captureDate nil rather than substituting the TIFF display date.

capturedAt remains a display string and can fall back to TIFF DateTime. Keeping it separate from captureDate prevents formatted UI text from becoming burst-ordering evidence.

rows returns non-empty display label/value pairs, while isEmpty lets the facade omit an empty metadata object. Numeric exposure time, aperture, focal length, ISO, exposure compensation, width, and height remain available so hosts do not have to parse formatted strings for analysis or domain rules.

RawFocusPoint stores normalized X and Y coordinates. Its failable focus-string initializer accepts the common "width height x y" shape, checks positive dimensions, and rejects coordinates outside 0...1.

RawCull’s RawParserKitImageLoader maps this parser-owned snapshot into its own ExifMetadata and RawCullFileItem values. ScanFiles carries the parsed capture instant and offset into the catalog; RawCullCore can then prefer camera time and explicitly detect a modification-date fallback. The similar types exist on purpose: each package owns the vocabulary at its boundary and neither must depend on the other.

6. Thumbnail Extraction Prefers Embedded Work

Thumbnails should not require full RAW development when a camera already stored a usable JPEG.

6.1 Sony

SonyThumbnailExtractor first asks SonyMakerNoteParser for embedded JPEG locations and decodes a selected JPEG directly. This bypasses macOS RAW decoder failures seen with newer ARW layouts. If the binary path cannot locate a JPEG, it falls back to ImageIO’s embedded-thumbnail behavior.

6.2 Nikon

NikonThumbnailExtractor asks ImageIO for a transformed embedded thumbnail. Both vendor extractors then redraw into an 8-bit premultiplied sRGB bitmap using interpolation quality derived from qualityCost.

6.3 DNG

DNGThumbnailExtractor follows the same cancellation-aware contract. Its binary fallback uses DNGMakerNoteParser and TIFF IFD/SubIFD classification to avoid treating JPEG-compressed raw image data as a display preview.

Both APIs run their synchronous ImageIO work through CancellableImageIOWork and throw ThumbnailError for an invalid source, failed generation, or failed bitmap context.

ThumbnailSharpener is an optional lower-level Core Image helper for producing a sharpened preview at a requested maximum dimension. The high-level boundary does not force sharpening on every caller.

7. Embedded Preview Extraction Has Two Paths

The three formats use the same building blocks in a different order. SonyEmbeddedJPEGExtractor prefers the binary TIFF locator, avoiding RAW decoder initialization on affected ARW files, then falls back to ImageIO. NikonEmbeddedJPEGExtractor inspects ImageIO sub-images first and uses the binary locator when the preview is not exposed there.

flowchart TD
    Source["RAW URL"] --> ImageIO["Inspect ImageIO image indexes"]
    Source --> Parser["Vendor TIFF parser"]
    ImageIO -->|usable JPEG| Decode["Decode or downsample"]
    Parser --> Offset["Absolute JPEG offset + length"]
    Offset --> Bytes["Read JPEG bytes"]
    Bytes --> Decode
    Decode --> Result["CGImage"]

fullSize: true permits a longest edge up to 8640 pixels. The normal preview path limits large images to 4320 pixels.

The Nikon fallback prefers the full-resolution SubIFD preview for full-size requests and IFD1 for smaller requests. Sony chooses the largest available JPEG first, with preview and thumbnail fallbacks.

DNG prefers standards-classified preview IFDs using NewSubFileType and Compression; files that omit NewSubFileType retain the positional fallback needed by older or nonconforming writers.

Extractor-level limiters default to two concurrent operations, and a caller can inject a shared limiter. This allows a host facade to enforce one budget across several decode paths instead of accidentally stacking independent limits.

8. Sony Full-Size JPEG Creation Is Different From Extraction

SonyRawFormat.createFullSizeJPEG(from:quality:) does not return a camera-embedded preview. SonyRAWJPEGCreator develops the ARW sensor data through macOS CIRAWFilter, renders it into sRGB, and encodes JPEG data.

Quality must be in 0...1. The operation can fail with:

  • invalidQuality;
  • unsupportedOrInvalidRAW when the installed macOS RAW decoder cannot develop that file;
  • encodingFailed.

This distinction matters in UI and caching. An embedded preview and a developed sensor image have different cost, pixels, appearance, and invalidation semantics even if both are JPEG-encoded at the end.

9. Sony MakerNote And TIFF Parsing

Sony ARW is TIFF-based. Focus parsing follows this structure:

TIFF IFD0
└── ExifIFD tag 0x8769
    └── MakerNote tag 0x927C
        └── Sony MakerNote IFD
            └── FocusLocation tag 0x2027
                (fallback: 0x204A)

The focus tag contains four unsigned 16-bit values: image width, image height, X, and Y. Sony MakerNote IFD offsets are interpreted as absolute file offsets.

The production parser uses a fast path and a fallback:

  • focus location reads the first 4 MB, then retries with the full file when necessary;
  • embedded-JPEG discovery reads the first 512 KB, then retries the full file when no locations were found.

The embedded locator walks TIFF IFDs and returns optional absolute locations for a small thumbnail, preview, and full JPEG. readEmbeddedJPEGData seeks directly to a validated location and reads its byte range.

The fast path keeps normal scans inexpensive; the full-file fallback supports bodies that place relevant TIFF structures near the end of the file.

10. Nikon MakerNote And TIFF Parsing

Nikon NEF is also TIFF-based, but modern Nikon Type-3 MakerNotes contain their own TIFF header:

TIFF IFD0
└── ExifIFD tag 0x8769
    └── MakerNote tag 0x927C
        ├── "Nikon\0" signature + version
        └── inner TIFF header
            └── Nikon IFD
                └── AFInfo2 tag 0x00B7

Offsets in the inner TIFF are relative to the MakerNote TIFF-header base, not the start of the NEF file. Keeping this offset rule inside the Nikon parser prevents a generic loader from acquiring vendor-specific exceptions.

For supported modern AFInfo2 layouts, the parser reads AF image dimensions, area position, and area size, and returns the same "width height x y" shape as Sony. The public shape lets all downstream code use one focus-point adapter.

Nikon embedded preview discovery examines Compression=6 SubIFDs referenced from IFD0 and the IFD1 JPEG interchange fields. It returns optional locations for the largest preview and IFD1 JPEG.

As on Sony, focus parsing starts with 4 MB and falls back to the full file. Embedded-location parsing uses a 1 MB fast path followed by a full-file retry when required.

10.1 DNG TIFF And SubIFD Parsing

DNG uses the same neutral focus-location string but has no single camera-vendor MakerNote layout. DNGMakerNoteParser walks TIFF IFD0 and SubIFDs, uses standard EXIF focus evidence when present, and exposes DNGEmbeddedJPEGLocations with thumbnail, preview, and full-JPEG candidates. Standards-classified previews are selected from TIFF NewSubFileType and Compression values; positional rules are used only when the classification tag is absent.

DNGRawFormat reports container-appropriate compression names for uncompressed, JPEG, Deflate, PackBits, Lossy DNG, and JPEG XL values. Its size-class policy is megapixel-based with small camera-family overrides because DNG is a cross-vendor container rather than a single body line.

11. Diagnostics Report The Failed Stage

The ordinary parser APIs return optionals because missing or unsupported MakerNote data is expected during normal browsing.

For troubleshooting, each vendor also exposes diagnostic forms for focus and embedded-JPEG lookup. RawParserDiagnostics<Value> contains:

  • the optional parsed value;
  • an ordered trace of stages and offsets checked;
  • an optional final failure explanation.

This keeps logging policy outside the binary parser while allowing RawCull’s diagnostics UI to show whether failure occurred at file access, TIFF validation, IFD lookup, MakerNote traversal, tag interpretation, or fallback.

12. Orientation Helpers Normalize Visual Coordinates

OrientationNormalizedImageLoader provides lower-level operations for rendered URLs, encoded JPEG data, source thumbnails, embedded thumbnails, and embedded previews.

ImageIO’s transform option is used when available. The loader also implements the eight EXIF orientation transforms, including mirrored and transposed cases, and can read orientation from the RAW source when decoding separately extracted JPEG data.

SupportedFileType enumerates .arw, .nef, .jpeg, .jpg, .png, .tif, and .tiff. Its rendered-image set distinguishes sources that can be loaded directly from formats that need RAW dispatch.

Orientation is part of the parser boundary because AF coordinates and subject analysis must refer to the same visual image the user sees.

13. Cancellation And Decode Limiting Solve Different Problems

CancellableImageIOWork bridges a synchronous ImageIO closure to async code on a global dispatch queue. It creates an ImageIOCancellationToken and uses a locked state machine to ensure the checked continuation is resumed exactly once, even when cancellation races completion.

Cancellation is cooperative. The token is checked before and after synchronous framework calls and between multi-stage loops. A framework function already executing may not stop internally, but its result is discarded when cancellation is observed.

DecodeConcurrencyLimiter is an actor that solves admission control. It:

  1. grants work immediately while slots are available;
  2. queues additional continuations;
  3. removes and resumes a cancelled waiter;
  4. transfers a released slot directly to the next waiter;
  5. releases the slot with defer when work completes.

Cancellation prevents obsolete work; limiting prevents too much valid work from running simultaneously. The loader needs both.

14. RawCull Adapter And Image Ownership

RawCull depends on its own RawImageLoading: Sendable protocol. The RawParserKitImageLoader value forwards to RawImageLoader.shared and performs the package-to-app translation:

RawCull requestPackage facade callBoundary result
fileMetadata(for:)metadata(for:)RawImageMetadata becomes app ExifMetadata, capture date/offset, legacy focus string, and normalized CGPoint
thumbnailCGImage(for:maxPixelSize:)thumbnailCGImage(for:maxPixelSize:)CGImage for cache and analysis paths
thumbnailImage(for:maxPixelSize:)thumbnail(for:maxPixelSize:)NSImage consumed by app/UI-isolated code
previewCGImage(for:)previewImage(for:)CGImage for the preview and analysis pipeline

App code should enter through this facade or the vendor-neutral registry. Sony and Nikon conformers remain implementation details except in diagnostics and package tests.

NSImage and CGImage are framework reference objects rather than ordinary Sendable values. RawCull therefore keeps their lifetime inside the actor or UI operation that needs them. RequestThumbnail converts a CGImage to JPEG Data inside its actor before starting the detached disk save; the value crossing that task boundary is Data, not the image object. Prefer the CGImage facade methods for background analysis and convert to presentation objects at the presentation boundary.

15. Compatibility APIs Support Staged Migration

The package retains deprecated names such as:

  • BrowserExifInfo and BrowserFocusPoint;
  • thumbnail200px, extractembeddedJPG, and exifInfo;
  • JPGSonyARWExtractor and JPGNikonNEFExtractor;
  • extractFullJPEG on RawFormat.

Each shim forwards to a current neutral name. This lets RawCull migrate call sites without forcing an all-at-once source break, while deprecation warnings make the intended direction visible.

New code should use RawImageMetadata, RawFocusPoint, thumbnail, previewImage, metadata, the embedded-JPEG extractors, and extractEmbeddedPreview.

16. Test Binary Rules Without Shipping Camera Files

Tests/RawParserKitTests/ uses Swift Testing and mostly synthetic TIFF-like byte buffers. The suite covers:

  • registry extension matching and dispatch;
  • Sony focus tags, offset rules, invalid byte-order markers, fallback tags, embedded JPEG locations, and diagnostics;
  • Nikon Type-3 MakerNote and AFInfo2 layouts, SubIFDs, IFD1 JPEGs, offset rules, and diagnostics;
  • DNG TIFF/SubIFD classification, focus and embedded-JPEG locations, compression labels, size classes, and malformed-data behavior;
  • direct reading of embedded JPEG bytes;
  • cancellation before decode and cancellation behavior in vendor extractors;
  • decode-limiter capacity;
  • Sony full-size JPEG quality validation and generated JPEG properties;
  • numeric exposure-time, focal-length, aperture, ISO, and exposure-compensation metadata;
  • capture-date offsets, subsecond precision, invalid-date behavior, and offset parsing;
  • current public naming and format-helper behavior.

Synthetic binary fixtures make edge cases reproducible and avoid committing large proprietary ARW, NEF, and DNG samples. Framework integration is tested with small generated images where needed.

17. How To Add Another Camera Vendor

Use the existing extension points:

  1. Add a stateless RawFormat conformer with its extension and display name.
  2. Implement vendor-specific thumbnail, preview, focus, compression, and size-class behavior.
  3. Put TIFF or MakerNote byte rules in a dedicated parser, including explicit offset bases and bounds checks.
  4. Return the common normalized focus-location string at the public boundary.
  5. Add ImageIO behavior first and a binary embedded-JPEG fallback when the framework does not expose the preview reliably.
  6. Make blocking decode stages cooperative with CancellableImageIOWork.
  7. Register the conformer in RawFormatRegistry.all.
  8. Add synthetic binary tests for endian, offsets, missing tags, corrupt lengths, and diagnostics.
  9. Leave analysis, cache placement, and UI policy in their owning layers.

Source Map

TopicRawParserKit source
Product and concurrency settingsPackage.swift
Format contract and dispatchSources/RawParserKit/RawFormat.swift, RawFormatRegistry.swift
Format conformersSources/RawParserKit/SonyRawFormat.swift, NikonRawFormat.swift, DNGRawFormat.swift
High-level facadeSources/RawParserKit/RawImageLoader.swift
Metadata and focus valuesSources/RawParserKit/BrowserExifInfo.swift, BrowserFocusPoint.swift
Sony TIFF and MakerNote parsingSources/RawParserKit/SonyMakerNoteParser.swift
Nikon TIFF and MakerNote parsingSources/RawParserKit/NikonMakerNoteParser.swift
DNG TIFF and preview parsingSources/RawParserKit/DNGMakerNoteParser.swift
Embedded preview extractionJPGSonyARWExtractor.swift, JPGNikonNEFExtractor.swift, DNEmbeddedJPEGExtractor.swift
Thumbnail extractionSonyThumbnailExtractor.swift, NikonThumbnailExtractor.swift, DNGThumbnailExtractor.swift
Full Sony sensor developmentSources/RawParserKit/SonyRAWJPEGCreator.swift
Orientation and rendered filesSources/RawParserKit/OrientationNormalizedImageLoader.swift
Cancellation bridgeSources/RawParserKit/CancellableImageIOWork.swift
Decode admission controlSources/RawParserKit/DecodeConcurrencyLimiter.swift
Parser diagnosticsSources/RawParserKit/RawParserDiagnostics.swift
Behavior and binary-fixture testsTests/RawParserKitTests/
RawCull metadata adapter and catalog scanRawCull/Model/RawImageLoading.swift, RawCull/Actors/ScanFiles.swift

Continue from decoded images into How PhotoAnalysisKit Is Constructed, or return to the package overview.

Version 1.3.1: explicit RAW 9 development

RawImageLoader.thumbnail(for:maxPixelSize:useRAW9:), thumbnailCGImage and previewImage(for:useRAW9:) accept an opt-in boolean, defaulting to false. The in-flight image key includes that flag, so an embedded-preview request does not coalesce with a RAW 9 request. Internal/RAWDecoder.swift selects version9, then version9DNG when available, and returns nil when neither can develop the file; callers preserve their existing embedded/sidecar fallback.

The renderer caps scale to the requested longest edge without upscaling and renders RGBA8 sRGB. CIRAWFilter applies source orientation. Its detached render checks cancellation before and after work; cancellation does not interrupt a framework call already executing. See Tests/RawParserKitTests/RAWDecoderTests.swift. In RawCull, Model/RawImageLoading.swift adapts these APIs and retains catalog access. Embedded export deliberately uses EmbeddedJPGExportLoader.swift rather than this display-oriented facade.

Version 1.3.2: generic macOS-backed RAW formats

The delta from 1.3.1 adds GenericRawFormat, GenericRawThumbnailExtractor and GenericEmbeddedPreviewExtractor, registers the generic conformer and adds registry/preview tests. It does not replace the dedicated Sony, Nikon or DNG parsers explained above. The current manifest is Package.swift.

GenericRawFormat admits the explicit extension set in GenericRawFormat.swift. Metadata can fall back to EXIF SubjectArea, but no new vendor MakerNote parser is provided. Thumbnail work uses the existing cancellation-aware ImageIO bridge; preview work has a two-operation limiter and selects ImageIO-exposed JPEG candidates without a binary vendor fallback. Orientation is applied at the facade boundary after generic preview extraction.

Read RAW Formats and Exposure Inspection for the full call sequence, pixel limits, extension list and display/export distinction. Current tests are RawFormatRegistryTests.swift and GenericEmbeddedPreviewExtractorTests.swift. Adding an extension is not sufficient evidence for a camera-support promise; qualify a real file on the intended macOS decoder.

Current preload-save boundary is app-owned

RawCull preload returns encoded JPEG data to its bounded worker, which releases the file’s grid gate, awaits saving, then returns its slot. Each preload group bounds pending saves and retains its catalog grant through completion. Interactive saving is unchanged. RawParserKit’s decode limiter, coalescing and public thumbnail APIs remain unchanged by this host-side change. Version 1.3.3 changes executor placement as described below.

Version 1.3.3: bounded concurrent thumbnail execution

The app now pins 26df4abc2178d5c07d08f3883d84d0648f5141d3 (1.3.3). RawImageLoader.thumbnail calls a private static @concurrent decodeThumbnail inside the existing six-slot limiter. Admission alone did not move synchronous ImageIO work onto the concurrent executor under the package isolation settings. The slot stays held until decode returns. Request coalescing, priority, cancellation checks, fallback order, orientation and public APIs are preserved; full-size preview loading is unchanged. Synchronous decode remains non-preemptive between cancellation checks.

The package evaluation records 105 passing tests in each Debug/Release package suite and ARW throughput experiments. Paired host-application empty-cache cohorts improved; warm disk cohorts showed no established benefit. Those are separate package-evaluation observations, not a fresh RawCull whole-catalog speed or UI smoothness measurement.

November 8 Integration Review: Close-up Source Delivery

The app still resolves RawParserKit 1.3.3 at 26df4abc2178d5c07d08f3883d84d0648f5141d3. Adding PhotoEvidenceKit does not make the parser depend on a UI package. RawCull implements CloseUpRendering and supplies decoded pixels to the evidence engine.

Follow The Actual Host Renderer

BurstCloseUpRenderer in RawCull’s RawCull/Views/ComparisonGridView/BurstCloseUpsView.swift is the adapter:

  1. Retain catalog access for the requested file.
  2. Check the file revision and render-source descriptor before decoding.
  3. For developed RAW, call ZoomPreviewHandler.loadDevelopedRAWPreview; for a preview, call FullSizePreviewLoader.shared.loadEmbeddedPreview.
  4. Label the returned source as developed RAW/full-size JPEG, sidecar JPG preview, or embedded preview as appropriate.
  5. Check cancellation and both identities again before rasterizing the crop.

These are host pipelines, not new RawImageLoader public methods. A developed image may be labeled RAW 9 only when the decoder reports RAW 9 support. A sidecar preview’s modification changes the preview render descriptor independently of the RAW file revision. The adapter does not silently replace unavailable preview pixels with a different source class.

Separate Decode Limits From Raster Limits

The package’s DecodeConcurrencyLimiter queues work and transfers a released slot to the next waiter. Cancellation while waiting removes that waiter; native work already running remains subject to cooperative cancellation behavior. In 1.3.3, thumbnail work runs on the concurrent executor under its existing bounded policy.

RawCull’s close-up renderer additionally serializes its own render tasks across actor suspension. PhotoEvidenceKit bounds returned crop/overview buffers, but it does not cap the memory needed to decode the full source. Audit thumbnail, full-preview and close-up concurrency together when assessing peak image memory.

Map AF Coordinates Once At The Host Boundary

The host reads EXIF orientation and maps sensor-normalized AF positions through all eight orientation cases into canonical top-left, x-right, y-down coordinates. Invalid points or unavailable orientation produce unavailable AF assistance. Do not pass sensor coordinates directly to a close-up whose pixels are already orientation-corrected, or apply orientation normalization a second time.

A close-up source change invalidates displayed pixels; a file-revision change also invalidates saved source-bound regions and stale AF targets. This distinction allows preview/development toggles to preserve a photographer’s manual region.

16.6 - How PhotoEvidenceKit Is Constructed

PhotoEvidenceKit contracts, close-up geometry, bounded rendering, retained references, region persistence, AF assistance, and RawCull integration.

How PhotoEvidenceKit Is Constructed

November 8 baseline: RawCull resolved PhotoEvidenceKit 1.0.7 at 7614fd1528bb7cf2549799fb937678ea39d90228. This guide reviews that source and the RawCull 3.4.0 build 434 integration on November 8, 2026. The package README and changelog still use initial/unreleased wording; the lockfile records that historical remote version.

PhotoEvidenceKit on GitHub is a reusable manual image-inspection package. It lets a photographer compare selected regions, retain a reference while navigating, and inspect crops with explicit pixel-source attribution. It was extracted from RawBrowse and preserves the original MIT attribution.

The package requires Swift tools 6.2, Swift 6 language mode, and macOS 26 or newer. It has no external package dependencies, bundled photo assets or model downloads.

Repository references: README, package manifest, and MIT license.

1. Products And Dependency Direction

ProductResponsibility
PhotoEvidenceContractsSendable frames, regions, viewports, requests, render-source descriptors, coordinate transforms and AF targets; main-actor region-store protocol
PhotoEvidenceEnginePure crop geometry, bounded rasterization, render results, errors and asynchronous rendering protocol
PhotoEvidenceUIEmbeddable SwiftUI panel and observable comparison-session model
PhotoEvidenceDemoExecutable example using synthetic portrait/landscape fixtures and public APIs
flowchart TD
    Host["RawCull host adapters"] --> UI["PhotoEvidenceUI"]
    Host --> Engine["PhotoEvidenceEngine"]
    Host --> Contracts["PhotoEvidenceContracts"]
    UI --> Engine
    UI --> Contracts
    Engine --> Contracts
    Host --> Decode["Host preview / RAW pipelines"]
    Host --> Store["Host region storage"]

No product imports RawCull, RawBrowse, RawParserKit, PhotoAnalysisKit, PhotoAIKit, or RawCullCore. Contracts contain no SwiftUI views or image buffers. The engine has no filesystem access, model inference or application file model.

The host owns file permissions, image loading, cache/concurrency policy, comparison membership, active selection, ratings and review decisions. The package does not identify subjects, track eyes or animals, score sharpness, choose winners or write XMP. Comparing several crops is an inspection activity, not an automatically calibrated measurement.

2. Separate File Identity From Render Identity

CloseUpFrame contains a stable URL id, a display name, and a host-supplied revision. The revision must remain stable across launches for an unchanged source and change when the source changes. A random session token would defeat saved-region reuse.

CloseUpRenderSource independently describes the pixels requested for display:

FieldMeaning
kindunspecified, original, embeddedPreview, or developedRAW
backendIDStable identifier for the host rendering pipeline
revisionSettings/source token that changes whenever that pipeline’s pixels can change

A preview/developed-RAW toggle changes the render descriptor without changing the file revision or the saved manual region. Development settings, crop, straightening, bit depth and color-pipeline changes should also revise the rendering token. The .unspecified default supports hosts with a single fixed pipeline.

A CloseUpRequest combines frame, region, scale mode, display scale, viewport, viewport size and render source. The renderer must honor the source and scale or fail. Returning a different source with the requested label would break the inspection contract.

3. Manual Regions And Coordinate Spaces

CloseUpRegion uses canonical orientation-corrected image coordinates: origin at the top left, x to the right, y downward. Its default center is (0.5, 0.5) and its default fraction is 0.25. Bounds clamp the fraction to 0.05...1 and keep the region within the image. Nonfinite values receive finite defaults.

The fraction applies independently to normalized width and height, so a region covering one quarter of each dimension in a landscape image is not necessarily a square in source pixels. pixelBounds(width:height:) expands to integral pixel bounds and intersects the source extent. The normalized representation is used for persistence and geometry.

CloseUpViewport represents temporary inspection around a frame’s own region. Its offset is measured in region fractions, not full-image fractions. Normalization limits each offset component to -4...4 and zoom to 0.25...8.

CloseUpCoordinateTransform maps canonical normalized coordinates into the actual rendered image, including developed crop/straightening. It must be finite and invertible. Supply the real transform when rendered pixels differ geometrically from the canonical source; identity is appropriate only when those spaces agree. Inverse mapping supports overview interactions back into canonical coordinates.

4. Fit Region And Source-Pixel Scale

CloseUpScaleMode.fitRegion fits the requested inspection region to the viewport. sourcePixels uses zoom in display points per source pixel; zoom 1 means one source pixel per display point. On a high-density display this is distinct from one source pixel per physical screen pixel. Display scale controls raster output resolution separately.

Requests default to a 280 × 210-point viewport. Viewport dimensions are normalized to 1...4096 and display scale to 1...4. The panel is 304 points wide and can be embedded on either side of a host workspace; placement belongs to the host.

The engine’s crop geometry computes bounds for the selected mode, viewport and transform. A region outside a developed crop yields regionOutsideRender rather than an unrelated fallback image.

5. Rendering And Memory Ownership

CloseUpRendering is a Sendable asynchronous provider with render(_:) async throws -> CloseUpRender. The host implements decoding and calls CloseUpRasterizer.render off the UI actor. Rasterization itself is synchronous.

A render returns independently owned crop and overview CGImage buffers, source width/height, a truthful source label, displayed bounds, render-source identity and the coordinate transform used. The rasterizer checks cancellation before and after work. Its maximum artifact dimension is derived from the larger viewport dimension multiplied by display scale, and it does not upscale a source.

The rasterizer redraws both artifacts into new 8-bit premultiplied RGB buffers. This matters because a CGImage crop alone can retain the whole decoded source. Bounded artifacts avoid that accidental ownership, but decoding a full-resolution source can still allocate a large transient image. Host decode concurrency and cache eviction remain necessary.

Failure And Stale-Result Handling

Error/stateMeaning
unavailableRequested pixels or raster buffers could not be produced
sourceChangedHost detected a changed file or render source
renderMismatchReturned source identity, dimensions or transform failed validation
regionOutsideRenderRequested canonical region cannot produce a valid developed crop
Cancelled/older generationCard ignores completion instead of publishing obsolete pixels

The card model increments a generation for each load. It validates the returned render descriptor, positive source dimensions and valid transform before displaying a result. It clears old pixels on frame/source changes; during region editing it can keep the overview mounted so an active drag is not destroyed by its own load. Releasing an offscreen card invalidates its generation and releases artifacts.

The UI cannot verify file contents from an opaque result alone. The host must check file/source revision before and after decoding as RawCull’s adapter does.

6. Comparison Session And Retained References

CloseUpModel is a main-actor observable session model. updateFrames deduplicates selected frames by URL and refreshes state for changed revisions. comparisonFrames places the reference first and includes it only once even if it is also selected.

pin, replacement by another pin, and unpin affect inspection state only. A reference survives removal from host selection. updateReference refreshes its metadata/revision without adding it back to selection. The host must continue supplying render-source and AF information for that retained reference.

Regions remain independent per frame. setLinked shares relative viewport offsets and zoom around each frame’s existing region; it does not copy one frame’s region onto another or establish subject correspondence. resetViews resets temporary viewports, while resetRegion restores a frame’s default manual region.

Current-frame labels and the optional activation callback let the host distinguish inspection membership from active review selection. Activation, rating changes and winner selection remain explicit host actions.

7. Region Persistence And Retry

Inject CloseUpRegionStoring into CloseUpModel to make regions durable. Its load(for:) and save(_:) methods are synchronous main-actor operations, so use fast preference-sized storage or an already hydrated repository.

CloseUpRegionRecord stores schema version 1, source URL, source revision and a normalized region. Loading accepts a record only when schema, URL and revision match. Crops, overview buffers, model output and temporary pan/zoom are not part of that record.

Without an injected store, regions live only in the current/pinned working set. Inactive state is trimmed. Failed saves are retained as pending records and expose persistenceFailure; retrySaving retries them and can retry failed loads. Pending choices remain available for retry even after leaving the active selection.

RawCull’s BurstCloseUpRegionStore encodes records as JSON in UserDefaults. Keys use the PhotoEvidenceKit.ManualRegion.v1. prefix plus a SHA-256 hash of the standardized URL string. The stored record performs source-revision validation; the key alone is not enough to establish freshness.

8. Recorded AF-Point Assistance

The panel accepts an afPoints dictionary keyed by frame URL. Omitting an entry hides assistance; .unavailable(reason:) displays a disabled action with an explanation. .available(CloseUpAFPoint) supplies a frame/revision-bound target. The target’s failable initializer rejects nonfinite and out-of-range coordinates.

The host decodes camera AF metadata, resolves any active-point ambiguity and maps orientation into canonical coordinates. A target from an obsolete frame revision is disabled/rejected. Supply entries for a retained reference as well as selected frames, and refresh them when metadata changes.

There are two related behaviors in 1.0.7:

  • useAFPoint(_:) performs one placement for one active frame. It preserves region size, viewport and linking, and persists through the normal store. Existing pan can still offset the displayed view.
  • usesAFPoint is a session preference. When enabled, updating frames or AF entries reapplies valid AF centers and clears displaced viewport offsets. Linked viewport propagation still follows the model’s normal linked behavior.

Both operate on manual regions and neither establishes focus quality or tracks a subject. The region remains editable. RawCull synchronizes this preference with its AF overlay state in the burst workspace.

9. RawCull Integration

RawCull/Views/ComparisonGridView/BurstCloseUpsView.swift defines the adapters:

TypeResponsibility
BurstCloseUpIdentityFile revision from standardized URL, size, modification time and inode; separate preview/RAW render descriptors
BurstCloseUpRendererRetain catalog access, serialize rendering, decode the requested source, validate identities twice and rasterize
BurstCloseUpRegionStorePersist source-bound region records in UserDefaults
BurstCloseUpAFPointRead EXIF orientation and map all eight orientation cases
BurstCloseUpSelectionPlain selection, command-toggle and shift-range comparison membership
BurstCloseUpsViewAssemble frames, render sources, retained-reference metadata, AF availability and host callbacks

The preview pipeline uses FullSizePreviewLoader; the RAW pipeline uses ZoomPreviewHandler.loadDevelopedRAWPreview. Source labels distinguish sidecar JPG, embedded preview, and developed RAW/full-size JPEG, including RAW 9 when supported. The preview descriptor includes sidecar identity so a changed sidecar can rerender without resetting a manual region bound to the RAW source.

BurstCullingWorkspaceView owns panel visibility, the model, renderer and comparison membership. The package has no knowledge of the app’s ranking results, rsync transfers, rating persistence or selected winner.

Detected crops in the local integration

The November 9 development build uses the sibling ../PhotoEvidenceKit checkout. RawCull’s BurstDetectedFacesView supplies normalized rectangles to DetectedFaceRasterizer, which adds context and clips the crop to the upright preview. The app obtains human face rectangles from PhotoAnalysisKit and derives animal head and eye rectangles from Vision landmarks in AnimalCloseUpDetector. These tiles sit above the manual CloseUpPanel and have no region records of their own.

See using Close Up for the source picker, manual regions and detected tiles.

10. Tests And Qualification

Run package checks from the PhotoEvidenceKit repository:

swift test
swift build -c release
swift run PhotoEvidenceDemo

The synthetic demo exercises the exported APIs without importing a host app. Package tests cover regions/geometry, AF validation, pin/replace/unpin, independent and linked viewports, saved-record revision checks, persistence retry, render-source changes, coordinate transforms and cancelled/out-of-order providers. RawCull’s RawCullTests/BurstCloseUpTests.swift additionally covers AF orientation, comparison selection, persisted regions and preview-versus-file source identity.

For host qualification, inspect portrait/mirrored sources, previews smaller than the requested viewport, mixed source classes, a retained deselected reference, rapid selection changes, source/settings changes during decoding, persistence failures and peak memory during full-resolution loads. The package tests establish contract behavior; they do not measure a host decoder’s cold/warm latency or memory budget.

Changes at 1.1.5

Source-pixel zoom 1 now maps a source pixel to one physical display pixel at the active display scale. Detected-face crops are redrawn into bounded, owned buffers. The earlier geometry walkthrough describes the original 1.0.7 implementation.

Source Map

Paths below belong to the PhotoEvidenceKit repository at the reviewed revision:

TopicPhotoEvidenceKit source
Products, platform and dependency graphPackage.swift
Frame, region, request, viewport and storage contractsSources/PhotoEvidenceContracts/CloseUpContracts.swift
Render identity and affine coordinate transformSources/PhotoEvidenceContracts/CloseUpRenderSource.swift
Validated AF targets and availabilitySources/PhotoEvidenceContracts/CloseUpAFPoint.swift
Fit/source-pixel bounds and coordinate mappingSources/PhotoEvidenceEngine/CloseUpCropGeometry.swift
Owned bounded raster buffersSources/PhotoEvidenceEngine/CloseUpRasterizer.swift
Async provider, result and error contractsSources/PhotoEvidenceEngine/CloseUpRendering.swift
Reference, regions, AF session preference, linked inspection and retrySources/PhotoEvidenceUI/CloseUpModel.swift
Generation checks, result validation and releaseSources/PhotoEvidenceUI/CloseUpCardModel.swift
Embedding API and controlsSources/PhotoEvidenceUI/CloseUpPanel.swift
Synthetic public-contract testsTests/PhotoEvidenceKitTests/

Continue with RawParserKit for decoding, PhotoAnalysisKit for measurements, RawCullCore for recommendations, and PhotoAIKit for optional inference workflows.

Build 466 resolves PhotoEvidenceKit 1.1.5 at e49d34adcfa2e2c43a4240c2e962dbe9defa4cad over HTTPS. This is the same source revision as build 462. Application lockfile

17 - File Read and Write Reference

Files, folders, and persistent data touched by RawCull

File Read and Write Reference

This page lists the main places RawCull reads and writes files. Use it before changing sandbox access, cache locations, persistence, or export behavior.

File Map

File/folderAccessOwner
User-selected catalog folderReadCatalogController, ScanFiles, DiscoverFiles, parser package
RAW files (dedicated and generic registered extensions)Readscan, thumbnails, focus parsing, zoom, export, diagnostics
focuspoints.json beside catalogRead optionalScanFiles fallback
App Support savedfiles.json and backupsRead/write/moveCullingModel, ReadSavedFilesJSON, WriteSavedFilesJSON
App Support settings.jsonRead/writeSettingsViewModel, SettingsFileWriter
App Support analysis artifacts and burst snapshotsRead/write/deletePerFileAnalysisArtifactStore, BurstAnalysisCache
App Support AI models and licence acceptanceRead/writeAI model download/resource and licence services
Thumbnail cache directoryRead/write/deleteDiskCacheManager
Full-size JPEG preview cacheRead/write/pruneFullSizeJPGDiskCache, ZoomPreviewHandler
Subject-mask cacheRead/write/deletePhotoAIKit subject-mask stores configured by RawCullAIModelRuntime
Exported .jpg files in a chosen destinationWriteExtractAndSaveJPGs, SaveJPGImage
Temporary rsync include lists / process streamsWrite/delete/readExecuteCopyFiles, ArgumentsSynchronize, PrepareOutputFromRsync
Destination security-scoped bookmarkRead/write UserDefaultsOpencatalogView, copy workflow
AI selections and managed-model metadataRead/write UserDefaults and app metadataRawCullAISettingsModel, model download service

Catalog Reads

The active catalog comes from the sidebar folder selection. CatalogController.startCatalogLoad(for:) starts security-scoped access and then runs the scan.

Catalog reads include:

  • directory enumeration,
  • URL resource values,
  • EXIF metadata via ImageIO,
  • MakerNote focus points via RawParserKit,
  • embedded thumbnails/JPEGs,
  • optional focuspoints.json.

DiscoverFiles uses RawFormatRegistry.allExtensions so it follows the parser registry.

App Support Files

Application Support is used for durable app-owned data:

~/Library/Application Support/RawCull/

Important files:

FilePurpose
savedfiles.jsonRatings, sharpness/saliency persistence, and manual burst winner overrides
savedfiles.backup.jsonAtomic backup of the previous valid saved-file store before replacement
savedfiles-corrupt-<timestamp>.jsonUser-approved archive of a store that failed decoding
settings.jsonThumbnail, cache, scoring, and focus-mask settings
AnalysisArtifacts/Per-file, descriptor-valid Vision/CLIP similarity artifacts
BurstAnalysis/Derived catalog snapshots containing grouping, ranking, artifacts, and review states
Models/Installed AI model bundles grouped by model identity
ModelLicenceAcceptances.jsonRecorded model-licence acceptance state
CopyLists/Operation-unique NUL-separated rsync include lists, removed during cleanup

savedfiles.json is written atomically after the old data is copied atomically to savedfiles.backup.json. A decode failure is surfaced to the UI; rating mutations are blocked until the user retries or explicitly archives the damaged store. settings.json, per-file artifacts, and burst snapshots also use atomic replacement. Burst-analysis validity is checked against file metadata, descriptors, artifact digest, and algorithm/signature versions before reuse.

Cache Files

Generated caches live under the user cache directory for the RawCull app identifier. They are performance data, not source-of-truth data.

CachePurpose
Schema-specific thumbnail disk cacheStores generated JPEG representations keyed by source fingerprint, purpose, requested size, and orientation policy
Full-size JPEG disk cacheStores larger embedded JPEG previews for zoom
Subject-mask cacheStores reusable segmentation masks outside the durable app-data namespace

Deleting these caches should only make RawCull slower until they are rebuilt. It should not lose ratings or manual decisions.

Exported JPEGs

ExtractAndSaveJPGs exports the current selection into a user-selected destination catalog. It supports two modes:

ModeInput pathOutput name
Embedded JPGEmbeddedJPGExportLoader.jpegData(for:)Original basename plus .jpg
Demosaiced RAWSonyRawFormat.createFullSizeJPEGOriginal basename plus _demosaic.jpg

The actor bounds parallel extraction, tracks progress and per-file failures, and passes JPEG Data to SaveJPGImage; non-Sendable image objects do not cross the save boundary. SaveJPGImage creates files without overwriting. If a name already exists, it retries with (1), (2), and so on; the filesystem enforces exclusivity for case-insensitive and simultaneous-export collisions. FileOperationsModel.startSelectedJPGExtraction starts destination security-scoped access before constructing the actor and stops it on the main actor after the awaited result returns.

rsync Copy Workflow

The copy workflow is separate from thumbnail/scoring export. It uses rsync to copy selected RAW files based on rating/tag choices.

Main files:

FileRole
CopyFilesView.swiftUI and execution lifecycle
OpencatalogView.swiftDestination picker and bookmark creation
ExecuteCopyFiles.swiftProcess owner and progress/result state
ArgumentsSynchronize.swiftBuilds rsync arguments
PrepareOutputFromRsync.swiftParses process output
RemoteDataNumbers.swiftSummarizes copied file counts and sizes

ExecuteCopyFiles.startcopyfiles first derives the selected filenames from the current CatalogController. It then creates an operation-unique file under Application Support/RawCull/CopyLists/. Each UTF-8 filename is terminated by NUL, and rsync receives --from0 plus --files-from=<path>. This preserves spaces and newlines without converting the list into command-line arguments.

The source is the currently selected catalog URL and the destination is restored only from destBookmark; there is no arbitrary path fallback. Both successful scope acquisitions remain owned by the ExecuteCopyFiles instance while /usr/bin/rsync runs. A stale destination bookmark is refreshed while its resolved grant is active. Process handlers stream progress and a typed CopyOutcome (success, failed, or cancelled) back to main-actor state.

Startup returns a typed CopyStartupFailure for unavailable arguments, missing model state, an empty selection, Application Support/include-list failures, security-scope failures, and process-launch failures. All failure paths call the same idempotent cleanup used by completion, cancellation, close(), and deinitialization. Cleanup finishes the progress stream, stops both acquired scopes exactly once, removes only this operation’s include-list file, and releases process handlers.

Security-Scoped Bookmarks

The copy workflow stores destination bookmark Data in UserDefaults after the user picks a folder. Picker access is balanced immediately after bookmark creation. At execution time, ExecuteCopyFiles starts a fresh scope for the active catalog URL and resolves destBookmark with .withSecurityScope for the operation-lifetime destination scope. Failure asks the user to reopen the catalog or reselect the destination rather than attempting a plain-path fallback.

The catalog browsing flow is different: CatalogLifecycleCoordinator owns one active security-scoped catalog URL and stops it during catalog transition or successful application termination. Do not transfer that ownership implicitly to a child actor.

See Security-Scoped URLs for lifecycle details.

Settings

SettingsViewModel stores its SavedSettings value as pretty-printed, sorted JSON in Application Support/RawCull/settings.json, not in UserDefaults. Settings affect:

  • thumbnail sizes,
  • cache size maximums,
  • focus/scoring options,
  • memory/cache defaults.

The main-actor model loads once through ensureLoaded(). Encoding happens on the main actor from a consistent observable snapshot, and SettingsFileWriter performs directory creation and atomic writing through an actor. Background actors use SettingsViewModel.shared.asyncgetsettings() to obtain a Sendable SavedSettings value rather than reading observable properties across isolation boundaries.

AI model selection and copy bookmarks are separate preferences and may still use UserDefaults; do not treat those as part of settings.json without an explicit migration.

Diagnostics Reads

Combined Review has durable diagnostic/evidence storage in Application Support/RawCull/AnalysisArtifacts/CombinedReview/, owned by ReviewArtifactStore. It stores run manifests, typed stage artifacts, optional exact PNG inputs and opt-in rejected responses. maximumInputBytes defaults to 256,000,000 bytes for retained inputs; this is not a universal limit on every artifact category. Run inspection is backed by ReviewDiagnostics and the Review Record window. Retained inputs and rejected model text can contain photographic content: follow the selected retention policy when sharing bundles. OSLog and focused tests remain separate diagnostic channels.

What To Check When Changing This Area

  • Writes outside the app container need active security-scoped access.
  • App-owned durable data belongs in Application Support, not Caches.
  • Rebuildable performance data belongs in Caches, not Application Support.
  • Keep savedfiles.json backup/corruption recovery semantics when changing culling persistence.
  • Keep settings.json separate from bookmarks and AI-selection preferences unless a migration is designed.
  • If a cache stores derived algorithm output, include enough version/signature metadata to reject stale data.
  • Keep process-output parsing separate from process lifecycle management.
  • Keep rsync include lists operation-unique and remove them on success, failure, cancellation, and deinitialization.
  • Balance every successful security-scope start exactly once at the layer that owns its lifetime.

Persistence initialization and recovery

The live CullingModel begins .unloaded. ensureLoaded() coalesces concurrent callers onto one load task; mutation is admitted only in .ready with no load failure. A missing store means a valid empty start, while a decoding/read failure preserves the original and enters .failed. flushPersistence() also ensures initialization, so switching catalog cannot overwrite an unread store with an empty snapshot.

retryCullingPersistence() retries a failed load or pending save. After a load recovery, restoreCullingPresentation() rebuilds rating lookups, valid scores, filters and selection. Archive/reset also refreshes the UI when the subsequent write fails, because the in-memory store has already changed. Failed saves remain dirty. Rating edits refresh dateTagged, including edits of existing records. See CullingModel.swift, CullingController+Ratings.swift and RawCullTests/ReviewPersistenceTests.swift.

loadPersistedScoringandSaliency() builds a filename lookup once, validates signature/size/modification date, and publishes score dictionaries in a batch. It keeps the first legacy duplicate and accepts AF scores only with a valid AF point and a finite positive score. This avoids repeated normalization after each restored item. See CatalogController+Sharpness.swift.

Settings failures are represented separately by SettingsPersistenceFailure with .load or .save. SettingsView exposes the failure and retry/dismiss controls; a missing settings file uses defaults without reporting corruption. See RawCullTests/SettingsPersistenceTests.swift.

Embedded export is independent of display preview

EmbeddedJPGExportLoader reads camera JPEG ranges from ARW, NEF or DNG parser locations. It validates candidate data as JPEG and returns the original bytes when standalone orientation is present or the RAW orientation is upright. Otherwise it normalizes orientation and encodes a standalone JPEG. It does not export a same-basename sidecar or a lossy display-cache entry. No usable embedded JPEG is a per-file export failure. The Sony demosaic mode remains a separate path. RawCullTests/RawImageLoadingIntegrationTests.swift protects this boundary.

Saved Files and cache deletion in Settings

The old Saved Files menu/sheet presentation has been removed from RawCullMainView. RawCullApp.swift passes the stable view model into Settings; CacheSettingsTab.swift shows Saved Files separately from the cache total.

WriteSavedFilesJSON.diskUsage() runs through the shared writer actor and sums the current savedfiles.json and savedfiles.backup.json sizes. It does not count corrupt archives or every file in Application Support. The confirmed Delete Saved Files action calls clearAllCullingState(), awaits flushPersistence() and refreshes the size. Persistence errors retain their existing failure/dirty-state contract; a refreshed byte count is not proof of a successful write. This operation resets culling records, not source photos.

Delete Cache is a different confirmed operation: it removes saved Combined Reviews before clearing thumbnail, full-size, similarity and burst caches. The confirmation includes report history, masks and retained inputs. The button is disabled while the Combined lease is held. If review deletion throws, the later purge steps are not executed and the error is surfaced. See Cache System for the category boundary.

Temporary exposure inspection writes neither a RAW editing sidecar nor an exported JPEG. Generic RAW browsing does not extend embedded-byte export beyond the loader’s ARW/NEF/DNG cases. See RAW Formats and Exposure Inspection.

Shared review-state serialization

BurstReviewStateMapping.swift implements snapshot/restore rules for cached analysis and live review. It derives membership signatures, omits .none, filters missing file references and restores compatible decisions onto current group IDs. Groups without a valid signature cannot restore state. The stored schema is unchanged.

BurstReviewSessionModel owns live decisions; the burst workflow and coordinator retain persistence orchestration. Thumbnail preload now also owns its saves through completion: each worker awaits saving before returning its slot. The interactive save path is unchanged.

October 31 integration

Normal ZoomView fit requests reuse an existing developed JPEG before rendering a bounded RAW preview. New direct fit pixels and adjusted exposure inspection do not write that persistent cache. Normal native development, loupe, burst and exports retain their established JPEG paths. See RAW viewing policy.

Close-up regions are a separate preference store

BurstCloseUpRegionStore in BurstCloseUpsView.swift encodes CloseUpRegionRecord as JSON Data in UserDefaults. Keys begin with PhotoEvidenceKit.ManualRegion.v1. followed by a SHA-256 hash of the standardized source URL string. The record stores schema version, source URL/revision and normalized region; it does not store crop images, viewport pan/zoom, ratings or manual winners. Loading rejects a replaced source revision; moving a file changes its URL identity.

The key namespace is separate from savedfiles.json, burst-cache snapshots and Combined Review stores. Existing Delete Saved Files and Delete Cache paths do not explicitly clear these keys. Do not promise that either action resets manual regions. A preview-sidecar change updates render identity without invalidating a manual region still bound to the unchanged RAW file.

The host supplies synchronous main-actor storage methods. Package save failures remain pending for retry and surface in the panel; successful rendering does not establish that a region was saved. See the PhotoEvidenceKit guide.

Burst assessment storage

The in-app Assess All Bursts command publishes its results to session memory. The app can show them alongside saved MCP assessments in AI Assessments. Only the latter use the shared job store and its retention rules. BurstBatchAssessment

18 - Developer and API Documentation

Developer guides and internal Swift API references for RawCull.

Developer and API Guides

These guides follow RawCull’s normal flow of operation and explain its architecture, internal Swift interfaces, ownership, persistence and error handling.

GuideCoverage
RawCullApplication startup, catalog scanning, culling, analysis, and export.

The API references describe application-internal Swift interfaces, rather than HTTP endpoints or a versioned public SDK.

The RawCull guide is split into a narrative application tour and Internal Swift API method contracts. For current presentation and image-source policy, use Viewer Architecture and RAW Formats and Exposure Inspection.

The current guides also cover Review admission, explicit decision actions, ranked-pair assessment and the App Store release checks. The historical build-426 references include explicit burst-review commands, dedicated semantic-state ownership, AF evidence backfill and bounded preload saves. For measured behavior and its limits, read Performance Measurement.

18.1 - RawCull Developer Guide

RawCull developer documentation

Reviewed against RawCull 3.4.9 build 466 on 23 November 2026. Source revision

Read this guide in order for a tour from application launch to exported photographs. The walkthrough establishes the ownership and data-flow model; the API reference then explains individual operations, inputs, results and failure behavior. Source links identify the application revision used for each excerpt so the described implementation remains reproducible. Code marked source excerpt is copied from the implementation; usage example means an illustrative call inside the app module, with existing application objects and selected files. Neither kind is intended to be pasted into an unrelated standalone Swift program.

RawCull has no HTTP server or REST endpoints in the application workflows documented here. “API” means the internal Swift application interface. Requests are arguments and configuration; responses are return values or observable state. Errors use Swift error types, result cases, optional values, and presentation state—not HTTP status codes. These interfaces are generally internal to the app target, not a versioned public SDK.

Start with A photograph’s journey through RawCull, then continue through setup, architecture and the separate internal API reference.

  1. Developer setup and quick start — immediate development needs.
  2. Architecture and ownership — understand boundaries before making changes.
  3. Main function API reference — implement and debug workflows.
  4. Errors and recovery — interpret failures accurately.
  5. Stakeholder onboarding — review photographs without development knowledge.
  6. Comments and docstrings — document contracts consistently.
  7. Troubleshooting — resolve common development and operational issues.
  8. Contributing — preserve correctness and reviewability.
  9. Changelog template — record updates.
  10. Maintenance and automation — keep this guide useful over time.

A photograph’s journey through RawCull

Imagine opening a folder containing a short sequence of owl photographs. You want to inspect the images, find the sharpest frame, record a decision and export a keeper. That apparently simple interaction crosses several boundaries: permission to read the folder, metadata scanning, image decoding, state publication, saved decisions, optional model inference and output writing. RawCull coordinates those boundaries rather than treating the folder as a single array of images.

1. Launch creates the objects that will survive navigation

Begin in RawCullApp.swift. Its initializer asks RawCullApplicationState.live() for the application assembly and retains two roots: RawCullViewModel and RawCullIntelligenceRuntime.

Source excerpt — application initialization:

let applicationState = RawCullApplicationState.live()
let runtime = applicationState.intelligenceRuntime
_viewModel = State(
    initialValue: applicationState.viewModel,
)
_intelligenceRuntime = State(
    initialValue: runtime,
)
_burstBatchAssessment = State(initialValue: BurstBatchAssessment(
    qwen: runtime.modelRuntime.qwenInference as? QwenInferenceRuntime,
    prepareModel: { await runtime.settingsModel.refresh() },
    unavailableReason: runtime.settingsModel.canRunQwenReview
        ? nil : String(localized: "AI assessment needs at least 16 GB of unified memory."),
))

The workspace root assembles the catalog, selection and workflow owners. The runtime retains the AI feature instances, model runtime, settings model and downloads model. Opening a sheet or changing the focused photograph should use those same instances. Otherwise, a settings screen could configure one inference service while a review screen uses another.

Follow RawCullApplicationState.make(...) in RawCullIntelligenceRuntime.swift. It constructs a shared similarity model, passes it to similarity and semantic-search features, creates the view model, and binds the application context and settings consumer. Identity assertions at the assembly boundary check that these objects share the intended dependencies. This is the best entry point for understanding dependency wiring.

The main window then passes feature instances to RawCullMainView and injects workspace models and controllers through workspaceEnvironment(_:). Its startup tasks load culling data, apply stored scoring settings and refresh AI settings. Construction establishes ownership; those tasks initialize persisted and capability state.

2. Opening a folder is a guarded transition

In CatalogController+Loading.swift, startCatalogLoad(for:) first recognizes an already active source with valid access. Otherwise, it requests a transition from CatalogLifecycleCoordinator.swift.

The coordinator flushes pending decisions before allowing the replacement. After that suspension, it checks cancellation, transition generation and whether the requested source is still selected. A successful flush for folder B must not open B if the user has already selected folder C. A failed flush restores the previous source selection.

Source excerpt — transition admission after the save attempt:

guard !Task.isCancelled, transitionGeneration == generation,
      isStillSelected() else { return }
if didFlush {
    onReady()
} else {
    onFailure()
}

Once admitted, beginCatalogLoad(for:) clears selection, cancels old catalog work, resets the working arrays and obtains security-scoped access. The coordinator retains access for the load task. The URL identifies a location; the access grant keeps that location readable while work uses it. Cancelling the old catalog also invalidates the Combined Review lease and cancels hydration, burst analysis, thumbnail preload and preview-cache warming.

This explains why UI code should call the catalog controller instead of merely replacing files: replacing the array would skip save ordering, task cancellation and access management.

3. Scanning builds file descriptions before loading every preview

Open ScanFiles.swift. scanFiles(url:onProgress:) lists the immediate folder, skips hidden entries and admits formats recognized by RawFormatRegistry. It uses a task group with a bounded number of pending metadata reads. Before scheduling beyond that bound, it waits for a result. This limits simultaneous file access rather than starting a decode task for every photograph at once.

Each admitted file becomes a FileItem containing its URL, name, size, modification date, optional capture time, EXIF metadata and normalized autofocus point. RawCullFileItem.swift aliases FileItem and ARWSourceCatalog to RawCullCore domain types: the application uses package models through familiar local names.

Metadata and native focus information are read together. If no native focus locations were collected, the scanner attempts the catalog’s focuspoints.json fallback. This fallback is chosen for the collected scan, rather than filling each individual missing native point independently. Progress counts discovered supported files; it is not a count of successfully rendered previews.

Usage example — inspect metadata without starting the app’s catalog workflow:

let scanner = ScanFiles(maximumConcurrentReads: 2)
let discovered = await scanner.scanFiles(url: catalogURL)
let ordered = await ScanFiles.sortFiles(
    discovered,
    by: FileItemSortDescriptor(field: .name, direction: .ascending),
    searchText: ""
)
for file in ordered {
    print(file.name, file.size, file.dateModified)
}

This lower-level example is useful for understanding the scanner. It does not restore ratings, hydrate similarity artifacts or update the application’s current catalog. Also, metadata tasks finish in completion order; use the sorting operation when a deterministic presentation order matters.

4. The working set has several distinct projections

Back in handleSourceChange(url:), the catalog controller scans, sorts, assigns the discovered files, hydrates compatible similarity artifacts, constructs visible results, restores persisted decisions and scoring, and preloads thumbnails. It checks that the load is still active after asynchronous boundaries before publishing further state.

Read the following names as different questions, not interchangeable collections:

StateQuestion it answers
filesWhich files were discovered in the loaded folder?
catalogDisplayCandidatesWhich files pass filename filtering, in the requested base order?
filteredFilesWhich files are currently displayed after rating, sharpness and similarity/search rules?
activeCatalogFilesWhich files belong to the active catalog scope, including a semantic-search selection?
selectedFileIDWhich photograph currently has focus?
selectedFileIDsWhich photographs form the explicit grid selection?

For example, a folder may contain 200 files, filename filtering may admit 80, and a star filter may display 12. Semantic search can establish a further active selection used by downstream workflows. A count of selected thumbnails, a count of visible files and a count of files in the folder can all be correct while differing.

applyFilters(to:) first applies nonsemantic rules. When semantic results exist, it keeps and orders admitted files by semantic result order. An empty semantic index yields an empty visible result. Without semantic search, image-to-image similarity ordering can take precedence over sharpness ordering, with the anchor first.

Usage example — inspect the scope before choosing an operation:

print("Discovered:", catalog.files.count)
print("Visible:", catalog.filteredFiles.count)
print("Active scope:", catalogController.activeCatalogFiles.count)
let analysisInput = catalogController.aiAnalysisFiles(for: .gridSelection)
print("AI input:", analysisInput.count)

These are observations of current state. Do not reconstruct a workflow’s input by guessing from one count: use its input resolver.

5. A thumbnail request follows the cache and shares duplicate work

RequestThumbnail.swift is an actor that coordinates preview requests. It resolves a ThumbnailCacheKey from source identity, purpose and requested pixel size. With a usable key, concurrent callers for the same thumbnail join one in-flight request.

The resolution order is memory cache, disk cache, then the RAW loading interface. A disk hit is promoted to memory. A decoded image is added to memory and encoded to JPEG data for a background disk save. Display can proceed before that disk save finishes. If a trustworthy cache key cannot be produced, the actor still attempts to load the image, but avoids keyed cache reuse.

flowchart TD
    Request[Thumbnail request] --> Key{Usable cache key?}
    Key -->|yes| Shared[Join or create in-flight request]
    Key -->|no| Decode[Decode through RAW loader]
    Shared --> RAM{Memory hit?}
    RAM -->|yes| Return[Return image to waiting callers]
    RAM -->|no| Disk{Disk hit?}
    Disk -->|yes| Promote[Promote to memory]
    Promote --> Return
    Disk -->|no| Decode
    Decode --> Cache[Cache when identity is available]
    Cache --> Return

Each waiting caller has its own cancellation identity. Cancelling one waiter resumes that waiter with nil; the shared task is cancelled when no waiters remain. A request generation prevents a late result from completing a replacement request with the same key. These details matter when scrolling creates and destroys many thumbnail views quickly.

A nil return means no image is available to that caller, including cancellation or decode failure. It is not a recommendation to remove the source file from the catalog. Thumbnail loading and full JPEG export have different purposes and result contracts.

6. Rating changes state immediately and persists it separately

Follow the public action in CullingController+Ratings.swift, then the store in CullingModel.swift. The view model keeps the UI’s derived state consistent; the store updates the record identified by catalog and filename and schedules persistence.

The store must reach ready before mutations are admitted. A missing store initializes an empty collection. An unreadable or damaged store produces a failed load and blocks automatic mutation, preserving the original data for recovery.

Repeated updates debounce saving with a default delay of 350 milliseconds. Each scheduled save captures a snapshot and revision. If another edit occurs while an earlier save is suspended, that earlier save must not mark the newer state clean.

Source excerpt — clearing the dirty flag only for the saved revision:

try await saveHandler(snapshot)
if revision == persistenceRevision {
    hasUnsavedChanges = false
    persistenceError = nil
}

Usage example — apply a decision and explicitly inspect durability:

culling.updateRating(for: file, rating: 3)
if await ratings.cullingModel.flushPersistence() {
    print("Current decisions saved")
} else {
    print(ratings.cullingModel.persistenceError ?? "Save failed")
}

Normally the UI lets debouncing handle repeated ratings. A catalog transition or quit requires explicit flushing because the user is leaving the context containing those decisions. AppDelegate.beginTermination(...) in the application entry file delays termination, retries saving when requested and releases folder access only when quitting is accepted. Cancel Quit keeps the process and unsaved decisions alive.

7. Analysis input is resolved before inference starts

CatalogController+AIAnalysis.swift centralizes selection rules. Grid input uses explicit selected IDs or falls back to the focused photograph, intersected with visible files. Tagged input resolves saved ratings of at least 2 in the active scope. preserveAIAnalysisGridSelection() captures the fallback selection before browsing tagged photographs changes focus.

Sharpness scoring measures image detail, burst analysis groups and ranks related frames, and semantic search ranks compatible CLIP artifacts against text. Review evaluates the selected photos with the chosen preset. Results affect ratings only when the photographer acts.

The shared runtime also coordinates settings changes. apply(configuration:) rejects obsolete configuration revisions, avoids replacing unchanged services and updates the affected similarity, semantic-search or segmentation configuration. Model identity and preprocessing matter because cached evidence from one configuration may not be reusable under another.

8. Combined Review freezes a reproducible run

Read CombinedReviewFeature.swift alongside ReviewRunContract.swift. The feature coordinates execution and presentation; the contract defines snapshots, typed IDs, compatibility and work stages.

analyze(_:) prepares admission, acquires a shared lease and captures the preset, criteria, depth, source preference and retention settings. The worker then freezes source descriptions, retains catalog access, reads model identities, validates a run snapshot, saves its initial manifest and executes the work. The async method awaits that worker; returning still requires inspecting result and failure state because failures are captured internally.

The snapshot records what the run intended to analyze. The manifest records the run and its work. Compatibility keys describe whether evidence can be reused. Source fingerprints use path, size, modification time and file resource identity; they are metadata-derived fingerprints, not a full hash of every RAW byte.

The depth settings define budgets rather than a promise that every possible crop will run:

DepthCrops per imageCrops across selectionFollowups per imageFollowups across selectionPair cap
standard316000
deep832282
exhaustive16644164

The contract validates nonempty, uniquely identified input, nonblank criteria, supported source preference and bounded response tokens. Selections larger than eight require an expanded-selection plan in the snapshot contract; this does not mean the ordinary UI automatically supplies one. Regions must reference selected images and lie within normalized image bounds.

Resume revalidates source fingerprints, model identities and pipeline versions before continuing. A retained observation can remain useful even if report synthesis fails. Exact-input retention controls saved imagery, so deleting retained inputs and deleting review records are separate operations.

9. Export creates output; copying has its own process lifecycle

JPEG export uses ExtractAndSaveJPGs.swift and returns a batch result with successes and per-file failures. Embedded export uses the camera preview; developed export renders the RAW. These can look different because they use different image sources. Cancellation can leave successful outputs already written.

RAW copying starts through ExecuteCopyFiles.swift. It prepares access, selection and a unique include list before launching rsync. Startup success means the subprocess launched. Final completion and dry-run status determine what can be reported as copied. This is a different completion contract from awaiting a JPEG export result.

At this point the complete chain is visible: the assembly owns services, the lifecycle admits a folder, scanning creates domain records, projections determine scope, workers load imagery, decisions persist independently, analysis produces evidence, and explicit output workflows write or copy files. The reference below gives the individual calls for each part of that chain.

Developer setup and quick start

Requirements

The repository README specifies Apple Silicon, macOS 27, Xcode 27, and Swift 6. The Xcode project sets macOS deployment to 27.0 and Swift language version to 6.0; app configurations use default MainActor isolation. Use the project settings as the authority if these requirements change.

Open RawCull.xcodeproj in Xcode, choose the RawCull scheme and a local Mac destination, and resolve packages using the checked-in lockfile. Configure an appropriate signing team if Xcode requires it for your local build.

From the repository root:

xcodebuild \
  -project RawCull.xcodeproj \
  -scheme RawCull \
  -destination 'platform=macOS,arch=arm64' \
  -onlyUsePackageVersionsFromResolvedFile

Launch from Xcode, open a folder containing supported RAW photographs, inspect a preview, rate a frame, and export a JPEG to a separate destination folder. Start with a small catalog so problems are easy to isolate. Optional AI features require compatible local models; they are not needed for the basic browsing workflow.

make debug builds and exports a Debug archive. For ordinary development, the direct scheme build above avoids the release pipeline. make build signs, notarizes, staples, and creates a DMG; it requires configured release credentials and the external create-dmg tool. It is not the quick-start command.

Dependencies

ComponentResponsibility
SwiftUI and AppKitApp scenes, views, commands, macOS lifecycle and integration
Foundation, ImageIO, CoreGraphics, OSLogFiles, serialization, images and diagnostics
RawParserKitRAW formats, metadata, embedded JPEGs, rendered previews and MakerNotes
PhotoAnalysisKitFocus, sharpness, saliency and calibration
PhotoAIKitLocal AI capabilities, similarity, segmentation and model support
RawCullCoreShared photo, burst, ranking and review domain models
PhotoEvidenceKitManual close-up contracts, crop rendering and embeddable comparison UI
RsyncArguments and RsyncProcessStreamingCopy arguments and process execution
ParseRsyncOutputInterpretation of rsync output
DecodeEncodeGenericCodable persistence support

Read exact direct and transitive pins in Package.resolved. Model bundles are separate assets with separate licences; consult ModelAssets and its notices. Avoid copying a static version list into additional documents.

Tests and release checks

CommandWhat it verifies
make test-smokeEnumerates the smoke manifest before running the selected critical paths. Build 466 expects 384 unique test identifiers.
make test-fullRuns the RawCull plan serially with Thread Sanitizer.
make test-performanceVerifies the performance selection and runs that plan.
make analyzeBuilds for testing in isolated DerivedData and runs the SwiftLint analyzer against the clean compiler log, including unused declarations and imports.
make combinedreviewtest, make combinedinputstest, make combinedselectiontestOpt-in single-image Review, encoder/input-contract and six-file selection probes. Supply the relevant model assets and fixtures.
make releasesharpnesstestRuns the hostless Release sharpness comparison on the chosen catalog.

For a release candidate, tag the clean commit for the app’s Xcode marketing version and run make release-check. It runs preflight (including tag-on-HEAD and model provenance), the AI import boundary, MCP helper and Release store tests, then smoke tests. Confirm app and downloader build numbers match. Upload with make upload-app-store, install the processed build through TestFlight, verify its model downloads and workflows, then submit that tested build in App Store Connect. Upload and submission are separate steps. The Developer ID DMG has its own build path. Make targets · Release checklist

Architecture and ownership

Application structure

flowchart TD
    App[RawCullApp] --> Assembly[RawCullApplicationState.live]
    Assembly --> VM[RawCullViewModel]
    Assembly --> Runtime[RawCullIntelligenceRuntime]
    App --> Views[SwiftUI views and session models]
    Views --> VM
    Views --> Runtime
    VM --> Lifecycle[CatalogLifecycleCoordinator]
    VM --> Culling[CullingModel]
    VM --> Workers[Scan and thumbnail actors]
    VM --> Burst[BurstAnalysisCoordinator]
    Runtime --> Features[Similarity, Semantic Search, Review]
    Features --> Packages[PhotoAIKit and PhotoAnalysisKit]
    Workers --> Parser[RawParserKit through loading interfaces]
    Workers --> Cache[SharedMemoryCache and disk caches]
    Culling --> JSON[SavedFiles JSON]
    Features --> Artifacts[Analysis artifacts and review manifests]
    VM --> Export[JPEG export and rsync copy]

RawCullApp constructs the live application assembly once and retains the view model and intelligence runtime in SwiftUI state. The runtime supplies stable feature instances to views. Preserve shared identity: creating independent similarity or inference services in a view can split indexing, search, model configuration, and cancellation state.

RawCullViewModel assembles the workspace. CatalogController, CullingController, FileOperationsModel and BurstWorkflowController handle operations against dedicated state owners. Session models own focused UI interactions such as loupe, zoom, comparison and burst workspace state. CullingModel owns saved decisions and persistence state.

Actors coordinate scanning, decoding, caches and export. MainActor models publish UI-facing state. async describes suspension; it does not by itself guarantee background execution. Retain explicit actor boundaries and the existing loading interfaces when moving expensive work.

Catalog lifecycle

sequenceDiagram
    participant UI as Catalog selection
    participant VM as CatalogController
    participant LC as CatalogLifecycleCoordinator
    participant Store as CullingModel
    participant Scan as ScanFiles actor
    participant AI as Similarity feature
    UI->>VM: startCatalogLoad(for:)
    VM->>LC: Start guarded transition
    LC->>Store: flushPersistence()
    alt Save succeeds and source remains selected
        LC->>VM: Begin load and retain folder access
        VM->>Scan: scanFiles(url:onProgress:)
        Scan-->>VM: Files and focus metadata
        VM->>AI: hydrateCatalog(request)
        VM->>Store: ensureLoaded()
        VM->>VM: Restore decisions and preload thumbnails
    else Save fails
        LC->>VM: Restore previous selection
    end

Catalog and sort generations reject stale asynchronous results. Changing catalogs cancels existing load, preload, extraction, hydration and burst work and invalidates the Combined Review lease. File access must remain valid while downstream tasks use source URLs.

Persistence and cache boundaries

  • Decisions and compatible sharpness metadata are represented by SavedFiles and FileRecord. The default culling store is ~/Library/Application Support/RawCull/savedfiles.json.
  • CullingModel debounces writes, tracks unsaved changes, and exposes persistence failures. Catalog transitions flush pending decisions; app termination offers retry, cancellation or explicit discard if flushing fails.
  • Thumbnail identity includes source metadata and rendering identity. A path alone cannot safely identify a replacement image. Missing source fingerprint metadata disables thumbnail reuse.
  • Per-file analysis artifacts and burst snapshots have compatibility requirements. Do not interpret an artifact from a different backend or model as current evidence.
  • Combined Review retains run manifests, evidence and optionally exact model inputs. Clearing retained input images is different from deleting all reports.

Caches can be rebuilt; ratings and saved review records are user data. Recovery guidance must preserve that distinction.

Maintenance: revise diagrams when ownership, workflow ordering, persistence schemas, or package boundaries change.

Main function API reference

The detailed method tables and usage examples have moved to RawCull Internal Swift API. The walkthrough above introduces the owners; use the reference to inspect arguments, observable outputs, cancellation and recovery for a specific action.

Errors and recovery

These are source-level identifiers, not numeric API status codes. Preserve the associated message or underlying error in diagnostics. Do not promise a stable external error-code protocol.

Error surfaceCases or representationHandling
CopyStartupFailurersyncArgumentsUnavailable, missingViewModel, noMatchingFilesCheck copy configuration, application binding and selected/rated scope.
CopyStartupFailureapplicationSupportDirectoryUnavailable, includeFileWriteFailed(String)Restore writable support-folder access and free space; retry startup.
CopyStartupFailuresourceAccessFailed, destinationAccessFailedReopen source or reselect destination to restore access.
CopyStartupFailureprocessLaunchFailed(String)Inspect executable/configuration and supplied diagnostic.
CopyOutcomefailed(message:), cancelledReport the final process outcome; distinguish cancellation and partial output from success.
JPGExportResultsucceeded, [JPGExportFailure(fileName, message)]Report each failed file and retain successful output.
QwenModelErrormodelUnavailable, visionModelRequired, imageUnavailableValidate model capability or source image availability.
QwenModelErroremptyResponse, invalidStructuredResponse, invalidTokenLimitInspect bounded diagnostics/configuration; do not treat malformed text as an accepted assessment.
ReviewRunErrorinvalidSnapshot, sourceUnavailable, modelUnavailableCheck frozen input and installed capabilities; prepare a valid new run if needed.
ReviewRunErrorinvalidDependency, invalidTransition, budgetExhaustedInspect manifest ordering and limits; do not bypass execution admission.
ReviewRunErrorincompatible, corrupt, unsupportedVersion(Int)Preserve evidence and diagnose compatibility; rerun under current settings where appropriate.
ReviewRunErrorstorageLimit, invalidEvidenceReview retention/storage or evidence validation; do not synthesize unsupported conclusions.
Model download serviceserviceNotConfigured, backgroundAssetsUnavailable(String), releaseBlocked(String), assetPackNotFound(String), downloadedModelNotFound(String)Check distribution configuration, asset availability and validation.
Model download servicelicenceAcceptanceRequired(String), missingVerifiedLicenceText(String)Complete the actual licence/provenance flow; do not bypass it.
Culling JSON read.missing(URL), .loaded([SavedFiles]), .failed(SavedFilesReadFailure)Missing store is different from damaged/unreadable data. Failed data must not be silently replaced.
Settings / culling writesBool return plus persistence stateRetry after fixing storage/access; retain unsaved in-memory decisions.
Swift cancellationCancellationError or task cancellation statePreserve completed work where supported and stop presenting the operation as running.

Optional image returns and empty nonthrowing scan results do not carry a detailed error code. Use logs, capability state and the surrounding workflow to distinguish causes.

Maintenance: add new cases when error enums change; keep wording aligned with recovery behavior and tests.

Stakeholder onboarding

RawCull helps you choose photographs to keep. A catalog is a folder of photographs. A preview is a JPEG representation used for fast viewing. A burst group contains related frames that may be useful to compare.

  1. Open a folder. Choose a small RAW catalog first and allow scanning to finish. RawCull is focused on Sony ARW workflows; support for a camera’s metadata and previews depends on its format.
  2. Review photographs. Browse thumbnails, enlarge a frame, and compare detail. Focus points and sharpness overlays are evidence to inspect, not a replacement for your judgment.
  3. Record decisions. Use the rating/tag/reject controls. A rejection records a culling decision; it does not delete the original photograph.
  4. Compare related frames. Open burst comparison and inspect recommended candidates. Applying Keep Best or Keep Top Two changes the group’s ratings; undo is available for the last captured burst action.
  5. Try optional local AI. Install the required models through AI settings and complete their licence prompts. CLIP supports search, SAM 3 supports subject masks, and Qwen provides photo assessments. These features run locally; downloading model assets requires connectivity.
  6. Check the input scope. Review can use selected or tagged photos. Semantic search also narrows the active working set; clear it when you want the ordinary catalog again.
  7. Export keepers. Export JPEGs or copy RAWs to a chosen folder. Use copy dry run to inspect the planned operation. Check final completion and any per-file errors, then verify destination files.
  8. Close safely. If saving fails during quit, retry after restoring access or cancel quitting to keep changes in memory. Quit Without Saving explicitly discards unsaved decisions.

Example: for a sequence of owl photographs, open the folder, inspect the eye detail in comparison, rate the strongest frame, and export its embedded JPEG for a quick share. A developed RAW export can differ from the camera’s embedded preview.

In Review, select a finding to highlight its region and inspect the associated crop. Choose Region details for geometry and provenance. Open Coverage & limits or Technical record in the separate Review Record window. Review presets and subject masks

Maintenance: revisit onboarding when visible labels, input scope rules, export modes or recovery dialogs change. Avoid documenting shortcuts without checking the current command and keyboard-routing code.

Comments and docstrings

All proposed comments stay in this document; this documentation task does not change Swift source files. When applying comments in a later code change, place them on the actual declaration and keep them focused on its contract.

/// Starts a guarded transition to the requested RAW catalog.
///
/// Flushes pending culling decisions before replacing the current catalog.
/// The operation publishes progress through the view model rather than returning files.
/// - Parameter source: Catalog to open, or nil to clear the current working set.
func startCatalogLoad(for source: ARWSourceCatalog?)

/// Rates compatible cached CLIP artifacts for the current admitted files by query relevance.
///
/// Applies the selected results as the application's active catalog scope.
/// This operation does not create missing image embeddings.
/// - Parameter query: Natural-language description; blank text clears search.
func search(for query: String) async

/// Exports the files configured at initialization into the selected destination.
///
/// Completed output remains on disk if cancellation stops the batch.
/// - Returns: Successful export count and per-file failures collected during the run.
func extractAndSavejpgs() async -> JPGExportResult

/// Flushes pending culling decisions before leaving the current workflow.
/// - Returns: True if persistence succeeded or no changes required writing;
///   false if loading or saving failed. Inspect persistence state for details.
func flushPersistence() async -> Bool

/// Prepares and launches the configured rsync operation.
/// - Returns: Startup success or a typed preparation/launch failure.
///   Startup success does not indicate that the copy has completed.
func startCopyFiles() -> Result<Void, CopyStartupFailure>

These are declaration/comment examples, not a compilable extension. For throwing APIs, include - Throws: and describe when the error occurs. For stateful APIs, document the observed state and cancellation behavior. Explain important invariants inline, for example:

// Reject an obsolete catalog result so a completed scan cannot replace a newer selection.
// Helper function: resolves a display title from an already determined copy outcome.

Do not document every trivial formatter or view builder separately. Mark a helper’s purpose where it is not obvious. Avoid comments that only repeat a function name or claim guaranteed success for asynchronous work.

Maintenance: change comments in the same review as their function contract. DocC generation becomes useful once these comments are applied to source; Markdown snippets alone do not populate symbol documentation.

Troubleshooting

SymptomLikely checksRecovery
Project will not buildSelected Xcode/SDK, macOS target, pinned package resolution and signingUse Xcode 27 and supported Mac; inspect the first actionable build error. Resolve the checked-in package graph before changing versions.
Folder appears emptyImmediate directory contents, supported RAW extensions, hidden files and accessOpen the folder containing the files directly; reopen permission through the picker and inspect scan logs. Scan is nonrecursive.
Old catalog appears after switchingPersistence flush failure or stale task handlingResolve save failure first. In development, inspect lifecycle generation guards and current source identity.
Thumbnail or preview is missingSource access, changed file metadata, decoder result, cache identityReopen source; retry decoding with an isolated fixture. Do not disable source-fingerprint checks to force reuse.
Focus points are absentCamera metadata availability and parser supportConfirm metadata for that camera/file; allow browsing without the overlay.
Ratings appear lost or do not persistLoad failure, unsaved state, storage permissions and available spaceRetry persistence. Preserve a damaged store before the explicit archive/reset recovery action. Do not delete savedfiles.json as a first step.
Quit is blockedPending decisions failed to saveRetry after restoring access/freeing space or cancel quitting. Use discard only when losing pending changes is acceptable.
Sharpness used fewer files than expectedSelection, star filter and semantic scopeInspect sharpnessScoringTargetFiles and its displayed target description; clear scope if appropriate.
Semantic search finds nothingCLIP availability, compatible indexed count, rating/name admissionIndex with a compatible CLIP backend, then search again. A search does not automatically decode missing source images.
AI action is disabledModel validation, missing licence, empty input/prompt, another operationInspect capability and progress state; complete model installation or finish/cancel the conflicting review.
Review has no usable subject maskPreset, SAM 3 availability, segmentation result and retained imageDescribe has no mask stage. In Focus check or Full, inspect Coverage & limits for segmentation or registration failures.
Combined Review cannot resumeSource changed, model identity changed, contract/version mismatchPreserve saved evidence; start a new run with current inputs and settings when compatibility cannot be restored.
Combined Review shows observations onlySynthesis failed or evidence was insufficientRead retained observations and coverage limits; do not relabel them as a completed recommendation.
JPEG export partially failsPer-file decode/write messages and destination accessRetain successful output, fix the named cause and retry affected files.
RAW copy does not startTyped CopyStartupFailureCheck active scope, rsync configuration, source/destination access and writable include-list storage.
Dry run completes but destination is emptyCopyOperation.dryRunRun an actual copy after reviewing the preview. A dry run is not an export.
Test manifest verification failsChanged suite names/selectors or countsUpdate the source, response file and expected enumeration inventory together when the change is intentional.
Tests depend on local user filesProduction singletons or hardcoded paths in fixturesUse isolated cache/settings/model factories; move real-photo probes to the opt-in release path.

For a reproducible issue, record the app/build version, macOS/Xcode version, workflow, source format, active filters, selected model/backend and exact error. Prefer synthetic or permission-cleared sample files when sharing a reproduction. Logs and retained diagnostics may include filenames or source paths.

Maintenance: add an entry when a recurring issue gains a verified recovery path, and remove obsolete workarounds after fixes.

Contributing

The following is a recommended team workflow grounded in the current boundaries and test architecture; it does not imply a repository-enforced PR policy.

  1. Describe the user-visible problem and identify the owning model, actor or feature before changing code.
  2. Keep views focused on presentation and user intent. Reuse the runtime’s shared feature instances and the existing injectable service boundaries.
  3. Preserve MainActor ownership, bounded decoding concurrency, security-scoped access lifetimes and cancellation checks. Never apply stale catalog/model results to current state.
  4. Treat persistence and compatibility as part of the change. Keep nil ratings distinct from zero, preserve damaged data for recovery, and update signatures/schema versions when reuse rules change.
  5. Add meaningful behavior tests for changed logic using Swift Testing and isolated temporary stores. Existing helpers in TestIsolationHelpers.swift provide cache, settings, thumbnail and view-model isolation.
  6. Update manifest selectors and expected enumeration inventory when adding/renaming selected suites. Keep deliberately shared-state stress tests explicit.
  7. Run relevant checks, then the appropriate broader test target. For AI-boundary changes, run make verify-ai-import-boundary; use installed-model checks when actual inference compatibility needs verification.
  8. Update this document, relevant source comments and release notes in the same change. Explain observable behavior, validation and remaining limits in the review description.

Example review description:

Problem: semantic results from an earlier catalog could overwrite a newer selection.
Change: reject completion when the catalog generation no longer matches.
Validation: isolated catalog-switch regression test and smoke suite.
Documentation: updated catalog lifecycle and cancellation notes.

Keep credentials, signing keys, private photo fixtures and downloaded model bundles out of source control. Model redistribution must follow the repository’s licence/provenance records. Use the current release scripts and preflight checks for distribution rather than recreating their steps from memory.

Maintenance: revisit this guidance when test infrastructure, release processes or code ownership change.

Changelog template

Use this template for future entries. It is not a claim that any listed change has shipped. Order released entries newest first; move completed items from Unreleased into the actual release version and date.

# Changelog

## [Unreleased]

### Added
- User-facing feature and the workflow it enables.

### Changed
- Observable behavior change and affected input/scope.

### Fixed
- Trigger, previous behavior and corrected result.

### Compatibility and data
- Minimum macOS/Xcode changes, model/backend compatibility,
  persistence migration or cache invalidation requirements.

### Developer documentation
- API contracts, diagrams, onboarding or troubleshooting updates.

### Validation
- Relevant automated checks and opt-in model probes completed.
- Known limitations or checks not performed.

## [X.Y.Z] - YYYY-MM-DD

### Added
- ...

### Changed
- ...

### Fixed
- ...

### Compatibility and data
- ...

Example prospective entry: “Fixed: changing catalogs during indexing no longer applies results from the previous catalog.” Replace examples with verified changes before publishing. Do not infer release history from the current source tree.

Maintenance: review Unreleased during every release and verify the version against Xcode project metadata.

Maintenance and automation

The API reference and recovery rules are the immediate priority. Setup, architecture and isolated tests support sustained development. Onboarding and changelog entries should evolve with visible features and releases.

Documentation areaReview triggerSuggested automation
API functions and errorsSignature, state or enum changeCI symbol/enum inventory diff that flags documentation review; a human confirms semantics.
Setup and dependenciesSDK, scheme, target or package updateCompare documented requirements with project settings; link the lockfile instead of duplicating pins.
Architecture diagramsOwnership, service wiring or lifecycle changeRender Mermaid in documentation CI and check referenced source paths.
Source docstringsMain entry-point changeAdopt DocC for documented symbols and publish generated output after validating target support.
OnboardingUI label, selection or export behavior changeAdd a release-review checklist with a short real workflow walkthrough.
TroubleshootingRepeated incident or recovery changeLink issue reports to regression tests and update the verified recovery entry.
Contribution/testing guideTest selector or isolation rules changeReuse existing manifest enumeration checks and AI import-boundary verification.
ChangelogRelease preparationGenerate a draft from reviewed changes, then edit for behavior and compatibility rather than raw commit titles.

Additional suggested documentation checks, beyond the source-review selector described in the review record: Markdown lint, local-link validation, Mermaid rendering, fenced Swift snippet validation in a suitable app test harness, and documentation-review prompts when core files change. Keep context snippets separate from standalone compilable examples.

A maintainer should review this document whenever a main workflow changes and during release preparation. Record the review date only after checking implementation and commands. Generated documentation can detect drift, but it cannot establish cancellation semantics, privacy claims, failure recovery or the meaning of a photographic recommendation without implementation review.

Current viewer, format and Settings architecture

The October viewer refactor removes the old GridThumbnailViewModel environment object and composes focused loupe, zoom, burst, comparison and AI sections. Sessions retain source/viewport state; presentation models and coordinators own async results and keyboard lifetimes. Read Viewer Architecture for the full trace.

RawParserKit 1.3.2 adds generic RAW admission through macOS decoding. Display support, camera AF metadata, RAW 9 availability and embedded-byte export remain separate capabilities. Temporary exposure inspection has its own serialized renderer, display histogram and clipping overlay; it writes no editing sidecar. See RAW Formats and Exposure Inspection.

Single Images opens one synthetic workspace while persisting real singleton group states. Saved Files cleanup now lives in Settings, and Delete Cache also removes stored Combined Review evidence. Follow Burst Groups and File Read and Write before changing these user-visible behaviors.

Build 426 ownership and validation

Review decisions live in BurstReviewSessionModel; semantic evidence and queries live in RawCullSemanticSearchModel, retained by the similarity model. Existing interfaces forward to them. Use the internal API commands instead of assigning result/state dictionaries.

Preload releases each file’s grid gate before awaiting saving, and retains its worker slot and catalog grant through completion. See Performance Measurement for the cache-preserved recordings and the unproven backlog-performance benefit.

The smoke manifest expects 384 unique identifiers; parameterized invocations are separate from identifier counts. make releaseafcomparison is an additional opt-in real-photo export/comparison workflow, not a production scoring change.

Catalog progress and navigation updates — October 25

handleSourceChange(url:) owns separate metadata and thumbnail progress coalescers. They publish intermediate observable values at a 100 ms cadence and initial/terminal values immediately. Cancelling or replacing a catalog cancels pending ticks and rejects obsolete callbacks. The pipeline still accounts for every file; thumbnail readiness and awaited disk saves do not wait for presentation ticks. ProgressCount animates only the ring for 100 ms and respects Reduce Motion.

Zoom navigation reuses a revision-keyed projection rather than rebuilding ordered files and lookup maps on every selection. Sharpness control descriptions use a membership count without sorting the target execution list. See Viewer Architecture and Performance Measurement for the cache inputs and evidence limits. The October 24–25 investigation retained no further encoder, grid, parser or picker optimizations in Phases 3–6.

October 31 integration

Build 428 introduces RAWPreviewRenderer, RAWPreviewCache and RAWPreviewSizing for bounded ZoomView fit pixels, native geometry and exposure inspection. ZoomPreviewHandler.loadOverlayRAWPreview preserves native JPEG/disk-cache policy. See RAW inspection and performance.

November 2–3 preview presentation

ZoomView now distinguishes reduced previews from full-detail RAW results using renderer-provided metadata and shows preparation progress plus the latest request duration. See viewer ownership and the internal API for publication and cleanup. The expanded scripts guide documents benchmark, analysis and repository-check commands, including make test-scripts for fixture-based Python checks.

3.4.0: manual Close-ups and review maintenance

The shared burst/Single Images workspace embeds PhotoEvidenceKit’s three library modules. The host supplies catalog access, file/render identity, preview/RAW loading, orientation-corrected AF targets and UserDefaults region storage. The package owns manual-region interaction, retained references, crop geometry and bounded display artifacts. The panel shares source choice with the main stage, while its comparison membership and rendering lifetime remain separate.

Manual regions and pinning do not set ratings, override winners, recompute scores or automatically submit Combined Review. The existing Delete Cache and Delete Saved Files commands do not explicitly clear manual-region preference keys. Read Burst Groups, Viewer Architecture, and internal adapter contracts.

The review record now documents a machine-readable baseline and read-only source-change selector. Use it before another documentation pass; unmatched changes require triage rather than an automatic no-review decision.

3.4.5 development branch inspection

The manual panel has a separate automatic inspection strip for human faces and animal landmarks. The host owns preview admission, cancellation and human face cache compatibility. See Close Up and the internal API.

Metal cache console messages

The source troubleshooting guide describes MDB_MAP_FULL messages from macOS Metal’s per-user shader archive database. If they recur, the guide shows how to identify and clear RawCull’s Metal cache while the app and tests are stopped. RawCull troubleshooting

18.2 - RawCull Internal Swift API

Application-internal catalog, culling, preview, scoring, similarity, AI, persistence and copy method contracts.

RawCull Internal Swift API

Use this reference alongside the application walkthrough. These Swift interfaces belong to the RawCull application target. This review covers 3.4.9 build 466. Observable progress and completion state remain part of asynchronous contracts. Source excerpts show the reviewed implementation; usage examples are illustrative calls inside the application target.

Internal method reference

Calling conventions

Examples below run inside the app module. Names such as catalogController, culling, ratings, burstWorkflow, runtime, feature, file, groupFiles, source, and destinationURL represent existing, correctly configured instances or selected values. They are context snippets, not standalone programs. Use MainActor context for UI-facing models and await for actor calls. Void-returning actions often communicate success or failure through observable state, so completion alone is not proof of success.

1. Catalog loading and sorting

Source: CatalogController+Loading.swift, ScanFiles.swift.

FunctionRequestResponse and effects
startCatalogLoad(for:)Optional ARWSourceCatalogReturns Void; schedules a persistence-safe transition. A nil source clears the working set. Same active source with access is a no-op.
handleSourceChange(url:) asyncActive catalog URLScans, sorts, hydrates compatible similarity state, restores ratings/scoring, and preloads previews. Guards against obsolete catalog results.
cancelCatalogLoad()NoneCancels transition and active load-related tasks. Does not delete catalog files.
ScanFiles.scanFiles(url:onProgress:) async -> [FileItem]Folder URL; optional MainActor progress callbackScans immediate directory contents, skips hidden files and admits formats recognized by RawFormatRegistry; reads metadata with bounded concurrency. Focus metadata is available through decodedFocusPoints.
ScanFiles.sortFiles(_:by:searchText:) async -> [FileItem]Files, FileItemSortDescriptor, filename querySorts by name, modification date or size and filters names case-insensitively. This is filename filtering, separate from semantic search.
handleSortOrderChange() asyncCurrent sort and filter stateUpdates catalogDisplayCandidates and filteredFiles; ignores superseded work.
applyFilters(to:) -> [FileItem]Pre-sorted filesApplies rating/sharpness policies and semantic ranking or image similarity ordering. Semantic empty-index state yields no visible results.
// App UI entry point; this schedules the lifecycle transition.
catalogController.startCatalogLoad(for: source)

// Lower-level scan for an isolated integration path.
let scanner = ScanFiles()
let files = await scanner.scanFiles(url: catalogURL) { count in
    print("Discovered \(count) RAW files")
}
let ordered = await ScanFiles.sortFiles(
    files,
    by: FileItemSortDescriptor(field: .name, direction: .ascending),
    searchText: "DSC"
)

The scanner is nonthrowing; directory errors produce an empty result, and its catch-path warning is currently commented out. Cancellation detected after collection also returns an empty array. An empty array does not distinguish an empty folder from an access/read problem. In the app, prefer the lifecycle entry point over directly invoking its worker.

Helper functions: beginCatalogLoad, isActiveCatalogLoad, resetCatalogWorkingSet, and selection reconciliation implement transition bookkeeping.

2. Culling decisions and persistence

Source: CullingController+Ratings.swift, CullingModel.swift.

FunctionRequestResponse and effects
updateRating(for:rating:)One FileItem or an array, integer ratingUpdates saved decisions for the selected catalog and refreshes derived UI state. No selected catalog means no mutation.
updateRatingAndAdvance(for:rating:in:)File, rating, explicit ordered listRates the file, marks an active comparison group reviewed, and selects the next item when present.
rating(for:) -> Int?FileReturns explicit cached rating or nil.
getRating(for:) -> IntFileReturns rating or zero; this collapses unrated and explicit zero for display.
extractTaggedfilenames() -> [String]Current catalog and active scopeReturns stored names rated at least 2 within activeCatalogFiles.
extractRatedfilenames(_:) -> [String]Minimum ratingReturns qualifying names from filteredFiles.
ensureLoaded() async -> BoolNone, on CullingModelLoads the store if necessary; false indicates loading did not succeed.
flushPersistence() async -> BoolNone, on CullingModelImmediately persists pending changes; true also covers an already clean store.
retryCullingPersistence() async -> BoolNone, on CullingControllerRetries loading or saving and restores presentation after successful load recovery.
archiveCullingStoreAndReset() async -> BoolNone, on CullingControllerArchives a damaged store before resetting; subsequent save can still fail. This is a recovery action, not normal loading.
clearCurrentCatalogCullingState() / clearAllCullingState()Current catalog / all stored catalogsClears saved culling state at the indicated scope; expose through the app’s explicit user action.

Rating conventions: -1 means rejected; .keepers filters explicit 0; star filters use 2...5. A nil stored rating is distinct from explicit zero, even though getRating displays both as zero. Do not invent a one-star convention.

culling.updateRating(for: file, rating: 3)
let persisted = await ratings.cullingModel.flushPersistence()
if !persisted {
    print(ratings.cullingModel.persistenceError ?? "Save failed")
}

Response example: rating a file at 3 updates in-memory decisions immediately, while persistence may still be pending. Check hasUnsavedChanges, persistenceError, and load-failure state when reporting durability.

Helper functions: rebuildRatingCache, refreshCullingDerivedState, and scheduleSave maintain projections and write scheduling.

3. Preview loading, zoom and JPEG export

Source: RequestThumbnail.swift, FileOperationsModel.swift, ExtractAndSaveJPGs.swift.

FunctionRequestResponse and effects
RequestThumbnail.requestThumbnail(for:targetSize:purpose:) async -> CGImage?Source URL, pixel size, ThumbnailCacheKey.PurposeResolves cached/generated thumbnail; coalesces matching requests. Nil means no image was produced.
SelectionModel.select(_:)FileChanges the focused file and reconciles the selected IDs.
WorkspaceNavigationModel.closeZoomOverlay()NoneCloses the overlay. Session models hold detailed interaction state.
presentExtractJPGsSheet()Current selectionPrepares the export sheet.
startSelectedJPGExtraction(destination:exportMode:)Destination ARWSourceCatalog, ExtractJPGExportModeStarts selected-file export and publishes completion/failure presentation.
ExtractAndSaveJPGs.extractAndSavejpgs() async -> JPGExportResultFiles, destination and mode supplied at initializationReturns successful count plus per-file failures. Empty input returns zero successes and no failures.
cancelExtractJPGSTask()None, on exporterRequests cancellation. Result counts can describe partial work.
ScanAndExtractJPGs.extractCatalogJPGs() async -> IntSource URLs configured on the actorWarms the full-size preview cache. The count is processed files, including cache hits and unsuccessful decode attempts—not successful exported files.
abort()Current catalog workflowCatalogController cancels catalog loading and JPG work through their owners.
let exporter = ExtractAndSaveJPGs(
    files: selectedFiles,
    destinationCatalogURL: destinationURL,
    exportMode: .embeddedJPG
)
let result = await exporter.extractAndSavejpgs()
print("Saved: \(result.succeeded)")
for failure in result.failures {
    print("\(failure.fileName): \(failure.message)")
}

.embeddedJPG exports embedded preview data. .demosaicedRAW renders a full-size JPEG through SonyRawFormat. Output names are name.jpg and name_demosaic.jpg; collisions produce numbered suffixes such as name (1).jpg. Existing files are protected by exclusive creation. Cancellation is cooperative and does not remove already written output; JPGExportResult has no separate cancellation flag.

Helper functions: SaveJPGImage.outputURL, JPEG encoding, timing estimates, progress callbacks, and per-file extraction routines support the public workflow. SaveJPGImage.save performs the actual throwing write.

4. Sharpness and focus analysis

Source: CatalogController+Sharpness.swift, SharpnessScoringModel.swift.

calibrateAndScoreCurrentCatalog() async calibrates and scores sharpnessScoringTargetFiles, re-sorts, and persists compatible scoring metadata after a non-cancelled run. Despite its name, the target may be a selection or filtered scope:

  1. Explicit selected IDs take precedence.
  2. A star filter narrows scoring to that rating.
  3. Otherwise, scoring uses the active catalog scope, including semantic-search selection when active.

handleSharpnessSortingChange(isEnabled:) async applies current sorting and selects the first visible file when sharpness sorting is enabled. Read sharpnessModel.scores, afPointScores and saliencyInfo for results; these are measurements, not guaranteed judgments of photographic quality.

await catalogController.calibrateAndScoreCurrentCatalog()
let score: Float? = sharpnessModel.scores[file.id]

CatalogWorkspace.focusPoints(forFileWithID:) -> [FocusPoint]? supplies selected-image focus information when available. Missing camera metadata is a supported absence; overlays must not invent focus points.

Helper functions: calibration adapters, persisted-score hydration, mask rendering and numeric scoring routines support these workflows. Preserve scoring signatures when reusing saved measurements.

Source: RawCullSimilarityFeature.swift, RawCullSemanticSearchFeature.swift.

FunctionRequestResponse and effects
hydrateCatalog(_:) async -> BoolRawCullSimilarityCatalogHydrationRequestLoads compatible cached artifacts for a catalog identity; false covers rejected or obsolete hydration.
indexCurrentCatalog(forceRefresh:) asyncOptional refresh flag, default falseBuilds similarity artifacts for the current application scope. Read feature indexing progress and capability.
hasCompleteIndex(for:) -> BoolFilesReports coverage; does not perform indexing.
search(for:) asyncNatural-language queryRanks admitted files with compatible cached CLIP artifacts and applies result selection to the application. Blank text clears search.
resultEvidence(for:)File IDOptional rank and score for CLIP results. Rank is one-based; score is not a calibrated probability.
setShowsAllResults(_:) async / adjustSelection(by:) asyncResult scope flag / count deltaChanges active semantic selection and invalidates scoped burst analysis.
clear() async / cancel() asyncNone, on semantic featureClears or cancels search and restores ordinary catalog presentation.
await runtime.similarityFeature.indexCurrentCatalog()
await runtime.semanticSearchFeature.search(for: "an owl in flight")
let ids = runtime.semanticSearchFeature.orderedResultIDs
let summary = runtime.semanticSearchFeature.resultSummary

Search does not decode or index missing images as a side effect. It requires compatible CLIP artifacts; a Vision similarity backend alone does not supply text search. Read presentation, state, progress, and hasEmptyIndex to explain availability. A held Combined Review lease prevents starting a semantic search.

Semantic results create a durable active catalog scope used by other workflows until cleared or reindexed. Filename and rating admission still apply before semantic ranking. This matters when an export or analysis operates on fewer files than the whole folder.

Helper functions: generation checks, application binding, identity probes, backend projections, and selection reconciliation coordinate shared state.

6. Burst grouping and decisions

Source: BurstWorkflowController+Grouping.swift, BurstAnalysisCoordinator.swift.

FunctionRequestResponse and effects
reindexBurstAnalysis() asyncCurrent catalog scopeRebuilds burst analysis through the coordinator.
reGroupBursts() asyncCurrent state and grouping configurationRecomputes grouping using the application’s current analysis context.
restoreExistingFullCatalogBurstAnalysis() async -> BoolCurrent catalogAttempts to restore full-catalog analysis; inspect returned success.
keepBestInGroup(from:)Group filesWhen admitted, rates the winner 3 and others -1, captures undo and marks a decision applied. Winner preference is manual override, recommendation, sharpest file, then first file.
keepTopTwoInGroup(from:)Group filesWhen admitted, rates first 3, second 2 and remaining frames -1, with undo capture.
compareBurstGroup(_:)Group filesOpens group comparison.
undoLastBurstAction()NoneRestores the most recently captured burst action.
markBurstGroupReviewed(groupID:) / deferBurstGroup(groupID:)Group IDUpdates review-queue state.
advanceToNextBurstGroup(after:) -> BoolCurrent group IDAttempts navigation; false means no next activation was made.
burstWorkflow.compareBurstGroup(groupFiles)
// Invoke after the user chooses to apply the group decision.
burstWorkflow.keepBestInGroup(from: groupFiles)

These actions update culling decisions; rejection is a rating, not deletion of source RAW files. Empty or ineligible groups can be no-ops. Inspect ranking confidence and cautions before presenting automatic recommendations as certain.

Helper functions: group signatures, cache snapshots, ranking assembly, undo capture and review-state serialization maintain compatibility and presentation.

7. AI analysis input and feature actions

Source: CatalogController+AIAnalysis.swift and feature files under RawCull/Intelligence.

aiAnalysisFiles(for:) -> [FileItem] resolves .gridSelection or .taggedImages. Grid selection uses selectedFileIDs, falling back to the focused ID, and admits only visible filtered files. Tagged input uses persisted ratings of at least 2 within the active scope. preserveAIAnalysisGridSelection() freezes the fallback batch before browsing tagged images changes focus.

The Review workspace passes this selection into CombinedReviewFeature. The separate burst-list action calls BurstBatchAssessment.makePlan(catalog:catalogName:generation:groups:results:files:) using completed rankings. Its start(_:navigation:isStillCurrent:) publishes session entries and rechecks the generation between groups. BurstBatchAssessment

For result actions, ReviewDecisionActions.act(on:_:) resolves a saved file and checks its fingerprint before executing the closure. Tagging sets two stars. A rating of three or more disables the tag toggle. burstGroupID(for:) returns a group only for unambiguous membership, which controls whether Mark Reviewed is available. ReviewDecisionActions

8. Review run API

Source: CombinedReviewFeature.swift, ReviewRunContract.swift, and execution/backend files in the same directory.

FunctionRequestResponse and effects
prepareParameters(_:) async[ReviewSelectedFile]Prepares admission and model/source information for the selected input.
canStartReview(for:) -> BoolSelected filesEvaluates current admission; it does not run review.
analyze(_:) asyncSelected files plus preset, criteria, depth, source preference and retention propertiesAcquires the shared lease, freezes source metadata, validates models and snapshot, persists manifest, executes stages and publishes results.
restoreStoredRun() asyncNoneRestores latest manifest and saved history when idle.
resume() asyncExisting manifestRevalidates sources, models, pipeline and artifacts before resuming compatible pending work.
cancel()NoneCancels worker and marks the manifest; completion handling retains finished evidence.
exactInput(_:) async -> CGImage?Retained input keyDecodes retained image when available; nil does not imply the report is missing.
currentManifest() throws -> CombinedReviewRunV1Current stateReturns the validated current manifest or throws.
clearAllReviews() async throwsNoneDeletes stored reviews through the feature’s cleanup path.
clearRejectedResponses() async throws / clearRetainedInputs() async throwsNoneRemoves optional rejected-text diagnostics / retained source inputs.
// selectedReviewFiles is the UI-prepared [ReviewSelectedFile].
feature.criteria = "Compare subject detail and explain coverage limits."
await feature.prepareParameters(selectedReviewFiles)
if feature.canStartReview(for: selectedReviewFiles) {
    await feature.analyze(selectedReviewFiles)
}
let manifest = feature.manifest
let failure = feature.failureMessage

preset selects the work graph. Historical snapshots without it decode as Full. See preset requirements. Depth uses standard, deep or exhaustive budgets. The run records criteria, source fingerprints, model identities, stage versions, pipeline/render versions and retention policy. Source, overview, segmentation, identity, measurement, CLIP, crop observation, reconciliation, report and comparison are explicit stage categories; work dependencies and budgets constrain execution.

Success is observable evidence and run state, not simply the absence of a thrown error: analyze catches failures into failureMessage and progress. Failed synthesis can leave observations without a synthesized conclusion. Resume rejects changed sources or incompatible models/contracts rather than silently merging different evidence. Exact-input retention consumes storage and is optional.

Helper functions: manifest construction, work IDs, evidence grounding, geometry, mask registration, source decoding and budget admission implement the review contract.

9. Model installation and settings

Source: RawCullAIModelDownloadsModel.swift, RawCullAIModelDownloadService.swift, SettingsViewModel.swift.

FunctionInputResponse and effects
refresh() asyncNone, on downloads modelRefreshes installation states and applies managed locations to the configured consumer.
acceptModelLicence(for:) asyncRawCullAIModelDownloadIDRecords acceptance through coordinator; errors become failed download state.
startModelDownload(_:)Model IDStarts only when the current state admits download and no conflicting task/removal exists. Returns before download completes.
cancelModelDownload(_:)Model IDRequests download cancellation.
removeManagedModel(_:) asyncModel IDRemoves an idle managed model and refreshes capability state.
SettingsViewModel.ensureLoaded() asyncNoneEnsures settings loading has been attempted.
saveSettings() async -> BoolCurrent settings valuesSaves settings; inspect false and persistence-failure state.
retryPersistence(_:) asyncOptional failed settings operationRetries settings persistence.
asyncgetsettings() async -> SavedSettingsNoneReturns settings snapshot across the model’s isolation boundary.
let settings = await SettingsViewModel.shared.asyncgetsettings()
print(settings.thumbnailSizePreview)
let didSave = await SettingsViewModel.shared.saveSettings()

Download state is explicit: checking, unavailable, licenceRequired, notConfigured, ready, downloading, validating, installed, removing or failed. Downloading bytes is not the same as a validated installed model. App Store and self-hosted distribution can use different delivery mechanisms; use configured services rather than hardcoded download URLs.

Helper functions: catalogue descriptors, capability validation, licence provenance, presentation mapping and configuration revisions support model management.

10. RAW copy and process completion

Source: ExecuteCopyFiles.swift.

ExecuteCopyFiles.startCopyFiles() -> Result<Void, CopyStartupFailure> resolves configuration and selected files, obtains source/destination access, writes an operation-specific include list and launches streaming rsync. Its instance carries config, dryrun, rating, copyTaggedFiles and the bound view model. A successful return means the process started; it does not mean copying completed.

// copyOperation is an ExecuteCopyFiles configured by the copy UI.
switch copyOperation.startCopyFiles() {
case .success:
    print("Copy process started; await completion presentation")
case .failure(let error):
    print(error.localizedDescription)
}

Completion is represented by CopyDataResult, containing output, view output, CopyOutcome, and the frozen CopyOperation settings. Outcomes are .success, .failed(message:) and .cancelled. CopyOperation.dryRun distinguishes a preview from an actual copy; a successful dry run must not be reported as files copied. close() stops/closes the operation through its cleanup path.

Helper functions: streaming handler setup, unique include-list generation, output parsing, bookmark resolution and cleanup support startup and completion. Preserve unique include lists so overlapping operations cannot overwrite each other’s selection.

Reading asynchronous code without losing the thread

When following an async function, track three things: the state captured before suspension, the work performed by the awaited call, and the conditions checked before publishing its result. Actor isolation serializes access to actor state, but another operation can change that state while the function is suspended.

handleSortOrderChange() is a compact example. It captures the sort generation, catalog identity, selected source, sort order and text. After sorting, it verifies that those inputs still describe the current request.

Source excerpt — publication guard in CatalogController+Loading.swift:

let sorted = await self.catalog.sortFiles(self.catalog.files, order, text)
guard !Task.isCancelled, self.catalog.sortGeneration == generation,
      currentSimilarityCatalogSnapshot.identity == catalog,
      self.catalog.selectedSource == source, self.catalog.sortOrder == order, self.catalog.searchText == text else { return }
self.catalog.catalogDisplayCandidates = sorted
self.catalog.filteredFiles = applyFilters(to: sorted)

Cancellation asks work to stop; the identity and generation checks decide whether its answer still belongs to the current application state. Both are needed because an awaited dependency can complete after cancellation or after the user changes the request. The function’s deferred cleanup also checks the generation before clearing isSorting, so an older sort cannot hide a newer sort’s progress.

Use this pattern as a reading aid throughout catalog loading, similarity hydration and model configuration. A guard after an await often expresses an ownership rule, not just defensive boilerplate.

Use the tests as executable explanations

After following the implementation, open the corresponding tests. Their arranged state and expected outcomes make edge cases concrete. These links are a reading route through existing tests, not a claim that the suites have been run as part of editing this guide.

QuestionTest referenceWhat to look for
Can an old sort overwrite a new one?CatalogConcurrencyTests.swiftGates deliberately release an older sort before the newer one; the older result must not publish or clear current progress.
Does analysis use selection or focus?AIAnalysisSelectionTests.swiftExplicit selection is resolved in visible catalog order; focus is a fallback, and browsing tagged images preserves the captured batch.
Are the runtime services shared?RawCullIntelligenceRuntimeTests.swiftFollow assembly and configuration expectations alongside the runtime’s identity assertions.
What happens when saving during quit fails?QuitRecoveryTests.swiftRead the injected flush, recovery and termination callbacks alongside AppDelegate.beginTermination.
What counts as a valid review run?ReviewRunContractTests.swiftCompare snapshot and work-contract validation with ReviewRunContract.swift.
Why did copying fail before starting?ExecuteCopyFilesStartupTests.swiftCompare setup failures with the typed startup result instead of assuming a subprocess ran.

For example, this excerpt from the first selection test starts with three visible files and selects the third and first. The resolver returns the first and third because it walks the visible array, rather than iterating the unordered ID set.

Source excerpt — selection behavior, with first, second, third and state prepared earlier in the test:

state.viewModel.catalog.filteredFiles = [first, second, third]
state.viewModel.selection.selectedFileIDs = [third.id, first.id]

#expect(
    state.viewModel.catalogController.aiAnalysisFiles(for: .gridSelection).map(\.id)
        == [first.id, third.id],
)

For further test setup, read TestIsolationHelpers.swift and TEST_ARCHITECTURE.md. Injected loaders, writers, settings and temporary paths let tests exercise failures without depending on the user’s production catalogs or installed models.

Viewer and inspection interfaces

OwnerEntry pointObservable result / guard
ZoomSessionModelbeginRAWExposureInspection(), endRAWExposureInspection()Snapshot/restore selected source, EV and clipping; begin selects developed RAW
ZoomSessionModelnavigate(by:from:in:using:)Returns false while inspecting exposure
LoupeFocusPresentationModelrequest(url:source:delay:operation:), cancel(), reset()Generation-gated image/loading state; reset also clears cached identity
SubjectOutlinePresentationModelload(operation:), reset()Obsolete async completion cannot replace current outline
WriteSavedFilesJSONdiskUsage() async -> IntCurrent primary plus backup byte sizes via writer actor
BurstWorkflowControllerburstGroupReviewState(groupID:)For ID −1, common explicit singleton state or .none

Read ZoomSessionModel.swift, LoupeFocusPresentationModel.swift, SubjectOutlinePresentationModel.swift and WriteSavedFilesJSON.swift. The viewer guide explains task ownership; the RAW guide defines the render and display-evidence contracts.

Dedicated review and semantic owners

BurstWorkflowController exposes read-only result/state dictionaries from BurstReviewSessionModel.swift. Use commands:

OwnerCommandContract
BurstReviewSessionModelapplyAnalysis(rankings:restoredReviewStates:)Apply rankings and explicit states without conflating their meanings
BurstReviewSessionModelreplaceRankings(_:), restoreReviewStates(_:)Replace the corresponding owned state
BurstReviewSessionModelapplyManualWinnerOverride(groupID:winnerID:)Set explicit override state and update any existing ranking
BurstReviewSessionModelsetReviewState(_:groupID:scopedGroups:)Update ordinary or synthetic singleton workflow state
BurstReviewSessionModelreset()Clear data while retaining session identity
SharpnessScoringModelloadMissingAFPointScores(for:) asyncAdd AF-center evidence without replacing blended scores
RawCullSemanticSearchModelhydrateSemanticArtifacts(_:) async -> IntLoad compatible evidence with generation/provider guards
RawCullSemanticSearchModelrankSemantically(query:files:) asyncQuery cached evidence and publish guarded results
RawCullSemanticSearchModelacceptArtifacts(_:sources:preservingExisting:catalogFileCount:)Replace indexing evidence or preserve existing legacy-import entries

RawCullSemanticSearchModel.swift is retained by SimilarityScoringModel, whose forwarding API remains available. App admission and selection remain in the semantic feature. Combined Review’s orchestration/work/comparison extensions still share one feature/run owner; ReviewRunError now has its own file.

Catalog performance contracts — October 25

CatalogProgressCoalescer<Value> is a main-actor helper with update, finish and cancel operations. Each load owns independent metadata and thumbnail instances. Intermediate publication waits for a 100 ms tick; initial/terminal values publish immediately. Cancellation rejects pending callbacks. This is a presentation contract, independent of completed file accounting and image readiness. ScanAndCreateThumbnails.progressCounts() supplies final completed/total counts.

zoomNavigationProjection() memoizes ordered files, indices and membership against catalog/grid/context revisions, source, rating filter and analysis-order mode. sharpnessScoringTargetCount supplies control labels without sorting the execution array; sharpnessScoringTargetFiles retains execution order. These are internal app helpers, not package API additions.

See Performance Measurement for benchmark and signpost semantics, historical comparison restrictions and incomplete UI validation.

October 31 integration

handleOverlay now accepts maximumDimension, preservingImage, injectable renderRAW/loadAnalysis, and onFinished. loadOverlayRAWPreview(url:maximumDimension:inspectionExposureEV:renderer:diskCache:) returns RAWPreviewRenderer.Preview with image and nativeSize. ZoomSessionModel.beginPreviewLoad(preservingImage:) returns an optional operation UUID; finishPreviewLoad(_:) accepts only the active ID. rawPreviewMaximumDimension selects fit/native. RAWPreviewRenderer exposes render, cachedPreview, releaseSource and clearCache; renderer calls cross its actor boundary. These are internal interfaces, not package API.

RAW preview result metadata — November 2–3

RAWPreviewRenderer.Preview also exposes var isReducedResolution: Bool = false. The direct renderer sets it to scale < 1; native/JPEG results keep the default. Callers injecting renderRAW should set it explicitly for reduced fixture images.

ZoomOverlayModel.rawIsReduced: Bool? and rawRenderSeconds: Double? describe the displayed RAW result. handleOverlay measures the awaited renderer/loader call, including cache hits, and publishes these with the image. Preserved-image replacement retains the previous values until publication; ordinary clearing and overlay reset set them to nil. These remain application-internal presentation data.

Close Up host adapters

These app-internal adapters are defined in BurstCloseUpsView.swift. The three PhotoEvidence* imports expose package modules; they are not app facade methods. See package/import concepts.

OwnerEntry pointContract
BurstCloseUpIdentityrevision(_:)URL, size, modification time and inode token for a source
BurstCloseUpIdentitysource(_:raw:)Separate preview/developed render descriptor; preview includes sidecar revision
BurstCloseUpRendererrender(_:) async throws -> CloseUpRenderSerialize this renderer’s loads, retain catalog access, check identities before/after loading, rasterize owned buffers
BurstCloseUpRegionStoreload(for:), save(_:)Synchronous main-actor JSON/UserDefaults region storage; schema/revision acceptance is handled by the record/model
BurstCloseUpSelectionselect(_:in:current:selection:modifiers:)Pure comparison-membership calculation; UI separately activates the clicked frame
BurstCloseUpAFPointavailability(frame:point:orientation:)Validate and map recorded AF coordinates; return an explanation if unavailable
BurstWorkspaceSessionModelresetForGroupChange()Reset image/viewport/source state while retaining the AF-overlay preference

The workspace owns comparison membership and creates a new close-up model when the group changes. Pin/reference state is session state; saved regions are durable preferences. Show image opens ZoomView with group navigation and selected source. These operations do not persist ratings, declare winners or launch AI review.

Detected Close Up adapters

BurstDetectedFacesView owns loading and retry for the active frame. FaceEvidenceCache stores versioned human face evidence. AnimalCloseUpDetector maps Vision head joints into normalized top-left crop rectangles. ReviewSourceRequest.embeddedPreviewMaximumDimension lets this caller cap the embedded-preview decode. compareBurstGroup(_:startingAt:) optionally selects a valid member when opening a group.

19 - Performance Measurement

RAW ZoomView preview measurements, historical catalog findings, benchmark semantics, and validation limits.

Performance Measurement

Treat performance claims as workload-specific evidence. A bounded task group establishes an ownership/admission invariant; it does not by itself establish faster browsing, lower total CPU work or a leak-free application.

RAW ZoomView measurements — 31 October 2026

The selected build-428 policy uses direct bounded fit previews on a completed-pixel and persistent-JPEG cache miss. Native zoom retains the established JPEG pipeline; inspection remains native. See source selection.

The app measurement record and raw results cover six filename-sorted Sony ARWs, all RAW 9 at 9984 × 6656 pixels, three passes per mode (18 samples). Fit uses 3072 pixels; modes run in separate processes.

PipelineMedian image deliveryMedian materialized bitmapProcess peak RSS
Legacy JPEG, disk-cache miss4382 ms4644 ms919 MiB
Selected native policy, disk-cache miss4372 ms4632 ms919 MiB
Direct fit, 3072 pixels1418 ms1425 ms391 MiB
Completed fit-pixel cache hit0.040 ms7.8 ms499 MiB

Uncached fit delivery was approximately 3.1× faster with 57% lower process peak RSS in this standalone workload. These compare different display resolutions; normal native performance stayed effectively unchanged. Cache-hit delivery is lookup/readiness, not a painted frame. RSS includes frameworks and benchmark bitmap materialization, not just the renderer’s 256 MiB cache. OS/storage caches were not flushed. GUI first paint, hitches, other cameras and real portrait RAWs were not measured.

Native geometry and successive fit/native size transitions passed on all six photos. Maximum fit mean absolute RGB error against the native JPEG was 0.779/255 (bound 3/255); native exposure checks at −1, 0 and +1 EV matched sampled reference pixels at 0/255. This bounded cohort does not establish universal decoder quality. Direct-native rendering was rejected (4807 ms delivery median, 1394 MiB peak RSS).

The recorded focused run passed 32 tests, including 10 new RAW preview tests. The recorded full run executed 696 tests with three pre-existing failures: README/project version mismatch (3.3.5 versus 3.3.6), README/parser pin mismatch (1.3.2 versus 1.3.3), and a launch-context expectation of thumbnail while the unchanged default is embedded JPEG. These are source-recorded results; this documentation pass did not rerun them. Temporary full logs/images were under /tmp/rawcull-raw9-20261031; the committed JSON retains samples and source hashes.

Deferred catalog source-load tails

The October 25 follow-up records a separate matched 809-file comparison: empty-cache median 8.617 → 8.188 s, warm median 3.973 → 3.634 s, but maximum source-load latency 343.486 → 2011.928 ms. Its 200-pixel grid output differs from the earlier 200-point path, so memory and resize improvements require that workload qualification. The wrapper includes access, scheduling, parser waits, I/O and journal delivery; it does not isolate decoder CPU time. Rare-tail causes and user impact remain unproven.

That comparison predates the RawParserKit 1.3.3 executor update. Separate package thumbnail experiments do not replace a new RawCull catalog measurement. Preserve the source/load-stage diagnostics and collect matched runs before attributing an app speedup or tail fix to the new pin.

Historical catalog findings — 25 October 2026

RawCull 3.3.5, build 426 closed the October 24–25 investigation with qualified acceptance. The retained Phase 2 changes coalesce metadata and thumbnail progress independently at a 100 ms cadence, publish initial and terminal states immediately, and cancel pending publication when a catalog is replaced. The progress ring uses a 100 ms linear transition and respects Reduce Motion; numeric progress changes immediately. Accounting, image readiness, bounded workers and awaited saves retain their contracts.

The current reference passed three benchmark repetitions on 809 ARWs (50,126,917,632 bytes), 1616 px previews and 100 browsing steps, optimized Release with testability. This workload differs from the historical 1,198-file session below. The benchmark source was 53c80dbb; the final documentation revision is linked in the reports below. The CPU recording’s app UUID was verified, but its source hash was not independently established.

Pooled medianHistorical 809-file baselineCurrent reference
Empty-thumbnail-cache preload8.206 s8.415 s
Warm-thumbnail-cache preload3.553 s3.647 s
JPEG encoding5.005 ms4.989 ms
Grid preload resize4.308 ms4.335 ms
Prepared disk image readiness0.330 ms0.314 ms
Zoom preview readiness3.316 ms3.376 ms

These numbers are historical context, not an accepted automated before/after comparison: harness fingerprints differ and the runner rejects comparison. Three repetitions and unmatched cache/power/background conditions do not establish significance or a general loading speedup. Source-load wrapper medians rose 13.563 → 23.296 ms and the worst rose 2.781 → 6.187 s; metadata and resource changes also remain unresolved regression signals, without established causality.

A separate phase-aligned app capture observed preload main-thread sampled weight falling 4.575 → 1.325 s (71%), while elapsed preload was 20.577 → 20.254 s. This supports less sampled main-thread progress work, with differing capture configuration/provenance and no matched repetition. It does not establish a 71% loading speedup, exact CPU savings, or smoother painted frames. Component benchmark and app preload times measure different workloads.

Phases 3–6 deferred further encoder, grid, parser, picker and view optimizations. They retained diagnostics and findings. A reduced warm-cache recording contained 74 hitches, worst 416.694 ms; actions and capture settings differ from earlier recordings, so counts must not be compared as a regression rate. Full SwiftUI acceptance, first-painted-frame smoothness, matched cancellation/catalog-switch coverage and long-duration stability remain incomplete. Phase 7 did not rerun Swift report tests; its Python runner/exporter suite passed 18 tests. Performance close-out permits the normal release process, not complete release certification.

See the final findings, Phase 2 measurements, and the phase plan and outcomes for provenance, validation and deferred work. The durable final trace/app/dSYM/export archive is /Volumes/MacMini4/TestRunPerformance/phase7-evidence-2026-10-25; the benchmark reference is stored separately under /Volumes/MacMini4/TestRunPerformance/phase7-reference-20261025-062837.

Run the catalog benchmark

Run from the RawCull app repository with Xcode and pinned dependencies available:

python3 -B Scripts/RunCatalogPerformance.py "/Volumes/Photos/My ARW Catalog" \
  --output /tmp/rawcull-reference --runs 3 --steps 100 --pixels 1616

Use a new output directory outside the repository and catalog. The source folder is read only and nonrecursive; the benchmark requires valid ARWs. The CLI defaults to 1600 pixels while the app source default is 1616, so pass the actual app setting. Every repetition starts with a separate empty thumbnail disk cache, then measures warm preload and prepared browsing with documented RAM resets. OS/parser caches are not flushed. Results measure image readiness, not first painted pixels or AI throughput. The benchmark build disables App Sandbox only for its command-line catalog access; normal application settings are unchanged.

Retain run-configuration.json, results.json, report.md, per-run events/results, xcodebuild.log and tests.xcresult. Add --baseline /path/to/previous-output only for compatible catalog, machine/OS, Xcode, settings, version and harness identities. Do not bypass fingerprint checks. An optional --max-regression-percent 20 gate requires both a median increase over 20% and over 5 ms; tails still need review.

Benchmark semantics and the Instruments workflow explain the complete procedure. App phase instrumentation uses subsystem no.blogspot.RawCull, category CatalogPerformance, intervals CatalogOpen, CatalogMetadataScan, CatalogThumbnailPreload and event CatalogThumbnailPreloadComplete. Scripts/ExportCatalogTrace.py exports available tables and records missing/empty data; Scripts/ValidateCatalogSignposts.py validates pairing and completion. A successful export alone does not establish usable phase or UI evidence. Preserve complete traces and matching binaries/dSYMs before cleaning temporary data.

Historical October 23 evidence

The remaining sections preserve the earlier 1,198-file workload. They describe that session and its limitations; use the October 25 findings above for current performance status.

Recorded implementation and catalog

The October 23 remeasurement used the approved preload-save implementation from 54058fce, built as optimized Release with coverage disabled. The arm64 build UUID was 60782AD2-A618-385A-A5BA-3BD3A30B07A9. These measurements predate the historical build-426 documentation baseline; do not describe them as a new recording of every later source change.

The catalog contained 1,198 ARW files totaling 68,527,349,760 bytes, matching the preceding day’s catalog. Existing disk caches were preserved. This was not a cold-cache benchmark. The full measurement report and durable process samples, timing markers and analysis live in the app repository. Raw Instruments traces were temporary files; do not assume they still exist.

Preload owns its pending saves

ScanAndCreateThumbnails.swift returns encoded JPEG data and its cache key from processing. Each worker:

  1. Processes the image and prepares any cache-save payload.
  2. Releases that file’s ThumbnailPreloadGate waiters.
  3. Checks cancellation and awaits the disk save when a payload exists.
  4. Returns its task-group slot only after saving completes.

The existing limit, min(4, max(1, activeProcessorCount / 2)), now covers pending preload saves and encoded payloads within each group. It is not a global limit across independent operations. DiskCacheManager.save already awaits its background atomic writer. Interactive RequestThumbnail saves are unchanged. The catalog grant remains retained through the group’s completion, and an atomic write already underway is awaited rather than interrupted.

ThumbnailPreloadSaveOwnershipTests.swift stalls saves to check the bound, gate ordering, completion ownership, cancellation, unchanged preview-RAM admission and disk-backed warm reload. A cache-preserved real catalog does not necessarily stress this write path.

Process resource observations

Physical footprint and process disk-I/O counters were sampled approximately once per second with proc_pid_rusage. MiB means bytes divided by 1,048,576. Process I/O accounting is not physical-storage throughput.

ObservationBrowsing, source switching and reloadsSeparate fresh-process load
Sampling duration285.04 s81.28 s
Initial footprint531.2 MiB666.9 MiB
Peak footprint4,836.9 MiB990.2 MiB
Final footprint692.9 MiB989.9 MiB
Read delta14,782.4 MiB5,131.2 MiB
Write delta261.3 MiB0.0 MiB

The longer session included adjacent-image navigation, grid scrolling, full-size JPEG selection, 140% zoom, developed RAW selection, multiple loads, early-load abort and recovery. Its largest footprint occurred during the full-size source-exercise interval; that timing does not identify allocation ownership or a leak. It later declined substantially. The separate fresh-load sample ended near its peak and does not establish long-term stability.

Yesterday’s manual workload differed in duration, actions and unrecorded cache state. Comparing its 1,428.4 MiB peak directly with today’s peaks would not be a controlled regression or improvement measurement. Thumbnail-cache budgets also do not cap full-size display images or framework scratch allocations.

Timing and cancellation scope

For an explicit same-process warm reload, the app was still scanning at the 5.586-second observation; all 1,198 files and a preview were observed by 8.358 seconds after Open began. Those are automation observation bounds, including overhead, not exact internal completion times.

Open followed immediately by Command-K returned to an empty/no-progress state within a 1.074-second combined action sequence. A subsequent load recovered the catalog and preview. This exercised early-load cancellation, not cancellation specifically during thumbnail writing. Comparison multi-selection and AI review were not verified in this measurement.

Several same-folder reopen attempts produced a zero-file state and recovered on repeated selection. Restored picker locations also sometimes had Open disabled until selecting the catalog from its parent directory. These remain separate correctness observations: neither a shared cause nor a regression from bounded saves was established.

CPU and responsiveness limits

The primary SwiftUI trace did not finalize and could not export. Two shorter Time Profiler traces saved recoverable CPU/hang tables, but both reported a corrupt or incomplete logging stream. Their conclusions remain qualified. No usable SwiftUI cause graph or animation-hitch measurement was obtained.

The 60.33-second fresh-process trace exported 12,341 symbolicated samples:

Call pathInclusive sampled weight
Preload paths3,072 ms, approximately 24.9% of sampled weight
Preload grid downscaling2,803 ms, approximately 22.7%; overlaps preload
JPEG encodingNo matching sampled frames
Recorded hangs0

Do not add overlapping call-path weights or read sampled CPU weight as elapsed load time. No sampled JPEG encoding plus zero process disk writes means this fresh load did not meaningfully stress a preload write backlog. It does not prove every source was a cache hit or quantify a backpressure improvement. Zero recorded hangs in these windows is not a general absence-of-stalls claim.

The same-process fallback also recorded no hangs, but did not sample preload. handleSourceChange skips preload for a URL already in processedURLs during that app session. Repeated folder selection therefore does not reproduce a fresh-process preload workload.

Comparable-measurement requirements

Use the same implementation fingerprints, source mode, preview size, catalog, action sequence and cache preparation for both sides. Separate a cached load from a controlled cache-miss/write workload. Record phase boundaries so source switches and full-size development do not become catalog-load peaks. Observe cancellation while the intended phase is active and verify recovery afterward.

The October 24 grid investigation deferred optimization; the historical October 23 trace does not establish that downscaling causes foreground latency. Reproduce the intermittent reopening issue independently before assigning its cause. Keep photographic quality, task ownership and runtime performance as separate validation questions.

Current preview instrumentation and scripts — November 4 review

Build 429 adds a ZoomView duration badge around the awaited RAW preview loader. It includes memory/disk-cache retrieval and excludes the later analysis wait; it does not measure decoder-only CPU work or first paint. This instrumentation is separate from the October 31 standalone measurements above. No new benchmark or application test run was performed for this documentation update.

The November 1 README corrects the version/parser-pin statements implicated in two of that recorded run’s failures. This source correction does not establish a new passing run or resolve the separately recorded launch-context expectation.

Run the standalone preview benchmark with a clean checkout of the pinned parser:

python3 Scripts/RunRAW9PreviewBenchmark.py "/path/to/ARWs" \
  --parser-source "/path/to/pinned/RawParserKit" \
  --output /tmp/rawcull-raw-preview-new

The runner checks the parser HEAD against the app lockfile and rejects dirty parser Sources. Defaults select six files, three passes and separate processes for baseline, native, fit, revisit and validation modes; validation uses one pass. It writes per-mode JSONL/stderr, compiled artifacts and summary.json, including renderer/benchmark source hashes. Use a fresh output directory: unlike the catalog runner, this tool allows an existing directory and opens per-mode logs for writing.

The expanded scripts guide also covers trace export, grid/source-load analysis, model evidence runners and make test-scripts. Script tests use temporary fixtures and mocked Xcode calls; real photographs and installed models are not required. They do not run Swift diagnostics, real-catalog/model probes or release uploads. Source-load durations include scheduling, waits and I/O; summed overlapping durations are not CPU time.

November 8 source review: Close-ups is a separate workload

The November 8 checkout was 3.4.0 build 434. The earlier tables remain measurements of their recorded versions and actions. Adding Close-ups does not supply new latency, first-paint, photographic-quality or memory-pressure measurements.

The panel’s host renderer serializes its own full-size loads and returns bounded crop/overview artifacts. The main stage and other loaders remain separate consumers. A future comparison should record frame count, selected source, sidecar/cache state, pinned-reference membership, crop/viewport settings, peak process memory and cancellation behavior. Do not transfer the ZoomView fit-preview results directly to this full-size crop pipeline.

At that review the README identified 3.3.6 and lists the older dependency snapshot, while project.pbxproj identified 3.4.0 build 434 and the lockfile had 19 pins. Use project settings and the lockfile as the current source baseline; this documentation review does not modify the app README or establish release availability.

Build 436 adds current-frame detection on an embedded preview capped at 1,600 pixels. Human cache hits skip the Vision face request, but still need the preview pixels for crops. Animal detection runs separately. This source review adds no latency, memory or detection-accuracy measurements.

Vision gate measurements on 275 Sony ARWs

On 21 November the source project compared PhotoAnalysisKit 1.3.9 and 1.4.0 on a 27 GB catalog on a 10-core Mac. All 275 records matched on the compared analysis fields, all 1,650 generated masks and close-up crops were byte-identical, and the burst winners matched. Batch scoring took 22.8 s before and 21.6 s after. The source report treats that timing difference as within noise.

With Fast scoring at six tasks and Vision indexing at four concurrent decodes, two warmed Debug runs completed both workloads in 18.1 s each. All 275 files were scored and indexed in each run. A separate Release sharpness run completed 3,025 comparisons in 86 minutes. The catalog had no ground-truth labels for ranking accuracy. These measurements predate the 1.4.1 shared Core Image context change. The recorded end-to-end MCP burst run for this gate change was still outstanding. Vision implementation and catalog results

20 - Synchronous Code

Synchronous Code

Most RawCull code uses async/await, actors, and task groups. Some framework and system APIs are still synchronous: ImageIO decode, Core Image RAW rendering, JPEG encoding, filesystem calls, binary MakerNote parsing, and process launch. async on a caller does not make one of those calls nonblocking. This page records where the blocking work lives and which execution strategy each path uses.

Source Map

AreaFiles
Cancellation-aware blocking bridgeRawParserKit/Sources/RawParserKit/CancellableImageIOWork.swift
RAW thumbnail and embedded JPEG extractionSonyThumbnailExtractor.swift, NikonThumbnailExtractor.swift, DNGThumbnailExtractor.swift, JPGSonyARWExtractor.swift, JPGNikonNEFExtractor.swift, DNEmbeddedJPEGExtractor.swift
RAW development and orientationSonyRAWJPEGCreator.swift, ThumbnailSharpener.swift, OrientationNormalizedImageLoader.swift
Binary RAW parsingSony, Nikon, and DNG MakerNote/format files in RawParserKit/Sources/RawParserKit/
Thumbnail and preview callersRequestThumbnail.swift, ScanAndCreateThumbnails.swift, ScanAndExtractJPGs.swift, FullSizePreviewLoader.swift, ZoomPreviewHandler.swift, ComparisonImageLoader.swift
Export and JPEG encodingExtractAndSaveJPGs.swift, SaveJPGImage.swift, DiskCacheManager.swift, FullSizeJPGDiskCache.swift
Filesystem and persistenceScanFiles.swift, DiscoverFiles.swift, PerFileAnalysisArtifactStore.swift, SettingsViewModel.swift, ReadSavedFilesJSON.swift, WriteSavedFilesJSON.swift
Image analysisRawCullPhotoAnalysisAdapter · ReviewImageSource · SubjectMaskOutlineRenderer
External processExecuteCopyFiles.swift, RsyncProcessStreaming.RsyncProcess

Why Blocking Work Matters

Swift’s cooperative thread pool expects async tasks to suspend instead of occupying threads for long periods. ImageIO and CoreImage calls often do not suspend; they block until decode/render work is done.

If RawCull runs those calls directly inside many task-group children, the calls can occupy the cooperative pool together. The UI may remain on the main actor, but unrelated async work can stop making progress and cancellation can appear late. Actor isolation prevents data races; it does not prevent a synchronous call from monopolizing the thread executing that actor.

The Bridge

CancellableImageIOWork.run(qos:_:) wraps blocking work like this:

flowchart LR
    A["Swift async caller"] --> B["withTaskCancellationHandler"]
    B --> C["withCheckedThrowingContinuation"]
    C --> D["DispatchQueue.global(qos).async"]
    D --> E["Synchronous ImageIO/CoreImage operation"]
    E --> F["Resume continuation once"]

The operation receives an ImageIOCancellationToken. The token checks its own lock-backed cancellation flag and Task.isCancelled. Cancellation resumes the awaiting continuation promptly, but it cannot forcibly interrupt an ImageIO or Core Image call already executing. The worker must reach a checkpoint before it observes cancellation.

WorkState protects the continuation with a lock so cancellation and completion races resume exactly once.

Current RAW Extractor Pattern

The parser package uses stateless enum extractors. A typical extractor exposes an async public API and a private synchronous implementation:

public async extractThumbnail(...)
    -> CancellableImageIOWork.run(...)
        -> private extractSync(...)

That shape appears in the Sony, Nikon, and DNG thumbnail/embedded-preview extractors. The compatibility enums JPGSonyARWExtractor and JPGNikonNEFExtractor remain deprecated public shims.

SonyRAWJPEGCreator.createFullSizeJPEG uses the same bridge at utility QoS for CIRAWFilter, render probing, and JPEG representation. DecodeConcurrencyLimiter separately bounds how many expensive decodes are admitted; limiting concurrency and moving blocking work off the cooperative executor solve different problems and both protections should remain.

Blocking-Work Audit

Synchronous operationCurrent execution boundaryWhy
ARW/NEF/DNG thumbnail and embedded-preview ImageIO decodeCancellableImageIOWork on a global GCD queue, with cancellation checkpoints and decode limiting where suppliedDecode duration is input- and OS-decoder-dependent and may be repeated across a catalog.
Sony developed RAW via CIRAWFilter and JPEG representationCancellableImageIOWork at utility QoSFull RAW development and encoding are long, nonsuspending framework calls.
Sharpened RAW previewDetached task in ZoomPreviewHandler; concurrent task in ComparisonImageLoaderThumbnailSharpener performs synchronous CIRAWFilter and CIContext rendering. The detached zoom path is appropriate for potentially long rendering; a concurrent task alone still uses Swift’s cooperative executor and must remain bounded.
Orientation-normalized ImageIO loadDetached task in disk/full-size preview cache callers; otherwise kept inside an already isolated workerFile decode can block. The synchronous loader is a leaf API, so the caller owns the execution boundary.
Thumbnail/full-size cache reads, writes, size scans, and pruningTask.detached with user-initiated, background, or utility priority according to latencyData.write, directory enumeration, resource-value reads, ImageIO cache decode, and deletion are filesystem-bound and nonsuspending.
JPG export writesEncode CGImage to Sendable Data in the owning actor, then atomic Data.write in a detached background taskAvoids sending a non-Sendable image across isolation and keeps file writes off the actor/cooperative executor.
Catalog enumerationSynchronous contentsOfDirectory at the start of the ScanFiles actor operationOne bounded directory listing precedes parallel per-file work. Revisit this boundary if catalogs or remote volumes make enumeration measurably slow.
focuspoints.json and settings readsDetached utility taskWhole-file Data(contentsOf:) can block even for normally small JSON files.
ARW/NEF/DNG TIFF, MakerNote, and embedded-JPEG parsingRuns within RAW-loader, extractor, scan, or package-test worker contextFileHandle and mapped/full-file fallback reads are synchronous. They must not be called directly from the main actor; full-file fallbacks make duration input-dependent.
Sorting, filtering, histogram math, and small result transforms@concurrentCPU work is bounded, does not wait on blocking APIs, and benefits from leaving the caller’s actor without requiring a dedicated blocking thread.
rsync startupSynchronous argument/include-list preparation and executeProcess() on ExecuteCopyFiles’ main-actor method; output and completion are streamed asynchronously by RsyncProcessStreamingexecuteProcess() launches and returns; it does not synchronously wait for rsync to finish. Include-list size and launch latency must stay bounded or be moved off the main actor.

App-owned artifact and culling persistence actors also perform atomic reads/writes and directory maintenance. Serialization protects their state, but it does not make filesystem APIs suspend. Keep batches bounded and move any measured long operation to detached I/O while passing only Sendable values back to the owner.

@concurrent, Detached Tasks, And The GCD Bridge

These mechanisms are not interchangeable:

MechanismUse it forDo not use it as
@concurrentBounded CPU work such as sorting, filtering, small transformations, or a short diagnostic calculation that should not inherit actor isolationA general wrapper for ImageIO, full-file reads, RAW rendering, JPEG encoding, or other calls that may block for an unbounded time
Task.detachedA contained filesystem or rendering operation where the caller passes immutable/Sendable inputs and awaits the resultA way to escape ownership, priority, cancellation, or Sendable rules; cancellation must still be checked and structured lifetime retained by awaiting .value where required
CancellableImageIOWorkReusable, cancellation-aware package APIs around nonsuspending ImageIO/Core Image workProof that the underlying call itself is cancellable; it only controls the waiter and checkpoints around the call
Dedicated process APIA long-running external command whose output, cancellation, and termination have their own lifecycleWork to wait for synchronously on an actor or Swift task thread

Quality Of Service

The chosen GCD QoS communicates user impact:

WorkTypical QoSReason
On-demand thumbnailsuserInitiatedUser is scrolling or selecting images
Bulk cache warmingutility/backgroundUseful but should yield to direct UI work
JPEG export/cache warmingutilityBatch work that can run behind UI interaction
Memory diagnostics samplingutility/detachedShould not block UI rendering

The exact QoS is set in the package extractor or caller. When adding a new path, choose based on whether the user is waiting for the result right now.

Image Analysis

Sharpness scoring uses RawCullPhotoAnalysisAdapter. Scoring renders, Review source renders and subject-outline renders each reuse a static Core Image context. Creating a context initializes expensive rendering resources. Reusing it reduces repeated setup while preserving each renderer’s options. Decode and synchronous render work still need bounded admission. RawCullPhotoAnalysisAdapter · ReviewImageSource · SubjectMaskOutlineRenderer

The scoring image can come from:

SourceMeaning
embeddedPreviewPrefer embedded JPEG or ImageIO thumbnail for speed
rawDemosaicUse CIRAWFilter for a slower but more precise demosaiced thumbnail

The code normalizes decoded images to 8-bit sRGB RGBA before the focus pipeline. That makes scoring less sensitive to source color space or bit depth and provides a clear Sendable/value boundary where possible.

Direct Binary Parsing

Sony, Nikon, and DNG parsers use FileHandle to read bounded leading regions first, but some fallbacks read the full file to find later TIFF/MakerNote structures or JPEG ranges. They locate focus-point data and embedded JPEG offsets, then may read the selected JPEG byte range directly. These synchronous operations must remain inside scan/parser/extractor worker contexts.

The parsers are written as stateless enums, so they do not need actor isolation.

Safe Rules For New Blocking Work

  • Keep blocking APIs out of SwiftUI view bodies and @MainActor methods. The narrow rsync launch path is an explicit exception only while launch remains short and non-waiting.
  • Put reusable blocking ImageIO/Core Image work in RawParserKit behind an async API and the GCD continuation bridge.
  • Use detached I/O for isolated app-owned filesystem work, capture only Sendable values, and await the result when subsequent ownership or security-scope cleanup depends on completion.
  • Use @concurrent for bounded CPU work, not merely because a function is synchronous.
  • Bound catalog-wide decode/render fan-out with a limiter; executor choice does not impose backpressure.
  • Add cancellation checkpoints before and after expensive framework calls.
  • Convert non-Sendable image objects before crossing actor/task boundaries when needed.
  • Put pure parsing or calculation logic in package code with fixtures and tests.

When A Synchronous Call Is Acceptable

A synchronous call is safe inside an actor only when all of these are true:

  • it is small and bounded,
  • it does not perform network/removable-volume I/O or decode/render a full image,
  • it cannot expand from a small header/record into an unbounded full-file or directory operation,
  • it does not capture mutable UI state,
  • cancellation delay would not be visible to the user,
  • multiplying it by the maximum actor/task-group concurrency still leaves cooperative threads available.

Examples include formatting values, cache-key construction, parsing a fixed-size in-memory record, or calculating display data. Move the work to detached I/O or CancellableImageIOWork when duration depends on file size, decoder behavior, volume latency, catalog size, or external-process completion. When uncertain, measure with a representative large RAW file and catalog; an actor is an ownership boundary, not a blocking-work queue.

Review Checklist

  • Search for CGImageSource, CGImageDestination, CIRAWFilter, CIContext, Data(contentsOf:), Data.write, FileHandle, directory enumeration, and process launch when auditing a new release.
  • Verify package extractors still go through CancellableImageIOWork and catalog callers still apply decode limits.
  • Verify detached closures capture Data, URL, scalar configuration, or other Sendable values rather than actor-owned CGImage/NSImage state.
  • Verify cancellation and completion races resume continuations exactly once; CancellableImageIOWorkTests.swift covers this bridge.
  • Verify export/security-scope owners await detached writes before stopping access.
  • Remove deprecated compatibility names from call sites and documentation as migrations complete.

Export and RAW 9 worker boundaries

EmbeddedJPGExportLoader.swift is an explicit concurrent app helper that reads embedded byte ranges and may normalize/encode orientation synchronously. It is bounded by ExtractAndSaveJPGs batch admission and retains source access through the operation. @concurrent moves it off inherited main-actor isolation; it does not turn those framework calls into suspension points. Profile this path before increasing batch extraction concurrency.

RawParserKit 1.3.1 also adds Internal/RAWDecoder.swift: optional RAW 9 rendering uses a detached utility task. Its post-render cancellation check discards a late image but cannot preempt an executing CIRAWFilter/CIContext call. The package guide explains the opt-in flag and fallback. These paths are distinct from the GCD continuation bridge used by the established embedded ImageIO extractors.

Generic extractors and temporary exposure renders

RawParserKit 1.3.2’s GenericRawThumbnailExtractor and GenericEmbeddedPreviewExtractor use the established GCD ImageIO bridge. The generic preview extractor adds a two-operation default limiter; no vendor-specific binary fallback runs on that route.

The app’s RAWPreviewRenderer actor is different: it serializes inspection requests, retains source access and performs synchronous Core Image rendering on that actor. Cancellation is checked around the render, not inside the native call. Histogram and clipping calculations use explicit concurrent functions with bounded sampling. The exact adjustment and display-pixel contracts are in RAW Formats and Exposure Inspection. Do not infer that every rendering path uses the same blocking bridge.

Detached writing does not bound pending writes

Preload now awaits DiskCacheManager.save before releasing its task-group slot, with file-gate release preceding that await. This bounds each preload group’s pending saves and encoded data while keeping the background atomic writer. JPEG encoding still runs synchronously in the image-owning actor; this change did not move encoding to another executor. See Performance Measurement before assigning a throughput or responsiveness benefit to this ownership change.

October 24–25 investigation outcome

Progress publication and ring animation were simplified to reduce sampled main-thread presentation work. JPEG encoding, grid resizing, source loading and picker/UI paths were investigated without retaining further speculative optimizations in Phases 3–6. Immutable encoder-option reuse showed no useful repeatable benefit. Source-load wrapper latency includes parser waits, I/O and scheduling; it is not a decode-CPU measurement. The final reference retains unresolved source-load and resource signals. See Performance Measurement before assigning a speedup or claiming all expensive paths run away from the main thread.

October 31 integration

The renderer uses a half-float working context with intermediate caching disabled and eagerly completes sRGB display pixels. Fit rendering scales the RAW filter; inspection stays native. Closing releases the active graph. See RAW preview policy; serialized native work can still be expensive.

Close-up decode serialization

The close-up host renderer uses an explicit task chain plus an @concurrent worker for file access, preview/developed loading and synchronous rasterization. A renderer actor’s reentrant methods alone would not serialize all awaited work. Cancellation is checked before and after native loading; a synchronous decoder already running can finish before cancellation is observed.

Owned bounded crop/overview buffers limit retained results, not the temporary cost of full-size decoding. The main burst stage uses a separate loader and cache. Read Concurrency for the task chain and Viewer Architecture for session lifetime.

Cancellation for image workers

The helper named detachedCancellable runs its closure as a child task in a task group. Cancellation propagates to the child, including when the caller is already cancelled. The helper runs the closure off the caller’s actor. Synchronous decoding or rendering that has entered a system call still depends on the next cancellation checkpoint. extension+Task+Detached.swift

21 - Documentation Review Record

Build 466 source review, per-page dispositions, and the incremental documentation baseline.

Documentation Review Record

Reviewed source

On 23 November 2026 the review compared RawCull 3.4.9 build 466, commit 0513a30e, with the previous build 462 baseline, a0c72d11. The clean application checkout was on version-3.4.9. The local main branch also contains the reviewed commit. Build 466 identifies the Xcode project configuration. The local release tag points to an earlier commit of that version.

The comparison covered 181 added, modified or deleted paths when renames are counted as deletion and addition. The site has 37 technical pages and four site pages. The previous inventory still listed four retired pages. Review and diagnostics are covered by the AI guides, and the XMP and unified burst evidence proposals are in the roadmap.

Findings that affect readers

  • Review. The current entry point accepts one to eight selected or tagged photos. Focus check needs SAM 3. Describe and Full need Qwen. The inspector links findings to regions, and the separate Review Record window follows the selection. Acting on a saved result requires a matching live file. Review guide
  • Burst assessment. The burst list can assess the ranked pair from each eligible group. Completed results with usable findings appear in the session’s AI Assessments window. An MCP follow-up publishes through a separate authorized job. Burst groups · MCP
  • Vision scheduling. PhotoAIKit 3.1.0 forwards feature-print work through an injected serializer, and RawCull connects it to PhotoAnalysisKit’s gate. The 275-photo comparison covers the gate change. PhotoAnalysisKit 1.4.1 separately adds focus-engine context reuse. PhotoEvidenceKit’s repository URL changed at the same revision. Performance · Package snapshot
  • Developer commands. The Makefile requires a clean, version-tagged HEAD for release preflight. The release checklist uploads the candidate for testing through TestFlight. A stale README example still names releaseaiobjectstest. The Makefile defines the current Review probes. Developer guide

Validation and limits

The documentation site built with Hugo. Rendered internal page links and fragment targets were checked, and immutable GitHub source paths were resolved against their named revisions in the local repositories. The application version and build were checked in the Xcode project. The package snapshot and review manifest were compared with the app’s lockfile.

This was a source and documentation review. The app UI, Swift test suites, installed models, TestFlight upload, photographic benchmarks and vendor comparisons were not rerun. The performance guide attributes measurements to the original source-project runs. The model recipe and competitor comparison retain their original dates.

Page dispositions

PageReview outcome
_index.mdUpdated the application map, Review entry point, smoke count and source baseline.
ai/_index.mdReplaced the tab tour with task, input and storage choices for Review, burst assessments and MCP.
ai/aiinrawcull.mdRebuilt the Review guide around preset requirements, registered evidence, decision guards, outlines and resume. Preserved the CLIP walkthrough and a link to the historical evaluation.
ai/airuntime.mdTraced model activation, live backend admission, Qwen generation, the shared lease and Vision scheduling.
ai/rawcullai.mdCorrected the app pin and replaced the retired diagnostic runner. The dated exporter and model recipe remains historical.
apidocs/_index.mdUpdated the developer reading route for Review, batch assessment and release checks.
apidocs/rawcull-internal-api.mdReplaced removed controller calls with the current Review, batch plan and culling action interfaces.
apidocs/rawcullapidoc.mdUpdated launch code, Review flow, smoke inventory, model probes and tag-to-TestFlight release procedure.
burstgroup.mdDocumented eligibility, preview inputs, rubric, cancellation and session lifetime for Assess All Bursts. Updated mask lookup.
cache-accounting.mdRetained the owned-eviction-delegate walkthrough. The cache bookkeeping implementation has no relevant delta.
cache.mdDistinguished obsolete Objects cache cleanup from retained Review masks and reports.
closeups.mdChecked manual crop and AF behavior and documented scheduling of automatic face and animal detection.
concurrency.mdReplaced the temporary processor cap with the implemented Vision gate, cancellation semantics and quality limits.
detailsfocusmask.mdUpdated viewer ownership and distinguished the calibrated focus overlay from a retained Review subject mask.
detailsharpnessscoring.mdCorrected effective concurrency for embedded previews and RAW demosaics. The formula audit retains its original revision.
filereadandwrite.mdUpdated Review inspection and distinguished in-memory burst entries from shared MCP records.
focusmask.mdIdentified the current package pin and removed the deleted AI preview helper from the viewer map.
heavy.mdReplaced retired Deep Review paths with the scoring, Review source and outline renderers that reuse Core Image contexts.
mcp.mdChecked helper schemas and controller admission. Documented shared inference and the two result lifetimes.
memorypressure.mdRetained the pressure-event and cache-budget guide. Review memory eligibility is documented with the presets.
newfeatures/_index.mdChecked the roadmap destination and its distinction between implemented features and proposals.
newfeatures/newfeatures.mdUpdated source and tag evidence, assessment scope and Vision qualification. Competitor evidence remains dated 5 November.
packages/_index.mdReconciled all 24 app pins and distinguished the helper lockfile and earlier package snapshots.
packages/package-modules.mdConfirmed the PhotoEvidenceKit revision and library products. The repository transport change leaves the module example intact.
packages/photoaikit.mdChecked the 3.1.0 serializer against its resolved source. Distinguished current integration from the October audit.
packages/photoanalysiskit.mdChecked 1.4.0 queue admission and the 1.4.1 shared focus-engine context at the resolved revision.
packages/photoevidencekit.mdVerified the HTTPS repository change at the same 1.1.5 revision.
packages/rawcullcore.mdConfirmed the app pin and distinguished it from the original domain-model walkthrough.
packages/rawparserkit.mdConfirmed 1.3.3 at the recorded revision. The change to Review consumers does not change parser dispatch.
performance.mdAdded the source project’s 275-ARW gate comparison, stress run, Release sharpness evidence and limits.
pushpull.mdRetained the documentation-repository Git workflow. App release tagging is covered in the developer guide.
raw-inspection.mdChecked viewer changes against the guide. Review rendering and outline changes leave the zoom exposure policy intact.
security.mdTraced the separate session-catalog and MCP-grant access paths used by the assessment window.
sonymakernoteparser.mdConfirmed the current parser pin and retained the historical MakerNote walkthrough.
thumbnail.mdUpdated the Review consumer name and checked grid/preload admission against the source delta.
update.mdReconciled the current page inventory, changed pins, source findings and validation record.
viewer-architecture.mdUpdated outline lookup, Review geometry, inspector navigation and the source baseline.

The four site pages cover the home page, About, site information and search. The home and About text was revised for platform and distribution accuracy. Their individual review records are in the manifest.

Next review

Run the read-only selector from the documentation repository:

python3 scripts/review_docs.py --source /path/to/RawCull

For a committed target other than the checkout’s HEAD:

python3 scripts/review_docs.py --source /path/to/RawCull --target COMMIT

The selector reads data/documentation-review.json. It compares committed paths, flags staged/unstaged/untracked source paths when reviewing HEAD, checks resolved pins, and detects documentation edits using recorded SHA-256 hashes. Each page has explicit source-path patterns and package identities in that file. Immutable source references also contribute exact-path triggers.

A report is a review candidate list, not a semantic approval. It never edits files or advances the baseline. Unmapped source changes are printed prominently and return exit status 2; inspect them and extend the map before deciding which pages can be skipped. If source ownership moves across subsystems, review the map itself. Externally dated research, recipes and historical measurements are not silently requalified by an empty app diff.

For a manual comparison:

git -C /path/to/RawCull log --oneline 0513a30e4567b4b5e3093e10791d49c86ecfe7e6..HEAD
git -C /path/to/RawCull diff --stat 0513a30e4567b4b5e3093e10791d49c86ecfe7e6..HEAD

After reviewing the candidate pages, record the new actual commit, project version/build, full lockfile pins, per-page dispositions and document hashes in data/documentation-review.json; update this page and the documentation index. Advance a page’s reviewed_* front matter only after checking its relevant delta. An unchanged subsystem can receive a delta-verification marker while preserving its content lastmod and historical audit links. Never advance the baseline just because the selector ran or the site rebuilt.

22 - Sony, Nikon, and DNG Metadata Parsers

Sony, Nikon, and DNG Metadata Parsers

RawParserKit 1.3.2, revision 07801a34a82d7720d301a80724c36a5b8c9f1d6c, provides one neutral result shape for Sony ARW, Nikon NEF, and Adobe DNG autofocus metadata. RawCull enters through RawImageLoader.metadata(for:) or RawFormatRegistry; diagnostics and package tests may call a format parser directly.

Current Source Map

AreaRawParserKit file
Neutral format contract and registrationSources/RawParserKit/RawFormat.swift, RawFormatRegistry.swift
Normalized focus value and metadata snapshotSources/RawParserKit/BrowserFocusPoint.swift, BrowserExifInfo.swift
Facade and EXIF fallbackSources/RawParserKit/RawImageLoader.swift
SonySonyMakerNoteParser.swift, SonyRawFormat.swift, SonyThumbnailExtractor.swift, SonyEmbeddedJPEGExtractor
NikonNikonMakerNoteParser.swift, NikonRawFormat.swift, NikonThumbnailExtractor.swift, NikonEmbeddedJPEGExtractor
DNGDNGMakerNoteParser.swift, DNGRawFormat.swift, DNGThumbnailExtractor.swift, DNEmbeddedJPEGExtractor.swift
RawCull consumerRawCull/Model/RawImageLoading.swift, RawCull/Actors/ScanFiles.swift

RawFormatRegistry.all registers SonyRawFormat for .arw, NikonRawFormat for .nef, and DNGRawFormat for .dng. Each conformer supplies focus-point parsing, thumbnail and embedded-preview extraction, compression labels, and RAW size thresholds.

Shared Focus Contract

All three parser paths return:

imageWidth imageHeight focusX focusY

RawFocusPoint validates four numbers, positive dimensions, and normalized coordinates in 0...1. The RawCull adapter converts that value to CGPoint for FileItem.afFocusNormalized while retaining the four-number compatibility string for the focus overlay.

flowchart LR
    Parser["ARW / NEF / DNG parser"] --> Format["RawFormat.focusLocation"]
    Format --> Meta["RawImageLoader metadata + RawFocusPoint"]
    Meta --> Adapter["RawParserKitImageLoader"]
    Adapter --> Item["FileItem.afFocusNormalized"]
    Adapter --> Overlay["FocusPointsModel and overlay"]
    Item --> Analysis["focus evidence and ranking"]

For example, "6000 4000 3000 2000" normalizes to (0.5, 0.5). A Nikon AFInfo2 value such as "8256 5504 2064 1376" normalizes to (0.25, 0.25). The examples describe the contract; package tests use synthetic TIFF/MakerNote structures rather than camera files.

Fallback Order

RawImageLoader.metadata(for:) asks the registered format for a focus location first. If none is produced, it reads kCGImagePropertyExifSubjectArea, treats the first two numbers as pixel X/Y, and normalizes them against image width and height. Invalid dimensions or out-of-range values produce no point.

RawCull then has a catalog-wide compatibility fallback: ScanFiles reads focuspoints.json only when the entire native-point collection is empty. If even one file has a native MakerNote or EXIF point, JSON is not merged into the partly populated result. JSON supplies overlay compatibility data; it does not retroactively populate every FileItem.afFocusNormalized.

Format-Specific Parsing

  • Sony follows TIFF IFD0 to EXIF and the Sony MakerNote IFD, including FocusLocation 0x2027, and reports embedded JPEG candidates.
  • Nikon validates the Type-3 MakerNote and reads supported AFInfo2 0x00B7 layouts. Unsupported layouts return nil.
  • DNG walks TIFF IFD0 and SubIFDs. Standards-classified files use NewSubFileType plus Compression to distinguish thumbnails/previews from JPEG-compressed raw strips. Files without NewSubFileType retain a positional fallback. DNG compression labels include uncompressed, JPEG, Deflate, PackBits, Lossy DNG, and JPEG XL.

The DNG container is camera-neutral, so its size classes use generic megapixel thresholds with overrides for known high-resolution, full-frame, and smaller sensor camera families.

Tests At The Pinned Revision

TestContract
SonyMakerNoteParserTests.swiftSony focus tags, offsets, malformed input, and embedded JPEG discovery
NikonMakerNoteParserTests.swiftNikon Type-3/AFInfo2 layouts, byte order, and embedded JPEG discovery
DNGMakerNoteParserTests.swiftDNG TIFF/SubIFD focus and preview discovery, including malformed data
DNGRawFormatTests.swiftDNG compression labels, size classes, and format behavior
RawFormatRegistryTests.swiftCase-insensitive ARW/NEF/DNG dispatch and unregistered formats

Checklist For Another RAW Format

  1. Add a stateless RawFormat conformer with extensions, display name, extraction, focus location, compression labels, and size thresholds.
  2. Register it in RawFormatRegistry.all; keep app code on the registry and RawImageLoader facade.
  3. Normalize autofocus output to "width height x y" and prove bounds, endianness, truncation, missing tags, and unsupported versions are safe.
  4. Add synthetic parser, registry, metadata-fallback, preview, orientation, cancellation, and diagnostics tests.
  5. Verify the RawCull adapter maps the result into the same visual coordinate system and preserves the catalog-wide JSON fallback rule.

Generic RAW metadata does not add a vendor parser

The 1.3.2 registry also includes GenericRawFormat.swift. Its focusLocation returns nil; standard EXIF SubjectArea may still supply a normalized point through the facade. The three dedicated binary parser paths above remain separate. Before writing another vendor parser, decide whether ImageIO-only support is enough or whether AF locations, container offsets and body-specific metadata require a dedicated conformer. See RAW Formats and Exposure Inspection.

Current app pin

RawCull 3.4.9 build 466 pins RawParserKit 1.3.3 at 26df4abc2178d5c07d08f3883d84d0648f5141d3. The 1.3.2 parser walkthrough above retains its source identity: the intervening source delta changes thumbnail executor placement, not MakerNote parsing or AF interpretation. See the package delta.

23 - Repository Git Workflow

Repository Git Workflow: Linear History

This page documents the preferred repository workflow for RawCull documentation changes: branch-based development, signed commits when configured, rebasing onto main, and fast-forward integration without merge commits.

Create a Branch

git checkout -b <new-branch>
git push --set-upstream origin <new-branch>

Daily Workflow

You always work on a dedicated branch. Commit often as you make progress.

Stage changes

git add .

Commit

If you use the Claude CLI, it can generate a Conventional Commits message from the staged diff:

git commit -m "$(git diff --staged | claude -p 'Write a short conventional commit message. Output only the message, nothing else.')"

Claude pipes the staged diff into the claude CLI and returns a single-line message such as feat(cache): add LRU eviction for thumbnail layer. The -p flag runs Claude non-interactively (print mode) so the output can be captured directly into -m.

If you want to review the message before committing, capture it first:

MSG=$(git diff --staged | claude -p 'Write a short conventional commit message. Output only the message, nothing else.')
echo "$MSG"
git commit -m "$MSG"

Repeat staging and committing as often as needed while working.

Push

git push origin <your-branch>

Keep your branch current

If others have pushed to main while you were working, rebase your commits on top of their work rather than merging.

git fetch origin
git rebase origin/main

This puts your commits aside, fast-forwards your branch to the latest main, then replays your commits on top — keeping history a straight line.


Integrate into main (fast-forward)

When your branch is finished and ready to ship, follow this procedure to keep history linear.

1. Update main from the server

git checkout main
git pull --rebase origin main

2. Rebase your branch onto the fresh main

git checkout <your-branch>
git rebase main

3. Fast-forward merge into main

--ff-only makes Git abort instead of creating a merge commit.

git checkout main
git merge --ff-only <your-branch>

4. Push main to GitHub

git push origin main

5. Delete the branch locally

git branch -d <your-branch>

6. Delete the branch on GitHub

git push origin --delete <your-branch>

Using git fetch and git diff

The git fetch command is used to update your local repository with the latest changes from the remote repository without merging them. You can then use git diff to compare the branches.

Step 1: Fetch the Latest Changes

Fetch the latest changes from the remote repository to ensure you have the most up-to-date information.

git fetch origin

Step 2: Compare the Branches

Use the git diff command to compare your local branch with the remote branch.

git diff <local-branch> origin/<remote-branch>

For example, if you want to compare your local main branch with the remote main branch:

git diff main origin/main

Using git log

The git log command can be used to compare commit histories between your local and remote branches. This is useful for seeing which commits are present in one branch but not the other.

Fetch the Latest Changes:

Ensure your local repository is updated with the latest changes from the remote repository.

git fetch origin

Compare Commit Histories:

Use the git log to see the differences in commit histories.

git log <local-branch>..origin/<remote-branch>

For example, to compare your local main branch with the remote main branch:

git log main..origin/main

You can also reverse the comparison to see commits in the remote branch that are not in the local branch:

git log origin/main..main

Using git status

The git status command provides a quick summary of the differences between your local branch and the remote branch.

Fetch the Latest Changes:

Update your local repository with the latest changes from the remote repository.

git fetch origin

Check the Status:

Use git status to see the differences between your local branch and the remote branch.

git status

The output will show messages like “Your branch is ahead of ‘origin/’ by X commits” or “Your branch is behind ‘origin/’ by X commits”, indicating the differences.


Pull and track a remote repository

The error means your local branch has no upstream tracking set. Fix it with:

git branch --set-upstream-to=origin/<your-branch> <your-branch>
git pull

Or do both in one step:

git pull origin <your-branch>

To avoid this in the future, whenever you create or checkout a new local branch that should track a remote, use:

git checkout --track origin/<your-branch>

Verify linear history

git log --oneline --graph --decorate

A clean linear history shows a straight vertical line with no merge nodes.


Re-sign and remediation

Re-sign the last commit without changing its message

git commit --amend --no-edit -S

Push after re-signing (the commit hash changed)

git push origin <your-branch> --force-with-lease

Fix GPG if signing fails

git config --global gpg.format openpgp
git config --global gpg.program gpg

# Confirm the Key ID is correct (no leading '0x')
git config --global user.signingkey <YOUR_KEY_ID>

# Restart the agent
gpgconf --kill gpg-agent

One-time setup

Run these commands once per machine to configure Git correctly for this workflow.

1. Set your identity

git config --global user.name "Your Name"
git config --global user.email "you@example.com"

2. Verify the remote uses SSH

git remote -v

If the URL starts with https://, switch it to SSH:

git remote set-url origin git@github.com:<user>/<repo>.git

3. Configure GPG signing

# Find your GPG Key ID (the 16-character code after '/' on the 'sec' line)
gpg --list-secret-keys --keyid-format LONG

# Tell Git which key to use (omit the leading '0x')
git config --global user.signingkey <YOUR_KEY_ID>

# Auto-sign all commits and tags
git config --global commit.gpgsign true
git config --global tag.gpgSign true
git config --global gpg.program gpg

4. SSH connection

  1. Go to github.com/settings/keys and delete the old key.
  2. Copy your current public key to the clipboard:
pbcopy < ~/.ssh/id_ed25519.pub
  1. On GitHub: Settings → SSH and GPG keys → New SSH key → paste → Save.
  2. Test again:
ssh -T git@github.com

5. Test the SSH connection to GitHub

ssh -T git@github.com

A successful response looks like:

Hi <username>! You've successfully authenticated, but GitHub does not provide shell access.

If you get a Permission denied (publickey) error, the most likely cause is a stale key.

6. Enforce linear history (no merge commits)

# Always rebase instead of merge when pulling
git config --global pull.rebase true

# Refuse any merge that would create a merge commit
git config --global merge.ff only

# Simplify first push of a new branch (Git ≥ 2.37)
git config --global push.autoSetupRemote true

24 - Security-Scoped URLs

Security-Scoped URLs

RawCull is a sandboxed macOS app. Any access outside the app container must come from user consent, usually a file/folder picker. RawCull uses two security-scope patterns:

  1. active catalog access for browsing/culling and as the rsync source,
  2. a persistent bookmark for the rsync destination.

Source Map

AreaFiles
Active catalog scopeRawCullViewModel.swift, CatalogController+Loading.swift, RawCullApp.swift
Catalog scan scopeActors/ScanFiles.swift
CLIP indexingCatalogController+Similarity.swift, SimilarityScoringModel.swift, RawCullVisionSimilarityService.swift
Semantic searchCatalogController+Similarity.swift, SimilarityScoringModel.swift, RawCullSemanticSearchService.swift
Similarity artifact cacheIntelligence/Persistence/PerFileAnalysisArtifactStore.swift
Copy-folder bookmarksViews/CopyFiles/OpencatalogView.swift, SourceAndDestinationSection.swift
rsync runtime scopeModel/ParametersRsync/ExecuteCopyFiles.swift
Selected JPG exportExtractJPGsSheetView.swift, FileOperationsModel.swift, ExtractAndSaveJPGs.swift, SaveJPGImage.swift
App terminationMain/RawCullApp.swift, CullingModel.swift

API Basics

The core calls are:

let ok = url.startAccessingSecurityScopedResource()
url.stopAccessingSecurityScopedResource()

Persistent access is stored as bookmark data:

let data = try url.bookmarkData(options: .withSecurityScope, ...)
let url = try URL(resolvingBookmarkData: data, options: .withSecurityScope, ...)

Every successful startAccessing... must eventually be paired with stopAccessing....

Active Catalog Scope

CatalogController coordinates catalog loading. CatalogLifecycleCoordinator owns transition and load tasks and the active catalog grant.

sequenceDiagram
    participant UI as Sidebar picker
    participant VM as CatalogController
    participant Work as Scan/thumbnail/export work
    UI->>VM: startCatalogLoad(source)
    VM->>VM: cancelCatalogLoad()
    VM->>VM: startSecurityScopedAccess(url)
    VM->>Work: scan and preload
    Work-->>VM: results/progress
    VM->>VM: release session grant on cancel/empty/cleanup

startSecurityScopedAccess(for:) is idempotent for the currently active URL. If a different catalog is selected, it releases the previous session grant before starting the new one. Existing workers can retain the old grant until completion.

cancelCatalogLoad() cancels related work and releases the session grant. An empty scan also releases the session reference. Worker-held references keep the grant alive until their reads finish; the actual stop happens once, in RawCullCatalogGrant deinitialization. Coordinator teardown cancels its tasks and releases its reference. A cancellation request alone does not close access under a synchronous decode that is still running.

Catalog changes are persistence boundaries: startCatalogLoad(for:) waits for CullingModel.flushPersistence() before it cancels the old catalog and its scope. If the flush fails, RawCull restores the previous selection and keeps the old catalog active.

ScanFiles Scope

ScanFiles.scanFiles(url:onProgress:) also starts and stops access around directory scanning:

let didStartSecurityScope = url.startAccessingSecurityScopedResource()
defer {
    if didStartSecurityScope {
        url.stopAccessingSecurityScopedResource()
    }
}

This is a local defensive scope for the scan actor. It stops only when its own start succeeded. The broader catalog scope remains owned by CatalogLifecycleCoordinator so later preload, diagnostics, export, zoom, and AI work can still access files while the catalog is active.

Scope Ownership Matrix

The owner is the component that records a successful start and is therefore responsible for the matching stop. A borrower may use URLs covered by a longer-lived owner, but must not stop that owner’s scope.

OperationScope ownerStartStopFailure and cancellation cleanup
Active catalogCatalogLifecycleCoordinator and retained RawCullCatalogGrantstartSecurityScopedAccess(for:) before catalog workFinal grant release after session and retained workers finishA failed start is not recorded. Switching first flushes culling persistence; a failed flush retains the old catalog and scope.
Directory scanScanFiles.scanFilesLocal startAccessingSecurityScopedResource()defer, but only when the local start returned truedefer covers success, thrown filesystem errors, cancellation, and early return. The view model’s broader scope is not stopped.
Selected JPG exportFileOperationsModel.startSelectedJPGExtractionStart the chosen destination immediately before creating ExtractAndSaveJPGsOn return from extractAndSavejpgs(), before publishing completion or failure UIFailed destination start aborts without a stop. Per-file failures are collected; the operation-level stop still runs after the actor returns. Source reads retain catalog grants for the operation lifetime.
rsync copyExecuteCopyFilesStart the selected catalog URL, then resolve and start destBookmarkIdempotent cleanup() after normal completion, close/cancel, startup failure, launch failure, or deinitThere is no direct-path fallback. If destination setup fails, cleanup stops the already-started source. didCleanUp prevents duplicate stops and include-file removal.
AI indexingActive catalog (CatalogLifecycleCoordinator)No per-file start; indexing borrows the selected directory scopeNo per-file stopIndex cancellation stops AI work. Catalog cancellation/change releases the session grant; workers release their retained grants when they exit.
Semantic queryNone for ranking; active catalog remains open for follow-on actionsNo start; ranking reads hydrated in-memory artifactsNo stopQuery cancellation discards query work. Any subsequent preview/export uses the appropriate catalog or export scope.

CLIP indexing and semantic search use the active catalog scope differently. Indexing reads source images, while a search query operates on cached embeddings.

flowchart LR
    A["Active security-scoped catalog"] --> B["FileItem URLs"]
    B --> C["Decode RAW thumbnail, max 512 px"]
    C --> D["CLIP image encoder"]
    D --> E["Validated similarity artifact"]
    E --> F["Application Support cache"]
    Q["Text query"] --> T["CLIP text encoder"]
    F --> S["Cosine similarity ranking"]
    T --> S
    S --> R["Ranked catalog selection"]

CLIP indexing requires the catalog scope

RawCullSimilarityFeature.indexCurrentCatalog(forceRefresh:) first hydrates reusable artifacts and then asks SimilarityScoringModel.indexFiles(_:) to generate any missing or stale artifacts. Each FileItem becomes an AIImageSource containing the file URL.

For an artifact that must be generated, RawCullSimilarityImageDecoder reads the source URL. It first asks RawParserKitImageLoader for a thumbnail with a maximum dimension of 512 pixels and then tries ImageIO as a fallback. Because these URLs point into the user-selected catalog, decoding depends on the catalog directory’s security-scoped access still being active.

RawCull does not start a new OS security scope for every image. The adapters retain the existing directory grant through RawCullCatalogAccess, and batches retain it across later files as well. Access was already started for the selected directory by CatalogLifecycleCoordinator, and that scope covers its files. The lifecycle coordinator keeps the directory scope open after the initial scan so indexing, thumbnail generation, previews, exports, and other catalog operations can read the same URLs.

The decoded image is passed to the selected local similarity backend. When the selected backend is CLIP, PhotoAIKit creates a normalized image embedding. Semantic-search coverage can only be populated when the active similarity backend produces artifacts compatible with the selected CLIP semantic-search backend. If Vision similarity is selected, the UI asks the user to enable Use selected CLIP model for similarity before building missing semantic-search artifacts.

Successfully validated artifacts are written one file at a time to:

~/Library/Application Support/RawCull/AnalysisArtifacts/Similarity/

In the sandbox, that resolves inside RawCull’s container. It is app-owned storage and does not need a security-scoped URL. Cache records are keyed and validated against the source fingerprint, artifact schema, model/backend descriptor, and RawCull’s embedding pipeline signature. A moved, renamed, changed, incompatible, or corrupt source is therefore treated as a cache miss and must be indexed again while the catalog scope is active.

Semantic search reuses cached CLIP artifacts

Opening a catalog hydrates compatible artifacts from the app-owned cache into RawCullSemanticSearchModel’s private semantic-artifact store. A semantic query then:

  1. applies the ordinary catalog admission rules, such as filename and rating filters,
  2. keeps only files with an artifact compatible with the currently selected CLIP backend,
  3. encodes the literal text query with the local CLIP text encoder,
  4. computes cosine similarity between that temporary text embedding and the cached image embeddings,
  5. sorts the matches and exposes the selected highest-ranked files as the active catalog working set.

searchSemantically(for:) and rankSemantically(query:files:) do not decode RAW files, generate image embeddings, or read image contents from the catalog. The text-query embedding exists only for that search call and is not persisted. Consequently, semantic ranking itself does not acquire a new security scope; it uses in-memory artifacts that were restored or created earlier.

The catalog scope nevertheless remains active during semantic search. Ranked files can immediately flow into preview, zoom, export, culling, burst, or Review operations that do need their source URLs. Clearing a search changes the working set, not the security-scope owner or lifetime.

Scope lifetime for the AI workflow

sequenceDiagram
    participant User
    participant VM as CatalogController
    participant Index as CLIP indexing
    participant Cache as App-owned artifact cache
    participant Search as Semantic search
    User->>VM: Select catalog
    VM->>VM: startAccessing catalog URL
    VM->>Cache: Hydrate compatible artifacts
    User->>Index: Index Similarity
    Index->>VM: Read source URLs under active scope
    Index->>Cache: Persist validated image artifacts
    User->>Search: Submit text query
    Search->>Cache: Use hydrated CLIP artifacts
    Note over Search: No source decoding and no new scope
    User->>VM: Close, cancel, or select another catalog
    VM->>VM: release session grant; final worker release stops access

Copy Workflow Bookmark

The copy workflow reuses the active catalog as its source and persists only the destination. OpencatalogView creates destBookmark when the user picks that folder.

flowchart TD
    A["User picks destination"] --> B["startAccessing"]
    B --> C["bookmarkData(.withSecurityScope)"]
    C --> D["UserDefaults destBookmark"]
    D --> E["stopAccessing"]
    E --> F["Later: ExecuteCopyFiles resolves bookmark"]
    F --> G["start destination scope during rsync"]
    S["Selected catalog URL"] --> H["start source scope during rsync"]
    G --> I["cleanup stops both scopes"]
    H --> I

If the selected catalog scope cannot be started, the user is asked to reopen the catalog. If destBookmark is missing or cannot be resolved, the user must reselect the destination. A stale bookmark is regenerated while its resolved scope is active. If source access succeeds but destination access fails, cleanup() releases the source before returning the startup error.

rsync Runtime Cleanup

ExecuteCopyFiles stores the accessed URLs in:

  • sourceAccessedURL,
  • destAccessedURL.

cleanup() finishes the progress stream, stops both security-scoped resources, clears process references, and is guarded by didCleanUp so multiple termination paths are safe.

close() sets isClosing, cancels the process, and calls cleanup. Normal termination constructs a CopyDataResult containing the output, typed outcome, and immutable CopyOperation source/destination snapshot, invokes completion, and then cleans up. There is no timing-delay dependency in the completion path.

The include list is written under Application Support/RawCull/CopyLists, not the user-selected source or destination. Cleanup removes the per-operation list on every path after it has been created.

Selected JPG Export Destination

The export sheet can use an existing catalog or a folder returned by its Choose… file importer. extractJPGDestination remembers that choice for the lifetime of FileOperationsModel; it is not a persistent rsync-style bookmark.

Pressing Extract starts a separate security scope for the destination immediately before ExtractAndSaveJPGs begins. The scope remains active for the entire batch, including detached atomic writes performed by SaveJPGImage, and is stopped when extractAndSavejpgs() returns. The active source catalog scope remains a different ownership unit and covers RAW/JPEG reads. If source and destination happen to be the same URL, each successful start still belongs to its own operation and must receive its own stop.

Destination access failure prevents actor creation and presents Export Not Started. Individual extraction or write failures do not shorten the destination lifetime: the actor returns an aggregate result, the view model stops the destination scope, and then it presents Export Incomplete if needed.

App Termination And Persistence

AppDelegate.applicationShouldTerminate(_:) returns .terminateLater and starts one termination task. That task awaits cullingModel.flushPersistence() before releasing the active catalog scope. A second termination request while the task is running also returns .terminateLater rather than starting another flush.

If persistence succeeds, the app stops the active catalog scope and replies true to AppKit. If persistence fails, a modal recovery choice offers retry, cancel quitting, or Quit Without Saving. Retry repeats the flush; cancel keeps the app and scope alive; discard releases the scope and terminates while explicitly acknowledging unsaved culling changes. Only one termination task is active. Export and rsync retain their own cleanup ownership.

File Writes

Writes outside the app container require an active user-granted scope. The main examples are:

WriteScope source
Extracted JPEG sidecars next to RAW filesactive catalog scope
Selected JPG export folderoperation-owned destination scope
rsync destination writesdestBookmark scope
rsync include fileapp Application Support folder, no external scope required

App-owned JSON/cache files under Application Support or Caches do not need security-scoped access.

What To Check When Changing This Area

  • Keep one clear owner for each long-lived scope.
  • Pair every successful start with a stop on all exit paths.
  • Keep catalog switching and app termination behind a successful culling-state persistence flush.
  • Keep the selected JPG destination scope open until the whole export actor returns; do not stop it after scheduling detached writes.
  • Keep the active catalog scope alive for CLIP indexing and for operations launched from semantic-search results.
  • Do not add per-file security-scope calls inside the CLIP indexer; the selected catalog directory owns that access.
  • Keep semantic ranking cache-only. If it begins decoding source images, its security assumptions and UI behavior must be revisited.
  • Store similarity artifacts and query-independent embeddings in app-owned storage, not beside the RAW files.
  • Use bookmarks for persistent copy-folder access, not for every temporary catalog scan.
  • When adding a new file write, ask whether it targets the app container or a user folder.
  • If copy closes early, verify ExecuteCopyFiles.cleanup() still runs exactly once.
  • Test partial rsync startup (source succeeds, destination fails) and partial JPG export failures as ownership cases, not only as UI errors.

Read the grant implementation before changing cancellation

Read Model/ViewModels/CatalogLifecycleCoordinator.swift for flush-before-switch and task ownership, then Model/RawImageLoading.swift for RawCullCatalogGrant and RawCullCatalogAccess. The registry holds weak references; it cannot extend a session by itself. retainAccess(for:) deduplicates covering roots and uses path components, avoiding a string-prefix match such as /Photos covering /PhotosOther. Retaining an existing grant does not call the OS start API again.

FileOperationsModel.swift retains source access separately from the operation-owned destination scope. EmbeddedJPGExportLoader.swift and FullSizePreviewLoader.swift retain access at the read boundary as well. Tests in CatalogLifecycleCoordinatorTests.swift verify that worker lifetime, rather than the selected URL alone, controls the final stop.

Exposure inspection and current release metadata

The private exposure renderer in ZoomPreviewHandler.swift retains a grant from RawCullCatalogAccess until its render operation returns, including cancellation that occurs during synchronous rendering. Generic parser support does not change catalog grant ownership or turn a plain filesystem URL into permission.

The checked-in privacy manifest is PrivacyInfo.xcprivacy. ReleaseMetadataTests.swift checks tracking is false and asserts the file-timestamp and app-owned UserDefaults declarations. This is release metadata, separate from security-scope access and from notarization. This source review does not certify sandbox behavior or platform compliance.

Preload saves retain their operation owner

A preload task retains its catalog grant until its worker group drains. Each worker releases the file’s grid gate before awaiting its disk save, but retains its slot until saving returns. Cancellation prevents later work at checked boundaries; an atomic write already underway is awaited. Releasing a UI waiter or cancelling a catalog does not prove every native operation has stopped.

October 31 integration

ZoomPreviewHandler retains catalog access around the awaited RAW overlay render. The renderer owns pixels and source state, while the handler owns this access lifetime. Cancellation is checked around expensive native calls; grant ownership must cover their completion.

Close-ups retain the catalog grant through rendering

BurstCloseUpsView.swift retains RawCullCatalogAccess while reading source revisions/orientation and again for each render worker. withExtendedLifetime holds the worker’s access reference through preview/developed loading and rasterization, including failure paths. Closing a panel or cancelling a task does not justify stopping a grant while a native decoder still uses it. The host revalidates file/render identity after the awaited load before returning pixels.

Saved manual regions are preference-sized UserDefaults records, not writes to the photo catalog, XMP sidecars or the rating store. The renderer itself writes no region file into the catalog; existing developed-JPEG loader persistence continues to follow its own established policy.

Photo access from AI Assessments

The assessment window can display findings from an in-app burst batch or an MCP request. For session entries the app asks the workspace to retain access to the session catalog. For MCP entries it delegates to the controller’s saved follow-up grant. The shared window chooses access from the selected request’s origin. RawCullApp