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.


Last modified November 24, 2026: update (c1748b4)