Skip to content

feat(enrichment): Firestore Outbox + package-owned sr- callback (lane 9, C2 slices 2-3; absorbs #21968) - #22444

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

Git-on-my-level merged 13 commits into
integration/legacy-retirefrom
lr/09-outbox

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 C2 slices 2 and 3 (legacy-sync retirement). Stacked on #22431 (slice 1, the move); once that merges, this diff shrinks to its own three commits.

Slice 3: the enrichment package owns the sr- callback (and absorbs #21968)

Slice 2: database/outbox_firestore.py, the Firestore Outbox for OutboxKind.ENRICHMENT (contract (b))

  • Row compatibility. The row stays compatible with mark/run: same collection, document ids, field names and sr- names. Additive fields: policy_id, claim_attempts, and a transient summary_seen_by.

  • Token mapping. lease_token is the per-claim owner uuid and wake_token is task_token. Every later call is fenced on both (invariant 1).

  • claim_key. In order:

    1. privacy discard (invariant 6);
    2. demand admission;
    3. STALE/BUSY checks;
    4. a not-due re-arm that wakes itself and returns DEFERRED.

    The implementation owns wake creation (lead ruling 10-19).

  • enqueue. It 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 the idempotent wake() after commit (invariants 4–5).

  • ack. It keeps today's finish rules: retire when unchanged, a dormant receipt via record_summary, re-arm when the version moved.

  • defer/release. defer mints a new wake; release keeps the wake.

  • sweep. It gains a privacy discard hook. Pull claim() uses the new due_rows query (single-field due_at), which is registered in the query-shape drivers.

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

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

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

  • Outbox and callback tests:
    • test_outbox_firestore 13 passed (fencing, wake dedupe, coalescing, defer/release, the ack version rules, the dormant receipt, transactional enqueue + wake, the sweep privacy discard, pull claim)
    • test_enrichment_callback_fence 4 passed
    • test_enrichment_callback_parity 3 passed
  • Existing enrichment and batch suites:
    • test_sync_reprocess_coalesce 88 passed
    • test_sync_enrichment_custody 10 passed
    • test_batch_pipeline_projection 40 passed
    • test_batch_pipeline_serving 31 passed
    • test_listen_finalization_cloud_tasks 278 passed
  • Firestore contract suites: query shapes 481, outside-query 30, runtime witnesses 24, index oracle 132.
  • Ratchets and guardrails: background-task ratchet, LLM gateway coverage and compute inventory guardrails all passed.
  • pyright 1.1.403: 0 errors.
  • Not run locally: the emulator suites (test_sync_reprocess_emulator now patches the package callback) and lane 12's conformance suite, which has not landed yet.

Product invariants affected

INV-DATA-1: cited only because the local preflight diffs against main, and integration (lane 7's #22430) carries .github/workflows/gcp_*.yml changes. This PR's own diff against integration/legacy-retire changes no workflow, release pipeline or data-plane routing.

Failure-Class: none

Contracts: (b) invariants 1–7; (c) invariant 3 (no new env reads; SYNC_* reads moved, flagged to lane 14). No deploy class (ships with the M3 train).

🤖 Generated with Claude Code

Git-on-my-level and others added 6 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]>
@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-19T08:53:12.854241Z d41d898 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.

Git-on-my-level and others added 2 commits October 19, 2026 14:39
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]>

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

ℹ️ 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 +681 to +683
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.

P1 Badge Run privacy discard before skipping unbound rows

When a due row lacks a valid dispatch binding and the host has no replacement binding, repair returns ('unbound', None), so this row is not None guard prevents discard_blocked from ever examining it. Because an unbound row also has no task that could reach claim_key, account-deletion or protection-fenced obligations retain their owner/conversation metadata indefinitely until dispatch configuration is restored; perform the privacy discard independently of whether the row can be rewoken.

Useful? React with 👍 / 👎.

Comment on lines +312 to +315
def firestore_outbox(kind: OutboxKind):
"""The Firestore implementation behind ``database.outbox.outbox_for`` in this window."""
if OutboxKind(kind) is OutboxKind.ENRICHMENT:
return ENRICHMENT_OUTBOX

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 Wire the Firestore implementation into the public selector

The documented entry point remains database.outbox.outbox_for, but it still unconditionally raises NotImplementedError; this newly added selector is never called anywhere in the repository. Consequently, any worker or integration using the public outbox API cannot obtain the enrichment implementation even though this commit claims to provide it; make outbox_for(OutboxKind.ENRICHMENT) delegate to this implementation.

Useful? React with 👍 / 👎.

Comment on lines +162 to +163
if not admit(row_id, now=now, token=wake_token):
return Outcome.DEFERRED # Demand processing owns this row's next wake.

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 Return a push-consumable result for deferred claims

When demand admission postpones a delivery, this returns Outcome.DEFERRED, but utils.workers.consumer.run_push only handles BUSY, STALE, and DISCARDED claim outcomes and raises ValueError for DEFERRED. Thus an ordinary demand-scheduled wake produces a 500 instead of the documented consumed 200 response, causing Cloud Tasks retries and potentially bypassing the intended scheduling delay; align this return path with the push-driver contract or add a deferred claim mapping.

Useful? React with 👍 / 👎.

Comment on lines +701 to +708
.where('due_at', '<=', now)
.order_by('due_at')
.limit(max(1, min(100, limit)))
)
rows = []
for snapshot in query.stream():
row = snapshot.to_dict() or {}
if not row.get('dormant') and row.get('lease_until', 0) <= now and row.get('task_token'):

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 Scan past leased rows when pulling due work

This query limits the result set before filtering out active leases in Python. If the first 4*n due documents (or the first 100 because of the cap) are leased, claim(n, ...) returns no work even when later due rows are unleased, so sustained long-running claims can starve the rest of the queue for the full lease duration. Page through due rows until enough claimable rows are found or a bounded scan is exhausted, as the sweep path already does.

Useful? React with 👍 / 👎.

Comment on lines +192 to +193
for row_id, row in _outbox().due_rows(now=now, limit=n * 4, client=self._bound_client):
claimed = self.claim_key(row_id, row['task_token'], lease_seconds, now=now)

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 Use the bound client for claim mutations

When FirestoreEnrichmentOutbox is constructed with a client, claim reads due rows from that bound client but claim_key and every subsequent lease operation call mutate_row, which resolves the global Firestore client instead. With an emulator, alternate project, or injected test client, the pull path therefore reads one store and claims another, yielding false STALE results or mutating the wrong project; route the CAS operations through the same bound client.

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

Useful? React with 👍 / 👎.

Comment on lines +119 to +122
if coalesced:
outbox.COALESCED.inc()
if not outbox.valid_dispatch_binding(row.get('dispatch')):
outbox.UNBOUND.labels(action='mark').inc()

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 Move counter increments outside retried transactions

For enqueue(tx=...), these counters execute inside the Firestore transaction callback used by ProjectionStore.mark_enrichment. Firestore and the explicit contention wrapper may invoke that callback multiple times before one commit, so a single coalesced or unbound projection can increment the metric once per aborted attempt and corrupt operational rates; return the counter outcome from the transaction and increment only after the successful commit.

Useful? React with 👍 / 👎.

row, coalesced = outbox.mutate_row(dedupe_key, update)
else:
row, coalesced = self._mutate_in(tx, dedupe_key, update)
wake = bool(row.get('_wake', not coalesced)) and outbox.valid_dispatch_binding(row.get('dispatch'))

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 Accept effects-only bindings when deciding to wake

Effects-only obligations explicitly support the listen-finalization handler through valid_effects_binding, but this decision uses the stricter valid_dispatch_binding, which only accepts /v2/sync-jobs/run. When an effects enqueue carries the supported /v1/conversation-finalization-jobs/run fallback binding, the durable row is written but wake_token is returned as None and no task is created; use the row-aware effects validator here (and preserve that binding during coalescing) so lazy enrichment is not delayed until a sweep.

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: 66b98f675e

ℹ️ 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 +43 to +46
def _outbox():
from utils.enrichment import outbox

return outbox

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 Remove the reverse database-to-utils dependency

When any caller uses this Firestore implementation, _outbox() imports utils.enrichment.outbox from inside the database layer, reversing the repository's strict database/ → utils/ dependency order and hiding the cycle-prone dependency in a function-local import. Move the Firestore CAS/wake primitives into the database layer or inject them without making database/ depend on utils/.

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

Useful? React with 👍 / 👎.

Comment on lines +9 to +12
from utils.enrichment import outbox as _module
from utils.enrichment.outbox import * # noqa: F401,F403

from google.cloud import firestore
from google.api_core.exceptions import AlreadyExists, FailedPrecondition, NotFound
from prometheus_client import Counter

from utils.conversations import summary_delivery
from config.summary_guarantee import (
ADMITTED_OWNER,
deadline_seconds,
enabled as summary_enabled,
first_summary_pending,
preserves_admitted,
)
from config.sync_reprocess import settle_seconds
from config.repeat_work import revision_reuse
from database._client import get_firestore_client
from database.summary_processing import record_empty_failure, EMPTY_BLOCKED_REASON

Row: TypeAlias = dict[str, Any]
ResultT = TypeVar('ResultT')

logger = logging.getLogger(__name__)

COLLECTION = 'sync_reprocess_outbox'
LEASE_SECONDS = 1800 # Greater than the Cloud Tasks dispatch deadline.
FIRST_SUMMARY_LEASE_SECONDS = 120
FIRST_SUMMARY_HEARTBEAT_SECONDS = 30
REPAIR_SECONDS = 1800
WAKE_CHECK_SECONDS = 300
LIVE_DEFER_SECONDS = 120
COALESCED = Counter('sync_reprocess_coalesced_total', 'Sync updates folded into an existing enrichment obligation')
UNBOUND = Counter('sync_reprocess_unbound_total', 'Sync obligations awaiting a complete worker binding', ['action'])


class FirstSummaryCallbackPending(RuntimeError):
"""No processing output exists yet; retain the lease/debt without empty-result spend."""


def key(uid: str, conversation_id: str) -> str:
return hashlib.sha256(f'{uid}\0{conversation_id}'.encode()).hexdigest()


def owns_runtime() -> bool:
from utils.sync.stage import production_stage

return bool(os.getenv('FIRESTORE_EMULATOR_HOST')) or production_stage()


def _mutate(document_id: str, operation: Callable[[Row | None], tuple[Row | None, ResultT]]) -> ResultT:
if not owns_runtime():
raise RuntimeError('sync reprocess outbox requires production or a Firestore emulator')
client = get_firestore_client()
ref = client.collection(COLLECTION).document(document_id)

# All state for one obligation is in one document. Optimistic conditional
# writes avoid read-lock upgrade deadlocks under simultaneous appends while
# fencing claims, extension and completion against the exact read revision.
for attempt in range(10):
snapshot = ref.get()
old = snapshot.to_dict() if snapshot.exists else None
new, result = operation(old)
if new == old:
return result
try:
if old is None:
ref.create(new)
else:
fence = firestore.LastUpdateOption(snapshot.update_time)
if new is None:
ref.delete(option=fence)
else:
ref.update(new, option=fence)
return result
except (AlreadyExists, FailedPrecondition, NotFound):
if attempt == 9:
raise
time.sleep(random.uniform(0.005, min(0.2, 0.01 * 2**attempt)))
raise AssertionError('outbox CAS loop must return or raise within its retry budget')


def valid_dispatch_binding(dispatch: object) -> TypeGuard[dict[str, str]]:
"""A binding belongs to the receiving sync handler, including its audience."""
if not isinstance(dispatch, dict):
return False
for field in ('queue', 'handler', 'audience', 'invoker_sa'):
value = dispatch.get(field)
if not isinstance(value, str) or not value or value != value.strip():
return False
try:
url = urlsplit(dispatch['handler'])
except ValueError:
return False
return (
url.scheme == 'https'
and bool(url.netloc)
and url.path.endswith('/v2/sync-jobs/run')
and not url.query
and not url.fragment
and dispatch['audience'] == dispatch['handler']
)


def valid_effects_binding(row: dict[str, Any]) -> bool:
dispatch = row.get('dispatch')
if valid_dispatch_binding(dispatch):
return True
if not row.get('effects_only') or not isinstance(dispatch, dict):
return False
if not all(
isinstance(dispatch.get(field), str) and dispatch[field].strip() == dispatch[field] and dispatch[field]
for field in ('queue', 'handler', 'audience', 'invoker_sa')
):
return False
try:
handler, audience = urlsplit(dispatch['handler']), urlsplit(dispatch['audience'])
return (
handler.scheme == audience.scheme == 'https'
and bool(handler.netloc)
and handler.netloc == audience.netloc
and not handler.query
and not handler.fragment
and handler.path.endswith('/v1/conversation-finalization-jobs/run')
and audience.path in ('', '/', handler.path)
and not audience.query
and not audience.fragment
)
except ValueError:
return False


def _dispatch_binding() -> dict[str, str] | None:
handler = os.getenv('SYNC_TASKS_HANDLER_URL', '')
binding = {
'queue': os.getenv('SYNC_TASKS_QUEUE', ''),
'handler': handler,
'audience': os.getenv('SYNC_TASKS_OIDC_AUDIENCE') or handler,
'invoker_sa': os.getenv('SYNC_TASKS_INVOKER_SA', ''),
}
return binding if valid_dispatch_binding(binding) else None


def _task_name(row: Row) -> str:
document_id = row.get('document_id') or key(row['uid'], row['conversation_id'])
name = f"sr-{document_id}-{row['task_token']}"
if row.get('wake_generation'):
name += f"-repair-{row['wake_generation']}"
return name


def _wake_exists(row: Row) -> bool:
from utils.cloud_tasks import named_task_exists

return named_task_exists(row['dispatch']['queue'], _task_name(row))


def _enqueue(row: dict[str, Any]) -> None:
from utils.cloud_tasks import enqueue_named_task

# A backfill obligation is repaired by the fresh service's sweep. Retain
# the originating queue/worker/identity rather than borrowing that sweep's
# fresh capacity or audience. These bindings contain no credentials.
dispatch = row.get('dispatch')
if not valid_effects_binding(row):
raise RuntimeError('sync reprocessing requires a complete worker binding')
assert isinstance(dispatch, dict)
handler = dispatch['handler']
if not (
handler.endswith('/v2/sync-jobs/run')
or row.get('effects_only')
and handler.endswith('/v1/conversation-finalization-jobs/run')
):
raise RuntimeError('sync reprocessing requires the sync worker handler binding')
from utils.conversations.demand_processing import schedule

document_id = row.get('document_id') or key(row['uid'], row['conversation_id'])
payload = {'kind': 'sync_reprocess', 'key': document_id, 'task_token': row['task_token']}
name = _task_name(row)

first_summary = first_summary_pending(row)
if not first_summary and schedule(
row['uid'],
document_id,
payload,
dispatch,
name,
not_before=row['due_at'],
effects_only=bool(row.get('effects_only')),
immediate=bool(row.get('immediate')),
):
return
from config.demand_processing import enabled

eager_recovery = bool(row.get('effects_only')) and enabled(row['uid'])
enqueue_named_task(
dispatch['queue'],
handler,
name,
payload,
audience=dispatch['audience'],
invoker_sa=dispatch['invoker_sa'],
schedule_at=math.ceil(time.time() if eager_recovery else row['due_at']),
)


def mark(
uid: str,
conversation_id: str,
language: str,
*,
now: float | None = None,
mutate: Callable | None = None,
effects_only: bool = False,
) -> None:
"""Record one enrichment obligation.

Projection may inject a transactional mutation to commit its replay receipt
and privacy fences with this obligation. The default retains the normal
CAS path; both paths enqueue only after durable persistence.
"""
if mutate is not None and not owns_runtime():
raise RuntimeError('sync reprocess projection requires production or a Firestore emulator')
current = time.time() if now is None else now

def update(old: Row | None) -> tuple[Row, tuple[Row, bool]]:
if old and old.get('summary_blocked_reason') == EMPTY_BLOCKED_REASON:
return old, ({**old, '_wake': False}, True)
row = dict(old or {})
row.pop('_wake', None) # Dispatch intent belongs to this CAS result, not its persisted replay.
row.update(
document_id=key(uid, conversation_id + ('\0effects' if effects_only else '')),
uid=uid,
conversation_id=conversation_id,
language=language,
version=row.get('version', 0) + 1,
due_at=max(row.get('due_at') or 0, current + settle_seconds()),
)
# Timestamp every durable obligation, even before rollout. Neither an
# append nor a retry owns the original acceptance time.
row['first_pending_at'] = current if old and old.get('dormant') else row.get('first_pending_at', current)
row['dormant'] = False
row['summary_repair'] = False
row['effects_only'] = effects_only

if first_summary_pending(row):
row['summary_deadline_at'] = min(
row.get('summary_deadline_at', float('inf')),
row['first_pending_at'] + deadline_seconds(),
)
row['due_at'] = min(row['due_at'], row['summary_deadline_at'])
from config.demand_processing import enabled

demand_enabled = enabled(uid)
if demand_enabled or revision_reuse():
# Keep demand's processing headroom when both policies are enabled;
# revision reuse alone retains its upstream one-hour ceiling.
row['first_pending_at'] = row.get('first_pending_at', current)
ceiling = 3540 if demand_enabled else 3600
row['due_at'] = min(row['due_at'], row['first_pending_at'] + ceiling)

row.setdefault('summary_lane', 'batch' if mutate is not None else summary_delivery.lane({}))
if old is None:
row.update(
task_token=uuid.uuid4().hex, task_due_at=row['due_at'], lease_until=0, dispatch=_dispatch_binding()
)
elif old.get('dormant'):
row['dispatch'] = _dispatch_binding()
elif not valid_dispatch_binding(row.get('dispatch')):
row['dispatch'] = None
wake = old is None
if old is not None and (old.get('dormant') or (row.get('task_due_at') or 0) > row['due_at']):
row.update(task_token=uuid.uuid4().hex, task_due_at=row['due_at'])
wake = True
return row, ({**row, '_wake': wake}, old is not None)

document_id = key(uid, conversation_id + ('\0effects' if effects_only else ''))
row, coalesced = (mutate or _mutate)(document_id, update)
if coalesced:
COALESCED.inc()
if row.get('_wake', not coalesced) and valid_dispatch_binding(row.get('dispatch')):
_enqueue(row) # Failure leaves the obligation durable for the sweep.
elif not valid_dispatch_binding(row.get('dispatch')):
UNBOUND.labels(action='mark').inc()


@contextmanager
def _heartbeat(document_id: str, task_token: str, owner: str, context: Row) -> Iterator[None]:
"""Renew only this request's owner/token, stopping when the request exits.

This scoped daemon does only a bounded CAS heartbeat, never model work.
A lost owner cannot resurrect its lease; an in-flight RPC on shutdown also
checks the stop event inside its CAS before writing.
"""
stopped = threading.Event()

def renew() -> None:
while not stopped.wait(FIRST_SUMMARY_HEARTBEAT_SECONDS):

def update(old: Row | None) -> tuple[Row | None, bool]:
if (
stopped.is_set()
or old is None
or old.get('dormant')
or old.get('owner') != owner
or old.get('task_token') != task_token
):
return old, False
expiry = time.time() + FIRST_SUMMARY_LEASE_SECONDS
context['lease_until'] = expiry
return {**old, 'lease_until': expiry}, True

try:
if not _mutate(document_id, update):
return
except Exception as error:
logger.warning('event=summary_heartbeat outcome=error exception_type=%s', type(error).__name__)

worker = threading.Thread(target=renew, name='first-summary-heartbeat', daemon=True)
worker.start()
try:
yield
finally:
stopped.set()
worker.join(timeout=2)


def run(document_id: str, task_token: str, process: Callable[[str, str, str], Any], *, now: float | None = None) -> str:
current = time.time() if now is None else now
from utils.conversations.demand_processing import admit
from config.demand_processing import enabled

if not admit(document_id, now=current, token=task_token):
return 'priority_wait'
owner = uuid.uuid4().hex

def claim(old: Row | None) -> tuple[Row | None, tuple[str, Row | None]]:
if old is None or old.get('dormant') or old['task_token'] != task_token:
return old, ('stale', None)
if old.get('lease_until', 0) > current:
return old, ('busy', None)
row = dict(old)
if row['due_at'] > current and (not row.get('effects_only') or not enabled(row['uid'])):
row.update(task_token=uuid.uuid4().hex, task_due_at=row['due_at'])
return row, ('deferred', row)

first_summary = first_summary_pending(row)
lease_seconds = FIRST_SUMMARY_LEASE_SECONDS if first_summary else LEASE_SECONDS
row.update(lease_until=current + lease_seconds, owner=owner)
return row, ('claimed', row)

status, row = _mutate(document_id, claim)
if status == 'deferred':
assert row is not None
_enqueue(row)
return status
if status != 'claimed':
return status
assert row is not None
# Exceptions leave a leased, dirty row. Retry/sweep recovers after expiry.
summary_policy = summary_enabled(row['uid'], include_admitted_context=False) or preserves_admitted(row)
summary_seen = False
superseded = False
retry_revision = None
empty_blocked = False
process_context = None
if row.get('effects_only'):
from utils.conversations.lazy_enrichment import enrich_settled

enrich_settled(row['uid'], row['conversation_id'], row['language'])
else:

lane_token = summary_delivery.LANE_CONTEXT.set(
row.get('summary_lane')
or (
'backfill' if (row.get('dispatch') or {}).get('queue') == 'sync-backfill' else summary_delivery.lane({})
)
)
process_context = (
{'owner': owner, 'lease_until': row['lease_until']}
if summary_policy and not row.get('summary_seen')
else None
)
process_token = summary_delivery.PROCESS_CONTEXT.set(process_context)
accept_token = summary_delivery.ACCEPT_CONTEXT.set(row.get('first_pending_at'))
context_token = summary_delivery.REPAIR_CONTEXT.set(row if row.get('summary_repair') else None)
admitted_token = ADMITTED_OWNER.set(row['uid'] if preserves_admitted(row) else None)
try:
with _heartbeat(document_id, task_token, owner, process_context) if process_context else nullcontext():
output = process(row['uid'], row['conversation_id'], row['language'])
if summary_policy:
summary_seen = output is not None and summary_delivery.present(
summary_delivery.field(output, 'structured')
)
discarded = (output is not None and summary_delivery.field(output, 'discarded', False)) or (
preserves_admitted(row) and bool(process_context and process_context.get('discarded'))
)
blocked = bool(process_context and process_context.get('blocked_reason'))
custody = bool(
process_context and (process_context.get('redirect_to') or process_context.get('defer_reason'))
)
if output is None and preserves_admitted(row) and not discarded and not blocked and not custody:
raise FirstSummaryCallbackPending('first-summary callback has no output yet')
if output is not None and not summary_seen and not discarded and not blocked:
raise summary_delivery.SummaryOutputUnavailable('first-summary output is empty')
except summary_delivery.SummaryRepairSuperseded as error:
output = None
superseded = True
retry_revision = error.retry_revision
except summary_delivery.SummaryOutputUnavailable:
if not process_context or not record_empty_failure(
get_firestore_client(), COLLECTION, document_id, owner, task_token
):
raise
empty_blocked = True
finally:
ADMITTED_OWNER.reset(admitted_token)
summary_delivery.REPAIR_CONTEXT.reset(context_token)
summary_delivery.LANE_CONTEXT.reset(lane_token)
summary_delivery.ACCEPT_CONTEXT.reset(accept_token)
summary_delivery.PROCESS_CONTEXT.reset(process_token)

if empty_blocked:
return 'blocked'

if process_context and process_context.get('redirect_to'):
from utils.sync.enrichment_custody import transfer_redirect

pending = transfer_redirect(document_id, task_token, owner, process_context['redirect_to'], now=current)
if pending is not None:
_enqueue(pending) # Transactional custody survives a lost enqueue acknowledgement.
return 'redirected'

if process_context and process_context.get('defer_reason'):

def defer(old: Row | None) -> tuple[Row | None, Row | None]:
if old is None or old.get('owner') != owner or old.get('task_token') != task_token:
return old, None
pending = dict(old)
pending.update(
deferred_reason=process_context['defer_reason'],
due_at=current + LIVE_DEFER_SECONDS,
task_due_at=current + LIVE_DEFER_SECONDS,
task_token=uuid.uuid4().hex,
lease_until=0,
owner=None,
wake_check_after=current + LIVE_DEFER_SECONDS,
)
# Scheduling is deferred; the original admitted deadline is not.
return pending, pending

pending = _mutate(document_id, defer)
if pending is not None:
_enqueue(pending)
return 'deferred'

def finish(old: Row | None) -> tuple[Row | None, Row | None]:
if old is None or old.get('owner') != owner:
return old, None

if superseded and retry_revision is not None:
# An append may precede the repair claim without another outbox
# mark/version bump. Keep that obligation and refresh its fence.
pending = dict(old)
pending.update(
summary_repair=True,
summary_expected_revision=retry_revision,
lease_until=0,
task_token=uuid.uuid4().hex,
task_due_at=min(current, pending['due_at']),
due_at=min(current, pending['due_at']),
)
return pending, pending

if old['version'] == row['version']:
if summary_policy and summary_seen:
# Retain only scheduling metadata as the first-summary receipt.
# Future revisions keep their trailing-edge coalescing policy.
settled = dict(old)
settled.update(
summary_seen=True,
dormant=True,
due_at=None,
lease_until=0,
uid=None,
conversation_id=None,
language=None,
dispatch=None,
summary_repair=False,
summary_expected_revision=None,
)
return settled, None
return None, None
pending = dict(old)
if summary_seen and summary_policy:
pending['summary_seen'] = True
pending['first_pending_at'] = current
pending['summary_repair'] = False
pending['summary_expected_revision'] = None
pending['due_at'] = max(current, pending['first_pending_at']) + settle_seconds()
pending.update(
lease_until=0,
task_token=uuid.uuid4().hex,
task_due_at=pending['due_at'],
)
return pending, pending

pending = _mutate(document_id, finish)
if pending is not None:
_enqueue(pending)
return 'superseded' if superseded else 'processed'


def sweep(*, now: float | None = None, limit: int = 100) -> dict[str, int]:
from utils.sync import enrichment_scan

current = time.time() if now is None else now
counts = {'repaired': 0, 'error': 0}
if not owns_runtime():
return counts

binding = _dispatch_binding()
limit = max(1, min(100, limit))
client = get_firestore_client()
# One range/order field uses the automatic single-field index.
previous, cursor = enrichment_scan.begin(client, COLLECTION)
query = (
client.collection(COLLECTION)
.where('due_at', '<=', current)
.order_by('due_at')
.order_by('__name__')
.limit(limit)
)
exhausted = False

def due_snapshots():
nonlocal exhausted
page_query = query.start_after(cursor) if cursor else query
# Pending valid wakes at the front must not hide missing wakes behind
# them. Bound both scanning and external task probes independently.
for _ in range(10):
page = list(page_query.stream())
yield from page
if len(page) < limit:
exhausted = True
return
page_query = query.start_after(page[-1])

checked = 0
check_started = monotonic()
last = None
for snapshot in due_snapshots():
if monotonic() - check_started >= 10:
break
last = snapshot

def repair(old: Row | None) -> tuple[Row | None, tuple[str, Row | None]]:
if old is None or old.get('dormant') or old.get('lease_until', 0) > current:
return old, ('skipped', None)
row = dict(old)
if row.get('wake_check_after', 0) > current:
return old, ('skipped', None)
if not valid_effects_binding(row):
if binding is None:
return old, ('unbound', None)
# Claim and fence the repaired binding in the same CAS. Any old
# task delivery becomes stale; valid backfill bindings stay put.
row.update(dispatch=binding, task_token=uuid.uuid4().hex, task_due_at=current)

row['wake_check_after'] = current + WAKE_CHECK_SECONDS
if first_summary_pending(row):
# Probe outside CAS, then recheck the exact name under CAS below.
return row, ('check', row)
if row['task_due_at'] + REPAIR_SECONDS <= current:
row.update(task_token=uuid.uuid4().hex, task_due_at=current)
return row, ('ready', row)

try:
status, row = _mutate(snapshot.id, repair)
if status == 'check' and row is not None:
checked += 1
if _wake_exists(row):
if checked >= limit:
break
continue
checked_name = _task_name(row)

def replace(old: Row | None) -> tuple[Row | None, Row | None]:
if (
old is None
or old.get('dormant')
or old.get('lease_until', 0) > current
or _task_name(old) != checked_name
):
return old, None
replacement = dict(old)
# Absence includes an exhausted/deleted task's name tombstone.
replacement.update(task_token=uuid.uuid4().hex, task_due_at=current)
replacement.pop('wake_generation', None)
return replacement, replacement

row = _mutate(snapshot.id, replace)
if status == 'unbound':
UNBOUND.labels(action='repair').inc()
if row is not None:
_enqueue(row)
counts['repaired'] += 1
except Exception as error:
counts['error'] += 1
logger.error('event=sync_reprocess action=repair outcome=error exception_type=%s', type(error).__name__)
if checked >= limit:
break
enrichment_scan.finish(previous, last, exhausted)
return counts


def mark_effects(uid: str, conversation_id: str, language: str, *, immediate: bool = False) -> None:
"""Blind-write lazy debt: no extra Firestore read on visible completion.

Increment preserves concurrent dirtying; merge preserves an active worker's
lease. The existing CAS completion sees that increment and retains the debt.
Token changes fence older deliveries; all effects read the settled row.
"""
if not owns_runtime():
raise RuntimeError('lazy enrichment requires production or a Firestore emulator')
current = time.time()
# Preserve the daytime merge window as far as the hard completion ceiling
# permits; open/explicit demand still bypasses this closed-surface wait.
quiet_seconds = 3540
document_id = key(uid, conversation_id + '\0effects')
row = dict(
document_id=document_id,
uid=uid,
conversation_id=conversation_id,
language=language,
effects_only=True,
immediate=immediate,
task_token=uuid.uuid4().hex,
due_at=current + quiet_seconds,
task_due_at=current + quiet_seconds,
dispatch=_effects_binding(),
)
get_firestore_client().collection(COLLECTION).document(document_id).set(
{**row, 'version': firestore.Increment(1)}, merge=True
)
if valid_effects_binding(row):
_enqueue(row)
else:
# Match the sync outbox's unbound-host contract: visible work survives,
# and the configured sweep CAS-rebinds the durable obligation later.
UNBOUND.labels(action='mark').inc()


def _effects_binding() -> dict[str, str]:
binding = _dispatch_binding()
if binding is not None:
return binding
# Listen/pusher already have the durable finalization queue, identity and
# worker. Reuse that protected handler for the same sync outbox protocol.
from utils.cloud_tasks import listen_finalization_binding

return listen_finalization_binding()
sys.modules[__name__] = _module

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 Migrate callers instead of installing a module alias

This preserves the retired utils.sync.reprocess API by replacing its module object, while in-tree production callers such as services/summary_debt_repair.py, utils/batch_pipeline/serving.py, and routers/sync.py still import that path. Migrate those callers in this change and remove the alias; otherwise import and monkeypatch behavior remains dependent on which module name was loaded first, contrary to the repository's migration rule.

AGENTS.md reference: AGENTS.md:L34-L34

Useful? React with 👍 / 👎.

Comment on lines +350 to +352
if old is not None and (old.get('dormant') or (row.get('task_due_at') or 0) > row['due_at']):
row.update(task_token=uuid.uuid4().hex, task_due_at=row['due_at'])
wake = True

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 Preserve the active claim when advancing a wake

When a coalesce='min' enqueue advances the deadline while the row has a live lease, this rotates task_token but retains the current owner and lease_until. The running claim is then fenced because _holds requires its old wake token, while the newly created delivery sees the retained lease and returns BUSY as a consumed response; even a successful worker therefore cannot settle the row, and processing stalls until the lease expires and the sweep revisits it. Avoid rotating the wake token under a live lease and let the current claim's version-aware acknowledgment re-arm the row.

Useful? React with 👍 / 👎.

Comment on lines +98 to +100
conversation_id, language = payload['conversation_id'], payload['language']
effects_only = bool(payload.get('effects_only'))
if dedupe_key != outbox.key(owner_id, conversation_id + ('\0effects' if effects_only else '')):

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 Persist the immediate scheduling flag

When an enrichment caller enqueues an effects-only payload with immediate=True, this extracts only effects_only, and mark_update has no way to persist immediate. Although the implementation explicitly includes immediate in claim payloads and _enqueue reads it to force demand scheduling into the eager tier, the stored row always loses the flag, so explicitly demanded effects can still wait for the normal quiet-window schedule.

Useful? React with 👍 / 👎.

# writer owns the conversation and marks its own obligation. The outbox settles this claim
# as superseded (re-armed when the version moved, retired otherwise) instead of retrying.
logger.info('event=sync_reprocess outcome=conversation_fenced')
raise SummaryRepairSuperseded('conversation persistence fenced') from 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.

P1 Badge Retry lease-expiry fences instead of retiring the row

When SyncConversationPersistenceFenced is raised because claim_from_snapshot returns false solely after PROCESS_CONTEXT.lease_until expires, this converts the retryable lease failure into SummaryRepairSuperseded without a retry revision. reprocess.run then deletes the outbox row when its version is unchanged, even though no newer writer or mark exists, permanently dropping the enrichment obligation; distinguish lease/CAS failures from proven supersession or leave the unchanged row retryable.

Useful? React with 👍 / 👎.

Git-on-my-level and others added 5 commits October 19, 2026 15:04
…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]>

@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: 1beb82b756

ℹ️ 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 +101 to +102
if self._privacy_blocked is not None:
return self._privacy_blocked(row_id)

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 Delete rows rejected by injected privacy checks

When a factory caller supplies the supported privacy_blocked predicate, this branch only returns its result. claim_key then reports DISCARDED and the push delivery is acknowledged, while sweep merely increments its discarded count; neither path removes the durable row, so its owner and conversation metadata remain indefinitely and every later sweep repeats the same check. Close the row with a fenced mutation when the injected predicate fires.

Useful? React with 👍 / 👎.

from utils.sync import reprocess
from utils.conversations.summary_delivery import SummaryRepairSuperseded
from utils.enrichment import outbox as reprocess
from utils.enrichment.custody import discard_blocked

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 Retarget the remaining emulator monkeypatches

After moving discard_blocked into utils.enrichment.custody, this module no longer defines get_firestore_client, but both test_completed_receipt_old_wake_acks_without_null_owner_privacy_error and test_loopback_http_acks_redirect_deferred_busy_and_real_deletion still call monkeypatch.setattr(enrichment, 'get_firestore_client', ...) with the default raising=True. Those emulator tests now fail immediately with AttributeError before exercising their custody and route assertions, so retarget the patches to the new owning module; integration tests are not covered by selector auto-discovery.

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

Useful? React with 👍 / 👎.

Comment on lines +330 to +331
return SweepCounts(
rewoken=counts['repaired'], expired_leases=0, discarded=counts.get('discarded', 0), errors=counts['error']

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 Count expired leases recovered by the sweep

When the watchdog encounters a row whose nonzero lease_until has expired, the underlying sweep re-wakes that row, but this adapter always reports expired_leases=0. Consumers of the new SweepCounts contract therefore cannot detect lease-expiry recovery even while it is occurring, making the exported recovery telemetry inaccurate; track expired rows separately in the underlying sweep and return that count here.

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: d41d89835d

ℹ️ 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 +103 to +105
from utils.enrichment.custody import discard_blocked

return discard_blocked(row_id)

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 Keep privacy checks on the bound Firestore client

When FirestoreOutbox(..., client=client) is created without an explicit privacy_blocked callback, _blocked delegates to custody.discard_blocked, which resolves the global Firestore client even though the due query and all subsequent mutations use the bound client. In emulator or alternate-project use, a claim can therefore inspect or delete a same-ID row in the wrong database, or allow a privacy-fenced row from the bound database; pass the bound client through the default discard path as well.

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

Useful? React with 👍 / 👎.

@@ -294,14 +359,7 @@ def update(old: Row | None) -> tuple[Row, tuple[Row, bool]]:
wake = True
return row, ({**row, '_wake': wake}, old is not 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 Report reactivated receipts as new obligations

When a completed first-summary obligation leaves a dormant receipt, the next enqueue reactivates it and creates a new wake, but this expression still returns coalesced=True solely because a document existed. That contradicts EnqueueResult.coalesced, which is defined as an already-open row, increments the coalescing metric for a new obligation, and can cause generic callers to skip new-obligation handling; base the result on whether the old row was open rather than merely present.

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit 25559f9 into integration/legacy-retire Oct 19, 2026
24 checks passed
@Git-on-my-level
Git-on-my-level deleted the lr/09-outbox branch October 19, 2026 09:12
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