Skip to content

feat(enrichment): /v2/enrichment/run on the outbox consumer, 409-only retries (lane 9, C3) - #22462

Merged
Git-on-my-level merged 20 commits into
integration/legacy-retirefrom
lr/09-c3
Oct 19, 2026
Merged

Git-on-my-level merged 20 commits into
integration/legacy-retirefrom
lr/09-c3

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Summary

Swarm lane 9, plan C3 (legacy-sync retirement). #22444 has merged; this diff is C3 only.

  • utils/enrichment/consumer.py: EnrichmentConsumer, a QueueConsumer for OutboxKind.ENRICHMENT on the workers role. Every lease is 120s with a 30s heartbeat. It mirrors reprocess.run outcome for outcome and settles through the Outbox:

    Outcome What happens
    processed DONE (ack; 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.

    • OIDC for the enrichment queue (TaskEdge enrichment).
    • It also accepts the legacy {"kind":"sync_reprocess",...} payload, so rows bound to either handler drain (contract (b) invariant 7).
    • Responses follow contract (d) only: 200 for consumed deliveries, 409 retry, 400 for a malformed task, 500 only for an unexpected exception.
  • config/enrichment.py.

    • ENRICHMENT_ROUTE (sync_handler | enrichment_queue, default sync_handler) is the deployment default for contract (c)'s enrichment_route until E1 records it per unit.
    • ENRICHMENT_TASKS_{QUEUE,HANDLER_URL,OIDC_AUDIENCE,INVOKER_SA} is the binding.
    • An incomplete binding falls back to the sync handler, counted via record_fallback.
  • valid_dispatch_binding and _enqueue accept both handler paths.

Captain / other lanes

  • Lane 1: mount routers/enrichment.py in main.py.
  • Registry rows (captain):
    • ENRICHMENT_ROUTE: owner lane 9; default sync_handler. Ramp: staging at M2 under replay (gate: sr- 120s dispatch SLI clean, old bindings drain, zero 5xx); prod after the M3 train, flipped under the C3 24h sr- SLI gate (Grafana sr- dispatch SLI; lead expands). It is replaced by E1's enrichment_route policy field.
    • ENRICHMENT_TASKS_*: deploy wiring.
  • Lane 7 queue: enrichment / staging-enrichment, max-concurrent 50, 25/s, backoff 10–300s, unlimited attempts, target backend-integration (workers).

Verification (local unit layer, serial, nice -n 19)

  • test_enrichment_route 13 passed:
    • callback-pending → 409 with the wake kept;
    • fence → superseded;
    • live defer → new wake;
    • not-due wake → 200 deferred/not_due with a re-arm;
    • 400s for malformed tasks;
    • a stale wake → 200;
    • an unexpected error → 5xx with the lease kept;
    • route binding plus the counted fallback.
  • Other suites: test_outbox_firestore 16, test_workers_consumer_contract 25, test_cross_service_deploy_contract 18, test_sync_reprocess_coalesce 88.
  • pyright: 0 errors.

Product invariants affected

INV-DATA-1: cited only because the local preflight diffs against main and integration carries #22430's workflow files. This PR changes no workflow or data-plane routing.

Failure-Class: none

🤖 Generated with Claude Code

Git-on-my-level and others added 18 commits October 19, 2026 13:19
…lice 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]>
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]>
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]>
… 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]>
…e 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]>
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]>
… 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]>
…lr/09-outbox

# Conflicts:
#	backend/database/batch_pipeline_projection.py
#	backend/tests/support/firestore_query_driver_registry.py
#	backend/utils/enrichment/outbox.py
#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]>
…lr/09-outbox

# Conflicts:
#	backend/routers/batch_pipeline.py
…cy 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]>
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]>
…ests

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]>
@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 ✅ Completed 2026-10-19T09:37:18.838426Z 3bafffa 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.

…lr/09-c3

# Conflicts:
#	backend/database/outbox_firestore.py

@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: e92ad87eb5

ℹ️ 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 +56 to +57
@router.post('/v2/enrichment/run', include_in_schema=False)
async def run_enrichment_task(request: Request, _retry_count: int = Depends(verify_enrichment_task)):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Register the enrichment router before enabling its dispatch route

When ENRICHMENT_ROUTE=enrichment_queue, new obligations are dispatched to this endpoint, but backend/main.py neither imports this router nor calls app.include_router(enrichment.router). The production application therefore answers 404 for every enrichment task, leaving the new queue unable to process any rows; the route tests hide this because they construct a separate FastAPI app and mount the router explicitly.

Useful? React with 👍 / 👎.

Comment on lines 718 to +722
if status == 'unbound':
UNBOUND.labels(action='repair').inc()
if row is not None and discard is not None and discard(snapshot.id):
counts['discarded'] += 1
row = None

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 Apply privacy deletion before filtering unbound sweep rows

When a due obligation has no valid dispatch binding and the current host also has no binding, repair() returns ('unbound', None), so this condition never invokes discard. Such a row has no task that could reach claim_key() and perform the privacy check either, meaning a deletion/protection-fenced obligation remains stored until dispatch configuration is repaired, potentially indefinitely. Run the discard check independently of whether repair produced a wakeable row.

Useful? React with 👍 / 👎.

Comment on lines +65 to +66
lease_seconds: ClassVar[float] = 120.0
heartbeat_seconds: ClassVar[float] = 30.0

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 Align failed-delivery repair with the shortened lease

For a non-first-summary delivery that raises an unexpected exception, a normal Cloud Tasks retry can arrive while this 120-second lease is still held, receive the consumed BUSY response, and disappear. After the lease expires, the sweep only rotates these rows' wake tokens when task_due_at + REPAIR_SECONDS is reached, and REPAIR_SECONDS remains 1800 seconds in utils/enrichment/outbox.py; unlike the legacy consumer, whose corresponding lease was also 1800 seconds, this leaves an unleased obligation without a usable wake for roughly half an hour. The sweep threshold or lease duration needs to follow the new consumer lease.

Useful? React with 👍 / 👎.

Comment on lines +45 to +49

return outbox


def _claim(row: Mapping[str, Any], row_id: str) -> Claim:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep the database outbox below the utils layer

The new database implementation resolves its core persistence behavior through utils.enrichment.outbox here, with additional imports from utils throughout the class. This reverses the backend's strict dependency hierarchy, so database callers now depend on the business-logic layer and correctness becomes sensitive to lazy import order and future circular imports. Move the Firestore CAS, scheduling, and wake primitives into the database layer and have the utils compatibility surface call downward instead.

AGENTS.md reference: backend/AGENTS.md:L161-L169

Useful? React with 👍 / 👎.

@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: 3bafffafe1

ℹ️ 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 +331 to +334
pending = outbox.mutate_row(claim.row_id, rearm)
if pending is None:
return None
outbox.wake_row(pending)

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 Re-arm repairs through the bound outbox instance

When a consumer uses FirestoreOutbox(..., client=..., create_wake=...) and the callback raises SummaryRepairSuperseded with a retry revision, this bypasses both injected boundaries: mutate_row targets the default Firestore store and wake_row targets the production task creator. The claimed row in the bound store therefore remains leased without the new repair fence or wake. Use self._mutate and self._wake, as the other state transitions do.

AGENTS.md reference: backend/AGENTS.md:L173-L175

Useful? React with 👍 / 👎.

Comment on lines +50 to +51
except Exception as error:
logger.warning('event=enrichment_heartbeat outcome=error exception_type=%s', type(error).__name__)

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 Treat prolonged heartbeat errors as a lost lease

When heartbeat calls keep raising for longer than the 120-second lease during a long callback, this handler only logs and leaves lost unset. If the Cloud Tasks request then times out or another wake is delivered, a second worker can claim the expired row while the first worker continues processing and may repeat enrichment side effects; the original settlement being fenced later cannot undo those effects. Track the last successful lease deadline and abort or fence processing once renewal failures outlive it.

Useful? React with 👍 / 👎.

Comment on lines +16 to +17
value = os.getenv('ENRICHMENT_ROUTE', 'sync_handler').strip().lower()
return 'enrichment_queue' if value == 'enrichment_queue' else 'sync_handler'

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 Align queue routing with the declared task-edge flag

When an operator enables the new runtime path with ENRICHMENT_ROUTE=enrichment_queue, the cross-service deployment check does not validate its handler, audience, or target route because the enrichment TaskEdge in backend/scripts/cross_service_contract.py:163 is gated by the unrelated ENRICHMENT_DISPATCH_MODE=cloud_tasks. A repo-wide search at this commit finds no production code reading that latter flag, so validation is skipped exactly when this code starts dispatching and can allow a structurally valid but wrong target to receive durable work. Use the same activation flag in the runtime and task-edge contract.

AGENTS.md reference: backend/AGENTS.md:L153-L153

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit 5bb1199 into integration/legacy-retire Oct 19, 2026
24 checks passed
@Git-on-my-level
Git-on-my-level deleted the lr/09-c3 branch October 19, 2026 10:22
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
Rollout flag, default sync_handler; enrichment_queue binds new sr- obligations to
/v2/enrichment/run. Ramp per #22462: staging at M2 under replay, prod after the M3 train under
the C3 24h sr- dispatch SLI gate; must be enrichment_queue before legacy draining. The
ENRICHMENT_TASKS_* keys are queue wiring for lane 7's ops file, not flags.

Verified: scripts/check_feature_flag_registry.py OK; rendered doc regenerated.

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