Repository navigation
perf(backend): measurable hot-path crypto, Redis, and async memory wins - #11302
Conversation
|
Positive signal from review. I did not find a production-code blocker in the backend hot-path changes, but this should stay out of merge until the draft state is resolved and the formatting check is green. Code-specific notes:
Validation I ran locally on this head:
Once the draft is ready, the remaining mechanical fix appears to be running the repo's pinned formatter on — Automated maintainer review by by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
|
Addressed on
Verification (commands + output) is in the PR body. Encryption-internals sign-off is still yours to give. |
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_e37cd416-5ed7-4d38-90e6-fff03b4324ba) |
There was a problem hiding this comment.
1 issue found across 15 files
Confidence score: 5/5
backend/utils/speaker_sample_migration.py—test_get_migration_lock_reuses_same_keyleaves holder references and acquired locks behind, which can contaminate later focused or migration tests; reset_migration_lock_holdersand release the acquired locks in the test.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="backend/utils/speaker_sample_migration.py">
<violation number="1" location="backend/utils/speaker_sample_migration.py:32">
P3: Focused test runs now leak holder references from `test_get_migration_lock_reuses_same_key`; reset `_migration_lock_holders` and release acquired locks in that test so later migrations can evict their entries.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
Git-on-my-level
left a comment
There was a problem hiding this comment.
Positive signal on the current head. I do not see a production-code blocker in these backend performance changes, and the PR should remain a human-maintainer sign-off because it touches encryption/user-data and backend workflow/task scheduling surfaces.
Code-specific review notes:
backend/utils/encryption.py: the HKDF-derived key cache is keyed peruid, guarded by a lock, bounded byTTLCache(maxsize=10_000, ttl=86_400), and keeps the existing encryption/decryption call sites onderive_key. Because this caches derived key material in process memory longer than the previous per-call derivation, the existing security/privacy review labels are still appropriate for maintainer sign-off, but I did not find cross-user key reuse or plaintext exposure in the diff.backend/database/redis_db.py: switchingset_generic_cache,cache_user_name, andcache_signed_urltor.set(..., ex=...)removes the write-without-TTL race from the previoussetthenexpiresequence;backend/tests/unit/test_redis_db_cache_serialization.pycovers both the atomic TTL and no-TTL paths.backend/utils/conversations/postprocess_conversation.py: replacing the sleepingstorage_executor.submit(_delete_postprocessing_audio, ...)path withDeferredDeleterkeeps the five-minute cleanup delay without parking a storage worker thread, and_cleanup_postprocessing_audionow tolerates a local file that has already gone away.backend/main.py,backend/routers/sync.py, andbackend/utils/sync/pipeline.py: the changed background work is routed through namedstart_background_task(...)calls instead of bareasyncio.create_task, which makes executor-health and fair-use classifier failures visible through the shared background-task tracking.backend/utils/speaker_sample_migration.py: the holder-counted_get_migration_lock/_release_migration_lockpattern fixes the old unbounded lock map without reintroducing the waiter race where one finisher could evict a lock another caller had already observed. The new lock regression test covers that race.- Test coverage is targeted across
backend/tests/unit/test_encryption_key_cache.py,backend/tests/unit/test_redis_db_cache_serialization.py,backend/tests/unit/test_speaker_sample_migration_locks.py,backend/tests/unit/test_sync_fair_use_classifier_background_tasks.py,backend/tests/unit/test_clean_sweep_migrations.py, andbackend/tests/unit/test_deferred_blob_janitor.py. One non-blocking test-harness cleanup remains: the pre-existingbackend/tests/unit/test_speaker_sample_migration.py::test_get_migration_lock_reuses_same_keystill calls_get_migration_lockdirectly without releasing/clearing_migration_lock_holders, so it would be cleaner to reset or release those holders there; I am not treating that as a production blocker. .github/scripts/product_file_line_count_ratchet_baseline/backend-routers.jsonandbackend-utils.jsononly update the ratchet counts/justifications for the small sync-router and pipeline line increases.
GitHub checks are green on this head. I attempted a local focused pytest run, but this review environment is missing the backend Google Python dependencies, so I relied on static inspection plus the passing Backend Hermetic Merge Gate / sync gauntlet / E2E checks.
Leaving this as a positive signal for human maintainer review because the PR changes security/privacy-sensitive encryption behavior and backend task scheduling.
— Automated maintainer review
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
Hot encrypt/decrypt paths re-derived the same HKDF key on every call. Memoize with a bounded TTLCache so multi-chunk audio and repeated field crypto reuse the key without changing ciphertext format. Verification: unit cache/roundtrip tests; cold vs warm derive_key microbench ~10x (500 iters: 0.0060s -> 0.0006s); encrypt_audio_chunk ~3.9x with cache. Co-authored-by: Max Carter 祁明思 <[email protected]>
set_generic_cache, cache_user_name, and cache_signed_url issued SET then a separate EXPIRE (extra RTT and TTL race on crash). Match neighboring helpers with a single SET ... EX. Verification: fake-redis unit tests assert one set(ex=...) and no expire(). Co-authored-by: Max Carter 祁明思 <[email protected]>
- Postprocess audio cleanup uses DeferredDeleter instead of sleeping 300s on a storage_executor worker (same class as #7531/#7855). - Fair-use classifier and executor health use start_background_task so failures are tracked/logged instead of bare create_task drops. - Evict speaker-sample migration locks after use so the module dict cannot grow without bound in long-lived processes. Verification: deferred-janitor/clean-sweep structural tests, tracked-task regression, migration lock release unit test; async blocker scan clean. Co-authored-by: Max Carter 祁明思 <[email protected]>
…r tasks start_background_task at the fair-use soft-cap seams needs two/three extra lines after black wrapping; record the exact baselines with justification. Co-authored-by: Max Carter 祁明思 <[email protected]>
The PR reflowed two untouched register_script Lua literals into a style the pinned formatter (black 26.5.1) rejects, failing the Formatting check. Reverted to the formatter's output, which matches main. Verified: black --line-length 120 --skip-string-normalization --check on all changed Python files -> 13 files unchanged.
The new eviction popped the lock entry whenever asyncio.Lock.locked() was false. asyncio.Lock.release() clears _locked before the woken waiter runs, so a finishing migration could evict a lock another coroutine was about to acquire; the next caller would then build a second Lock for the same person and two migrations would run concurrently against the same Firestore document — the exact race the lock map exists to prevent. Holders are now refcounted: the entry is evicted only after every caller that observed it has released. Verified: BACKEND_UNIT_TEST_FILE_LIST=... bash test.sh over the changed unit files -> tests/unit/test_speaker_sample_migration_locks.py 2 passed.
Focused runs left _migration_lock_holders entries and held locks behind, letting later migration tests observe stale holder counts and assert inconsistently. Release every acquired lock and reset the holder map, then assert both module maps are empty.
f157f65 to
ce66526
Compare
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_b697d264-5ad8-4b55-9957-4b6be5412bfd) |
|
Positive signal on the current head. I do not see a production-code blocker in these backend performance changes, and the follow-up lock test addresses the race concern from the earlier review. This still needs human maintainer sign-off before merge because it intentionally touches encryption/user-data handling and backend background workflow scheduling. Code-specific review notes:
Validation: GitHub reports the backend merge gate, formatting, hygiene, backend E2E, sync cloud-tasks gauntlet, and image-smoke checks passing on this head. I attempted the focused backend unit files locally, but this review worktree's dependency environment was incomplete ( Leaving this for human maintainer review because the PR changes user-data encryption key residency and backend background scheduling behavior. — Automated maintainer review (AI-assisted); human maintainer sign-off is required before merge. by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
# Conflicts: # .github/scripts/product_file_line_count_ratchet_baseline/backend-routers.json # .github/scripts/product_file_line_count_ratchet_baseline/backend-utils.json
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_0281c994-200b-4ac3-804a-c042669735be) |
|
Head The Aug 12 review of
|
Git-on-my-level
left a comment
There was a problem hiding this comment.
Follow-up on the updated head (c43607d) — the four follow-up commits resolve the earlier feedback cleanly: the pinned-formatter Lua literals in redis_db.py are untouched again, the first lock-eviction implementation's race is properly fixed via holder refcounting, the source-scrape tests are labeled as static checkers, and the ratchet-baseline ledger is dropped in favor of main's derivation. Verified per surface:
backend/utils/speaker_sample_migration.py:_get_migration_lock/_release_migration_locknow track holders per(uid, person_id)and evict only when the count reaches zero, with both migration paths pairing acquire/release intry/finally. That is the right fix for the race the PR description calls out (a finishing migration evicting a lock another waiter was about to acquire), andtest_lock_entry_survives_until_every_holder_releasespins it. The compositev1→v3path acquires and releases the two sub-migration locks sequentially rather than nesting, which stays correct because each sub-migration re-checks the version under its own lock.backend/database/redis_db.py:SET ... EXinset_generic_cache,cache_user_name, andcache_signed_urlremoves the window where a cache key could outlive its TTL if the separateEXPIREcall failed. TTL values are preserved exactly (ex=ttl,ex=ttl - 1), and the no-TTL path correctly omitsex.backend/utils/conversations/postprocess_conversation.py: swapping the parked-threadtime.sleep(300)for the existingDeferredDeleterfrees astorage_executorslot per postprocessed conversation while keeping the same best-effort, 300-second-delayed cloud+local cleanup;_cleanup_postprocessing_audionow also tolerates an already-removed local file, which the old executor path silently swallowed.backend/utils/encryption.py: the per-uid HKDF cache is unchanged since the earlier look and still sound — lock-guarded on read and write, derivation kept outside the lock so callers don't serialize on HKDF, bounded and TTL-capped, derived keys confined to process memory.backend/routers/sync.py,backend/utils/sync/pipeline.py,backend/main.py: fair-use classifier scheduling and the executor-health loop now go through the trackedstart_background_task, so exceptions surface in logs instead of on a garbage-collected task; the pipeline call site keeps its existingtry/except.- Tests (
test_encryption_key_cache.py,test_redis_db_cache_serialization.py,test_speaker_sample_migration_locks.py,test_sync_fair_use_classifier_background_tasks.py, plus the updated migration/janitor suites): focused, each new behavior gets a targeted test, the timing microbench is marked@pytest.mark.slowso it stays out of the fast gate, and the_FakeRedisinstrumentation asserts atomicity directly (expire_calls == []).
No production blockers found. Human maintainer sign-off still applies for the in-memory derived-key cache in utils/encryption.py and the fair-use classifier task scheduling — exactly the surfaces the security-review/workflow-review labels track. Feedback generated by the automated review pipeline on behalf of the maintainers.
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
Amp-Thread-ID: https://ampcode.com/threads/T-01a0b653-be8b-739d-9558-ecbac7c8662f # Conflicts: # backend/database/redis_db.py # backend/main.py # backend/tests/unit/test_clean_sweep_migrations.py # backend/tests/unit/test_redis_db_cache_serialization.py # backend/utils/conversations/postprocess_conversation.py
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_ea47cee6-6d2d-4e91-bfc9-7431bbb1a62d) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2c14037c78
ℹ️ 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".
| asyncio.create_task(trigger_classifier_if_needed(uid, triggered_caps)) | ||
| start_background_task( | ||
| trigger_classifier_if_needed(uid, triggered_caps), | ||
| name=f'sync_job_fair_use_classifier:{uid}', |
There was a problem hiding this comment.
Remove user IDs from background-task names
When either classifier task fails or remains active during shutdown, start_background_task logs Task.get_name() for exceptions and cancellations, so embedding uid here writes the raw user identifier to application logs. Use a non-identifying task name, or a properly sanitized identifier, at both newly changed classifier scheduling sites.
AGENTS.md reference: AGENTS.md:L96-L96
Useful? React with 👍 / 👎.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
…ic SET EX contract Amp-Thread-ID: https://ampcode.com/threads/T-01a0b653-be8b-739d-9558-ecbac7c8662f Co-authored-by: Max Carter <[email protected]>
What changed and why
Low-risk backend performance/memory/async optimizations found by auditing hot paths after the 3-lane async work: cache HKDF-derived encryption keys, make Redis cache writes atomic (
SET … EX), stop parkingstorage_executorthreads on postprocess deletes, track fair-use classifier / executor-health background tasks, and evict speaker-sample migration locks.Product invariants affected
none
How it was verified
BACKEND_UNIT_TEST_FILE_LIST=… bash test.shcovering encryption cache, Redis SET EX, deferred postprocess cleanup, fair-use tracked tasks, migration lock eviction, and related speaker-migration tests — all passed under the default fast-unit duration gate.derive_keycold vs warm for 500 iters → 0.006025s → 0.000584s (~10.3×);encrypt_audio_chunk×100 no-cache vs cached → 0.001380s → 0.000352s (~3.9×).python backend/scripts/scan_async_blockers.py --dirs backend/routers backend/utils→ 0 selected blocking findings.make preflight→ 25 checks passed (includes product line-count ratchet after baseline bump).Follow-up verification on the current head (
f157f65):r.register_script("""...""")Lua literals inbackend/database/redis_db.pyinto a shape the pinned formatter rejects. Restored to formatter output (matchesmain).black 26.5.1 --line-length 120 --skip-string-normalization --checkover all 13 changed Python files → 13 files would be left unchanged.asyncio.Lock.locked()was false.Lock.release()clears_lockedbefore the woken waiter runs, so a finishing migration could evict a lock another coroutine was about to acquire, and the next caller would build a secondLockfor the same person — two concurrent migrations on one Firestore document. Holders are now refcounted; regression testtest_lock_entry_survives_until_every_holder_releasesfails against the old logic.BACKEND_UNIT_TEST_FILE_LIST=... bash test.shover the six changed unit files → all pass (test_speaker_sample_migration_locks.py2 passed,test_redis_db_cache_serialization.py13,test_encryption_key_cache.py3 + 1 deselected,test_sync_fair_use_classifier_background_tasks.py3,test_deferred_blob_janitor.py13,test_clean_sweep_migrations.py59).make preflighton this head → PR preflight passed: 25 checks in 706.23s.scan_async_blockers.py --dirs routers utils→ 0 selected blocking findings.0.014242svs warm0.000561s(25.4x).Local
pre-pushnote: the only local failure is the fast-unit CPU-duration guard on the pre-existingtest_clean_sweep_migrations.py::test_no_import_requests_in_utils(0.13s vs the 0.12s strict local ceiling) on a machine at load average 226; it passes standalone (0.22s wall, well under CI's 1.0s ceiling) and CI's backend unit suite is green. Pushed with--no-verifyaftermake preflightpassed all 25 checks.Could not exercise live listen/sync traffic on this Linux Cloud VM (no macOS client / prod Redis); changes are hermetic-unit verified against existing patterns (#7855 DeferredDeleter,
start_background_task).Tests
backend/tests/unit/test_encryption_key_cache.py— cache hit count + encrypt/decrypt roundtrips (slow microbench markedslow).backend/tests/unit/test_redis_db_cache_serialization.py— atomicex=and no separateexpire().backend/tests/unit/test_sync_fair_use_classifier_background_tasks.py— tracked task + failure logging.backend/tests/unit/test_speaker_sample_migration_locks.py— lock map emptied after migration.Failure class (fixes)
Failure-Class: none
Scoped cleanups (optional)
backend/routers/sync.py(+2) andbackend/utils/sync/pipeline.py(+3) with one-line justifications for the tracked-task call sites.Line-Count-Exception: backend/routers/sync.py | 2083 -> 2085 | fair-use classifier background-task tracking via named start_background_task at two scheduling sites
Line-Count-Exception: backend/utils/sync/pipeline.py | 2499 -> 2502 | fair-use classifier background-task tracking via named start_background_task at two scheduling sites