Skip to content

AI room staging rollout

This runbook is the release gate for room-staging v2. The implementation calls FLUX.2 [pro] directly on the Black Forest Labs API (POST https://api.bfl.ai/v1/flux-2-pro) and polls each task on the regional polling_url the create response returns, so task IDs can be persisted, polled and resumed across restarts. There is no provider fallback, no inbound webhook, and no provider-side cancel endpoint: a canceled job stops tracking its task, which finishes and bills on its own.

The provider contract is prompt plus one inline base64 input_image at an explicit width/height the worker derives from the source photo (helpers in apps/worker/src/bfl-client.ts); the source never leaves the platform as a URL. roomType and canonicalStyle remain audited application inputs and are rendered into the immutable, positively phrased prompt. Prompt versions are frozen in @repo/contract (PRO-60): the worker verifies each job’s prompt against the template of the version the job carries, so a prompt bump never orphans in-flight jobs. A worker that does not know a version still rejects it, so roll out a worker that carries the new version (and keeps the old ones) before the API producer that emits it. TV_ROOM is explicitly prompted as a TV/media room—it is not silently converted to a provider living_room enum.

Keep these official references open during rollout because provider schemas, pricing, and limits can change independently of this repository:

Treat every numbered section as a release gate. Complete the sections in order and do not continue past a failed pass condition. Commands are labeled by execution location:

  • Trusted workstation means a private terminal with curl, jq, openssl, psql, and optionally redis-cli/Docker. Shell history, screen recording, and support-session sharing should be disabled while handling secrets.
  • Deployment dashboard means the environment-variable and deploy/restart controls for the named service.
  • Worker terminal means a shell inside the deployed worker image, normally rooted at /app.
  • Database terminal means psql or the provider SQL console connected to the same writable PostgreSQL database used by apps/api and the worker.
  • Bull Board means the authenticated queue dashboard exposed by the worker. Never expose it without BULL_BOARD_USER and BULL_BOARD_PASSWORD.

Before starting, fill out and keep this worksheet with the release ticket. It prevents commands from being run against the wrong environment:

ItemValue to record
Environmentdevelopment, staging, or production
Release/image tagimmutable Git SHA or container tag
Public apps/api originfor example https://api.example.com
PostgreSQL host/databasehostname and database name only—never the password
Valkey host/databasehostname and database number only
QUEUE_SUFFIXexact value, including an empty value
Backup/snapshot IDprovider snapshot ID or encrypted dump path
Internal smoke listing IDunpublished/disposable listing
Release operatorperson running this runbook
Rollback ownerperson authorized to disable the feature
Start timeUTC timestamp

Stop the rollout, keep AI_ROOM_STAGING_ENABLED=false, and investigate if any of these occur:

  • the backup cannot be restored or its integrity cannot be checked;
  • migrations fail, are partially applied, or the second migration run is not a no-op;
  • an invariant query reports staged covers, invalid review state, duplicate variants, or duplicate nonterminal jobs;
  • a logical job creates more than two provider-attempt rows or a retry changes a still-active task ID;
  • a pending variant appears on an anonymous/public surface;
  • cancellation finalizes an image, or rejection/deletion removes a database row without a deletion-outbox record;
  • a staged image can become the listing cover;
  • provider spend, output quality, or error rate is not understood.

The kill switch is deliberately fail-closed: only the exact string true enables new paid task creation. Disabling it does not stop cancellation bookkeeping, polling of an already-persisted task, or storage-deletion cleanup. If deletion cleanup must also be paused for forensic review, stop/scale the worker process itself rather than relying on the staging flag.

  • PostgreSQL ai_jobs is the durable dispatch outbox; BullMQ is repairable delivery state.
  • A logical job can reserve only provider attempts 1 and 2.
  • A persisted task ID is polled on its stored providerPollUrl after restarts and BullMQ retries; a retry must not buy the same attempt again. A 429 on create leaves the attempt RESERVED (nothing was bought) and BullMQ backs off.
  • Every new result is private PENDING_REVIEW; only APPROVED variants reach public detail/search results.
  • A staged image can never be the cover, including after approval.
  • Rejection and original-image deletion write durable storage-deletion outbox entries.
  • AI_ROOM_STAGING_ENABLED=false stops creation of new paid tasks. It does not erase jobs or prevent recovery of an already-persisted attempt. BFL cannot cancel a running task: canceling a job stops tracking it, and the provider still bills it.

Purpose: establish the provider account, credential, and a deliberate spend owner before any process can create a paid task.

  1. On a trusted workstation, sign in to the Black Forest Labs organization account that will own production tasks (api.bfl.ai dashboard). Record the organization/account name and the teammate responsible for billing. Use an organization-owned account rather than a developer’s personal account so key revocation and billing survive staff changes.

  2. Confirm all of the following in the dashboard before buying anything:

    • the account can call flux-2-pro (the pinned model, not flux-2-pro-preview);
    • prepaid credits are loaded (one credit is $0.01; the API answers 402 when they run out and every staging job then fails PROVIDER_CREDITS_EXHAUSTED until topped up);
    • the account’s concurrency limit (24 active tasks by default) covers AI_STAGING_CONCURRENCY × worker replicas;
    • the provider’s data-processing/retention terms are acceptable for listing photos (the worker sends a downscaled copy of each photo inline; result URLs expire after ten minutes);
    • the current price is understood by the release and finance owners. FLUX.2 [pro] editing starts “from $0.045” per image and is billed by output megapixels; the worker records the settled credit cost of every task on the attempt, so no price is configured in the application.
  3. Create a dedicated API key for the worker. Name it so the environment and purpose are obvious, such as kottia-prod-ai-staging-worker. Save it directly in the deployment secret store as BFL_API_KEY on the worker only. apps/api and the clients never need this key; limiting its placement reduces the number of systems that can buy tasks.

  4. Generate an independent pseudonymization secret on the trusted workstation:

    Terminal window
    openssl rand -hex 32

    Save the 64-character result as AI_STAGING_USER_HASH_SECRET on the worker. It HMAC-hashes the internal user ID before the value is sent as BFL’s opaque user field, allowing abuse/cost correlation without revealing the database ID. Do not reuse BETTER_AUTH_SECRET or BFL_API_KEY, and do not rotate it during an incident unless you accept losing continuity in provider-side user attribution.

  5. Record the key creation date and owner in the secret manager metadata. Define a rotation owner, but do not rotate the key while tasks are active unless it is compromised: a task created under the old key is still polled under the new one, but a worker restarted mid-rotation with no key fails every job with PROVIDER_NOT_CONFIGURED.

Pass gate: the model is accessible and funded; both values are stored on the worker; no secret appears in Git, client configuration, logs, or the release ticket.

2. Place environment values on the correct services

Section titled “2. Place environment values on the correct services”

Purpose: keep every producer and consumer on one canonical provider configuration while guaranteeing that deployment alone cannot spend money.

In the deployment dashboard, set the kill switch to false everywhere before deploying. Environment-variable changes normally require a redeploy/restart; saving a value in the dashboard does not prove a running process has received it.

ServiceRequired staging values
svelte-web runtimeAI_ROOM_STAGING_ENABLED=false, AI_STAGING_LEGACY_ALIAS_SUNSET_AT, AI_STAGING_RESOLUTION, AI_STAGING_OUTPUT_FORMAT, plus the existing DATABASE_URL, VALKEY_URL, and QUEUE_SUFFIX
apps/apiThe same producer values as svelte-web; apps/api holds no provider credential and no staging webhook
workerAI_ROOM_STAGING_ENABLED=false, BFL_API_KEY, AI_STAGING_USER_HASH_SECRET, AI_STAGING_CONCURRENCY, AI_STAGING_RATE_LIMIT_PER_MINUTE, AI_STAGING_STRUCTURE_CHECK, and ANTHROPIC_API_KEY for the structure check

Recommended initial non-secret values:

Terminal window
AI_ROOM_STAGING_ENABLED=false
AI_STAGING_LEGACY_ALIAS_SUNSET_AT=2026-10-19T00:00:00.000Z
AI_STAGING_RESOLUTION=1mp
AI_STAGING_OUTPUT_FORMAT=jpeg
AI_STAGING_CONCURRENCY=4
AI_STAGING_RATE_LIMIT_PER_MINUTE=6
AI_STAGING_STRUCTURE_CHECK=log
AI_DESCRIPTION_CONCURRENCY=2

The values have the following operational meaning:

VariableWhy it exists and initial guidance
AI_ROOM_STAGING_ENABLEDPaid-create kill switch. Only exact true enables creation; start with false.
AI_STAGING_LEGACY_ALIAS_SUNSET_ATLast instant old style names are accepted. 2026-10-19 is 90 days from the v2 rollout baseline; move it only through an intentional compatibility decision.
AI_STAGING_RESOLUTIONPersisted output budget: match_input, 1mp (default), 2mp, or 4mp. The worker keeps the source photo’s aspect ratio, derives exact width/height on a 16-px grid (long side ≤ 2048), and the downloaded output is validated against that size. Raising it raises cost per task.
AI_STAGING_OUTPUT_FORMATjpeg is a pragmatic photo default. png is larger; webp requires confirming all downstream download/share clients.
AI_STAGING_CONCURRENCYMaximum simultaneous staging jobs in one worker process. Total effective concurrency is this value multiplied by worker replicas and must stay at or below BFL’s 24 active tasks per account.
AI_STAGING_RATE_LIMIT_PER_MINUTEBullMQ’s queue-wide start limiter across workers sharing this queue/Valkey namespace. Start at or below the verified BFL account limit.
AI_STAGING_STRUCTURE_CHECKWorker only. Structural guardrail mode (PRO-64): off, log (default: a Claude check records a verdict on every attempt and never rejects) or enforce (a drifted output fails with OUTPUT_STRUCTURE_DRIFT and is retried once on a new seed). Any other value is treated as log and logged as structure_check_mode_invalid. Switch to enforce only after the calibration gate in Structural guardrail.
AI_DESCRIPTION_CONCURRENCYSeparate description-worker concurrency. Keeping it independent demonstrates staging cannot head-of-line block descriptions.

Use the same QUEUE_SUFFIX on svelte-web, apps/api, and worker. Confirm the target Valkey URL, logical database number, TLS mode, and suffix are identical; otherwise producers write to one queue while the worker listens to another. An intentionally empty suffix is valid—record it as <empty> in the worksheet instead of leaving the worksheet ambiguous.

Producer values (AI_STAGING_RESOLUTION and AI_STAGING_OUTPUT_FORMAT) must match on apps/api and svelte-web. Each job persists them in PostgreSQL at submission, so a staggered change only affects jobs submitted after it.

There is no cost configuration: BFL reports a credit cost for every task (a quote on create, stored as costKind=ESTIMATED; the settled figure on the terminal poll, stored as costKind=ACTUAL) and the worker stores it on the attempt (costMicrousd, one credit = $0.01). Read spend from ai_provider_attempts, not from an estimate.

The shared contract (packages/contract/src/room-staging.ts) rejects resolution and format values it does not know. Deploy the producer and worker together when that list changes.

After each service is deployed—but before enabling—connect to its Railway container with railway ssh --project kottia.com --environment development --service <service> and verify presence without printing secret contents. Run only the block appropriate to that service:

apps/api
for name in DATABASE_URL VALKEY_URL; do
if [ -n "$(printenv "$name")" ]; then echo "$name=set"; else echo "$name=MISSING"; fi
done
printf 'AI_ROOM_STAGING_ENABLED=%s\n' "$AI_ROOM_STAGING_ENABLED"
printf 'QUEUE_SUFFIX=%s\n' "${QUEUE_SUFFIX:-<empty>}"
Terminal window
# worker
for name in DATABASE_URL VALKEY_URL BFL_API_KEY AI_STAGING_USER_HASH_SECRET ANTHROPIC_API_KEY AWS_ENDPOINT_URL AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_S3_BUCKET_NAME; do
if [ -n "$(printenv "$name")" ]; then echo "$name=set"; else echo "$name=MISSING"; fi
done
printf 'AI_ROOM_STAGING_ENABLED=%s\n' "$AI_ROOM_STAGING_ENABLED"
printf 'AI_STAGING_STRUCTURE_CHECK=%s\n' "${AI_STAGING_STRUCTURE_CHECK:-<unset: log>}"
printf 'QUEUE_SUFFIX=%s\n' "${QUEUE_SUFFIX:-<empty>}"
Terminal window
# svelte-web runtime
for name in DATABASE_URL VALKEY_URL; do
if [ -n "$(printenv "$name")" ]; then echo "$name=set"; else echo "$name=MISSING"; fi
done
printf 'AI_ROOM_STAGING_ENABLED=%s\n' "$AI_ROOM_STAGING_ENABLED"
printf 'QUEUE_SUFFIX=%s\n' "${QUEUE_SUFFIX:-<empty>}"

Every required line must say set, every kill-switch line must say false, and the suffix values must match the worksheet. Do not use env, printenv without a variable name, or deployment screenshots; those expose secrets.

Pass gate: all variables are on the intended services, all processes still report the kill switch as false, and producer/queue configuration matches exactly.

Purpose: create a tested recovery point and a written baseline before the backfill normalizes historical styles, approves legacy variants, clears staged cover flags, removes duplicate/orphan rows, and schedules their objects for deletion. Migration 0009 intentionally changes data; a schema-only rollback is not an acceptable substitute for a backup.

  1. Announce a maintenance window and name the release and rollback owners. Disable the staging action at the API/web layer first, then wait for active legacy staging jobs to finish or cancel them through the supported UI/API. Description generation can continue, but no one should manually retry or delete BullMQ jobs during this window.

  2. Take a provider-managed PostgreSQL snapshot of the writer database. Record its immutable snapshot ID, creation time, database name, retention period, and the provider’s restore procedure in the release ticket. A snapshot is useful only if the operator has permission to restore it.

  3. Verify the snapshot using the provider’s integrity/status check. Prefer restoring it to an isolated temporary database and connecting with psql; this proves more than a dashboard’s Completed badge. Never connect application or worker processes to the restored clone.

  4. If provider snapshots are unavailable, create an encrypted/private custom-format logical backup from a trusted workstation:

    Terminal window
    umask 077
    BACKUP_FILE="ai-room-staging-pre-v2-$(date -u +%Y%m%dT%H%M%SZ).dump"
    PGDATABASE="$DATABASE_URL" pg_dump --format=custom --no-owner --no-acl \
    --file "$BACKUP_FILE"
    pg_restore --list "$BACKUP_FILE" >/dev/null
    printf 'Verified backup: %s\n' "$BACKUP_FILE"

    pg_dump and pg_restore --list must both exit zero, and the file must be stored in an encrypted location with restricted access. The dump contains customer and authentication data. Do not upload it to Git, a ticket, chat, or an unencrypted shared drive.

  5. From a database terminal, confirm the connection target and record a UTC timestamp before collecting baseline counts:

    SELECT current_database() AS database,
    current_user AS database_user,
    inet_server_addr() AS server_address,
    CURRENT_TIMESTAMP AT TIME ZONE 'UTC' AS captured_at_utc;

    Compare the database/host with the worksheet. Stop if they do not match.

  6. Record pre-migration job, image, orphan, cover, and raw-style counts. Save query output with the release ticket; it is the basis for explaining backfill changes later:

    SELECT "status", count(*)
    FROM "ai_jobs"
    WHERE "type" = 'ROOM_STAGING'
    GROUP BY "status"
    ORDER BY "status";
    SELECT count(*) AS staged_images,
    count(*) FILTER (WHERE "isMain") AS staged_covers,
    count(*) FILTER (WHERE "styledFromId" IS NULL) AS staged_orphans
    FROM "property_images"
    WHERE "isStyled" = true;
    SELECT COALESCE("style", '<null>') AS submitted_style, count(*)
    FROM "property_images"
    WHERE "isStyled" = true
    GROUP BY COALESCE("style", '<null>')
    ORDER BY submitted_style;
    SELECT "styledFromId", COALESCE("style", '') AS submitted_style, count(*)
    FROM "property_images"
    WHERE "isStyled" = true
    GROUP BY "styledFromId", COALESCE("style", '')
    HAVING count(*) > 1
    ORDER BY count(*) DESC;

    staged_covers and staged_orphans may be nonzero in legacy data; the migration repairs them. Unexpectedly large counts, unknown style values, or many duplicates should be reviewed before continuing because the deterministic newest row will win.

  7. In Bull Board, open ai{QUEUE_SUFFIX} and record waiting, active, delayed, completed, and failed counts. Open a few legacy stage-room jobs and record their IDs without copying image URLs or user data. Wait for active staging jobs to reach a terminal state. Do not use Retry all, Clean, Drain, or Obliterate.

  8. Railway one-off worker commands use railway ssh against a running worker container, so leave exactly one replica on the new image with AI_ROOM_STAGING_ENABLED=false instead of scaling to zero. The verified backup and baseline are mandatory: once that worker sees the new tables, object cleanup can begin even though paid creation is disabled.

Pass gate: the correct database is documented, a restorable backup exists, baseline query and queue outputs are attached, no legacy staging job is active, and the team understands which historical rows the backfill may remove.

Section titled “4. Rehearse migrations on an empty database (recommended)”

Purpose: catch migration ordering, SQL syntax, extension, and idempotency failures before the release task touches shared data.

From the repository root on a trusted workstation, first remove a container left by an earlier rehearsal, if present:

Terminal window
docker rm --force staging-v2-postgres 2>/dev/null || true

Then apply the full migration chain to an isolated PostGIS database and prove a second run is a no-op:

Terminal window
docker run --name staging-v2-postgres \
--detach \
--publish 55439:5432 \
--env POSTGRES_PASSWORD=staging_test \
--env POSTGRES_DB=app \
postgis/postgis:16-3.5
until pg_isready -h 127.0.0.1 -p 55439 -U postgres; do sleep 1; done
DATABASE_URL=postgresql://postgres:[email protected]:55439/app \
bun run packages/database/scripts/migrate.ts
DATABASE_URL=postgresql://postgres:[email protected]:55439/app \
bun run packages/database/scripts/migrate.ts
docker rm --force staging-v2-postgres

The first migration command must exit zero and list the newly applied migrations. The second must exit zero and print Migrations up to date. Leave the container running for investigation if either command fails; capture the first SQL error and stop the rollout instead of editing the production migration table.

An empty database proves the chain is internally valid, but it cannot exercise legacy duplicates or malformed rows. For the strongest rehearsal, restore the section 3 backup into a network-isolated temporary PostgreSQL instance, ensure no API/worker can reach it, run the migration twice, and run every query in section 6 against that clone. Delete the clone according to the organization’s data-retention policy when the verification is complete.

Never substitute a shared development/staging/production URL into the rehearsal command. Before pressing Enter, read the literal host and port back to another release participant; the example must use local port 55439.

CI performs the same empty-database rehearsal (two runs, second a no-op, plus a kysely-codegen diff) on every PR touching packages/database/ — the Migrations job in .github/workflows/ci.yml — so a green PR already proves this gate; the manual rehearsal remains for the restored-data variant.

Pass gate: both empty-database runs pass, and a restored-data rehearsal either passes or is explicitly recorded as unavailable with the backup verification used instead.

5. Deploy schema and backward-compatible worker first

Section titled “5. Deploy schema and backward-compatible worker first”

Purpose: make the database and consumer understand both old and new messages before any new API/client can produce v2 work. This is the only safe direction for a rolling deployment.

  1. Reconfirm AI_ROOM_STAGING_ENABLED=false in the worker’s running environment, not only in the dashboard. Confirm the immutable worker image tag matches the worksheet.

  2. On Railway DEV, deploy exactly one worker replica on the new image with the feature disabled. The worker service carries the migration chain as its pre-deploy command (bun /app/packages/database/scripts/migrate.ts, see deploy/README.md § Database migrations): Railway applies the pending migrations in a one-off container from the new image before the new worker container starts, so the worker never runs against the old schema. The api deploy of the same commit runs the same command; Kysely’s migration lock serialises the two and the later one is a no-op. Nobody runs the script by hand, so two operators cannot race it. Remember that the disabled feature flag does not pause deletion cleanup after the schema appears.

  3. Open the worker deployment in Railway and read its pre-deploy step. It must begin with [migrate] target postgres.railway.internal:5432/… (never a workstation host) and exit 0. If the step fails, Railway marks the deploy failed and the previous deployment keeps serving — this is a stop condition: capture the first SQL error and stop the rollout instead of editing the production migration table.

  4. Require successful migration entries for all three names:

    0008_ai_room_staging_v2_schema
    0009_ai_room_staging_v2_backfill
    0010_ai_room_staging_v2_constraints

    Migration 0008 creates states/tables/columns, 0009 normalizes legacy data and writes cleanup/audit rows, and 0010 installs cascading relationships, uniqueness, staged-cover checks, and deletion/cancellation triggers. A failure between them is a stop condition—do not hand-edit kysely_migration or rerun only a copied SQL fragment.

  5. Prove the runner sees a complete transaction history: the api deploy of the same commit (or any later redeploy) must print Migrations up to date. in its pre-deploy step. To check without another deploy, connect from a trusted workstation and run the script once more — it prints the target first and must apply nothing:

    Terminal window
    railway ssh \
    --project kottia.com \
    --environment development \
    --service worker
    cd /app/packages/database && bun run scripts/migrate.ts
  6. Run every database check in section 6 before adding more worker replicas. Use the SSH session from step 5 and perform the checks immediately; deletion rows may already be DELETED, which is acceptable, but FAILED requires investigation.

  7. Keep the single worker replica at AI_ROOM_STAGING_ENABLED=false and watch its service for at least 60 seconds. Require no crash loop, successful PostgreSQL/Valkey connections, and no repeated schema/table errors. If a durable pending job is reconciled, require its job-level worker_started event and confirm no provider prediction is created while disabled. With an empty queue, the absence of worker_started is expected because that event is emitted when a staging job begins processing, not when the process boots.

  8. In Bull Board, confirm both ai{QUEUE_SUFFIX} and ai-staging{QUEUE_SUFFIX} exist and that their names use the worksheet suffix. Verify description jobs remain on ai; new staging jobs must use ai-staging. Failed or stalled legacy entries should be investigated individually, not bulk-retried.

  9. Increase to the intended worker replica count only after the single-replica observation passes. Effective concurrency is per-replica concurrency multiplied by replicas, while BullMQ’s limiter remains queue-wide for workers sharing the queue namespace. Confirm both values are acceptable to the provider account.

  10. Rebuild every active property search document so approved staged-card images carry their disclosure marker. From the worker container:

    Terminal window
    cd /app/apps/worker
    bun run search:schema -- --dry-run
    bun run search:schema -- --enqueue

    The dry run must complete without writing and report a plausible number of active property documents. Save that count. The enqueue command creates stable backfill jobs; it may be safely rerun, but do not run multiple copies simply because the queue is moving slowly.

    In Bull Board, wait until search-indexing{QUEUE_SUFFIX} has no active, waiting, or delayed backfill jobs and no failed backfill jobs. Compare completed/enqueued counts with the dry-run count, then run:

    Terminal window
    bun run search:schema -- --verify

    --verify must report success. Do not run it while jobs are still moving: it verifies completed search-document contents, not queue submission. Existing search hashes remain readable during this additive rollout, but a card cannot disclose an approved staged slide until its hash includes isStyled.

Pass gate: migrations apply once and are a no-op the second time; section 6 passes; one disabled worker remains healthy; both queues have the correct suffix; descriptions continue; and search backfill verification succeeds before API/client deployment.

6. Verify the migrated database before enabling

Section titled “6. Verify the migrated database before enabling”

Purpose: prove that the backfill produced a constrained, internally consistent state before the system is allowed to buy tasks.

Run the following from a database terminal and save the complete results. These checks are read-only:

SELECT "name", "timestamp"
FROM "kysely_migration"
WHERE "name" LIKE '0008%'
OR "name" LIKE '0009%'
OR "name" LIKE '0010%'
OR "name" LIKE '0038%'
ORDER BY "name";
SELECT to_regclass('public.ai_room_staging_jobs') AS staging_jobs,
to_regclass('public.ai_provider_attempts') AS provider_attempts,
to_regclass('public.property_image_review_events') AS review_events,
to_regclass('public.storage_deletion_outbox') AS deletion_outbox;
SELECT indexname
FROM pg_indexes
WHERE indexname IN (
'ai_jobs_active_staging_dedupe_uidx',
'property_images_live_staged_variant_uidx',
'property_images_live_legacy_staged_variant_uidx',
'property_images_aiJobId_uidx'
)
ORDER BY indexname;
SELECT conname
FROM pg_constraint
WHERE conname IN (
'property_images_staged_cannot_be_main_check',
'property_images_review_status_check',
'ai_provider_attempts_attemptNumber_check'
)
ORDER BY conname;
SELECT count(*) AS invalid_staged_covers
FROM "property_images"
WHERE "isStyled" = true AND "isMain" = true;
SELECT count(*) AS invalid_review_state
FROM "property_images"
WHERE ("isStyled" = true AND "reviewStatus" IS NULL)
OR ("isStyled" = false AND "reviewStatus" IS NOT NULL);
SELECT "styledFromId", "canonicalStyle", count(*)
FROM "property_images"
WHERE "isStyled" = true AND "canonicalStyle" IS NOT NULL
GROUP BY "styledFromId", "canonicalStyle"
HAVING count(*) > 1;
SELECT "styledFromId", COALESCE("style", '') AS legacy_style, count(*)
FROM "property_images"
WHERE "isStyled" = true AND "canonicalStyle" IS NULL
GROUP BY "styledFromId", COALESCE("style", '')
HAVING count(*) > 1;
SELECT "dedupeKey", count(*)
FROM "ai_jobs"
WHERE "type" = 'ROOM_STAGING'
AND "status" IN ('PENDING', 'PROCESSING', 'RETRYING', 'CANCEL_REQUESTED')
GROUP BY "dedupeKey"
HAVING count(*) > 1;
SELECT "aiJobId", count(*) AS provider_attempts
FROM "ai_provider_attempts"
GROUP BY "aiJobId"
HAVING count(*) > 2;

Interpret the results precisely:

QueryRequired result
Migration historyExactly one row each for 0008, 0009, 0010, and 0038
to_regclassFour non-null table names
Index listFour rows, one for every requested index
Constraint listThree rows, one for every requested constraint
Invalid staged coversCount 0
Invalid review stateCount 0
Canonical duplicate variantsZero rows
Display-only legacy duplicate variantsZero rows
Active dedupe collisionsZero rows
Jobs exceeding provider-attempt capZero rows

Next, review cleanup work created by the backfill:

SELECT "reason", "status", count(*)
FROM "storage_deletion_outbox"
GROUP BY "reason", "status"
ORDER BY "reason", "status";
SELECT "id", "objectKey", "reason", "status", "attempts",
"lastError", "createdAt", "processedAt"
FROM "storage_deletion_outbox"
WHERE "reason" LIKE 'MIGRATED_%'
ORDER BY "createdAt", "id";
SELECT "id", "objectKey", "reason", "attempts", "lastError"
FROM "storage_deletion_outbox"
WHERE "status" = 'FAILED'
ORDER BY "createdAt";

MIGRATED_ORPHAN, MIGRATED_DUPLICATE, MIGRATED_DUPLICATE_LEGACY, and MIGRATED_DUPLICATE_JOB_RESULT are expected only when the baseline contained corresponding legacy cleanup. For each reason, reconcile the count with the section 3 baseline or the restored-clone rehearsal. PENDING, PROCESSING, or DELETED are valid depending on whether the worker has started; any FAILED row must have an understood retryable storage error before rollout continues.

Do not manually delete S3 objects or outbox rows. The outbox is the durable proof that database deletion and storage deletion are coordinated; removing it defeats recovery and auditability.

The drain that moves these rows to DELETED is the drain-deletion-outbox job on the storage queue (apps/worker/src/storage.ts), running every minute. It is independent of AI staging: AI_ROOM_STAGING_ENABLED=false does not stop it, and neither does the staging worker failing to start. It used to be hung off that worker’s 30s interval, which is exactly the coupling PRO-15 removed.

Pass gate: all fixed row counts match the table, every invariant query is empty/zero, migration cleanup is reconciled, and no unexplained failed deletion is present.

Purpose: publish readers and thin adapters only after the database/worker understand the v2 contract, while the kill switch still prevents paid work.

  1. Deploy apps/api using the same immutable release tag as the worker. Keep AI_ROOM_STAGING_ENABLED=false. From its runtime terminal, repeat the non-secret configuration check in section 2 and confirm its health/readiness endpoint passes before testing staging.

  2. Confirm apps/api exposes no staging callback: POST /api/webhooks/replicate/staging/<anything> must return 404. The worker polls BFL itself; an inbound provider route on this host would be dead code at best and an unauthenticated mutation path at worst.

  3. Record the current database time, then deploy svelte-web with identical producer settings and the feature disabled:

    SELECT CURRENT_TIMESTAMP AS disabled_submission_test_started_at;

    As an authorized agent, open the staging control and attempt one submission. The UI must show the localized unavailable state, must not spin indefinitely, and must not imply a job was purchased. Then prove no room-staging job was inserted after the recorded timestamp:

    SELECT "id", "status", "createdAt"
    FROM "ai_jobs"
    WHERE "type" = 'ROOM_STAGING'
    AND "createdAt" >= '<DISABLED_SUBMISSION_TEST_STARTED_AT>'
    ORDER BY "createdAt";

    The result must contain no row caused by the test. Account for any known legacy traffic explicitly rather than assuming every row is the test.

  4. Deploy the shared API/client contract and agent-facing web/iOS/Android builds. Verify each agent client can decode ENQUEUED, EXISTING, and style_exists, plus RETRYING, CANCEL_REQUESTED, and CANCELED, without crashing or relabeling a terminal state.

  5. Deploy customer web/iOS/Android builds that render the exact localized AI · Virtually staged disclosure on staged thumbnails, galleries, and lightboxes. Test both the default locale and at least one translated locale. The disclosure is UI metadata; it must not be burned into or watermarked onto the image object.

  6. Confirm version/support policy before release. If mobile rollout is phased, the server must remain compatible with every supported installed version. Do not remove the legacy style aliases merely because the new store build has been submitted; wait until old producers are outside the supported floor.

  7. Exercise ordinary, non-staging image upload/edit/listing reads with the feature still disabled. This catches accidental contract regressions without spending provider credits.

Pass gate: API/web/native clients are healthy with staging disabled, the old staging callback path returns 404, disabled submissions create no job, ordinary image flows still work, and all supported public clients contain the disclosure UI before any pending image can be approved.

Purpose: enable consumption before production so every newly committed durable job has a compatible worker ready to reserve and persist its provider attempt.

  1. Start a live release call with the operator, rollback owner, and someone able to inspect PostgreSQL, Bull Board, S3, logs/Sentry, and the public listing surface. Record the UTC enablement time.
  2. Reconfirm apps/api can reach PostgreSQL and Valkey. Reconfirm the worker can reach PostgreSQL, Valkey, S3, and api.bfl.ai and that its QUEUE_SUFFIX matches.
  3. Set AI_ROOM_STAGING_ENABLED=true on the worker first, redeploy/restart it, and verify its running environment prints exactly true. Watch for a healthy worker_started event and no rapid provider/configuration errors. At this point the worker can recover durable work, but disabled producers should not accept a new submission.
  4. Set the flag to true on apps/api and svelte-web, then redeploy/restart both. Verify the running value on each service; do not infer a restart from a successful dashboard save.
  5. Keep Bull Board, structured worker logs, Sentry, and a database terminal open. Submit one low-risk job against the unpublished internal listing. Submit only once; a slow UI response is not a reason to click repeatedly because the durable dedupe path is part of what is being tested.
  6. Record the response’s original image ID, canonical style, AI job ID, disposition, and submission time. For a fresh image/style the disposition must be ENQUEUED. If it says EXISTING or style_exists, inspect existing state and choose a clean style instead of deleting records manually.
  7. Confirm the job appears in ai-staging{QUEUE_SUFFIX} with the AI job ID as its BullMQ ID, then moves through PENDING and PROCESSING to SUCCESS. A temporary RETRYING state is not a pass unless its error is understood and it still respects the two-attempt cap.
  8. Use the section 9 SQL query to verify exactly one provider-attempt row with provider='bfl', a non-null stable task ID and providerPollUrl, provider status Ready, costKind='ACTUAL' with a non-null costMicrousd, persisted dimensions/bytes/format matching the requested size, and one result image in PENDING_REVIEW. Confirm isMain=false, a non-null seed with seedReason='job', and, unless the structure check is off, a structure_check verdict whose outcome is not unavailable.
  9. Open the listing in a signed-out browser or incognito session and make a direct public API request. The pending image must be absent. Do not approve this canary until the privacy check passes.

If any step fails, immediately disable API/web producers first, then the worker flag, while leaving the worker process running for persisted task recovery and outbox cleanup. Follow section 12.

Pass gate: one canary completes with one paid attempt and one private pending result; no public surface exposes it; queue/log/database identifiers agree; and there are no unexplained errors or duplicate charges.

Purpose: validate prompt behavior, persistence/resume semantics, storage metadata, review privacy, approval publication, client disclosure, and every canonical room type against the real paid provider.

This is a manual paid release test. Eight successful logical jobs (seven furnishing rows plus one unstaged row) create at least eight tasks. Because each logical job may buy at most two provider attempts after a retryable terminal failure, authorize a worst-case budget of 16 tasks at the provider’s current price before starting (about $0.045 each at 1 MP). Stop if spend or retry rate exceeds the approved amount.

Prepare one internal unpublished/disposable listing with seven original photos already owned by the application’s S3 bucket—one representative image per canonical room type. Each original should be a normal supported image under the worker’s 20 MiB provider-download ceiling, free of people/sensitive documents, and classified through the normal agent UI. Do not use customer data unless provider-processing/retention terms and organizational policy permit it.

Before generating, record for every source: property ID, original image ID/object key, room classification, pixel dimensions, aspect ratio, file size, checksum if available, intended style, and tester. Confirm every source is an original (isStyled=false), belongs to the property, and is not a dangling external URL.

Run one generation for each row. Spread the six furnishing styles across rows 1–7; repeating one style for TV_ROOM is acceptable. Row 8 reuses one furnished original (a cluttered LIVING_ROOM or BEDROOM is ideal) with the unstaged value.

CaseCanonical roomWhat to inspect visually
1BEDROOMbed/furniture scale; walls, openings, flooring, crop unchanged
2LIVING_ROOMseating/contact shadows; no new built-ins or architecture
3DINING_ROOMtable/chair scale; hardwired lighting unchanged
4KITCHENonly movable decor/stools; cabinets, counters, appliances, plumbing unchanged
5BATHROOMonly towels/mats/decor; tile, mirror, vanity, fixtures unchanged
6OFFICEfreestanding desk/chair; no invented built-in shelves
7TV_ROOMTV/media intent is explicit; no wall alterations or silently generic living-room result
8any (unstaged)room is empty: furniture, rugs, curtains, art, plants gone; revealed floor/wall filled with matching material; built-ins, fixtures, openings, crop unchanged; promptVersion='room-unstaging-flux-2-pro-v2'

For each job:

  1. Submit from an authorized agent surface. Record the original image ID, submitted room classification, canonical style, AI job ID, disposition, and UTC time. A clean first submission must return ENQUEUED; save the per-assignment response rather than only a screenshot of a toast.

  2. Query the original image and verify its submitted room classification was persisted. The database value is now generation source of truth; changing only a client-side label after submission is not sufficient.

  3. In Bull Board, verify ai-staging{QUEUE_SUFFIX} uses the AI job ID as the BullMQ job ID. Record queue wait time and ensure staging activity does not delay a concurrently submitted description job.

  4. Run the SQL below repeatedly. A provider-attempt row should be reserved before purchase and its providerPredictionId (the BFL task id) and providerPollUrl should appear immediately after creation. That ID must remain stable through polling and ordinary BullMQ retries.

  5. For at least one row, restart one worker replica only after providerPredictionId is non-null and before provider completion. Record the ID before and after. The worker must resume the same task on its stored providerPollUrl; attempt 2 is valid only when attempt 1 contains a retryable terminal provider/transport failure (including OUTPUT_URL_EXPIRED, when the ten-minute signed output outlived the restart). A restart alone must never buy attempt 2.

  6. Confirm successful output metadata includes dimensions, format, download bytes, and checksum. Compare output dimensions with the size the worker requested (providerInputs.width/height on the image row, within 16 px), and open the stored image through the normal signed URL path. Reject truncated, non-image, unexpectedly huge, or architecturally altered results.

  7. Confirm exactly one staged row exists, has reviewStatus=PENDING_REVIEW, isMain=false, canonical provider inputs/task ID, and is visible only in authorized agent editing surfaces. Verify the localized disclosure appears there.

  8. Before approval, inspect anonymous web, a direct public API response, customer iOS, and customer Android. Refresh data and bypass local image/listing caches. The pending variant must be absent from all four surfaces.

  9. Record the staged object’s byte count/checksum, approve it through the review action, then refetch each public surface. The variant must appear with AI · Virtually staged on thumbnails, gallery, and lightbox. Download the object again and compare byte count/checksum: approval changes database visibility only and must not watermark or rewrite the generated pixels.

  10. Confirm the active listing’s Valkey search hash preserves the staged marker (replace the ID with the internal property ID):

    Terminal window
    redis-cli -u "$VALKEY_URL" --raw \
    HGET "psearch:property:PROPERTY_ID" images | jq

    The approved variant must contain "isStyled": true; originals must contain false. If the field is absent or wrong, stop the rollout and repeat the search-document rebuild in section 5 before exposing search results.

  11. Record a visual decision for the row: pass, reject/regenerate, or provider-quality incident. Review walls, windows, doors, fixed cabinetry, plumbing, electrical fixtures, perspective, crop, and room identity—not only whether the furniture looks attractive. Record the attempt’s structure_outcome next to your decision: a drift verdict on an output you pass, or a match on one you reject for architecture, is calibration evidence for the structural guardrail.

Use this query during the matrix:

SELECT
j."id" AS ai_job_id,
j."status",
j."phase",
j."errorCode",
s."canonicalRoomType",
s."canonicalStyle",
s."providerModel",
s."promptVersion",
s."resultImageId",
original."roomType" AS original_room_type,
a."attemptNumber",
a."providerPredictionId",
a."status" AS attempt_status,
a."providerStatus",
a."downloadBytes",
a."outputWidth",
a."outputHeight",
a."outputFormat",
a."costMicrousd",
a."costKind",
a."seed",
a."metrics"->>'seedReason' AS seed_reason,
a."metrics"->'structureCheck'->>'outcome' AS structure_outcome,
a."metrics"->'structureCheck'->'driftTypes' AS structure_drift_types,
result."reviewStatus",
result."isMain",
result."providerInputs",
result."providerPredictionId" AS result_prediction_id,
result."outputBytes" AS stored_output_bytes,
result."outputWidth" AS stored_output_width,
result."outputHeight" AS stored_output_height,
result."outputFormat" AS stored_output_format,
result."outputChecksum"
FROM "ai_jobs" j
JOIN "ai_room_staging_jobs" s ON s."aiJobId" = j."id"
LEFT JOIN "property_images" original ON original."id" = s."originalImageId"
LEFT JOIN "ai_provider_attempts" a ON a."aiJobId" = j."id"
LEFT JOIN "property_images" result ON result."id" = s."resultImageId"
WHERE j."id" = '<AI_JOB_ID>'
ORDER BY a."attemptNumber";

After all eight rows, confirm eight successful logical jobs, eight live variants (including the unstaged one), no job with more than two attempts, and no unexplained storage-deletion failure. Attach the completed matrix and provider spend to the release ticket. Keep the listing unpublished until lifecycle/race tests in section 10 finish.

Pass gate: every room category—including the distinct TV_ROOM prompt—and the unstaged row pass persistence, restart, metadata, privacy, approval, disclosure, search-index, and visual-architecture checks within the authorized spend.

Purpose: prove the hardening behavior under concurrency and cancellation timing, not only the happy-path image quality.

Complete every scenario before release using disposable originals on the unpublished smoke listing. Keep logs, Bull Board, and the section 9 SQL query open. Record the AI job, attempt, task, image, and outbox IDs produced by each scenario. Do not simulate results by directly editing application tables.

Configuration changes in this section affect the whole environment. Announce them, change one worker replica at a time, restart it, and restore the documented value immediately after the scenario. Each accidental job may spend up to two tasks, so keep the test set bounded.

  1. Generate a new style.
  2. Wait for SUCCESS and PENDING_REVIEW; record the pending image ID. Query the review-event table and confirm no APPROVED event exists yet.
  3. While pending, open the listing anonymously on web and customer mobile and call the public listing API. Refresh server data rather than relying on a previously cached response. The variant must be absent everywhere.
  4. Approve as the assigned/owning agent. An unrelated agent must receive an authorization/not-found response and must not learn the image’s existence.
  5. Confirm reviewStatus=APPROVED, reviewedByUserId and reviewedAt are populated, and exactly one APPROVED review event exists.
  6. Wait for the property search-index job to complete, then reopen/refetch public surfaces. The variant and exact disclosure label must appear; the original image remains available.
  1. Temporarily set the worker’s AI_STAGING_RATE_LIMIT_PER_MINUTE=1, restart it, and confirm the running value. Do not raise concurrency to manufacture this test.
  2. Submit one controlled job to consume the available start, then a second clean image/style and wait until the second job is visibly waiting in ai-staging. Record the second AI job ID; it is the cancellation subject.
  3. Cancel that waiting job from the authorized agent UI/API before it becomes active. Repeat cancellation once to verify the operation is idempotent rather than returning a server error.
  4. Confirm the database status is CANCELED, cancelRequestedAt/canceledAt are set, the waiting BullMQ job is removed, and zero ai_provider_attempts rows exist for that logical job. A task ID or charge is a failed test.
  5. Restore AI_STAGING_RATE_LIMIT_PER_MINUTE=6 (or the worksheet’s approved value), restart the worker, and verify the running value before continuing.
  1. Start a job and wait until providerPredictionId is non-null.
  2. Record the task ID and cancel from the authorized agent action. The immediate response/database status must be CANCEL_REQUESTED unless the worker has already finalized it.
  3. Repeat the same cancellation request. It must remain safe/idempotent and must not create another provider attempt.
  4. Confirm the worker stops tracking the task (BFL has no cancel endpoint, so no provider call is made and the task still bills) and the logical job becomes CANCELED. The attempt should end CANCELED or DISCARDED depending on the completion race; the task ID must remain the original ID.
  5. Confirm no staged row is finalized for the job. If the task completes first and output reached storage, require an output_discarded event and a storage_deletion_outbox row for the uploaded object; wait for DELETED.
  1. Generate a pending result and reject it.
  2. Confirm a REJECTED review event preserves the image ID snapshot, AI job ID, actor, timestamp, and optional reason even though the image row is gone.
  3. Confirm the image row is removed in the same transaction and an outbox row exists for its exact object key with reason STAGED_IMAGE_DELETED. Do not delete the S3 object manually.
  4. Wait for worker cleanup and confirm outbox status becomes DELETED, processedAt is populated, and the object is no longer retrievable through a fresh signed URL.
  5. Generate the same canonical style again. It must return ENQUEUED, not EXISTING or style_exists, and eventually create one new pending variant with a different job/image/object ID.
  1. Sign in as two authorized sessions and prepare the same original, room classification, and canonical style in both. Do not use different legacy aliases for this test.
  2. Release both submissions within the same second. Preserve the full per-assignment responses and request timestamps.
  3. One response may say ENQUEUED; the other must say EXISTING and return the same logical job ID. A completed/pending variant may instead make both responses style_exists; in that case reject it and repeat with a clean style.
  4. Confirm one nonterminal ai_jobs row for the dedupe key, one BullMQ job ID, at most two attempts for that logical job, and exactly one resulting image. Search logs for uniqueness errors; handled conflict resolution is acceptable, an HTTP 500 is not.
  1. Generate at least two staged derivatives for a disposable original.
  2. Approve one derivative and leave the other pending. Optionally start a third generation so cancellation-on-delete is exercised.
  3. Record all database image IDs/object keys, then delete the original through the normal API/UI. Never issue direct SQL for this scenario.
  4. Confirm every derivative row cascades. A queued job becomes CANCELED; an active/retrying job becomes CANCEL_REQUESTED and then CANCELED after provider handling.
  5. Confirm the original and every derivative object key have deletion-outbox records (ORIGINAL_IMAGE_DELETED or STAGED_IMAGE_DELETED) and eventually become DELETED.
  6. Confirm the listing/search document no longer references any deleted image and that the remaining property has a valid non-staged cover. If no original remains, the listing must have no cover rather than promote a staged variant.

After approving a variant, attempt the normal cover endpoint with an authenticated test session. Keep session credentials out of shell history; the placeholder below must be replaced only in a private terminal:

Terminal window
curl --include --request PATCH \
https://api.dev.useast.kottia.com/api/property-images/<STAGED_IMAGE_ID> \
--header 'content-type: application/json' \
--header 'cookie: <REDACTED_TEST_SESSION_COOKIE>' \
--data '{"isMain":true}'

Expect HTTP 400. Then independently verify the database constraint in a transaction that is rolled back:

BEGIN;
UPDATE "property_images"
SET "isMain" = true
WHERE "id" = '<STAGED_IMAGE_ID>';
ROLLBACK;

The update statement must fail with property_images_staged_cannot_be_main_check; issue ROLLBACK again if the SQL client leaves the transaction aborted. If the update succeeds, stop the release.

Then send DELETE /api/property-images/<STAGED_IMAGE_ID> with the same authorized session and expect HTTP 400. Reject the variant through ai.rejectStagedVariant; do not use the generic photo endpoint, because rejection must write review audit metadata before the deletion trigger schedules storage cleanup.

Pass gate: all seven lifecycle scenarios have recorded IDs/evidence, cancellation and rejection leave no live result, duplicate requests converge, cascades delete every derivative safely, and cover prohibition succeeds at both service and database boundaries.

Purpose: confirm operators can detect stuck, duplicated, expensive, or cleanup-failed work without waiting for a customer report.

During and after smoke tests, require the following worker structured events for the relevant job IDs:

  • worker_started with Bull attempt and queue wait;
  • task_created with attempt and task identifiers, the requested width/height, and the quoted cost;
  • provider_terminal with provider status;
  • output_validated with byte count, format, and dimensions;
  • completed with queue/provider timings;
  • canceled for cancellation tests;
  • output_discarded for a completion/cancellation race;
  • retry_scheduled or terminal_error with structured error code/category when deliberately exercised;
  • attempt_reserved with attempt number, seed and seedReason;
  • structure_check_mode (or structure_check_mode_invalid) once at worker start;
  • structure_check with outcome, drift types, confidence, latency and Claude tokens/cost, unless the mode is off;
  • structure_check_unavailable when the check could not answer, and structure_drift_rejected when enforce failed an attempt over.

Also require API events ai_room_staging.cancel_requested, ai_room_staging.variant_approved, and ai_room_staging.variant_rejected. Logs may contain internal IDs and task IDs, but must not contain the provider key, signed output URLs, base64 source bytes, cookies, or raw image bytes.

Operational gates:

  • No job PENDING over five minutes without a Sentry alert.
  • No stale PROCESSING/CANCEL_REQUESTED heartbeat over two minutes or RETRYING heartbeat over five minutes without a Sentry alert.
  • No logical job with more than two ai_provider_attempts rows.
  • No unbounded growth in storage_deletion_outbox FAILED rows.
  • Description generation latency remains normal while staging is busy, proving queue isolation.

Run these read-only queries after the canary, after the full matrix, and again 15 minutes later:

SELECT "status", count(*)
FROM "ai_jobs"
WHERE "type" = 'ROOM_STAGING'
AND "createdAt" > CURRENT_TIMESTAMP - INTERVAL '24 hours'
GROUP BY "status"
ORDER BY "status";
SELECT "status", count(*), max("attempts") AS max_attempts
FROM "storage_deletion_outbox"
GROUP BY "status"
ORDER BY "status";
SELECT "id", "status", "phase", "createdAt", "heartbeatAt", "errorCode"
FROM "ai_jobs"
WHERE "type" = 'ROOM_STAGING'
AND "status" = 'PENDING'
AND "createdAt" < CURRENT_TIMESTAMP - INTERVAL '5 minutes'
ORDER BY "createdAt";
SELECT "id", "status", "phase", "heartbeatAt", "errorCode"
FROM "ai_jobs"
WHERE "type" = 'ROOM_STAGING'
AND (
("status" IN ('PROCESSING', 'CANCEL_REQUESTED')
AND "heartbeatAt" < CURRENT_TIMESTAMP - INTERVAL '2 minutes')
OR
("status" = 'RETRYING'
AND "heartbeatAt" < CURRENT_TIMESTAMP - INTERVAL '5 minutes')
)
ORDER BY "heartbeatAt";
SELECT "aiJobId", count(*) AS attempt_count
FROM "ai_provider_attempts"
GROUP BY "aiJobId"
HAVING count(*) > 2;
SELECT "id", "objectKey", "reason", "attempts", "lastError", "createdAt"
FROM "storage_deletion_outbox"
WHERE "status" = 'FAILED'
ORDER BY "createdAt";

The four exception queries must return zero rows after expected in-flight work settles. Trigger one non-production alert path or inspect a captured test event to prove the Sentry environment, release tag, job ID, and error code are searchable. Compare description queue wait/provider latency to the pre-release baseline while staging is saturated; a shared-limiter slowdown is a release failure.

Pass gate: all expected events are searchable by job ID, Sentry routing is verified, exception queries are empty, deletion failures are not accumulating, and description latency remains within its established baseline.

FLUX.2 [pro] layout is seed-driven, so at some seeds an edit covers a door or window no matter how the prompt is worded (PRO-60). After the output is downloaded and before it is uploaded, the worker asks Claude (claude-haiku-5-5, effort medium) whether the edit is still the same room: same doors and windows in the same places, same geometry and camera, same built-ins (apps/worker/src/staging-structure-check.ts). The verdict is stored on the attempt as metrics.structureCheck in every mode except off.

Mode (AI_STAGING_STRUCTURE_CHECK)Effect
offThe check never runs.
log (default)The check runs and records its verdict; nothing is rejected.
enforceA drift verdict fails the attempt with OUTPUT_STRUCTURE_DRIFT before upload; attempt 2 runs on a re-rolled seed (seedReason='drift_retry'). A drift on attempt 2 fails the job with OUTPUT_STRUCTURE_DRIFT (category OUTPUT); the web dialogs show a dedicated message and ai-credit-refund-scan refunds the credit although BFL was paid.

The check sends both photos, downscaled to 768 px on the long side, inline (base64 image blocks) to the Anthropic Claude API (US) on the worker’s ANTHROPIC_API_KEY. Confirm the Anthropic data-processing and retention terms are acceptable for listing photos, as section 1 requires for BFL, before any mode other than off runs on real listings. The check has not yet been run against the live Claude API: verdicts, latency and cost measured with Gemini do not carry over, so the calibration gate below starts again on Claude.

A check that cannot answer (no ANTHROPIC_API_KEY, the 30 s timeout, model error, a refusal, malformed answer, unreadable source) records outcome='unavailable' and never rejects, in any mode, because the output is already paid for; in enforce it also raises a Sentry warning. Each check costs under a cent at Claude Haiku 5.5 prices ($0.10 / $0.50 per 1M input / output tokens, 16,000 output tokens at most) and runs before finalize; cost and latency per check are not yet measured on Claude. A rejected attempt is still a billed BFL task, so the worst case remains two tasks per job.

Calibration gate before enforce. Run in log for at least two weeks or 150 attempts, whichever is later, then:

  1. Score the check against agent review decisions. A drift verdict on an approved variant is a false positive:

    SELECT a."metrics"->'structureCheck'->>'outcome' AS outcome,
    img."reviewStatus",
    count(*)
    FROM "ai_provider_attempts" a
    JOIN "ai_room_staging_jobs" s ON s."aiJobId" = a."aiJobId"
    LEFT JOIN "property_images" img ON img."id" = s."resultImageId"
    WHERE a."metrics" ? 'structureCheck'
    AND a."createdAt" > CURRENT_TIMESTAMP - INTERVAL '30 days'
    GROUP BY 1, 2
    ORDER BY 1, 2;

    Rejected variants are an upper bound on misses only: agents also reject for reasons that are not structural.

  2. Re-score the PRO-60 repro set (source/output pairs labeled drift or match) on a trusted workstation:

    Terminal window
    cd apps/worker
    doppler run -- bun run staging:structure-check <dir-with-pairs> --max-fpr 0.02

    The command exits non-zero above a 2 % false-positive rate. The far-wall-door cases must be reported as drift.

  3. Require an unavailable rate under 2 % over the shadow period.

  4. Decide how to bound drift refunds. In enforce, a job that drifts twice is refunded although two BFL tasks and two Claude calls were paid, so a user who can reliably provoke a drift verdict (a non-room photo, text aimed at the model, an unstaged source whose openings are already half hidden) spends provider money at no credit cost, limited only by the ai.stage rate limit. Either add a per-subject cap on OUTPUT_STRUCTURE_DRIFT refunds per window, or monitor repeat drift refunds per subject with this query and act on outliers:

    SELECT coalesce(t."teamId", t."userId") AS subject,
    count(*) AS drift_refunds
    FROM "ai_credit_transactions" t
    JOIN "ai_jobs" j ON j."id" = t."aiJobId"
    WHERE t."reason" = 'REFUND'
    AND j."errorCode" = 'OUTPUT_STRUCTURE_DRIFT'
    AND t."createdAt" > CURRENT_TIMESTAMP - INTERVAL '7 days'
    GROUP BY 1
    HAVING count(*) >= 5
    ORDER BY 2 DESC;

Only then set AI_STAGING_STRUCTURE_CHECK=enforce on the worker and restart it; confirm the structure_check_mode startup line says enforce. For the first week, watch structure_drift_rejected volume, how many drift retries finalize on attempt 2, terminal OUTPUT_STRUCTURE_DRIFT jobs with their REFUND rows in ai_credit_transactions, and structure_check_unavailable warnings. To back out, set the mode to log (or off) and restart: no data changes are needed.

Prevention spike: FLUX 3 Image anchor boxes (PRO-107)

Section titled “Prevention spike: FLUX 3 Image anchor boxes (PRO-107)”

The guardrail detects drift after a paid task. PRO-107 evaluates preventing it instead: BFL’s flux-3-image endpoint takes bounding boxes, and a box whose source and target are the same region anchors what it covers. The staging state machine uses it only for jobs on that model, which no job uses until the API opts in (see The flux-3-image path below). apps/worker/src/staging-anchor-boxes.ts asks Claude (claude-opus-5-5, effort low, 30 s timeout) for every door, window, archway and built-in in the photo exactly as it is sent to the provider, and bun run staging:flux3-spike compares FLUX 3 with and without those anchors on the PRO-60 repro set.

Run it from a trusted workstation under a Doppler config that holds both BFL_API_KEY and ANTHROPIC_API_KEY (the worker branch config):

Terminal window
cd apps/worker
doppler run -c <worker-config> -- bun run staging:flux3-spike <cases-dir> --out <dir> --probe --yes
doppler run -c <worker-config> -- bun run staging:flux3-spike <cases-dir> --out <dir> --dry-run
doppler run -c <worker-config> -- bun run staging:flux3-spike <cases-dir> --out <dir> --yes

The first command sends the worker’s own request body to the live endpoint, with and without anchors, and checks that the fields BFL’s schema leaves out (seed, output_format, disable_pup) are refused. A rejected field (HTTP 422) is free, and each accepted probe is one billed task, six at most. The spike builds every body with the worker’s buildAnchoredStagingRequest, so it measures exactly what a job sends; --extra adds fields on top. --seeds only labels repeat draws, because the endpoint takes no seed. The second command prints every request body with images redacted and spends nothing.

The third command is paid: every run is a billed BFL task. Four cases × three seeds × two arms is 24 tasks, about $1.15 at the 1 MP list price. It creates nothing without --yes, --max-tasks caps a run, and outputs are cached in --out, so a re-run pays only for missing rows. It writes one contact sheet per case (source with its boxes drawn, then each arm), results.csv with the provider’s cost, latency and the structure-check verdict per run, and pairs/ in the layout staging:structure-check reads. Post the sheets and findings on PRO-107. A migration to flux-3-image waits until that issue’s acceptance criteria are met.

The flux-3-image path (built, switched off)

Section titled “The flux-3-image path (built, switched off)”

The worker can already run a job on flux-3-image; nothing sends one there until the API opts in. The pieces:

  • Model per job. AI_STAGING_PROVIDER_MODEL on apps/api and svelte-web picks the model for new jobs: unset (default) is flux-2-pro, flux-3-image opts in, anything else fails submission closed with staging_configuration_invalid. The job persists providerModel and a prompt version of its own family (room-staging-flux-3-image-v1 / room-unstaging-flux-3-image-v1, same wording as the FLUX.2 v2 pair). The worker accepts both models and rejects a job whose model and prompt family disagree (PROMPT_INTEGRITY_FAILED).
  • Anchor boxes, once per job (D2). Before the first paid task of a flux-3-image job, the worker runs detectAnchorBoxes on the exact bytes it sends and stores the record in ai_room_staging_jobs.anchorBoxes (migration 0057: outcome, boxes, detector version, latency, Claude cost). Every later attempt reuses it and never detects again.
  • Request. buildAnchoredStagingRequest in bfl-client.ts, from BFL’s published Flux3ImageInputs schema: prompt, images, width / height, safety_tolerance, grounding: false and user. The schema allows no other field, so seed, output_format and disable_pup are left out (each one is a 422, which the worker records as PROVIDER_REQUEST_REJECTED). There is no box field: each box becomes a Keep row (id, from: "ref_image_0", equal src_bbox / tgt_bbox, desc), and the rows go after the persisted prompt as a JSON array, behind a sentence that names them by <id>. When the detector found nothing, the body is a plain edit on the persisted prompt. The output format follows the provider; the output check reads it from the bytes.
  • Fallback (D3). When detection was unavailable (no ANTHROPIC_API_KEY, timeout, bad answer), that job runs on FLUX.2 [pro] for every attempt, logged as ai_room_staging.anchor_fallback. The attempt records the model it actually called in ai_provider_attempts.providerModel.
  • Guardrail. The PRO-64 structure check runs unchanged on both models.

Before turning it on, run the probe to confirm the live endpoint accepts the body, and check that output sizes come back as requested, because the output check compares against the computed size. The D1 gate (quality on par and cost per image within the agreed bound) still decides the switch.

Turning it on, after the gate passes:

  1. Deploy the worker first (it already accepts both models), then apps/api and svelte-web. Add AI_STAGING_PROVIDER_MODEL to dopplerManagedKeys in .railway/railway.ts in the same change that sets it in Doppler.
  2. Set AI_STAGING_PROVIDER_MODEL=flux-3-image on apps/api and svelte-web together (DEV first), keep AI_STAGING_STRUCTURE_CHECK=log, and run the section 9 smoke matrix plus the PRO-60 repro rooms.
  3. Recalibrate the structure check on the new model with bun run staging:structure-check before moving to enforce, and watch anchor_fallback, structure_drift_rejected and OUTPUT_STRUCTURE_DRIFT refunds.

Rollback is unsetting the variable: new jobs go back to FLUX.2 [pro], and jobs already persisted as flux-3-image finish on it (or on the fallback).

Purpose: stop new purchases quickly while preserving enough state to finish, cancel, clean up, and understand work already in progress.

  1. Declare the incident and record the UTC time, symptom, first affected job/task ID, and incident commander. Preserve logs before changing replica counts.
  2. Set AI_ROOM_STAGING_ENABLED=false on apps/api and svelte-web first, then restart/redeploy them. Verify an attempted submission shows unavailable and creates no new ai_jobs row after the disable timestamp. Disabling producers first closes the intake before consumer behavior changes.
  3. Set the worker flag to false and restart/redeploy it. New jobs without a paid task remain durable PENDING with phase PROVIDER_DISABLED; they can resume after recovery. A reserved-but-uncreated attempt also remains unpaid and resumable.
  4. Leave the worker process running unless storage deletion itself is suspected. The flag does not stop polling a persisted task, and the deletion outbox is drained by the separate storage queue, which the flag never touched. If deletion must be frozen for forensics, scale the worker to zero and accept that descriptions, heartbeats, cancellation, and cleanup will also pause.
  5. Decide what to do with already-paid active tasks. If output must not finalize, cancel each through the authorized API/UI and verify CANCEL_REQUESTED → CANCELED. BFL cannot cancel a running task, so it completes and bills regardless; cancellation only guarantees the output is never finalized. Do not delete the BullMQ entry or null the task ID.
  6. Inspect Bull Board, Sentry, ai_jobs, ai_room_staging_jobs, ai_provider_attempts, and deletion outbox. Export only the minimum IDs/status/metrics needed for the incident; redact signed URLs and credentials.
  7. Do not revert migrations, restore the backup over a live database, or delete job/attempt/outbox rows as a feature rollback. The additive schema and durable records are required by the already-deployed readers and recovery paths. A data restore is a separate disaster-recovery decision requiring downtime and reconciliation of post-snapshot writes.
  8. Fix and deploy a compatible release with the flag still false. Repeat sections 5–7 as applicable, then run one canary. Re-enable the worker first and API/web second; pending durable jobs reconcile automatically.
  9. Never route to the old interior-design model, to Replicate, or silently to another provider. A provider outage remains an explicit unavailable state until Black Forest Labs is safe again.

Pass gate for a disabled incident state: all producer runtimes report false, disabled submissions add no jobs, no new task ID appears after the worker disable time, existing paid attempts are either intentionally polling or canceled, and cleanup state is preserved.

Purpose: remove temporary compatibility code only when telemetry and the supported-client floor prove it is unused; the calendar date alone is not sufficient.

On or after the exact UTC instant in AI_STAGING_LEGACY_ALIAS_SUNSET_AT:

  1. Confirm product/release owners still want to end alias support. If a supported native version can submit aliases, extend the sunset explicitly and document the new date rather than breaking that client silently.

  2. Confirm current web/iOS/Android code and observed request telemetry submit only the six canonical styles. Query the last 30 days of persisted submissions:

    SELECT "submittedStyle", count(*)
    FROM "ai_room_staging_jobs"
    WHERE "createdAt" >= CURRENT_TIMESTAMP - INTERVAL '30 days'
    AND "legacyStyle" IS NOT NULL
    GROUP BY "submittedStyle"
    ORDER BY "submittedStyle";

    Require zero rows. Also search structured/API logs for validation or alias-normalization events; database evidence alone misses requests rejected before insertion.

  3. Check the application-store adoption dashboard and server-supported minimum versions. The supported client floor—not the latest available version—must be above the canonical-style release.

  4. In Bull Board, confirm the legacy ai{QUEUE_SUFFIX} queue holds no stage-room job. The bridge that consumed them was removed with the BFL cut-over (PRO-49), so any entry that still appears is historical and ages out with normal retention.

  5. Remove alias acceptance from the shared contract/service in a normal reviewed release. Keep the kill switch false during rollout and repeat contract tests, disabled-submission verification, and one canonical canary.

  6. Keep historical style, submittedStyle, legacyStyle, and legacyMetadata values readable for display/audit. Do not rewrite them merely to make telemetry appear clean.

  7. Do not add no-furniture back to the generation catalog. It remains display-only historical data and must never be sent as a FLUX.2 [pro] staging request. Emptying a room is the separate unstaged catalog value (PRO-48), which runs on FLUX.2 [pro] with its own prompt version (room-unstaging-flux-2-pro-v2).

Pass gate: no alias submission exists in 30 days of database/log evidence, all supported clients are canonical, the legacy queue is empty, product approves removal, and a post-removal canonical canary passes.

14. Provider cut-over: GPT Image 2 on Replicate → FLUX.2 [pro] on Black Forest Labs (PRO-49)

Section titled “14. Provider cut-over: GPT Image 2 on Replicate → FLUX.2 [pro] on Black Forest Labs (PRO-49)”

Purpose: move a tier that is already running v2 staging onto the Black Forest Labs provider without stranding paid work. The cut-over is hard: after the release there is one provider, and validateCanonicalJob fails any job that still carries the Replicate-era model with CANONICAL_INPUT_INVALID.

  1. Set AI_ROOM_STAGING_ENABLED=false on web, apps/api, and the worker (Doppler root config), wait for the sync, and redeploy all three so the running processes hold it.

  2. Drain. Repeat until the query returns no rows; cancel PENDING rows explicitly (they never progress while the flag is off) and let PROCESSING/RETRYING rows settle within the provider deadline:

    SELECT "status", count(*)
    FROM "ai_jobs"
    WHERE "type" = 'ROOM_STAGING'
    AND "status" IN ('PENDING', 'PROCESSING', 'RETRYING', 'CANCEL_REQUESTED')
    GROUP BY "status";
  3. In the Doppler <tier>_worker branch config only: add BFL_API_KEY (a branch-only key never syncs to api or svelte-web, matching the worker-only extras in .railway/railway.ts). In the Doppler root config: add AI_STAGING_RESOLUTION; delete REPLICATE_API_TOKEN, REPLICATE_WEBHOOK_BASE_URL, REPLICATE_WEBHOOK_SIGNING_SECRET, AI_STAGING_QUALITY, AI_STAGING_ASPECT_RATIO, AI_STAGING_OUTPUT_COMPRESSION, AI_STAGING_COST_MICROUSD_*, and AI_STAGING_PRICING_VERSION. Root deletes cascade to the service branches. railway config plan must then show no variable drift against .railway/railway.ts.

  4. Merge; Railway deploys apps/api, the worker, and svelte-web together from the tier branch.

  5. Run migration 0038_ai_room_staging_bfl_flux_2_pro from inside a container (see deploy/README.md § Database migrations). It renames quality → resolution, adds sourceWidth/sourceHeight and providerPollUrl, drops the webhook receipts table, and — as a safety net for anything the drain missed — fails still-open Replicate-era jobs and attempts with PROVIDER_MIGRATED. Verify with \d "ai_room_staging_jobs" and \d "ai_provider_attempts".

  6. Repeat the section 2 runtime checks on each service (no REPLICATE_* value present; BFL_API_KEY set on the worker only).

  7. Re-enable the worker first, then apps/api and svelte-web. Run one canary and require the section 8 pass gate: provider='bfl', providerModel='flux-2-pro', costKind='ACTUAL', output dimensions equal to the requested size, variant PENDING_REVIEW, hidden from public surfaces.

  8. Quota note: a job the migration failed is refunded only if it never obtained a task ID (spendOccurred in packages/api/src/services/plan-usage.ts). The drain in step 2 is what keeps paid attempts from being stranded.

Pass gate: no REPLICATE_* variable on any service, migration 0038 applied once, no ai_jobs row left in a non-terminal state from before the deploy, and one BFL canary finalized privately.

  • BFL_API_KEY (worker only), billing/credits, and user-hash secret configured; no REPLICATE_* variable remains.
  • Kill switch false during schema/worker/API/web rollout.
  • Database backup recorded; migrations 0008–0010 and 0038 applied twice/idempotently verified.
  • Schema/invariant SQL passes; migration cleanup outbox reviewed.
  • Dedicated ai-staging queue visible.
  • Active property search documents rebuilt and verified; staged search images retain isStyled: true.
  • The old staging callback path returns 404.
  • Eight paid smoke jobs pass, including explicit TV_ROOM behavior, one unstaged row, and a worker restart.
  • Approval/public privacy, queued/running cancellation, rejection/regeneration, duplicate race, original deletion, and cover rejection pass.
  • Public web/iOS/Android show only approved variants with AI · Virtually staged.
  • Sentry/log/queue/outbox dashboards are quiet and description jobs are not blocked.
  • Rollback owner knows the kill-switch procedure; no v1 fallback exists.
  • Release ticket contains worksheet values, baseline/migration SQL, smoke matrix, lifecycle evidence, spend, UTC enablement time, and operator/rollback sign-off.

Record the final decision and time:

Sign-offNameUTC timeDecision/notes
Release operatorGO / NO-GO
Database verifier
Client/privacy verifier
Rollback owner