Skip to content

fix(batch): multi-replica hardening and non-5xx enrichment retries - #22371

Merged
Git-on-my-level merged 6 commits into
mainfrom
lane/opus-batch-multireplica
Oct 19, 2026
Merged

Git-on-my-level merged 6 commits into
mainfrom
lane/opus-batch-multireplica

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Why

The prod batch worker is moving from 1 to 2–4 replicas (L4 GPU nodes, capped at 4), with an HPA planned. A multi-replica safety scan found no corruption path, but it did find three problems that get worse as replicas are added. This PR fixes them.

  1. The HPA goes blind when every replica is busy. Queue-age gauges were refreshed only at the top of Pump.run_once. run_once then waits for the whole GPU batch, and the prometheus-adapter drops any sampler series older than 60s. If every replica is inside a batch longer than 60s, every series drops and the HPA holds at its current size through the backlog peak.
  2. Maintenance loops run on every replica. Each worker runs scheduler.recover and the result_ready drain every 5s. Each serving instance runs reconcile every 20s, covering cleanup, staging reap, the enrichment sweep, quarantine discovery and recovery. Every one of these loops is idempotent and transaction-fenced, so the waste is in reads, enqueues and contention, not correctness.
  3. Expected enrichment retries return HTTP 500. FirstSummaryCallbackPending and SyncConversationPersistenceFenced are deliberate retain-and-retry signals, but they were answered with 500. Between 00:30Z and 03:30Z on 10-19 they made up about 7k of the backend-sync and backend-sync-backfill 5xx, which inflates the error gates and the sentinels.

What changed

  • Independent queue sampler (backend/diarizer/batch_pipeline_runtime.py, supervise). A supervised task calls the new Pump.sample_metrics() every 15s, independent of the GPU batch, so gauges stay well inside the adapter's 60s freshness window. Failures are logged and leave the last sample and its freshness unchanged. The worker builds its Pump(inline_metrics=False), so run_once no longer samples inline. Other Pump callers keep inline sampling.
  • Advisory single-owner lease (new backend/utils/batch_pipeline/leader.py):
    • Design: a TTL plus token row in {namespace}_leases. Holder renewal is read-only until half the TTL has passed. When a holder lapses (crash, a long GPU batch, drain), another replica takes over with a new token.
    • Failure handling: any lease-store error fails open, so every replica runs as it does today.
    • Kill switch: BATCH_PIPELINE_LEADER_LEASE_ENABLED, on by default. false restores per-replica maintenance. Registered in config/feature-flags.yaml.
    • Worker (pump.py): role pump_recovery with a 30s TTL, covering recover, project_pending and the global result_ready drain. Each pump still drains the owners of its own completions inline, so committing its own work never waits on the leader.
    • Serving (serving.py): role serving_maintenance with a 60s TTL. Only periodic ticks are gated: the supervisor loop and the /metrics scrape. The gated steps are staging reap, artifact cleanup, the enrichment sweep, quarantine discovery (recovery.sweep), lease recovery and the result_ready drain. The projection sweep and gauge refresh still run on every instance. Explicit POST /reconcile and the post-recovery drain in /recover-quarantine always run.
    • No change to quarantine_recovery.py or the other files in fix(batch): dispatch bounded quarantine recovery batches and keep recovery polls pending #22321.
  • Non-5xx expected enrichment retries (backend/routers/batch_pipeline.py, enrichment_response):
    • FirstSummaryCallbackPending returns 409 {"status":"retry","reason":"callback_pending"}. SyncConversationPersistenceFenced returns 409 with "reason":"persistence_fenced". Subclasses are included.
    • Cloud Tasks retries any non-2xx response. 409 does not trigger the queue throttling that 429 and 503 cause (the 10-18 incident).
    • Classes are matched by defining module and name, so the router does not import the sync pipeline at startup. A test pins both definitions.
    • Unexpected exceptions still return 500 and log at ERROR.
    • New counter batch_enrichment_sync_reprocess_retries_total{retry_class}, with callback_pending, persistence_fenced or unexpected. The log line keeps outcome=retry and adds retry_class=…. Expected classes log at WARNING.
  • Known fair-use admission overshoot, documented only (backend/utils/batch_pipeline/admission.py). The check-then-act overshoot gets a code comment. Behaviour is unchanged.
  • Docs: backend/docs/batch-pipeline-serving.md, backend/diarizer/batch_pipeline_runtime.md, and the regenerated backend/docs/feature-flag-registry.md.

Rollout and risk

  • No admission or ordering change, and no new paid path.
  • The lease is a cost and contention control only. Correctness still rests on the existing Firestore transactions and tokens.
  • The new collection holds one doc per role, with no user data and no index (document-ID reads only).
  • Rollback: set BATCH_PIPELINE_LEADER_LEASE_ENABLED=false, or revert. Returning 409 instead of 500 does not change Cloud Tasks retry semantics. The legacy queue's retry and maxAttempts behaviour is unchanged.
  • Sentinels counting batch_enrichment_sync_reprocess outcome=retry keep matching. To separate the two kinds, filter on retry_class=unexpected.

Merge ordering

Land this PR first. #22362 and #22373 then rebase onto it. Deploy the 2-replica change (#22376) only on an image that contains this PR. Without it, every pod runs recovery, cleanup and quarantine discovery, and both pods' queue series can go stale together while both are inside a GPU batch.

When #22373 rebases, its extracted pump _maintain must hold the leader check, i.e. if self.leader is None or acquire() around project_pending, recover and the global ready drain. It must also skip its inline metrics.refresh when inline_metrics is false; otherwise every replica runs two full queue samples per 15s.

Review follow-up (Grok FIX-FIRST item 1): a live lease row naming this process's holder is now adopted with its stored token. Before this, a lost commit acknowledgement or an overlapping acquire could clear the in-memory token, and every replica would stand down for a full TTL. acquire is also serialized with a lock, because the serving supervisor and /metrics share one lease object.

Test evidence

These are local targeted runs only; the full suite is left to CI. They used nice -n 19 and the test.sh runner with its CPU timing guard, via BACKEND_UNIT_TEST_FILE_LIST.

tests/unit/test_batch_pipeline_leader.py                    9 passed
tests/unit/test_batch_pipeline_pump.py                      17 passed
tests/unit/test_batch_pipeline_serving.py                   38 passed
tests/unit/test_batch_pipeline_runtime.py                   17 passed
tests/unit/test_batch_pipeline_worker.py                    91 passed
tests/unit/test_batch_pipeline_quarantine.py                19 passed
tests/unit/test_batch_pipeline_metrics.py                    6 passed
tests/unit/test_batch_pipeline_admission.py                 17 passed
tests/unit/test_batch_pipeline_chart.py                      7 passed
tests/unit/test_batch_pipeline_recovery_runtime_contract.py 13 passed
tests/unit/test_sync_cloud_tasks.py                        135 passed

New tests:

  • Leader lease:
    • a lost commit acknowledgement or a stale in-memory token heals on the next tick (the process adopts its own live row)
    • four overlapping acquires on one object leave the row's token in memory, another replica follows, and the next tick still leads
    • one holder per role
    • read-only renewal before half the TTL
    • handover after the TTL with a new token, after which the old holder follows
    • fail-open on store errors
    • the kill switch
    • bounded role and TTL
  • Pump:
    • only the lease holder recovers and drains others' result_ready
    • a broken lease store keeps per-replica recovery
    • with inline_metrics=False, sampling moves to sample_metrics
  • Runtime: the sampler keeps running while pump.run sits in one long batch, survives a failed sample, and stops with supervision.
  • Serving:
    • two instances on one lease run maintenance once, while projection and gauges run on both
    • explicit reconcile always runs
    • fail-open
  • Router:
    • 409 for both expected classes and a subclass
    • 500 for a same-named class from another module
    • counter and log retry_class, with the level split
    • an AST check that the matched classes exist where the router expects them

Also run: scripts/typecheck.sh (0 errors), scan_async_blockers.py (0), scan_import_time_side_effects.py (0), check_feature_flag_registry.py (OK), and make preflight.

Product invariants affected

none

Failure class (fixes)

Failure-Class: none

🤖 Generated with Claude Code

- Sample worker queue-age metrics on their own supervised task so gauges
  stay fresh (<60s) while every replica is inside a long GPU batch.
- Add an advisory single-owner Firestore lease (TTL + token, fail-open,
  BATCH_PIPELINE_LEADER_LEASE_ENABLED kill switch) so one worker runs
  pump recovery/drain and one serving instance runs periodic
  cleanup/sweep/quarantine discovery/recovery per tick.
- Answer expected enrichment retries (FirstSummaryCallbackPending,
  SyncConversationPersistenceFenced) with 409 instead of 500; add a
  retry_class counter and log label. Unexpected errors stay 500.
- Document the fair-use admission check-then-act overshoot.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-19T06:26:24.427859Z b6a67aa New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a7f00070cb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +59 to +60
now = self.clock()
current, candidate = self.token, uuid.uuid4().hex # Minted outside the retryable body.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Serialize concurrent lease acquisition

When the serving supervisor and a /metrics scrape call acquire() concurrently on the same fresh or expired LeaderLease, both capture current=None; after one transaction writes its candidate, the other's retried transaction sees that token as foreign and returns None, then overwrites the shared self.token with None. The still-live row is subsequently treated as belonging to another holder until its 60-second TTL expires, suppressing periodic recovery and result draining on the elected instance. Protect the acquisition and token update with a lock or otherwise make this state transition atomic.

Useful? React with 👍 / 👎.

Git-on-my-level and others added 5 commits October 19, 2026 11:38
A lost commit acknowledgement or overlapping acquires on the shared serving
lease could clear the in-memory token, so the process treated its own live
row as foreign and every replica stood down for a full TTL. Ownership now
keys on the row holder (adopting the stored token), and acquire holds a
process-local lock.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…replica

# Conflicts:
#	backend/docs/feature-flag-registry.md
#	config/feature-flags.yaml
@Git-on-my-level
Git-on-my-level merged commit 733a74a into main Oct 19, 2026
56 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/opus-batch-multireplica branch October 19, 2026 06:38
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
#22371 classifies expected enrichment retries by (defining module, class
name). #22431 moved FirstSummaryCallbackPending to utils.enrichment.outbox,
so on integration a callback-pending delivery fell through to the
unexpected branch and answered 500. That is the fast-5xx shape that
throttled the queues on 10-18 and 10-19. Match the new defining modules,
and keep the legacy pipeline fence until pipeline.py is deleted.

Failure-Class: none

Verification: test_batch_pipeline_serving 38 passed (it failed with
500 != 409 before this change on the merged integration tree).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
…ry invariant (#22453)

* test(staging): F1 Cloud Tasks throttle model + task-target retry invariant (lane 4)

Contract (d), plan F F1, cross-plan L5. First merges after the stubs.

- testing/fakes/cloud_tasks_queue.py: virtual-clock Cloud Tasks queue
  (token bucket, concurrency, retry backoff/max attempts, named-task
  dedupe) with an AIMD system throttle on 429/503 or a high fast-5xx
  share; a config PATCH caps but never resets it. Scenarios
  enrichment_fast_500_throttle (10-18 18:14Z sync-jobs) and
  sync_backfill_0452 (10-19 04:52Z sync-backfill) drive the REAL
  routers.batch_pipeline.enrichment_response for an expected
  first-summary wait. At 733a74a^ (pre-#22371, 500) the 1h run strands
  10,002 direct jobs at 0.1/s (prod 10-18: 10,399 at 0.1/s) and 2,322
  backfill jobs (prod 04:52Z: 3,552); at 733a74a (409) both keep the
  configured rate and drain.
- scripts/cross_service_checks/task_targets.py:
  check_task_target_retry_semantics(ctx), registered by #22420. AST scan
  of each TaskEdge handler and the router helpers it calls: 429/503
  anywhere, 500 outside an except-Exception fallback, ExpectedRetry not
  answered by retry_response. Keys carry no line numbers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* chore(contract): accept the 12 existing task-target retry violators (lane 4, contract (d))

Lane 1 ruling: F1 carries its own known-gap entries. Keys are the
contract (d) violator table plus the audit-only finalization and
account-deletion targets; new keys still fail.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(staging): mirror run record no longer deep-copies the stats lock

dataclasses.asdict deep-copies a threading.Lock and raised after the copy
finished, so the first live run wrote objects and the manifest but no
workspace record. Idempotent rerun fills it in.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
… 9, C2 slices 2-3; absorbs #21968) (#22444)

* refactor(enrichment): move the sr- outbox into utils/enrichment (C2 slice 1)

Plan C2, swarm lane 9. Pure move, no behaviour change:

- utils/sync/reprocess.py        -> utils/enrichment/outbox.py
- utils/sync/enrichment_custody.py -> utils/enrichment/custody.py
- utils/sync/enrichment_scan.py  -> utils/enrichment/scan.py

The old paths become sys.modules aliases of the new modules, so every
importer, mock.patch target and monkeypatch keeps reaching the same module
object. A star import gives pyright the public names. Batch projection
imports the new path; the frozen prod-track files (serving.py,
routers/batch_pipeline.py, batch_pipeline/enrichment.py) keep the shim until
their PRs reach integration.

Collection, document ids, field names and the sr- task prefix are unchanged
(contract (b) invariant 7). The query-shape driver and background-task
baseline follow the moved function.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor(enrichment): drop the test-only custody and scan aliases

Only tests imported utils.sync.enrichment_custody and enrichment_scan, so the
dead-code ratchet counts the aliases as new dead files. The tests now import
utils.enrichment.scan directly; utils.sync.reprocess keeps its alias for the
production importers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(enrichment): import the probe modules at collection time

The fast-unit CPU guard charged utils.cloud_tasks' first import to the probe
test's call phase (0.53s > 0.30s) once this file was selected. Module-level
imports keep the assertions unchanged and the call phase cheap.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(enrichment): own the sr- callback and absorb lifecycle fences (C2 slice 3)

Plan C2, swarm lane 9. Batch enrichment no longer imports legacy
transcription (utils/sync/pipeline.py):

- utils/enrichment/callback.py: enrich_conversation, extracted verbatim from
  pipeline._reprocess_conversation_after_update with its webhook helper,
  persistence fence and lineage sentinel. pipeline.py is frozen behind
  #21932/#20662 and keeps its copy for the non-coalescing direct path, so
  test_enrichment_callback_parity.py (a static tripwire, labelled as such)
  keeps the two bodies identical until C11 deletes the legacy one. The new
  copy logs no conversation id.
- utils/enrichment/custody.py now owns discard_blocked. The batch adapter
  re-exports it for its existing importers.
- Absorbs #21968 (lead ruling 10-19): a SyncConversationPersistenceFenced
  from the callback settles the claim as superseded. The obligation is
  retired when no newer mark landed and re-armed when one did, and the
  handler ACKs 200 instead of answering 500 to a delivery that can never win.
  Other errors keep their taxonomy. #21968's conversation_id log line is not
  carried; the event is logged without identifiers.

Failure-Class: none

Verification (local unit, serial, nice 19):
- test_enrichment_callback_fence 4 passed (fenced+unchanged -> retired;
  fenced+newer mark -> re-armed; ValueError propagates; the default callback
  is the package)
- test_enrichment_callback_parity 3 passed
- test_batch_pipeline_serving 31 passed
- test_listen_finalization_cloud_tasks 278 passed
- test_sync_reprocess_coalesce 88 passed
- test_sync_enrichment_custody 10 passed
- test_background_task_ratchet, test_llm_gateway_coverage_guardrails and
  test_generated_compute_inventory_guardrails passed
- pyright 0 errors
- test_sync_reprocess_emulator now patches the package callback (CI emulator lane)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(enrichment): Firestore Outbox for OutboxKind.ENRICHMENT (C2 slice 2)

Plan C2 / contract (b), swarm lane 9. database/outbox_firestore.py
implements the Outbox protocol over sync_reprocess_outbox, row-compatible
with mark/run: same collection, document ids, field names and sr- names.
Additive fields: policy_id, claim_attempts, a transient summary_seen_by.

- lease_token is the per-claim owner uuid and wake_token is task_token.
  heartbeat/ack/defer/release are fenced on both (invariant 1).
- claim_key: privacy discard first (invariant 6), then demand admission,
  a stale or busy check, and a not-due re-arm that wakes itself and returns
  DEFERRED. Wake ownership follows the lead's 10-19 ruling: this
  implementation creates the tasks through the existing _enqueue.
- ack keeps today's finish rules: retire when unchanged, a dormant receipt
  when record_summary marked the lease, re-arm when the version moved.
- enqueue shares mark's CAS operation (mark_update), with explicit
  available_at and min/max coalescing (invariant 3). With tx= it writes in
  the caller's transaction and returns the wake token; the caller calls
  wake() after commit (invariants 4-5). wake() is idempotent per token.
- sweep delegates to the existing sweep with a privacy discard hook. Pull
  claim() goes through the new utils.enrichment.outbox.due_rows
  (single-field due_at index), registered in the query-shape drivers.

Batch projection's mark_enrichment now calls enqueue(tx=...) and then
wake(), using its own client for both. A backfill binding is still resolved
only for a new row (new_dispatch callable), so a coalesced append never
raises on a missing backfill env, as before.

database.outbox.outbox_for is lane 1's stub; firestore_outbox(kind) is the
implementation it should return (wiring requested from the captain).

Verification (local unit, serial, nice 19):
- test_outbox_firestore 13 passed
- test_batch_pipeline_projection 40 passed
- test_sync_reprocess_coalesce 88 passed
- test_firestore_query_shapes 481 passed
- the outside-query, runtime-witness and index-oracle suites passed
- test_listen_finalization_cloud_tasks 278 passed
- pyright 0 errors
The emulator conformance suite is lane 12's and has not landed yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(enrichment): outbox_for selects the Firestore enrichment outbox

Lane 1 signed off on this one-function edit of its stub (10-19): in this
window the selector always returns the Firestore implementation; the
BATCH_JOBSTORE_MODE switch is lane 12's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(enrichment): match moved retry classes so callback-pending stays 409

#22371 classifies expected enrichment retries by (defining module, class
name). #22431 moved FirstSummaryCallbackPending to utils.enrichment.outbox,
so on integration a callback-pending delivery fell through to the
unexpected branch and answered 500. That is the fast-5xx shape that
throttled the queues on 10-18 and 10-19. Match the new defining modules,
and keep the legacy pipeline fence until pipeline.py is deleted.

Failure-Class: none

Verification: test_batch_pipeline_serving 38 passed (it failed with
500 != 409 before this change on the merged integration tree).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(enrichment): FirestoreOutbox factory with injected client, privacy check and wake

For lane 12's outbox conformance suite (build_outbox_backend('emulator')):
FirestoreOutbox(kind, client=, privacy_blocked=, create_wake=) binds every
CAS, the sweep and every wake to the injected seams. The default instance
keeps the production paths (discard_blocked, _enqueue, the shared client).
outbox._cas is the client-explicit CAS behind _mutate, and sweep takes
client=/wake= for the same purpose.

A not-due claim_key deferral leaves claim_attempts untouched (attempt stays
1 on the first real claim), as reprocess does today; there is a test for it.

Verification: test_outbox_firestore 16 passed, test_batch_pipeline_projection
40, test_sync_reprocess_coalesce 88, test_firestore_query_shapes 481,
test_sync_enrichment_custody 10; pyright 0 errors.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
… retries (lane 9, C3) (#22462)

* refactor(enrichment): move the sr- outbox into utils/enrichment (C2 slice 1)

Plan C2, swarm lane 9. Pure move, no behaviour change:

- utils/sync/reprocess.py        -> utils/enrichment/outbox.py
- utils/sync/enrichment_custody.py -> utils/enrichment/custody.py
- utils/sync/enrichment_scan.py  -> utils/enrichment/scan.py

The old paths become sys.modules aliases of the new modules, so every
importer, mock.patch target and monkeypatch keeps reaching the same module
object. A star import gives pyright the public names. Batch projection
imports the new path; the frozen prod-track files (serving.py,
routers/batch_pipeline.py, batch_pipeline/enrichment.py) keep the shim until
their PRs reach integration.

Collection, document ids, field names and the sr- task prefix are unchanged
(contract (b) invariant 7). The query-shape driver and background-task
baseline follow the moved function.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor(enrichment): drop the test-only custody and scan aliases

Only tests imported utils.sync.enrichment_custody and enrichment_scan, so the
dead-code ratchet counts the aliases as new dead files. The tests now import
utils.enrichment.scan directly; utils.sync.reprocess keeps its alias for the
production importers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(enrichment): import the probe modules at collection time

The fast-unit CPU guard charged utils.cloud_tasks' first import to the probe
test's call phase (0.53s > 0.30s) once this file was selected. Module-level
imports keep the assertions unchanged and the call phase cheap.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(enrichment): own the sr- callback and absorb lifecycle fences (C2 slice 3)

Plan C2, swarm lane 9. Batch enrichment no longer imports legacy
transcription (utils/sync/pipeline.py):

- utils/enrichment/callback.py: enrich_conversation, extracted verbatim from
  pipeline._reprocess_conversation_after_update with its webhook helper,
  persistence fence and lineage sentinel. pipeline.py is frozen behind
  #21932/#20662 and keeps its copy for the non-coalescing direct path, so
  test_enrichment_callback_parity.py (a static tripwire, labelled as such)
  keeps the two bodies identical until C11 deletes the legacy one. The new
  copy logs no conversation id.
- utils/enrichment/custody.py now owns discard_blocked. The batch adapter
  re-exports it for its existing importers.
- Absorbs #21968 (lead ruling 10-19): a SyncConversationPersistenceFenced
  from the callback settles the claim as superseded. The obligation is
  retired when no newer mark landed and re-armed when one did, and the
  handler ACKs 200 instead of answering 500 to a delivery that can never win.
  Other errors keep their taxonomy. #21968's conversation_id log line is not
  carried; the event is logged without identifiers.

Failure-Class: none

Verification (local unit, serial, nice 19):
- test_enrichment_callback_fence 4 passed (fenced+unchanged -> retired;
  fenced+newer mark -> re-armed; ValueError propagates; the default callback
  is the package)
- test_enrichment_callback_parity 3 passed
- test_batch_pipeline_serving 31 passed
- test_listen_finalization_cloud_tasks 278 passed
- test_sync_reprocess_coalesce 88 passed
- test_sync_enrichment_custody 10 passed
- test_background_task_ratchet, test_llm_gateway_coverage_guardrails and
  test_generated_compute_inventory_guardrails passed
- pyright 0 errors
- test_sync_reprocess_emulator now patches the package callback (CI emulator lane)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(enrichment): Firestore Outbox for OutboxKind.ENRICHMENT (C2 slice 2)

Plan C2 / contract (b), swarm lane 9. database/outbox_firestore.py
implements the Outbox protocol over sync_reprocess_outbox, row-compatible
with mark/run: same collection, document ids, field names and sr- names.
Additive fields: policy_id, claim_attempts, a transient summary_seen_by.

- lease_token is the per-claim owner uuid and wake_token is task_token.
  heartbeat/ack/defer/release are fenced on both (invariant 1).
- claim_key: privacy discard first (invariant 6), then demand admission,
  a stale or busy check, and a not-due re-arm that wakes itself and returns
  DEFERRED. Wake ownership follows the lead's 10-19 ruling: this
  implementation creates the tasks through the existing _enqueue.
- ack keeps today's finish rules: retire when unchanged, a dormant receipt
  when record_summary marked the lease, re-arm when the version moved.
- enqueue shares mark's CAS operation (mark_update), with explicit
  available_at and min/max coalescing (invariant 3). With tx= it writes in
  the caller's transaction and returns the wake token; the caller calls
  wake() after commit (invariants 4-5). wake() is idempotent per token.
- sweep delegates to the existing sweep with a privacy discard hook. Pull
  claim() goes through the new utils.enrichment.outbox.due_rows
  (single-field due_at index), registered in the query-shape drivers.

Batch projection's mark_enrichment now calls enqueue(tx=...) and then
wake(), using its own client for both. A backfill binding is still resolved
only for a new row (new_dispatch callable), so a coalesced append never
raises on a missing backfill env, as before.

database.outbox.outbox_for is lane 1's stub; firestore_outbox(kind) is the
implementation it should return (wiring requested from the captain).

Verification (local unit, serial, nice 19):
- test_outbox_firestore 13 passed
- test_batch_pipeline_projection 40 passed
- test_sync_reprocess_coalesce 88 passed
- test_firestore_query_shapes 481 passed
- the outside-query, runtime-witness and index-oracle suites passed
- test_listen_finalization_cloud_tasks 278 passed
- pyright 0 errors
The emulator conformance suite is lane 12's and has not landed yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(enrichment): outbox_for selects the Firestore enrichment outbox

Lane 1 signed off on this one-function edit of its stub (10-19): in this
window the selector always returns the Firestore implementation; the
BATCH_JOBSTORE_MODE switch is lane 12's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(enrichment): /v2/enrichment/run on the outbox consumer, 409-only retries (C3)

Plan C3 / contracts (a) and (d), swarm lane 9.

- utils/enrichment/consumer.py: EnrichmentConsumer, a QueueConsumer for
  OutboxKind.ENRICHMENT (workers role; 120s lease, 30s heartbeat on every
  lease). It mirrors reprocess.run outcome for outcome, with settlement
  through the Outbox calls:
  - processed -> DONE (ack; a dormant receipt via record_summary);
  - superseded or lifecycle fence -> DISCARDED;
  - repair race -> outbox.repair;
  - live target or missing conversation -> DEFERRED +120s;
  - redirect -> custody transfer;
  - empty budget spent -> retired;
  - callback pending or empty output -> RETRY callback_pending (409; release
    keeps the wake for the queue retry).
- routers/enrichment.py: POST /v2/enrichment/run with OIDC for the
  enrichment queue (TaskEdge enrichment). It accepts the legacy
  {"kind":"sync_reprocess",...} payload, so rows bound to either handler
  drain. 400 for a malformed task; 500 only for unexpected exceptions.
- config/enrichment.py: ENRICHMENT_ROUTE (sync_handler | enrichment_queue,
  default sync_handler) is the deployment default for the policy field
  enrichment_route until E1 records it per unit. ENRICHMENT_TASKS_* is the
  queue binding. An incomplete binding falls back to the sync handler and
  is counted through record_fallback.
- valid_dispatch_binding and _enqueue accept both handler paths (contract
  (b) invariant 7).

The router mount in main.py is lane 1's. Queue spec for lane 7: enrichment,
max-concurrent 50, 25/s, backoff 10-300s, unlimited attempts.

Verification (local unit, serial, nice 19):
- test_enrichment_route 12 passed (409 callback_pending keeps the wake;
  fence -> superseded; live defer -> new wake; 400s; stale wake -> 200;
  unexpected -> 5xx with the lease kept; route binding with fallback)
- test_outbox_firestore 14 passed
- test_sync_reprocess_coalesce 88 passed
- test_cross_service_deploy_contract and test_background_task_ratchet passed
- pyright 0 errors

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(enrichment): match moved retry classes so callback-pending stays 409

#22371 classifies expected enrichment retries by (defining module, class
name). #22431 moved FirstSummaryCallbackPending to utils.enrichment.outbox,
so on integration a callback-pending delivery fell through to the
unexpected branch and answered 500. That is the fast-5xx shape that
throttled the queues on 10-18 and 10-19. Match the new defining modules,
and keep the legacy pipeline fence until pipeline.py is deleted.

Failure-Class: none

Verification: test_batch_pipeline_serving 38 passed (it failed with
500 != 409 before this change on the merged integration tree).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(enrichment): FirestoreOutbox factory with injected client, privacy check and wake

For lane 12's outbox conformance suite (build_outbox_backend('emulator')):
FirestoreOutbox(kind, client=, privacy_blocked=, create_wake=) binds every
CAS, the sweep and every wake to the injected seams. The default instance
keeps the production paths (discard_blocked, _enqueue, the shared client).
outbox._cas is the client-explicit CAS behind _mutate, and sweep takes
client=/wake= for the same purpose.

A not-due claim_key deferral leaves claim_attempts untouched (attempt stays
1 on the first real claim), as reprocess does today; there is a test for it.

Verification: test_outbox_firestore 16 passed, test_batch_pipeline_projection
40, test_sync_reprocess_coalesce 88, test_firestore_query_shapes 481,
test_sync_enrichment_custody 10; pyright 0 errors.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(enrichment): a not-due wake re-arms and answers 200 not_due

Exercises #22437's claim_key DEFERRED mapping end to end through
/v2/enrichment/run: the outbox re-arms with a new wake and the delivery is
consumed, not retried.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(enrichment): load the callback at collection time in the route tests

The fast-unit CPU guard charged process_conversation's first import to the
first route test (6.8s > 0.30s).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
…ad selection (#22475)

* test(staging): F1 Cloud Tasks throttle model + task-target retry invariant (lane 4)

Contract (d), plan F F1, cross-plan L5. First merges after the stubs.

- testing/fakes/cloud_tasks_queue.py: virtual-clock Cloud Tasks queue
  (token bucket, concurrency, retry backoff/max attempts, named-task
  dedupe) with an AIMD system throttle on 429/503 or a high fast-5xx
  share; a config PATCH caps but never resets it. Scenarios
  enrichment_fast_500_throttle (10-18 18:14Z sync-jobs) and
  sync_backfill_0452 (10-19 04:52Z sync-backfill) drive the REAL
  routers.batch_pipeline.enrichment_response for an expected
  first-summary wait. At 733a74a^ (pre-#22371, 500) the 1h run strands
  10,002 direct jobs at 0.1/s (prod 10-18: 10,399 at 0.1/s) and 2,322
  backfill jobs (prod 04:52Z: 3,552); at 733a74a (409) both keep the
  configured rate and drain.
- scripts/cross_service_checks/task_targets.py:
  check_task_target_retry_semantics(ctx), registered by #22420. AST scan
  of each TaskEdge handler and the router helpers it calls: 429/503
  anywhere, 500 outside an except-Exception fallback, ExpectedRetry not
  answered by retry_response. Keys carry no line numbers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* chore(contract): accept the 12 existing task-target retry violators (lane 4, contract (d))

Lane 1 ruling: F1 carries its own known-gap entries. Keys are the
contract (d) violator table plus the audit-only finalization and
account-deletion targets; new keys still fail.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(staging): mirror run record no longer deep-copies the stats lock

dataclasses.asdict deep-copies a threading.Lock and raised after the copy
finished, so the first live run wrote objects and the manifest but no
workspace record. Idempotent rerun fills it in.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(staging): archive mirror reads only chunks/<owner>/ and can spread across history

David's 10-19 grant is conditioned to chunks/<uid>/ in omi-private-cloud-sync;
the mirror no longer lists raw-sync/ or raw-mobile-batch/ there. --family,
--spread and --max-group-mb pick parity conversations evenly across his
capture history (rows 1b/2) instead of only the newest.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
…legates to the consumer (lane 9) (#22476)

* refactor(enrichment): move the sr- outbox into utils/enrichment (C2 slice 1)

Plan C2, swarm lane 9. Pure move, no behaviour change:

- utils/sync/reprocess.py        -> utils/enrichment/outbox.py
- utils/sync/enrichment_custody.py -> utils/enrichment/custody.py
- utils/sync/enrichment_scan.py  -> utils/enrichment/scan.py

The old paths become sys.modules aliases of the new modules, so every
importer, mock.patch target and monkeypatch keeps reaching the same module
object. A star import gives pyright the public names. Batch projection
imports the new path; the frozen prod-track files (serving.py,
routers/batch_pipeline.py, batch_pipeline/enrichment.py) keep the shim until
their PRs reach integration.

Collection, document ids, field names and the sr- task prefix are unchanged
(contract (b) invariant 7). The query-shape driver and background-task
baseline follow the moved function.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor(enrichment): drop the test-only custody and scan aliases

Only tests imported utils.sync.enrichment_custody and enrichment_scan, so the
dead-code ratchet counts the aliases as new dead files. The tests now import
utils.enrichment.scan directly; utils.sync.reprocess keeps its alias for the
production importers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(enrichment): import the probe modules at collection time

The fast-unit CPU guard charged utils.cloud_tasks' first import to the probe
test's call phase (0.53s > 0.30s) once this file was selected. Module-level
imports keep the assertions unchanged and the call phase cheap.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(enrichment): own the sr- callback and absorb lifecycle fences (C2 slice 3)

Plan C2, swarm lane 9. Batch enrichment no longer imports legacy
transcription (utils/sync/pipeline.py):

- utils/enrichment/callback.py: enrich_conversation, extracted verbatim from
  pipeline._reprocess_conversation_after_update with its webhook helper,
  persistence fence and lineage sentinel. pipeline.py is frozen behind
  #21932/#20662 and keeps its copy for the non-coalescing direct path, so
  test_enrichment_callback_parity.py (a static tripwire, labelled as such)
  keeps the two bodies identical until C11 deletes the legacy one. The new
  copy logs no conversation id.
- utils/enrichment/custody.py now owns discard_blocked. The batch adapter
  re-exports it for its existing importers.
- Absorbs #21968 (lead ruling 10-19): a SyncConversationPersistenceFenced
  from the callback settles the claim as superseded. The obligation is
  retired when no newer mark landed and re-armed when one did, and the
  handler ACKs 200 instead of answering 500 to a delivery that can never win.
  Other errors keep their taxonomy. #21968's conversation_id log line is not
  carried; the event is logged without identifiers.

Failure-Class: none

Verification (local unit, serial, nice 19):
- test_enrichment_callback_fence 4 passed (fenced+unchanged -> retired;
  fenced+newer mark -> re-armed; ValueError propagates; the default callback
  is the package)
- test_enrichment_callback_parity 3 passed
- test_batch_pipeline_serving 31 passed
- test_listen_finalization_cloud_tasks 278 passed
- test_sync_reprocess_coalesce 88 passed
- test_sync_enrichment_custody 10 passed
- test_background_task_ratchet, test_llm_gateway_coverage_guardrails and
  test_generated_compute_inventory_guardrails passed
- pyright 0 errors
- test_sync_reprocess_emulator now patches the package callback (CI emulator lane)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(enrichment): Firestore Outbox for OutboxKind.ENRICHMENT (C2 slice 2)

Plan C2 / contract (b), swarm lane 9. database/outbox_firestore.py
implements the Outbox protocol over sync_reprocess_outbox, row-compatible
with mark/run: same collection, document ids, field names and sr- names.
Additive fields: policy_id, claim_attempts, a transient summary_seen_by.

- lease_token is the per-claim owner uuid and wake_token is task_token.
  heartbeat/ack/defer/release are fenced on both (invariant 1).
- claim_key: privacy discard first (invariant 6), then demand admission,
  a stale or busy check, and a not-due re-arm that wakes itself and returns
  DEFERRED. Wake ownership follows the lead's 10-19 ruling: this
  implementation creates the tasks through the existing _enqueue.
- ack keeps today's finish rules: retire when unchanged, a dormant receipt
  when record_summary marked the lease, re-arm when the version moved.
- enqueue shares mark's CAS operation (mark_update), with explicit
  available_at and min/max coalescing (invariant 3). With tx= it writes in
  the caller's transaction and returns the wake token; the caller calls
  wake() after commit (invariants 4-5). wake() is idempotent per token.
- sweep delegates to the existing sweep with a privacy discard hook. Pull
  claim() goes through the new utils.enrichment.outbox.due_rows
  (single-field due_at index), registered in the query-shape drivers.

Batch projection's mark_enrichment now calls enqueue(tx=...) and then
wake(), using its own client for both. A backfill binding is still resolved
only for a new row (new_dispatch callable), so a coalesced append never
raises on a missing backfill env, as before.

database.outbox.outbox_for is lane 1's stub; firestore_outbox(kind) is the
implementation it should return (wiring requested from the captain).

Verification (local unit, serial, nice 19):
- test_outbox_firestore 13 passed
- test_batch_pipeline_projection 40 passed
- test_sync_reprocess_coalesce 88 passed
- test_firestore_query_shapes 481 passed
- the outside-query, runtime-witness and index-oracle suites passed
- test_listen_finalization_cloud_tasks 278 passed
- pyright 0 errors
The emulator conformance suite is lane 12's and has not landed yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(enrichment): outbox_for selects the Firestore enrichment outbox

Lane 1 signed off on this one-function edit of its stub (10-19): in this
window the selector always returns the Firestore implementation; the
BATCH_JOBSTORE_MODE switch is lane 12's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(enrichment): /v2/enrichment/run on the outbox consumer, 409-only retries (C3)

Plan C3 / contracts (a) and (d), swarm lane 9.

- utils/enrichment/consumer.py: EnrichmentConsumer, a QueueConsumer for
  OutboxKind.ENRICHMENT (workers role; 120s lease, 30s heartbeat on every
  lease). It mirrors reprocess.run outcome for outcome, with settlement
  through the Outbox calls:
  - processed -> DONE (ack; a dormant receipt via record_summary);
  - superseded or lifecycle fence -> DISCARDED;
  - repair race -> outbox.repair;
  - live target or missing conversation -> DEFERRED +120s;
  - redirect -> custody transfer;
  - empty budget spent -> retired;
  - callback pending or empty output -> RETRY callback_pending (409; release
    keeps the wake for the queue retry).
- routers/enrichment.py: POST /v2/enrichment/run with OIDC for the
  enrichment queue (TaskEdge enrichment). It accepts the legacy
  {"kind":"sync_reprocess",...} payload, so rows bound to either handler
  drain. 400 for a malformed task; 500 only for unexpected exceptions.
- config/enrichment.py: ENRICHMENT_ROUTE (sync_handler | enrichment_queue,
  default sync_handler) is the deployment default for the policy field
  enrichment_route until E1 records it per unit. ENRICHMENT_TASKS_* is the
  queue binding. An incomplete binding falls back to the sync handler and
  is counted through record_fallback.
- valid_dispatch_binding and _enqueue accept both handler paths (contract
  (b) invariant 7).

The router mount in main.py is lane 1's. Queue spec for lane 7: enrichment,
max-concurrent 50, 25/s, backoff 10-300s, unlimited attempts.

Verification (local unit, serial, nice 19):
- test_enrichment_route 12 passed (409 callback_pending keeps the wake;
  fence -> superseded; live defer -> new wake; 400s; stale wake -> 200;
  unexpected -> 5xx with the lease kept; route binding with fallback)
- test_outbox_firestore 14 passed
- test_sync_reprocess_coalesce 88 passed
- test_cross_service_deploy_contract and test_background_task_ratchet passed
- pyright 0 errors

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(enrichment): match moved retry classes so callback-pending stays 409

#22371 classifies expected enrichment retries by (defining module, class
name). #22431 moved FirstSummaryCallbackPending to utils.enrichment.outbox,
so on integration a callback-pending delivery fell through to the
unexpected branch and answered 500. That is the fast-5xx shape that
throttled the queues on 10-18 and 10-19. Match the new defining modules,
and keep the legacy pipeline fence until pipeline.py is deleted.

Failure-Class: none

Verification: test_batch_pipeline_serving 38 passed (it failed with
500 != 409 before this change on the merged integration tree).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(enrichment): FirestoreOutbox factory with injected client, privacy check and wake

For lane 12's outbox conformance suite (build_outbox_backend('emulator')):
FirestoreOutbox(kind, client=, privacy_blocked=, create_wake=) binds every
CAS, the sweep and every wake to the injected seams. The default instance
keeps the production paths (discard_blocked, _enqueue, the shared client).
outbox._cas is the client-explicit CAS behind _mutate, and sweep takes
client=/wake= for the same purpose.

A not-due claim_key deferral leaves claim_attempts untouched (attempt stays
1 on the first real claim), as reprocess does today; there is a test for it.

Verification: test_outbox_firestore 16 passed, test_batch_pipeline_projection
40, test_sync_reprocess_coalesce 88, test_firestore_query_shapes 481,
test_sync_enrichment_custody 10; pyright 0 errors.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(enrichment): a not-due wake re-arms and answers 200 not_due

Exercises #22437's claim_key DEFERRED mapping end to end through
/v2/enrichment/run: the outbox re-arms with a new wake and the delivery is
consumed, not retried.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(enrichment): load the callback at collection time in the route tests

The fast-unit CPU guard charged process_conversation's first import to the
first route test (6.8s > 0.30s).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(batch): recover-quarantine kill switch answers 409; legacy sr- delegates to the consumer

Contract (d), swarm lane 9:
- /v2/batch-pipeline/recover-quarantine returned 503 for "recovery
  disabled" (host or owner). Cloud Tasks system-throttles a queue that
  sees fast 5xx/503 (10-18 18:14Z, 10-19 04:52Z stalls). A switched-off
  target now answers 409 {"status":"retry","reason":"kill_switch_off"}.
  Behaviour is otherwise unchanged: the intent stays prepared, nothing is
  spent, and the queue retries.
- enrichment_response (the legacy /v2/sync-jobs/run sync_reprocess
  delivery) runs through the C3 EnrichmentConsumer when
  ENRICHMENT_ROUTE=enrichment_queue, so one lever moves new rows onto the
  enrichment queue and drains old bindings through the same state
  machine. Default sync_handler keeps today's reprocess.run path.

Failure-Class: none

Verification (local unit, serial, nice 19):
- test_batch_pipeline_quarantine_recovery 67 passed (the disabled-host,
  -cohort and -missing cases assert 409 kill_switch_off)
- test_enrichment_route 14 passed (incl. legacy-handler delegation)
- test_batch_pipeline_serving 39 passed
- test_revision_drain_harness 7 passed
- test_cross_service_deploy_contract 18 passed

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
…weep (lane 9, C4) (#22517)

* refactor(enrichment): move the sr- outbox into utils/enrichment (C2 slice 1)

Plan C2, swarm lane 9. Pure move, no behaviour change:

- utils/sync/reprocess.py        -> utils/enrichment/outbox.py
- utils/sync/enrichment_custody.py -> utils/enrichment/custody.py
- utils/sync/enrichment_scan.py  -> utils/enrichment/scan.py

The old paths become sys.modules aliases of the new modules, so every
importer, mock.patch target and monkeypatch keeps reaching the same module
object. A star import gives pyright the public names. Batch projection
imports the new path; the frozen prod-track files (serving.py,
routers/batch_pipeline.py, batch_pipeline/enrichment.py) keep the shim until
their PRs reach integration.

Collection, document ids, field names and the sr- task prefix are unchanged
(contract (b) invariant 7). The query-shape driver and background-task
baseline follow the moved function.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor(enrichment): drop the test-only custody and scan aliases

Only tests imported utils.sync.enrichment_custody and enrichment_scan, so the
dead-code ratchet counts the aliases as new dead files. The tests now import
utils.enrichment.scan directly; utils.sync.reprocess keeps its alias for the
production importers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(enrichment): import the probe modules at collection time

The fast-unit CPU guard charged utils.cloud_tasks' first import to the probe
test's call phase (0.53s > 0.30s) once this file was selected. Module-level
imports keep the assertions unchanged and the call phase cheap.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(enrichment): own the sr- callback and absorb lifecycle fences (C2 slice 3)

Plan C2, swarm lane 9. Batch enrichment no longer imports legacy
transcription (utils/sync/pipeline.py):

- utils/enrichment/callback.py: enrich_conversation, extracted verbatim from
  pipeline._reprocess_conversation_after_update with its webhook helper,
  persistence fence and lineage sentinel. pipeline.py is frozen behind
  #21932/#20662 and keeps its copy for the non-coalescing direct path, so
  test_enrichment_callback_parity.py (a static tripwire, labelled as such)
  keeps the two bodies identical until C11 deletes the legacy one. The new
  copy logs no conversation id.
- utils/enrichment/custody.py now owns discard_blocked. The batch adapter
  re-exports it for its existing importers.
- Absorbs #21968 (lead ruling 10-19): a SyncConversationPersistenceFenced
  from the callback settles the claim as superseded. The obligation is
  retired when no newer mark landed and re-armed when one did, and the
  handler ACKs 200 instead of answering 500 to a delivery that can never win.
  Other errors keep their taxonomy. #21968's conversation_id log line is not
  carried; the event is logged without identifiers.

Failure-Class: none

Verification (local unit, serial, nice 19):
- test_enrichment_callback_fence 4 passed (fenced+unchanged -> retired;
  fenced+newer mark -> re-armed; ValueError propagates; the default callback
  is the package)
- test_enrichment_callback_parity 3 passed
- test_batch_pipeline_serving 31 passed
- test_listen_finalization_cloud_tasks 278 passed
- test_sync_reprocess_coalesce 88 passed
- test_sync_enrichment_custody 10 passed
- test_background_task_ratchet, test_llm_gateway_coverage_guardrails and
  test_generated_compute_inventory_guardrails passed
- pyright 0 errors
- test_sync_reprocess_emulator now patches the package callback (CI emulator lane)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(enrichment): Firestore Outbox for OutboxKind.ENRICHMENT (C2 slice 2)

Plan C2 / contract (b), swarm lane 9. database/outbox_firestore.py
implements the Outbox protocol over sync_reprocess_outbox, row-compatible
with mark/run: same collection, document ids, field names and sr- names.
Additive fields: policy_id, claim_attempts, a transient summary_seen_by.

- lease_token is the per-claim owner uuid and wake_token is task_token.
  heartbeat/ack/defer/release are fenced on both (invariant 1).
- claim_key: privacy discard first (invariant 6), then demand admission,
  a stale or busy check, and a not-due re-arm that wakes itself and returns
  DEFERRED. Wake ownership follows the lead's 10-19 ruling: this
  implementation creates the tasks through the existing _enqueue.
- ack keeps today's finish rules: retire when unchanged, a dormant receipt
  when record_summary marked the lease, re-arm when the version moved.
- enqueue shares mark's CAS operation (mark_update), with explicit
  available_at and min/max coalescing (invariant 3). With tx= it writes in
  the caller's transaction and returns the wake token; the caller calls
  wake() after commit (invariants 4-5). wake() is idempotent per token.
- sweep delegates to the existing sweep with a privacy discard hook. Pull
  claim() goes through the new utils.enrichment.outbox.due_rows
  (single-field due_at index), registered in the query-shape drivers.

Batch projection's mark_enrichment now calls enqueue(tx=...) and then
wake(), using its own client for both. A backfill binding is still resolved
only for a new row (new_dispatch callable), so a coalesced append never
raises on a missing backfill env, as before.

database.outbox.outbox_for is lane 1's stub; firestore_outbox(kind) is the
implementation it should return (wiring requested from the captain).

Verification (local unit, serial, nice 19):
- test_outbox_firestore 13 passed
- test_batch_pipeline_projection 40 passed
- test_sync_reprocess_coalesce 88 passed
- test_firestore_query_shapes 481 passed
- the outside-query, runtime-witness and index-oracle suites passed
- test_listen_finalization_cloud_tasks 278 passed
- pyright 0 errors
The emulator conformance suite is lane 12's and has not landed yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(enrichment): outbox_for selects the Firestore enrichment outbox

Lane 1 signed off on this one-function edit of its stub (10-19): in this
window the selector always returns the Firestore implementation; the
BATCH_JOBSTORE_MODE switch is lane 12's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(enrichment): /v2/enrichment/run on the outbox consumer, 409-only retries (C3)

Plan C3 / contracts (a) and (d), swarm lane 9.

- utils/enrichment/consumer.py: EnrichmentConsumer, a QueueConsumer for
  OutboxKind.ENRICHMENT (workers role; 120s lease, 30s heartbeat on every
  lease). It mirrors reprocess.run outcome for outcome, with settlement
  through the Outbox calls:
  - processed -> DONE (ack; a dormant receipt via record_summary);
  - superseded or lifecycle fence -> DISCARDED;
  - repair race -> outbox.repair;
  - live target or missing conversation -> DEFERRED +120s;
  - redirect -> custody transfer;
  - empty budget spent -> retired;
  - callback pending or empty output -> RETRY callback_pending (409; release
    keeps the wake for the queue retry).
- routers/enrichment.py: POST /v2/enrichment/run with OIDC for the
  enrichment queue (TaskEdge enrichment). It accepts the legacy
  {"kind":"sync_reprocess",...} payload, so rows bound to either handler
  drain. 400 for a malformed task; 500 only for unexpected exceptions.
- config/enrichment.py: ENRICHMENT_ROUTE (sync_handler | enrichment_queue,
  default sync_handler) is the deployment default for the policy field
  enrichment_route until E1 records it per unit. ENRICHMENT_TASKS_* is the
  queue binding. An incomplete binding falls back to the sync handler and
  is counted through record_fallback.
- valid_dispatch_binding and _enqueue accept both handler paths (contract
  (b) invariant 7).

The router mount in main.py is lane 1's. Queue spec for lane 7: enrichment,
max-concurrent 50, 25/s, backoff 10-300s, unlimited attempts.

Verification (local unit, serial, nice 19):
- test_enrichment_route 12 passed (409 callback_pending keeps the wake;
  fence -> superseded; live defer -> new wake; 400s; stale wake -> 200;
  unexpected -> 5xx with the lease kept; route binding with fallback)
- test_outbox_firestore 14 passed
- test_sync_reprocess_coalesce 88 passed
- test_cross_service_deploy_contract and test_background_task_ratchet passed
- pyright 0 errors

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(enrichment): match moved retry classes so callback-pending stays 409

#22371 classifies expected enrichment retries by (defining module, class
name). #22431 moved FirstSummaryCallbackPending to utils.enrichment.outbox,
so on integration a callback-pending delivery fell through to the
unexpected branch and answered 500. That is the fast-5xx shape that
throttled the queues on 10-18 and 10-19. Match the new defining modules,
and keep the legacy pipeline fence until pipeline.py is deleted.

Failure-Class: none

Verification: test_batch_pipeline_serving 38 passed (it failed with
500 != 409 before this change on the merged integration tree).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(enrichment): FirestoreOutbox factory with injected client, privacy check and wake

For lane 12's outbox conformance suite (build_outbox_backend('emulator')):
FirestoreOutbox(kind, client=, privacy_blocked=, create_wake=) binds every
CAS, the sweep and every wake to the injected seams. The default instance
keeps the production paths (discard_blocked, _enqueue, the shared client).
outbox._cas is the client-explicit CAS behind _mutate, and sweep takes
client=/wake= for the same purpose.

A not-due claim_key deferral leaves claim_attempts untouched (attempt stays
1 on the first real claim), as reprocess does today; there is a test for it.

Verification: test_outbox_firestore 16 passed, test_batch_pipeline_projection
40, test_sync_reprocess_coalesce 88, test_firestore_query_shapes 481,
test_sync_enrichment_custody 10; pyright 0 errors.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(enrichment): a not-due wake re-arms and answers 200 not_due

Exercises #22437's claim_key DEFERRED mapping end to end through
/v2/enrichment/run: the outbox re-arms with a new wake and the delivery is
consumed, not retried.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(enrichment): load the callback at collection time in the route tests

The fast-unit CPU guard charged process_conversation's first import to the
first route test (6.8s > 0.30s).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(batch): recover-quarantine kill switch answers 409; legacy sr- delegates to the consumer

Contract (d), swarm lane 9:
- /v2/batch-pipeline/recover-quarantine returned 503 for "recovery
  disabled" (host or owner). Cloud Tasks system-throttles a queue that
  sees fast 5xx/503 (10-18 18:14Z, 10-19 04:52Z stalls). A switched-off
  target now answers 409 {"status":"retry","reason":"kill_switch_off"}.
  Behaviour is otherwise unchanged: the intent stays prepared, nothing is
  spent, and the queue retries.
- enrichment_response (the legacy /v2/sync-jobs/run sync_reprocess
  delivery) runs through the C3 EnrichmentConsumer when
  ENRICHMENT_ROUTE=enrichment_queue, so one lever moves new rows onto the
  enrichment queue and drains old bindings through the same state
  machine. Default sync_handler keeps today's reprocess.run path.

Failure-Class: none

Verification (local unit, serial, nice 19):
- test_batch_pipeline_quarantine_recovery 67 passed (the disabled-host,
  -cohort and -missing cases assert 409 kill_switch_off)
- test_enrichment_route 14 passed (incl. legacy-handler delegation)
- test_batch_pipeline_serving 39 passed
- test_revision_drain_harness 7 passed
- test_cross_service_deploy_contract 18 passed

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(enrichment): enrichment-maintenance scheduler + /v2/enrichment/sweep (C4)

Plan C4, swarm lane 9. One maintenance owner for the enrichment outbox
on the workers role:

- POST /v2/enrichment/sweep (OIDC as /v2/enrichment/run) runs the outbox
  sweep (lost-wake repair, privacy discard), then summary_debt_repair.tick.
  It answers 200 with counts; a summary-debt failure is counted, never 5xx.
- deploy/scheduler/jobs.yaml: enrichment-maintenance (*/2) against
  backend-integration, lifecycle: planned until the route serves there.
  Prod ENABLED; dev PAUSED (dev shares prod Firestore, as the sequencer).

Both halves are safe beside the legacy sequencer sweep: the outbox sweep
is per-row CAS and the summary-debt tick holds its own cursor lease. The
sequencer sweep's reprocess.sweep and summary_debt_repair.tick calls
(routers/sync.py:1958) are deleted by lane 10's slice. Summary-debt
repair on backend-integration needs SUMMARY_DEBT_REPAIR_ENABLED in lane
7's ops file (today it is set on backend-sync only).

Verification: test_enrichment_route 16 passed; test_scheduler_reconcile
24 passed (job sets plus lifecycle/state pinned).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor(outbox): selector returns the Outbox protocol; one shared provider-STT instance

Follow-up nits from lane 9's sign-off on #22467: FirestoreOutbox and
firestore_outbox are annotated as returning the Outbox protocol, which drops
the type-ignore (both implementations satisfy it under pyright), and the
provider-STT branch caches one lazily built instance like enrichment's
module singleton.

Verification: pyright 0 errors; test_outbox_firestore 16,
test_provider_stt_outbox 11, test_enrichment_route 16,
test_batch_pipeline_projection 40, test_scheduler_reconcile 24 passed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* chore(enrichment): route policy for /v2/enrichment/sweep

Mirrors /v2/enrichment/run: service OIDC, internal task surface, no rate
limit, sync_job timeout class, conversations data domain.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant