Skip to content

fix: recover reset-clock sync uploads with receipt time - #24501

Merged
Git-on-my-level merged 19 commits into
mainfrom
lane/earlyclamp
Nov 3, 2026
Merged

Git-on-my-level merged 19 commits into
mainfrom
lane/earlyclamp

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Well-formed sync files dated 1995 by a reset pendant clock used to fail with a terminal 400 invalid_capture_time. V2 now admits these files by default and packs their stored time bounds in raw-file order, ending at server receipt time. Audio duration is preserved; bogus wall-clock gaps are discarded, including batches containing different reset years. Early and normal clocks stay in separate units, and untrusted client time bounds do not drive session lookup. Raw filenames remain the content, chunk and retry identity. Both batch and legacy sync paths consume the receipt clock; untrusted uploads retain backfill pacing. Valid historical siblings still obey lookback limits.

Coverage derivatives retain their original source clock, including repeated trimming across the date floor. Full and late cap holds preserve normalized offsets through manifest dates, frozen recovery pieces, lineage and held-to-batch decoding. Raw hold identity remains stable. Receipt metadata is early-only and optional in the shared durable task schema, with a real enqueue regression.

SYNC_EARLY_CAPTURE_CLAMP_ENABLED=false restores early-stamp rejection. Already admitted retained work keeps its frozen normalization. Malformed stamps, future-skew policy and deprecated V1 admission remain unchanged. Adds the closed accepted_early_clamped outcome to the existing capture-time counter and a content-free structured log. No client or workflow change. The flag has an owned budget exception with review due 2026-11-17, tracked on card:earlyclamp#early-capture-clamp-review; the seeded budget is unchanged.

Validation: source/order shard 537 PASS, main-integration shard 193 PASS, held-to-batch shard 125 PASS; focused production type checks report zero errors. After the latest main integration, 447 targeted tests PASS, including the corrected timestamped HTTP fixture and 205 listen-finalization tests under the unchanged timing guard. These contract shards run through backend/test.sh across capture-clock, batch audio/intake, source coverage, v2 coordinator, pull-worker, cap retention/recovery, closed labels and real durable enqueue. Coverage includes typed kill-switch 400, malformed/future stamps, raw-name duplicate retry, persisted legacy bounds, PCM/source ordering, mixed reset years, repeated trimming across the floor, frozen receipt propagation and retained replay after admission is disabled. Repository gates run through the unchanged singleflight pre-push hook; final results are recorded with the exact candidate head in the lane report and CI.

Read-only Luna review returned SHIP at caab333. All 19 authored production Python paths are unchanged since that review; the lead reviews the subsequent two-line fixture correction and flag-count integration, per the 17:05Z review-cap ruling. Exact-head CI remains required.

Published candidate: 9dc3abc01825c538fb4a6e931dd9c6ac22359c82. The normal pre-push gate passed with zero backend type errors and 720 selected unit tests; all six CI unit shards, guardrails and the aggregate unit suite are green (unit run). Both attempts of the hermetic run stopped at Checkout code before scenarios. The lead has authorized merging past this shared checkout infrastructure failure once every non-hermetic check is green on this exact head; only the lead merges. Workflow repair #24528 is separate and approval-gated. OpenAPI and Repo Checks each have one checkout retry in progress. No test assertion, timing guard or workflow was changed by this PR.

Local hermetic gauntlet: two attempts stopped before their first scenario at the fixed admission (45s) and worker (120s) startup deadlines on the overloaded shared Mac; a remaining worker was stopped by exact PID group. Lead ruling ea4bf0 at 2026-11-03 09:34Z permits unit+label guards locally and requires CI hermetic e2e before handoff. No harness assertion/deadline or pre-push hook was bypassed or changed.

Deploy: lead-owned backend/backend-sync Cloud Run train, including backend-sync-backfill and the backend-sync-backfill-worker pull role registered under gcp_backend.yml. Update processing roles before admission services: old processors ignore receipt metadata and would retain raw reset-clock times for newly accepted jobs. Observe omi_sync_capture_time_total{outcome="accepted_early_clamped"}. Existing refused uploads have no server-staged copy; recovery needs a client retry, and clients with the broken Retry button need an app update.

Product invariants: INV-DATA-1 — no data-plane identity or access changes; no production account data read or written during development. Capture identity remains raw while stored clock normalization uses the upload receipt.

Failure-Class: FC-closed-payload-schema-misses-producer-field
Failure-Class-Reason: The admission change adds a conditional durable field. The shared optional-key schema and the existing real enqueue guard evolve together; old payloads remain valid. The reset-clock policy itself is new, and existing future-skew policy is unchanged.

Tracking: https://anx.scalingforever.com/o/david-zhang/w/omi/r/card:earlyclamp

Line-Count-Exception: backend/utils/sync/pipeline.py | 3967 -> 4061 | Carry admitted receipt time and original source ordering through VAD, normalized spans, retained recovery and closed telemetry while keeping raw identity at the existing composition seam.
Line-Count-Exception: backend/routers/sync.py | 3738 -> 3757 | Carry an early-only receipt anchor across dispatch paths and omit reset-clock session bounds from temporal lookup.

Preserve raw filename identity and capture order while normalizing admitted
pre-2024 captures for both legacy sync and batch processing.
Preserve raw filename identity and capture order while normalizing admitted
pre-2024 captures for both legacy sync and batch processing.
Preserve raw filename identity and capture order while normalizing admitted
pre-2024 captures for both legacy sync and batch processing.
Preserve raw filename identity and capture order while normalizing admitted
pre-2024 captures for both legacy sync and batch processing.
Preserve raw filename identity and capture order while normalizing admitted
pre-2024 captures for both legacy sync and batch processing.
Preserve raw filename identity and capture order while normalizing admitted
pre-2024 captures for both legacy sync and batch processing.
Preserve raw filename identity and capture order while normalizing admitted
pre-2024 captures for both legacy sync and batch processing.
Preserve raw filename identity and capture order while normalizing admitted
pre-2024 captures for both legacy sync and batch processing.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-11-03T12:20:25.315897Z
We couldn’t complete this review. Comment @codex review to try again.
7d89bfb PR opened
ℹ️ About Codex in GitHub

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

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

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

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@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.

9 issues found across 20 files

Confidence score: 2/5

  • backend/routers/sync.py adds capture_received_at to upload tasks, but the durable task schema rejects it, so uploads cannot dispatch. Add the field to the schema.
  • backend/utils/batch_pipeline/intake.py and projection derive different IDs for reset-clock units, which can leave the same capture mismatched across those paths. Align the identity calculation.
  • backend/utils/sync/capture_clock.py defaults allow_early_clamp to true, so callers that do not opt out now accept pre-2024 stamps. Verify that permissive behavior is intended for every caller.
  • backend/utils/batch_pipeline/capture_decode.py skips the receipt anchor for pre-2024 files when received_at is missing, retaining their reset-clock timestamps and bogus gaps. Reject that case or otherwise avoid silently keeping those timestamps.
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/utils/request_validation.py">

<violation number="1" location="backend/utils/request_validation.py:109">
P3: This docstring implies that with the early-clamp switch off, pre-2024 stamps are kept and stored raw. They are actually rejected at admission (`REJECTED_EARLY`). Name the rejection explicitly, e.g. 'pre-2024 values are admitted for receipt-time normalization, or rejected when the early-clamp switch is off.'</violation>
</file>

<file name="backend/docs/listen_pusher_pipeline.mdx">

<violation number="1" location="backend/docs/listen_pusher_pipeline.mdx:6263">
P2: This paragraph documents receipt-time metadata in durable payloads, but not the rollout constraint that goes with it. Add that processing roles (backend-sync and the backfill worker) must deploy before admission services, since older processors ignore receipt metadata and would keep reset-clock times.</violation>
</file>

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

<violation number="1" location="backend/docs/feature-flag-registry.md:617">
P2: This flag is not registered in `backend/config/flag_budget.json`, so the `utils/sync/**` budget test will fail for the new `os.getenv` read in `capture_clock.py`. Add an entry such as `"SYNC_EARLY_CAPTURE_CLAMP_ENABLED": {"owner": "dazheng", "review_by": "..."}` to `names`. The doc row itself is consistent with `config/feature-flags.yaml`.</violation>
</file>

<file name="backend/utils/batch_pipeline/capture_decode.py">

<violation number="1" location="backend/utils/batch_pipeline/capture_decode.py:59">
P2: When `received_at` is None, pre-2024 files skip the receipt anchor and keep their reset-clock `capture_at`, so the bogus gaps and years are silently retained. Consider raising `ValueError` when an early path is present without `received_at`, so the decoder fails closed instead of falling back to raw clocks.</violation>

<violation number="2" location="backend/utils/batch_pipeline/capture_decode.py:77">
P3: Early-clock files are fully decoded twice: once in the `early_frames` pre-pass and again in the packing loop. Consider recording per-path canonical lengths in the first pass, or otherwise avoiding the second `_canonical` decode for early paths, so large reset-clock uploads do not double CPU work.</violation>
</file>

<file name="backend/utils/sync/capture_clock.py">

<violation number="1" location="backend/utils/sync/capture_clock.py:43">
P2: This kill switch will not turn off for a whitespace-padded value like `'false '`. Add `.strip()` to match the other kill switches in this package.</violation>

<violation number="2" location="backend/utils/sync/capture_clock.py:73">
P2: The new `allow_early_clamp: bool = True` default admits pre-2024 stamps for every caller that does not opt out. `safety_wal_coverage._materialize` (line 124) passes `future_skew_seconds=0` to keep a strict contract, but now accepts reset-clock derivatives instead of abstaining. Default to `False` and have the V2 admission callers opt in explicitly.</violation>
</file>

<file name="backend/routers/sync.py">

<violation number="1" location="backend/routers/sync.py:941">
P1: Cloud Tasks uploads now include `capture_received_at`, but the durable task schema does not allow that key, so `enqueue_sync_job` rejects the payload and the upload cannot dispatch. Add `capture_received_at` to `SYNC_JOB_TASK_PAYLOAD_KEYS` and its schema fixtures.</violation>
</file>

<file name="backend/utils/batch_pipeline/intake.py">

<violation number="1" location="backend/utils/batch_pipeline/intake.py:689">
P1: This receipt-time assignment makes reset-clock units use different identities across intake and projection: intake retains the raw timestamp in `conversation_id`, while projection derives the persisted ID and privacy fence from `item.capture_at`. Carry the raw filename-derived chunk identity through projection and use it for identity/privacy, while retaining the receipt-time value only for temporal bounds.</violation>
</file>

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

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

Comment thread backend/routers/sync.py Resolved
seed,
segment_id=hashlib.sha256(f'{content_id}:{index}'.encode()).hexdigest(),
capture_at=unit.capture_at,
capture_at=(

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: This receipt-time assignment makes reset-clock units use different identities across intake and projection: intake retains the raw timestamp in conversation_id, while projection derives the persisted ID and privacy fence from item.capture_at. Carry the raw filename-derived chunk identity through projection and use it for identity/privacy, while retaining the receipt-time value only for temporal bounds.

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/batch_pipeline/intake.py, line 689:

<comment>This receipt-time assignment makes reset-clock units use different identities across intake and projection: intake retains the raw timestamp in `conversation_id`, while projection derives the persisted ID and privacy fence from `item.capture_at`. Carry the raw filename-derived chunk identity through projection and use it for identity/privacy, while retaining the receipt-time value only for temporal bounds.</comment>

<file context>
@@ -686,7 +686,9 @@ def unit_item(unit, index):
                 seed,
                 segment_id=hashlib.sha256(f'{content_id}:{index}'.encode()).hexdigest(),
-                capture_at=unit.capture_at,
+                capture_at=(
+                    unit.stored_capture_at if getattr(unit, 'stored_capture_at', None) is not None else unit.capture_at
+                ),
</file context>

Comment thread backend/docs/listen_pusher_pipeline.mdx Resolved
Comment thread backend/docs/feature-flag-registry.md Resolved
*,
max_seconds: float = 3600,
coverage_context: dict | None = None,
received_at: float | None = 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: When received_at is None, pre-2024 files skip the receipt anchor and keep their reset-clock capture_at, so the bogus gaps and years are silently retained. Consider raising ValueError when an early path is present without received_at, so the decoder fails closed instead of falling back to raw clocks.

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/batch_pipeline/capture_decode.py, line 59:

<comment>When `received_at` is None, pre-2024 files skip the receipt anchor and keep their reset-clock `capture_at`, so the bogus gaps and years are silently retained. Consider raising `ValueError` when an early path is present without `received_at`, so the decoder fails closed instead of falling back to raw clocks.</comment>

<file context>
@@ -50,7 +52,11 @@ def _canonical(path: str) -> bytes:
+    *,
+    max_seconds: float = 3600,
+    coverage_context: dict | None = None,
+    received_at: float | None = None,
 ) -> Generator[AudioUnit, None, None]:
     unit_frames = min(UNIT_FRAMES, int(max_seconds * RATE))
</file context>



def early_capture_clamp_enabled() -> bool:
return os.getenv('SYNC_EARLY_CAPTURE_CLAMP_ENABLED', 'true').lower() != 'false'

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 kill switch will not turn off for a whitespace-padded value like 'false '. Add .strip() to match the other kill switches in this package.

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/sync/capture_clock.py, line 43:

<comment>This kill switch will not turn off for a whitespace-padded value like `'false '`. Add `.strip()` to match the other kill switches in this package.</comment>

<file context>
@@ -39,12 +39,43 @@ def maximum_future_skew_seconds() -> int:
 
 
+def early_capture_clamp_enabled() -> bool:
+    return os.getenv('SYNC_EARLY_CAPTURE_CLAMP_ENABLED', 'true').lower() != 'false'
+
+
</file context>
Suggested change
return os.getenv('SYNC_EARLY_CAPTURE_CLAMP_ENABLED', 'true').lower() != 'false'
return os.getenv('SYNC_EARLY_CAPTURE_CLAMP_ENABLED', 'true').strip().lower() != 'false'

*,
now: Optional[datetime] = None,
future_skew_seconds: Optional[int] = None,
allow_early_clamp: bool = 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.

P2: The new allow_early_clamp: bool = True default admits pre-2024 stamps for every caller that does not opt out. safety_wal_coverage._materialize (line 124) passes future_skew_seconds=0 to keep a strict contract, but now accepts reset-clock derivatives instead of abstaining. Default to False and have the V2 admission callers opt in explicitly.

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/sync/capture_clock.py, line 73:

<comment>The new `allow_early_clamp: bool = True` default admits pre-2024 stamps for every caller that does not opt out. `safety_wal_coverage._materialize` (line 124) passes `future_skew_seconds=0` to keep a strict contract, but now accepts reset-clock derivatives instead of abstaining. Default to `False` and have the V2 admission callers opt in explicitly.</comment>

<file context>
@@ -39,12 +39,43 @@ def maximum_future_skew_seconds() -> int:
+    *,
+    now: Optional[datetime] = None,
+    future_skew_seconds: Optional[int] = None,
+    allow_early_clamp: bool = True,
 ) -> Optional[SyncCaptureTimeReason]:
     """The closed rejection reason for an implausible capture time, else ``None``.
</file context>

the shared future-skew tolerance (utils.sync.capture_clock); beyond it or
before 2024-01-01 the timestamp is implausible and rejected.
malformed values are rejected. Pre-2024 values keep their raw identity;
storage normalizes them to receipt time unless the early-clamp switch is off.

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 docstring implies that with the early-clamp switch off, pre-2024 stamps are kept and stored raw. They are actually rejected at admission (REJECTED_EARLY). Name the rejection explicitly, e.g. 'pre-2024 values are admitted for receipt-time normalization, or rejected when the early-clamp switch is off.'

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/request_validation.py, line 109:

<comment>This docstring implies that with the early-clamp switch off, pre-2024 stamps are kept and stored raw. They are actually rejected at admission (`REJECTED_EARLY`). Name the rejection explicitly, e.g. 'pre-2024 values are admitted for receipt-time normalization, or rejected when the early-clamp switch is off.'</comment>

<file context>
@@ -105,7 +105,8 @@ def parse_sync_filename_timestamp(path: str, *, enforce_window: bool = True) ->
     the shared future-skew tolerance (utils.sync.capture_clock); beyond it or
-    before 2024-01-01 the timestamp is implausible and rejected.
+    malformed values are rejected. Pre-2024 values keep their raw identity;
+    storage normalizes them to receipt time unless the early-clamp switch is off.
 
     ``enforce_window=False`` skips the plausibility window for internal
</file context>
Suggested change
storage normalizes them to receipt time unless the early-clamp switch is off.
storage normalizes them to receipt time while SYNC_EARLY_CAPTURE_CLAMP_ENABLED is on; with it off they are rejected as early.

wavs, source_maps, generated = prepare((coverage_context or {}).get('uid'), wavs, frames, coverage_context)
# Count canonical samples before streaming the units. Untrusted clock
# gaps cannot place siblings years before receipt or overlap them.
early_frames = sum(

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: Early-clock files are fully decoded twice: once in the early_frames pre-pass and again in the packing loop. Consider recording per-path canonical lengths in the first pass, or otherwise avoiding the second _canonical decode for early paths, so large reset-clock uploads do not double CPU work.

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/batch_pipeline/capture_decode.py, line 77:

<comment>Early-clock files are fully decoded twice: once in the `early_frames` pre-pass and again in the packing loop. Consider recording per-path canonical lengths in the first pass, or otherwise avoiding the second `_canonical` decode for early paths, so large reset-clock uploads do not double CPU work.</comment>

<file context>
@@ -66,22 +72,49 @@ def decode_units(
         wavs, source_maps, generated = prepare((coverage_context or {}).get('uid'), wavs, frames, coverage_context)
+        # Count canonical samples before streaming the units. Untrusted clock
+        # gaps cannot place siblings years before receipt or overlap them.
+        early_frames = sum(
+            len(_canonical(path)) // 2
+            for path in wavs
</file context>

Keep source clock metadata through coverage derivatives and freeze normalized
offsets across cap retention and recovery. Bound storage only after admission
normalization, and register early-only receipt metadata in the shared durable
task schema. Pin trimming, retained identity, replay and real enqueue behavior.

Failure-Class: FC-closed-payload-schema-misses-producer-field
Preserve current record-drain, language-routing and seal-worker changes.
Reconcile the owned flag inventory count without changing the seeded budget.
Carry source starts through VAD and use source-first ordering for stored spans
and batch PCM. Keep endpoint and task fixtures on numeric normal clocks.
Pin the older-trimmed-tail/newer-file inversion with real source coverage.

Failure-Class: FC-closed-payload-schema-misses-producer-field
Retain upstream changes and reconcile the owned flag inventory to 235 names,
without changing the seeded budget of 169.
Carry the frozen stored capture time across legacy, source-coverage and native
held WAV decoding, while retaining raw capture identity and frame provenance.

Failure-Class: FC-closed-payload-schema-misses-producer-field
Keep the HTTP custody fixture consistent with its posted upload so receipt
classification reads an admitted timestamp rather than synthetic.bin.
Preserve the merged batch I/O and live custody work. Reconcile the combined
flag inventory at 237 names while keeping the seeded budget at 169.
The clean three-way merge combined 238 flag names but retained count237.
Record the measured count238 without changing the seeded budget169.
@Git-on-my-level
Git-on-my-level merged commit 79b94c0 into main Nov 3, 2026
70 of 87 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/earlyclamp branch November 3, 2026 22:25
Git-on-my-level added a commit that referenced this pull request Nov 4, 2026
Since #24501, sync admission parses a capture time from each staged path.
The repair-protocol fixture staged "synthetic-original", so the merged
request raised ValueError and answered 500 instead of the expected
409/410. Stage a parseable name, as main did in test_stt_cap_dispatch_http.

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