Skip to content

fix(backend): offload the sync billing and fair-use gates off the event loop - #15228

Merged
kodjima33 merged 3 commits into
BasedHardware:mainfrom
singhharsh1708:fix/backend-sync-v1-offload-gates
Sep 21, 2026
Merged

kodjima33 merged 3 commits into
BasedHardware:mainfrom
singhharsh1708:fix/backend-sync-v1-offload-gates

Conversation

@singhharsh1708

@singhharsh1708 singhharsh1708 commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #15227

sync_local_files is async def, so the six synchronous gates it called ran on the event loop and stalled every other request and WebSocket on the pod for the duration of each Firestore or Redis round trip. This is the large-upload endpoint, so those requests are long lived and overlap.

Each call is now offloaded with the executor the same call already uses elsewhere in the tree, so nothing here is a new judgement:

call executor precedent
get_hard_restriction_status critical_executor sync_local_files_v2, same file
is_daily_audio_ceiling_exceeded db_executor sync_local_files_v2, same file
has_transcription_credits critical_executor sync_local_files_v2, same file
get_enforcement_stage db_executor routers/listen/runtime.py via ListenPersistence.call
is_dg_budget_exhausted db_executor routers/listen/runtime.py via ListenPersistence.call
record_usage db_executor Firestore write through user_usage_db

ListenPersistence.call is run_blocking(db_executor, ...), so the last three follow the pool the listen path already picked for them.

No control flow changed: the same values are computed in the same order and the same branches are taken. record_usage stays inside its existing try.

Tests: backend/tests/unit/test_sync_local_files_async.py, an AST guard in the shape of the existing test_tts_ratelimit_async.py. It asserts the handler is async, that none of the six is called directly, that each is offloaded through an awaited run_blocking (a bare call would be a coroutine that never runs, so the gate would silently stop being enforced), and that each uses the executor above.

Verification:

$ cd backend && BACKEND_UNIT_TEST_FILE_LIST=... bash test.sh
4 passed in 0.10s

$ python3 scripts/scan_async_blockers.py --dirs routers utils
Selected blocking findings: 0

With routers/sync.py reverted to its state on main and the test kept, 3 of the 4 fail and only the test_handler_is_async control passes.

Worth noting for the manifest: scan_async_blockers.py reports 0 both before and after this change. Its mixed_await_sync_db detector resolves database.* names imported directly into the scanned file, and these six reach Firestore and Redis through utils/ wrappers, so it cannot see them. That is why this PR adds a file-local AST guard rather than extending the scanner, which would be a much wider change.

Product invariants affected

none

Failure class (fixes)

Failure-Class: none

The nearest existing class is FC-loop-bound-resource-shared-process-wide, but its contract is about a resource bound to one event loop being reused from another, not about synchronous I/O running on the loop, so it did not look like an honest fit.

Line-Count-Exception: backend/routers/sync.py | 2101 -> 2103 | wrapping six gate calls in awaited run_blocking

Review in cubic

@singhharsh1708

Copy link
Copy Markdown
Contributor Author

CI caught two suites I had not run: test_sync_record_usage.py and test_sync_fair_use_gate.py assert on the source text of the handler, and offloading the calls changed that text. My fault for only running the new test file before opening this.

Both are updated to the offloaded shape, not loosened:

test_sync_record_usage.py searched record_usage( for v1. Its own v2 class already searched record_usage, because v2 was already offloaded, so v1 now matches v2. The ordering, try/except and logging assertions around it are unchanged.

test_sync_fair_use_gate.py asserted 'get_hard_restriction_status(uid)' in source. That now reads 'run_blocking(critical_executor, get_hard_restriction_status, uid)' in source, which pins the executor as well as the presence of the gate, so it is stricter than before.

bash test.sh over the 106 sync, fair-use, usage, subscription and transcription suites: exit 0, no failures.

@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @singhharsh1708 — verified against head 3b742f6.

What I checked in backend/routers/sync.py: all six gates are now await run_blocking(...) (hard restriction L556 → critical_executor, daily audio ceiling L572 → db_executor, transcription credits L586 → critical_executor, fair-use stage L695 → db_executor, DG budget L698 → db_executor, record_usage L816 → db_executor). The executor choices match both the sync_local_files_v2 precedent in the same file (L953/L964/L976) and the lane policy documented in utils/executors.py (hard-restriction checks → critical; Firestore/Redis → db). run_blocking(executor, fn, *args, **kwargs) forwards kwargs, so the record_usage(uid, transcription_seconds=…, speech_seconds=…) offload is signature-safe, and an AST walk confirms it stays inside its existing try with no direct calls to any of the six gates left anywhere in the handler.

Tests: the new test_sync_local_files_async.py AST guard is the strongest part — especially the awaited-run_blocking assertion, which would catch a bare call whose coroutine never runs and silently disables a gate while still looking offloaded. The string-match updates in test_sync_record_usage.py (record_usage( → record_usage,) and test_sync_fair_use_gate.py are consistent with the new call form. I re-ran the assertion logic against the head source and it all holds; CI (hermetic merge gate, sync gauntlet, unit shards) is green too.

One non-blocking note: under saturation the three critical_executor gates can now raise ExecutorSaturatedError, where the inline calls couldn't. That's exact parity with the v2 handler's existing behavior and the executor's intended fail-fast design — just worth keeping in mind if gate ordering ever changes.

Leaving a positive signal — a human maintainer can take the formal approval from here.

🤖 Automated review 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.

@Git-on-my-level Git-on-my-level added positive-signal Automation verified a genuine fix/quality contribution backend Backend Task (python) labels Sep 20, 2026

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Fixes #15227: six synchronous gate checks in sync_local_files ran directly on the event loop, stalling other requests/websockets during the large-upload endpoint's long-lived requests. Now offloaded via the same executors already used by identical calls elsewhere in the file (critical_executor/db_executor) — no logic change, just moved off-loop. AST-guard regression test fails on revert (3/4). CI green.

@kodjima33
kodjima33 merged commit b61078a into BasedHardware:main Sep 21, 2026
46 of 47 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

POST /v1/sync-local-files runs six blocking billing and fair-use calls on the event loop

3 participants