Skip to content

fix(enrichment): park enrichment obligations older than 72h - #24580

Merged
Git-on-my-level merged 9 commits into
mainfrom
lane/freshtitles-agegate
Nov 4, 2026
Merged

Git-on-my-level merged 9 commits into
mainfrom
lane/freshtitles-agegate

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Requested by David

Park enrichment outside the past 72 hours, following David's 2026-11-04 ruling. Either an old conversation created_at or an old obligation first_pending_at is enough. /v2/enrichment/run checks on the database executor before borrowing an enrichment callback slot, returns HTTP 200 for a durably parked row, and makes no LLM call. The shared Firestore claim, sweep and summary-debt repair enforce the same cutoff.

Parking retains identity, policy, version, original acceptance/deadline and custody fields; it sets a dormant age_gate_parked/age_gate_72h marker, removes the due time and rotates the token under CAS. Active leases and newer wake tokens are preserved. Marks and repair sweeps do not reopen parked rows. Historical rows cannot consume the bounded fresh debt-admission budget. No data is deleted.

ENRICHMENT_MAX_AGE_HOURS=72 is declared on all four production Cloud Run services; invalid/negative values retain 72, and 0 disables new parking. Rollback stops new parking; existing parked obligations require a separate bounded unpark after increasing the window or setting 0. Lowering a nonzero window parks more work. The runbook describes the unpark fences and retained debt: backend/docs/runbooks/enrichment-age-gate.md. The lead owns review, merge, deployment and any operator action; this lane made no production writes.

Read-only backlog sample: 1,000 BASIC tasks at 04:04Z, joined to conversation creation metadata: 640 <8h, 242 at8-72h, 64 >72h, 54 unknown. This implements the historical-work cutoff; only 6.4% of this first-page sample is proven older than 72h. Fresh queue priority and the live-producer record-barrier investigation remain separate work.

Validation: BACKEND_UNIT_TEST_FILE_LIST=.../age-unit-files.txt backend/test.sh passed 163 tests (12 age-gate, 56 route, 95 coalescing) through omi-heavy and nice -n 19. It covers old HTTP200/no callback, fresh processing, old creation with new debt, token/lease fences, parked sweep/mark suppression, strict Firestore debt-repair ordering, and fresh admission behind historical debt. Focused hermetic E2E remained queued for shared capacity and was cancelled at the lead's 04:56Z direction to publish on unit-green with PR CI as the remaining gate. These checks measure local behavior; no deployed recovery is claimed.

Invariants: INV-MEM-4

Failure-Class: none
This adds an explicit historical-processing scope policy while retaining the existing custody and completion fences.

🤖 Generated with Claude Code

View guided diff Turn on auto-fix

Line-Count-Exception: app/lib/services/wals/local_wal_sync.dart | 2692 -> 2700 | growth inherited from the folded origin/main merge, not authored by this branch
Line-Count-Exception: backend/database/conversation_finalization_jobs.py | 3167 -> 3176 | PR 23370 fold: calendar-probe pre-read, terminal-visibility decorators and shared recover-deferred txn, net of orphan helpers moved to conversation_processing_recovery
Line-Count-Exception: backend/database/conversations.py | 4607 -> 4623 | PR 23370 fold: failed-status exclusion in is_visible_conversation and lifecycle_terminal decision stamping in claim_conversation_status
Line-Count-Exception: backend/database/firestore_index_registry.py | 2282 -> 2327 | PR 23334 fold: restore/revert scan query requirements for the stale-planner archive tool
Line-Count-Exception: backend/utils/sync/assignment.py | 1515 -> 1522 | PR 23370 fold: explicit sync-intake keep provenance stamp for newly created rows

UI-Evidence: none

Product invariants affected

  • INV-DATA-1
  • INV-MEM-4
  • INV-MEM-1
  • INV-CAP-1
  • INV-TASK-2

Git-on-my-level and others added 3 commits November 4, 2026 11:37
Retain historical debt with a fenced dormant age-gate marker and answer
old wakes without calling the enrichment callback. Apply the same cutoff
to outbox claims, sweeps and summary-debt repair.
@Git-on-my-level Git-on-my-level self-assigned this Nov 4, 2026

@cubic-dev-ai cubic-dev-ai 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.

7 issues found across 14 files

Confidence score: 3/5

  • outbox_firestore.py adds extra reads on every claim, including a check the run endpoint already performed. outbox.py also adds a separate CAS and conversation read for each fresh due row; fold the age check into the existing repair CAS.
  • claim_key’s new park branch has no test, and existing tests don’t reach the 72-hour cutoff. Add a test using a real-epoch now and an expired row.
  • enrichment-age-gate.md doesn’t give operators a runnable unpark procedure. Document the batch-size bound, command, stop condition, verification, and checkpoint and receipt locations.
  • feature-flag-registry.md is generated, so the hand-added entry can drift from the source. Add it to config/feature-flags.yaml and rerun the renderer.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/docs/feature-flag-registry.md">

<violation number="1" location="backend/docs/feature-flag-registry.md:514">
P3: This registry file is generated and marked do-not-edit, so this hand-added row will drift from `config/feature-flags.yaml`. Add the entry to the YAML and re-run `scripts/render_feature_flag_registry.py` instead. The prod cell also does not match the generator's format: it uses double-quoted literals and omits the service list that the other rows include, even though the four Cloud Run services declare this variable.</violation>
</file>

<file name="backend/docs/runbooks/enrichment-age-gate.md">

<violation number="1" location="backend/docs/runbooks/enrichment-age-gate.md:28">
P2: The unpark section lists invariants but no runnable procedure. Add the batch-size bound, the entry point or command, the stop condition, the verification step, and where the checkpoint and receipt are stored. Also define 'privacy fences' or link to where they are specified.</violation>
</file>

<file name="backend/utils/enrichment/age_gate.py">

<violation number="1" location="backend/utils/enrichment/age_gate.py:117">
P3: This log line also fires when the row was already parked, because `update()` returns True for `parked(old)`. Log or count only the transition that wrote `park_row`, so the `outcome=parked` signal reflects new parking.</violation>
</file>

<file name="backend/database/outbox_firestore.py">

<violation number="1" location="backend/database/outbox_firestore.py:234">
P2: This runs on every claim, so fresh work now pays an extra CAS read plus a conversation document read per delivery. On the run endpoint path the router has already performed the same check, so it is duplicated. Skip the claim_key check when the caller has already checked, or cache the conversation created_at check.</violation>

<violation number="2" location="backend/database/outbox_firestore.py:234">
P2: The new park branch in `claim_key` has no test. Existing `claim_key` tests use small `now` values that never reach the 72h cutoff. Add a test that calls `claim_key` with a real-epoch `now` on an expired row and asserts `Outcome.STALE` with the row parked.</violation>
</file>

<file name="backend/utils/enrichment/outbox.py">

<violation number="1" location="backend/utils/enrichment/outbox.py:388">
P3: Move `parked` to a module-level import. `age_gate.py` has no top-level imports from `utils`, so there is no cycle, and AGENTS.md requires top-level imports. The same applies to the `park_if_expired` import added in the sweep.</violation>

<violation number="2" location="backend/utils/enrichment/outbox.py:928">
P2: This adds a separate CAS and a conversation `get` for every fresh due row on each sweep pass, roughly doubling the reads on the hot repair path. Fold the age check into the existing `repair` CAS so it runs in one transaction and reads the conversation only once per row.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

after the serving configuration permits their age. Increasing the window admits
older work; decreasing a nonzero value parks more work, not less.

An unpark operation must re-read the row under CAS, verify the exact parked

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: The unpark section lists invariants but no runnable procedure. Add the batch-size bound, the entry point or command, the stop condition, the verification step, and where the checkpoint and receipt are stored. Also define 'privacy fences' or link to where they are specified.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/docs/runbooks/enrichment-age-gate.md, line 28:

<comment>The unpark section lists invariants but no runnable procedure. Add the batch-size bound, the entry point or command, the stop condition, the verification step, and where the checkpoint and receipt are stored. Also define 'privacy fences' or link to where they are specified.</comment>

<file context>
@@ -0,0 +1,35 @@
+after the serving configuration permits their age. Increasing the window admits
+older work; decreasing a nonzero value parks more work, not less.
+
+An unpark operation must re-read the row under CAS, verify the exact parked
+token and absence of an active lease, honor privacy fences, then clear the age
+marker/defer reason, set dormant=false and due_at/task_due_at=now, rotate the
</file context>

return Outcome.DISCARDED
from utils.enrichment.age_gate import park_if_expired

if park_if_expired(row_id, wake_token, now=now, client=self._bound_client):

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: This runs on every claim, so fresh work now pays an extra CAS read plus a conversation document read per delivery. On the run endpoint path the router has already performed the same check, so it is duplicated. Skip the claim_key check when the caller has already checked, or cache the conversation created_at check.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/database/outbox_firestore.py, line 234:

<comment>This runs on every claim, so fresh work now pays an extra CAS read plus a conversation document read per delivery. On the run endpoint path the router has already performed the same check, so it is duplicated. Skip the claim_key check when the caller has already checked, or cache the conversation created_at check.</comment>

<file context>
@@ -229,6 +229,10 @@ def claim_key(self, row_id: str, wake_token: str, lease_seconds: float, *, now:
             return Outcome.DISCARDED
+        from utils.enrichment.age_gate import park_if_expired
+
+        if park_if_expired(row_id, wake_token, now=now, client=self._bound_client):
+            return Outcome.STALE
         if not admit(row_id, now=now, token=wake_token):
</file context>

return Outcome.DISCARDED
from utils.enrichment.age_gate import park_if_expired

if park_if_expired(row_id, wake_token, now=now, client=self._bound_client):

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: The new park branch in claim_key has no test. Existing claim_key tests use small now values that never reach the 72h cutoff. Add a test that calls claim_key with a real-epoch now on an expired row and asserts Outcome.STALE with the row parked.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/database/outbox_firestore.py, line 234:

<comment>The new park branch in `claim_key` has no test. Existing `claim_key` tests use small `now` values that never reach the 72h cutoff. Add a test that calls `claim_key` with a real-epoch `now` on an expired row and asserts `Outcome.STALE` with the row parked.</comment>

<file context>
@@ -229,6 +229,10 @@ def claim_key(self, row_id: str, wake_token: str, lease_seconds: float, *, now:
             return Outcome.DISCARDED
+        from utils.enrichment.age_gate import park_if_expired
+
+        if park_if_expired(row_id, wake_token, now=now, client=self._bound_client):
+            return Outcome.STALE
         if not admit(row_id, now=now, token=wake_token):
</file context>


try:
if not injected:
from utils.enrichment.age_gate import park_if_expired

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: This adds a separate CAS and a conversation get for every fresh due row on each sweep pass, roughly doubling the reads on the hot repair path. Fold the age check into the existing repair CAS so it runs in one transaction and reads the conversation only once per row.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/enrichment/outbox.py, line 928:

<comment>This adds a separate CAS and a conversation `get` for every fresh due row on each sweep pass, roughly doubling the reads on the hot repair path. Fold the age check into the existing `repair` CAS so it runs in one transaction and reads the conversation only once per row.</comment>

<file context>
@@ -920,6 +924,11 @@ def update(old: Row | None) -> tuple[Row | None, None]:
 
         try:
+            if not injected:
+                from utils.enrichment.age_gate import park_if_expired
+
+                if park_if_expired(snapshot.id, None, now=current, client=bound):
</file context>

| `DREAM_HALF_HOUR_SWEEP_ENABLED` | Default-on: the Dream sweep job also ticks at :30 so Dream drains about 56 of every 60 minutes; 0/false/off/no makes the :30 tick return without work | backend | env | open | — | — | — | — | keep | keep | — | dazheng |
| `DREAM_TELEMETRY_V2_ENABLED` | Default-on structured dream_pass/dream_sweep JSON records (counts, durations, uuid run/sweep ids, allowlisted labels); 0/false/off/no stops them, leaving the legacy text lines | backend | env | open | — | — | — | — | keep | keep | — | dazheng |
| `ENRICHMENT_BACKFILL_ROUTING_ENABLED` | Default on; new non-first-summary backfill enrichment uses the existing backfill queue while retaining enrichment handler and identity | backend | env | open | — | — | — | — | keep | keep | — | two-lane lead |
| `ENRICHMENT_MAX_AGE_HOURS` | Default 72 hours: park historical enrichment without deleting its durable obligation; 0 disables new parking | backend | env | closed | — | — | {value: "72", category: ops_kill} | — | keep | keep | — | two-lane lead |

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: This registry file is generated and marked do-not-edit, so this hand-added row will drift from config/feature-flags.yaml. Add the entry to the YAML and re-run scripts/render_feature_flag_registry.py instead. The prod cell also does not match the generator's format: it uses double-quoted literals and omits the service list that the other rows include, even though the four Cloud Run services declare this variable.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/docs/feature-flag-registry.md, line 514:

<comment>This registry file is generated and marked do-not-edit, so this hand-added row will drift from `config/feature-flags.yaml`. Add the entry to the YAML and re-run `scripts/render_feature_flag_registry.py` instead. The prod cell also does not match the generator's format: it uses double-quoted literals and omits the service list that the other rows include, even though the four Cloud Run services declare this variable.</comment>

<file context>
@@ -511,6 +511,7 @@ and an explicit empty literal renders as `''`.
 | `DREAM_HALF_HOUR_SWEEP_ENABLED` | Default-on: the Dream sweep job also ticks at :30 so Dream drains about 56 of every 60 minutes; 0/false/off/no makes the :30 tick return without work | backend | env | open | — | — | — | — | keep | keep | — | dazheng |
 | `DREAM_TELEMETRY_V2_ENABLED` | Default-on structured dream_pass/dream_sweep JSON records (counts, durations, uuid run/sweep ids, allowlisted labels); 0/false/off/no stops them, leaving the legacy text lines | backend | env | open | — | — | — | — | keep | keep | — | dazheng |
 | `ENRICHMENT_BACKFILL_ROUTING_ENABLED` | Default on; new non-first-summary backfill enrichment uses the existing backfill queue while retaining enrichment handler and identity | backend | env | open | — | — | — | — | keep | keep | — | two-lane lead |
+| `ENRICHMENT_MAX_AGE_HOURS` | Default 72 hours: park historical enrichment without deleting its durable obligation; 0 disables new parking | backend | env | closed | — | — | {value: "72", category: ops_kill} | — | keep | keep | — | two-lane lead |
 | `EPISODES_ENABLED` | Default on unless set to a non-on value; live episodes overlay (per-moment gpt-5-nano update, provisional items, /v1/episodes capability). Off reports enabled=false and apps keep today's per-conversation UI | backend | env | open | — | — | — | — | keep | keep | — | dazheng |
 | `EPISODE_CARRY_ON_SESSION_END` | Default on; wait one moment-pause window after a pusher session ends, then flush its carried transcript if no reconnect arrives | backend | env | open | — | — | — | — | keep | keep | — | dazheng |
</file context>


result = outbox.mutate_row(row_id, update, client=client)
if result:
logger.info('event=enrichment_age_gate outcome=parked reason=%s', REASON)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: This log line also fires when the row was already parked, because update() returns True for parked(old). Log or count only the transition that wrote park_row, so the outcome=parked signal reflects new parking.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/enrichment/age_gate.py, line 117:

<comment>This log line also fires when the row was already parked, because `update()` returns True for `parked(old)`. Log or count only the transition that wrote `park_row`, so the `outcome=parked` signal reflects new parking.</comment>

<file context>
@@ -0,0 +1,118 @@
+
+    result = outbox.mutate_row(row_id, update, client=client)
+    if result:
+        logger.info('event=enrichment_age_gate outcome=parked reason=%s', REASON)
+    return result
</file context>

candidate: FirstSummaryPolicy | None = None

def update(old: Row | None) -> tuple[Row, tuple[Row, bool]]:
from utils.enrichment.age_gate import parked

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: Move parked to a module-level import. age_gate.py has no top-level imports from utils, so there is no cycle, and AGENTS.md requires top-level imports. The same applies to the park_if_expired import added in the sweep.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/enrichment/outbox.py, line 388:

<comment>Move `parked` to a module-level import. `age_gate.py` has no top-level imports from `utils`, so there is no cycle, and AGENTS.md requires top-level imports. The same applies to the `park_if_expired` import added in the sweep.</comment>

<file context>
@@ -385,6 +385,10 @@ def mark_update(
     candidate: FirstSummaryPolicy | None = None
 
     def update(old: Row | None) -> tuple[Row, tuple[Row, bool]]:
+        from utils.enrichment.age_gate import parked
+
+        if old and parked(old):
</file context>

Git-on-my-level and others added 6 commits November 4, 2026 14:34
Keep ENRICHMENT_MAX_AGE_HOURS in the existing enrichment config module so the
batch-stage environment ratchet stays at its baseline.

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

#24554 added a time.monotonic lease-hold cap to the enrichment consumer; the
emulator proof replaced the module clock with a namespace lacking monotonic, so
the proof failed whenever enrichment code changed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	backend/config/enrichment.py
#	backend/deploy/runtime_env.yaml
#	backend/deploy/runtime_env/prod.overlay.yaml
#	backend/utils/enrichment/outbox.py
#	config/deployment-setting-classification.json
#	config/feature-flags.yaml
# Conflicts:
#	backend/scripts/enrichment_recovery_emulator_test.py
@Git-on-my-level
Git-on-my-level merged commit 7b3911c into main Nov 4, 2026
61 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/freshtitles-agegate branch November 4, 2026 11:59
Git-on-my-level added a commit that referenced this pull request Nov 4, 2026
… enrichment (#24595)

## What changes

WP-C PR 1 (alarms 1+2): add bounded recent-cohort dwell metrics for
record_pending (24h cohort, 2h budget), enrichment fresh obligations
(24h cohort, 1h budget), and blocked_byok (7d cohort, 3d budget). BYOK
entries stamp blocked_byok_at on creation/reclaim. Historical stock
stays agent tier. No-job discovery is an explicitly incomplete 128-row
stock sample with an agent blind companion, per thread-owner ruling
135c64; it does not claim a seal dwell clock.

Record_pending/enrichment entries must also be at/after the fixed
2026-11-04T09:27Z brief cutoff. A rolling24h window alone would include
tonight's known 8-24h backlog and page on import. All-age stock remains
visible at agent tier.

All 13 new/replaced rules, their stale/blind companions, and the
existing dead-letter stock rule use the gate-based import. They live in
resilience.json, which is already in the egress workflow trigger list.
The combined export mirrors them. The four metric families are retained
by the sync GMP sidecar and both dev/prod bridge allowlists. No .github/
edits, no live.py or serving.py edits.

## Bounds and rollout

Samples run at most every five minutes per observer, with ten-second RPC
deadlines. Record_pending reads at most 1000 recent rows and uses a
stock COUNT capped at 5001. Enrichment reads at most 1000 recent rows
and a backfill COUNT capped at 20001. No-job reads at most 128
conversations plus 128 job existence results. BYOK reads at most 1000
new-state entries. Counts are lower bounds at caps; saturation and
stale/absent observation have separate agent rules. Runtime rates depend
on observer replicas; there is no unbounded client-side scan.

Cloud Run's existing bridge collects every 10m with a 1m offset.
Enrichment/BYOK allow 20m sample freshness (5m producer cadence + bridge
latency); direct batch keeps 15m. Threshold evidence and intended final
thresholds are annotated 2026-11-04. Existing unstamped BYOK rows are
excluded from the new page cohort, with no data backfill.

Deploy needed: reconcile the three new composites; backend/listen/sync
emitter train carrying the serving QueueMetrics and sync revision-local
GMP profile; then metrics-egress/Grafana import. This lane does not
merge or deploy. Live alert delivery is unverified.

## Validation

At head 937bccf, the guarded push passed full preflight, all 825
Firestore guard tests (including the digest sentinel), type checking and
276 selected backend tests. These are local source/index/type/unit
checks.

The complete selector-owned monitoring group passed: 536 tests across 21
files, with three existing skips. Notification timing, byte-identical
split/combined objects and the offline GMP inventory satisfy their
contracts. All 94 workflow-contract tests passed with the new pure index
module included in the hermetic control tree. The 118-test enrichment
integration shard passed after merging main #24580. At 937bccf, all
70 CI checks are terminal with no failures or pending checks; the PR is
CLEAN. Luna round one returned SHIP on e6e7237, and round two returned
SHIP on 937bccf.

The current-head [CI Listen Pusher Stack Gauntlet
passed](https://github.com/BasedHardware/omi/actions/runs/41829935111/job/126574693965).
Local stack verification was limited by lane-sandbox teardown EPERM;
ruling 39e8fe assigns stack proof to CI. No live/GCP validation is
claimed.

Initiative: capture/transcription/speakers
Failure-Class: none

Line-Count-Exception: backend/database/conversation_finalization_jobs.py
| 3167 -> 3169 | Add lifecycle entry metadata and registered bounded
observer indexes beside their existing owners.

Line-Count-Exception: backend/database/firestore_index_registry.py |
2282 -> 2284 | Add lifecycle entry metadata and registered bounded
observer indexes beside their existing owners.
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