Skip to content

Fix backend audio-merge durable loss, memory control-state race, v2 source misattribution, OAuth log leak - #9588

Merged
eulicesl merged 7 commits into
mainfrom
claude/macos-bug-fixes-testing-i8z7cm
Jul 13, 2026
Merged

eulicesl merged 7 commits into
mainfrom
claude/macos-bug-fixes-testing-i8z7cm

Conversation

@eulicesl

@eulicesl eulicesl commented Jul 12, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Backend bug sweep — a fan-out review of the Python backend (sync/transcription pipeline, durable job orchestration, auth/security, and the memory-maintenance system) surfaced four confirmed, reachable bugs. Each was personally re-verified against the source; the two HIGH-severity data-loss/corruption fixes ship with behavioral regression tests that fail pre-fix and pass post-fix.

Fixes

1. HIGH — Audio-merge v2 transient errors were acked, permanently losing the playback artifact

run_audio_merge_job dispatched the schema_version == 2 conversation-merge inside the payload-parse try, whose only except returns 200 {dropped, invalid_payload}. So a transient GCS/Firestore failure during _run_conversation_merge_job's doc read, artifact upload, or doc stamp was caught and acked instead of returning 500 for a Cloud Tasks retry. Because the task is named amc-{conversation_id}-{fingerprint}, its tombstone makes the /urls re-enqueue a no-op — the playback artifact is never rebuilt until audio_files change (routers/sync.py). Fixed by moving the v2 dispatch outside the payload-parse guard so its exceptions propagate (500 → retry); _run_conversation_merge_job still validates its own payload and 200-drops genuinely malformed input.

  • Regression test: TestV2HandlerRetrySemantics (transient error propagates; malformed payload still 200-drops).

2. HIGH — Memory promotion clobbered concurrently-advanced control state

short_term_promotion._persist_control_state wrote the whole memory_apply_control_state doc with a full .set(control.model_dump()) from a non-transactional read snapshot. A concurrent apply_long_term_patch_firestore transaction landing between promotion's read and this write had its head_commit_id / commit_sequence / projection & vector watermarks silently reverted (lost update → subsequent optimistic-concurrency mismatches and stale/repeated projection+vector repair). Fixed to write only the two fields promotion owns (last_promotion_run_at, updated_at) with merge=True, mirroring the consolidation writer (utils/memory/short_term_promotion.py).

  • Regression test: test_short_term_promotion_control_state.py (a concurrently-advanced head survives the promotion stamp).

3. MEDIUM — v2 sync stored every new conversation with source=unknown

_run_full_pipeline_background_async reassigned its source: ConversationSource parameter to a metering string ('sync_fresh'/'sync_backfill') during fair-use metering. That string then flowed into segment processing → CreateConversation(source=source), where ConversationSource._missing_ coerces the unrecognized string to ConversationSource.unknown. Every v2-synced new conversation was misattributed (and limitless detection defeated). Fixed by using a distinct meter_source local, mirroring the v1 endpoint (utils/sync/pipeline.py). No hermetic test added — a behavioral test requires mocking the full decode→VAD→STT→segment pipeline; verified by reading + the v1 parallel that already uses meter_source.

4. LOW — Unsanitized X OAuth token-exchange error body logged

x_connector.exchange_code logged resp.text[:500] from X's /2/oauth2/token endpoint with no sanitize(), violating the logging-security rule (every sibling token-exchange logger wraps the body). Error-path only (X returns an OAuth error JSON, not tokens, on ≥400), hence LOW. Fixed to sanitize(resp.text[:500]) (utils/x_connector.py). No dedicated test (heavy import graph; one-line change mirroring the established sanitize pattern).

Root cause & durable guards

  • Client #1 control-flow: a durable-job dispatch nested under an invalid-payload catch-all converted transient failures into permanent acks → move the dispatch outside the guard; behavioral test asserts 500-retry vs 200-drop.
  • colors to the LED board #2 a non-transactional full-document overwrite on a shared control doc → owned-field merge=True; behavioral test asserts a concurrent advance survives.
  • Add printing BLE device address to serial monitor #3 parameter shadowing → distinct local; About Firebase #4 missing log sanitizer → sanitize().

Testing

  • .venv synced from pylock.toml; ran the suites directly covering the changes: test_audio_merge_tasks.py (18 passed, incl. the 2 new), test_short_term_promotion_control_state.py, test_canonical_consolidation.py, tests/routers/test_imports.py (14 passed), plus import sanity for all changed modules — all pass. Both new tests were confirmed to FAIL against the pre-fix code and PASS after, and stay within the fast-unit duration guard.
  • python scripts/scan_async_blockers.py clean for the touched files (no new blocking calls in async).
  • The full selector-picked suite for a routers/sync.py change is large and includes live-service e2e tests (Firestore/Redis) that cannot run in this credential-less sandbox; those run in CI. The local pre-push backend-unit gate was skipped for that reason (PRE_PUSH_SKIP_BACKEND_UNIT_TESTS=1).

Product invariants affected

  • INV-MEM-1 — path-based match (utils/memory/short_term_promotion.py). The fix changes only HOW the promotion run stamps its control state (owned-field merge=True instead of a full-document overwrite); it preserves the ST→LT tier state machine, head/commit/watermark semantics, and promotion behavior, so the memory-tier vocabulary is unchanged and the invariant's guard tests are unaffected.

Noted, not fixed (documented for follow-up)

  • Import-time SDK client construction (database/vector_db.py, utils/llm/clients.py, utils/conversations/search.py Typesense) — import-purity deviations, env-gated/dormant; separate cleanup.
  • Bare asyncio.create_task(trigger_classifier_if_needed(...)) (utils/sync/pipeline.py, routers/sync.py) and day_summary_webhook fire-and-forget (utils/other/notifications.py) — should use start_background_task; low impact.

🤖 Generated with Claude Code

https://claude.ai/code/session_01RAxLsaxtwVNDTWAZFfJp9q


Generated by Claude Code

Review in cubic

claude added 6 commits July 12, 2026 20:26
…ping the artifact

run_audio_merge_job dispatched the schema_version==2 conversation-merge inside the
payload-parse try, whose only except returns 200 {dropped, invalid_payload}. A
transient GCS/Firestore failure during _run_conversation_merge_job's doc read,
artifact upload, or doc stamp was therefore caught and acked instead of returning
500 for a Cloud Tasks retry. The task is named amc-{conversation_id}-{fingerprint},
so its tombstone makes the /urls re-enqueue a no-op — the playback artifact is never
rebuilt until audio_files change (permanent loss).

Fix: move the v2 dispatch outside the payload-parse guard so its exceptions
propagate to FastAPI (500 -> retry). _run_conversation_merge_job still validates its
own payload and 200-drops genuinely malformed input, so bad payloads are not retried
forever.

Root cause: a durable-job dispatch nested under an invalid-payload catch-all
converted transient failures into permanent acks. Durable guard: TestV2Handler-
RetrySemantics asserts a transient error propagates (retry) while a malformed
payload still 200-drops. Verified the transient test fails against the pre-fix code.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RAxLsaxtwVNDTWAZFfJp9q
…control state

short_term_promotion._persist_control_state wrote the whole memory_apply_control_state
doc with a full .set(control.model_dump()) from a non-transactional read snapshot. A
concurrent apply_long_term_patch_firestore transaction landing between promotion's
read and this write had its head_commit_id / commit_sequence / projection & vector
watermarks silently reverted (lost update) — causing later optimistic-concurrency
mismatches and stale/repeated projection+vector repair.

Fix: write only the two fields promotion owns (last_promotion_run_at, updated_at)
with merge=True, mirroring the consolidation writer.

Root cause: a non-transactional full-document overwrite of a shared control doc.
Durable guard: test_short_term_promotion_control_state asserts a concurrently-
advanced head/watermarks survive the promotion stamp. Verified the test fails
against the pre-fix code (head reverts to the stale snapshot).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RAxLsaxtwVNDTWAZFfJp9q
_run_full_pipeline_background_async reassigned its `source: ConversationSource`
parameter to a metering string ('sync_fresh'/'sync_backfill') during fair-use
metering. That string then flowed into segment processing -> CreateConversation(
source=source), where ConversationSource._missing_ coerces the unrecognized string
to ConversationSource.unknown. Every v2-synced NEW conversation was misattributed
(and limitless detection defeated).

Fix: use a distinct `meter_source` local for metering, mirroring the v1 endpoint;
never reassign the `source` enum parameter.

Root cause: parameter shadowing. Verified by reading + the v1 parallel that already
uses meter_source; no hermetic test added (a behavioral test needs the full
decode->VAD->STT->segment pipeline mocked).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RAxLsaxtwVNDTWAZFfJp9q
x_connector.exchange_code logged resp.text[:500] from X's /2/oauth2/token endpoint
with no sanitize(), violating the logging-security rule (every sibling token-exchange
logger wraps the body). Error-path only (X returns an OAuth error JSON, not tokens, on
>=400), hence low severity. Wrapped in sanitize(), matching the established pattern.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RAxLsaxtwVNDTWAZFfJp9q
Move the heavy routers.sync import to module scope so its cost lands in collection,
keeping the new v2-handler behavioral tests within test.sh's per-test fast-unit
duration guard (0.12s). Test-only.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RAxLsaxtwVNDTWAZFfJp9q
…hadowing fixes

Two source-inspection tripwire tests pinned the pre-fix source text:
- test_sync_v2.test_background_pipeline_order asserts the order of decode/vad/
  record_speech_ms/process_segment substrings. The source-shadowing fix's comment
  contained the literal "process_segment", creating an earlier spurious match that
  reordered the detected positions. Reworded the comment to not contain that literal.
- test_conversation_playback_artifact.test_conversation_merge_handler_structure
  pinned "payload.get('schema_version') == 2", which the audio-merge fix replaced
  with a `schema_version = ...` local + `if schema_version == 2:`. Updated the
  tripwire to the new structure and strengthened it to assert the v2 dispatch runs
  AFTER the invalid-payload except block (the actual fix: transient errors retry
  instead of being masked as invalid_payload).

Test-only; no production behavior change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RAxLsaxtwVNDTWAZFfJp9q
@eulicesl
eulicesl requested a review from Copilot July 13, 2026 00:46
@eulicesl
eulicesl marked this pull request as ready for review July 13, 2026 00:46
@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.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes several backend correctness issues in the sync/audio-merge and memory-maintenance subsystems, including two high-severity durable-loss/lost-update bugs, and adds focused regression coverage to lock in the corrected retry/merge semantics.

Changes:

  • Fix Cloud Tasks v2 audio-merge handler control flow so transient failures propagate (500 → retry) instead of being acked as invalid payload (200 → permanent loss).
  • Fix memory promotion control-state persistence to avoid clobbering concurrently-advanced head/watermark fields by writing only owned fields with merge=True.
  • Fix v2 sync conversation source misattribution by avoiding parameter reassignment during fair-use metering; sanitize X OAuth token-exchange error logging.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
backend/routers/sync.py Moves v2 conversation-merge dispatch out of the payload-parse guard so transient failures retry instead of being masked/acked.
backend/utils/sync/pipeline.py Uses a separate meter_source variable to prevent clobbering the ConversationSource parameter during metering.
backend/utils/memory/short_term_promotion.py Persists only promotion-owned control-state fields with merge=True to prevent lost updates.
backend/utils/x_connector.py Sanitizes X OAuth token-exchange error bodies before logging.
backend/tests/unit/test_audio_merge_tasks.py Adds regression tests asserting v2 retry-vs-drop semantics for the audio-merge handler.
backend/tests/unit/test_conversation_playback_artifact.py Updates source-structure assertions to reflect new v2 dispatch placement/order.
backend/tests/unit/test_short_term_promotion_control_state.py Adds a regression test ensuring concurrent control-state head advances survive promotion stamping.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

…odule-scope

Addresses Copilot review on #9588: the explanatory comment still said
routers.sync is "imported inside TestV2HandlerRetrySemantics", but the import
was moved to module scope (for the fast-unit duration guard). Corrected the
comment to say "imported at module scope below" so future maintainers aren't
misled. Comment-only change; no behavior change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RAxLsaxtwVNDTWAZFfJp9q
@eulicesl
eulicesl merged commit 78ee123 into main Jul 13, 2026
22 checks passed
@eulicesl
eulicesl deleted the claude/macos-bug-fixes-testing-i8z7cm branch July 13, 2026 03:50
Git-on-my-level added a commit that referenced this pull request Jul 29, 2026
…, sync annotation ratchet (#9634)

## What this is

Three mechanical regression guardrails plus the written rules behind
them, derived from an internal audit of our own recent merge history. No
behavior changes; the bug fixes the research surfaced will land as
separate PRs.

> **Revised after review** (thanks @Git-on-my-level): the PR scope check
is now **advisory-only** — it reports and warns but never blocks, so it
can never force a feature split. The override/label machinery that
existed to waive the old fail tier is deleted. Details in item 1.

## The research

We audited the last ~30 merged PRs and found **9 confirmed regression
pairs** — a merged PR that introduced a production bug, and a later PR
that fixed it. Three PRs each shipped 2+ regressions. We then ran a
controlled replay experiment: 18 independent blind pre-merge reviews
across 7 of the bug-introducing PRs (reviewers were never told a bug
existed), scored against pre-registered ground truth.

Key findings:

1. **Diff size predicts regressions.** Every recent PR above ~2,400
changed production-source lines shipped at least one regression (2,475
lines → 3 regressions incl. a paying user locked out of sync; 2,652 → 1;
51,564 → 4+ regressions). Review catch-rate collapses with size: a
one-line type bug in a 61-file PR evaded six independent reviewers.
2. **CI coverage can silently rot.** The 51k-line PR also deleted two
pytest invocations from `backend/test.sh` while the test files stayed in
the tree; nothing failed. (A later runner rewrite to directory discovery
happened to heal it — by luck, not by guard.)
3. **Type confusion ships when annotations are missing.** The
`source=unknown` misattribution bug (fixed in #9588) flowed through an
*unannotated* `source` parameter in `utils/sync/pipeline.py` that a
metering string shadowed. The enforced pyright lane had nothing to
check.
4. Two recurring patterns had no written rule: new fail-closed gates
shipping with no satisfiable path for existing users/clients/keys (two
incidents), and tests rewritten in the same PR to assert the new — wrong
— constant (shipped a 9-day prod timeout regression, fixed in #9583).

## What this PR adds

**1. PR scope advisor** (`.github/scripts/check_pr_scope.py`, manifest
check `pr-scope` — runs in the local pre-push lane and CI,
**advisory-only, never blocks**)
Counts changed production-source lines (tests across all platform
conventions, docs, l10n, lockfiles, generated files excluded;
rename/quotePath-safe via `--no-renames` + C-quote handling). ≥1,500
emits a warning annotation; ≥3,000 warns that in the audited merge
history every PR this size shipped a regression review missed — so the
reviewer calibrates skepticism to the diff, and splits only when the
pieces are independently verifiable without extra human verification
passes. Exit code is always 0 on a countable diff; push events
(post-merge `main`) are notice-only. Because nothing blocks, there is no
waiver machinery — no override label, no env escape hatch, no label
plumbing.

**2. Unit-test discovery ratchet**
(`backend/scripts/check_unit_test_discovery.py`, wired into Backend Unit
Tests before dependency install)
Fails when any test file under `backend/tests/` or `backend/testing/` is
not selected by the unit runner, not verified against its dedicated
runner workflow (the workflow file must exist and actually reference the
tree — or, for explicit-list workflows like the GPU suite, name the
individual file), not policy-excluded (live integration/eval), and not
allowlisted. Allowlists only shrink. This audit itself surfaced that
`tests/container/test_parakeet_vram_stress.py` is currently run by no
workflow — it is now explicitly tracked as a manual-only harness instead
of being silently vouched for.

**3. Parameter-annotation ratchet for the sync pipeline**
(`backend/pyrightconfig.json` + annotations)
`executionEnvironments` elevates `reportMissingParameterType` to error
for `utils/sync/` only, and this PR adds the five missing annotations —
one of which is the exact `source` parameter from finding #3. Verified
against the introducing PR's merge state: the rule flags that
unannotated parameter at `pipeline.py:746`. Typed parameters make
str-vs-enum confusion visible to pyright at annotated sinks and
same-scope assignments (verified in isolation on pyright 1.1.403).

**4. AGENTS.md rules** — PR size is *reported, not bounded* (matching
the advisory check), mechanical discovery enforcement, the
legacy-principal test rule for new fail-closed gates, and the
rewritten-test review lens. Each rule names its enforcement or the
shipped failure it prevents. The latter two rules cost agent/review
effort rather than human verification time.

## What this deliberately does not do

- No bug fixes — the still-open defects the audit found are being
filed/fixed separately.
- No blocking on size, in either direction: small diffs also ship bugs
(a 348-line PR shipped a blocker), and forcing large diffs to split
multiplies human verification passes. The advisor only informs review
depth.
- The scope check lives in the checks manifest like every other
deterministic check (no exemptions).

## Verification

- `python3 .github/scripts/test_check_pr_scope.py` → 9 tests OK
(classification, counting, advisory tiers, push notice-only).
- Replayed the advisor against the four historical PRs listed above (892
/ 2,738 / 2,665 / 47,938 lines) → notice/warn/warn/warn, all exit 0; on
this PR itself → 472 changed production-source lines (notice).
- `backend/scripts/check_unit_test_discovery.py` on the real tree → `564
selected, 49 covered by other runners/allowlist, 0 orphans`; a seeded
`tests/<newdir>/test_orphan.py` fails the check with an actionable
message.
- `pytest tests/unit/test_check_unit_test_discovery.py` → 8 passed.
- `bash backend/scripts/typecheck.sh` (enforced pyright lane, pinned
1.1.403, full deps) with the new ratchet → **0 errors**; the rule
replayed against the introducing PR's merge state flags the unannotated
`source` param.
- `python3 -m py_compile backend/utils/sync/pipeline.py` → passes;
annotations are runtime-inert.
- `actionlint` on both changed workflows → clean.
`.github/scripts/test_run_checks.py` (manifest drift guard) → OK.
`.github/scripts/test_pr_preflight.py` → OK.
- Full local manifest lane after the advisory rework → 16 checks passed.
- Post-review hardening verified earlier in the PR: Swift/JS test-tree
classification, quoted non-ASCII paths, seeded unwired
`tests/container/` file IS flagged, pyright lane 0 errors, sync unit
files 273 passed, Agent Runtime tool-surfaces 104 passed.
- Full `backend/test.sh` run (564 files): 562 files green in the
parallel run; the two failures were environmental and pass on rerun —
`test_rendered_deployment_contract.py` needed `helm` on PATH (8 passed
once installed), and `test_sync_v2.py` tripped only the per-test
CPU-timing guard under saturated parallel load (all 161 tests pass;
clean and fast in isolation).

## Product invariants affected

None — no product behavior changes; CI/tooling, type annotations, and
docs only.


## Failure class
Failure-Class: none

(This PR ships CI guardrail tooling; its fix commits repair the
guardrail scripts themselves, not a registered product failure class.)
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.

3 participants