Skip to content

[codex] Add Retry-After to sync fair-use restrictions - #7893

Merged
Git-on-my-level merged 4 commits into
BasedHardware:mainfrom
tianmind-studio:codex/sync-fair-use-retry-after
Jun 29, 2026
Merged

Git-on-my-level merged 4 commits into
BasedHardware:mainfrom
tianmind-studio:codex/sync-fair-use-retry-after

Conversation

@tianmind-studio

@tianmind-studio tianmind-studio commented Jun 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Add a fair-use helper that derives a Retry-After value from an active restrict_until timestamp.
  • Include Retry-After on both deprecated /v1/sync-local-files and current /v2/sync-local-files hard-restriction 429 responses.
  • Keep the header fail-open: if the fair-use state cannot provide a usable expiry, the 429 still returns without Retry-After instead of becoming a 500.
  • Reuse the hard-restriction status read to avoid an extra Firestore read on every hard-rejection.
  • Normalize aware restrict_until values through UTC before comparing with datetime.utcnow().
  • Isolate fair-use test import stubs so Windows/lightweight pytest runs do not require Stripe, Firebase, or Firestore SDK modules just to collect the tests.

This addresses the sync follow-up noted in #7531 where clients fell back to a generic cooldown because hard fair-use 429s did not expose a server-driven retry window.

Refresh

  • Rebased on main at a13477934a2b2a7e0e6491af20deb47d5fd11150.
  • Current head: 497fdc251db13e9d1877a9b6364e3a9ada63872a.
  • GitHub currently reports this PR as mergeable.

Review follow-up

  • Addressed Greptile's double-read concern by using get_hard_restriction_status(uid) for both the restricted boolean and retry window.
  • Addressed the timezone concern by normalizing aware timestamps through UTC before dropping tzinfo.

Validation

  • From backend/: D:\codex-omi-work\.venvs\omi-backend-vad-refresh\Scripts\python.exe -m pytest tests\unit\test_sync_fair_use_gate.py tests\unit\test_fair_use_upgrade.py -q --tb=short
    • 52 passed, 2 warnings
  • From backend/: D:\codex-omi-work\.venvs\omi-backend-vad-refresh\Scripts\python.exe -m py_compile utils\fair_use.py routers\sync.py tests\unit\test_sync_fair_use_gate.py tests\unit\test_fair_use_upgrade.py
  • From backend/: D:\codex-omi-work\.venvs\omi-backend-vad-refresh\Scripts\python.exe -m black --line-length 120 --skip-string-normalization --check utils\fair_use.py routers\sync.py tests\unit\test_sync_fair_use_gate.py tests\unit\test_fair_use_upgrade.py
    • 4 files would be left unchanged
  • From repo root: PYTHONUTF8=1 D:\codex-omi-work\.venvs\omi-backend-vad-refresh\Scripts\python.exe backend\scripts\scan_async_blockers.py
    • exit 0; existing async-blocker backlog reported, no new sync.py blocker
  • git diff --check origin/main...HEAD and git diff --check
  • scripts/pre-commit with the backend Windows venv and local Dart SDK on PATH

@greptile-apps

greptile-apps Bot commented Jun 13, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds a Retry-After header to the 429 responses emitted by both the deprecated /v1/sync-local-files and the current /v2/sync-local-files endpoints when a user's account is hard-restricted under the fair-use policy. A new get_hard_restriction_retry_after_seconds helper reads the restrict_until timestamp from Firestore and returns the remaining seconds, failing open (returning None) on any read error so the 429 is still sent without the header rather than becoming a 500.

  • fair_use.py gains get_hard_restriction_retry_after_seconds, a read-only Firestore probe that inherits the same restrict_until timezone-stripping convention as is_hard_restricted.
  • sync.py introduces _hard_restriction_headers to merge the computed Retry-After value with any base headers; v2 wraps both the restriction check and the header call in run_blocking, while v1 (deprecated, async) calls both directly on the event loop, adding a second new blocking I/O call to its existing backlog.
  • The test file gains sys.modules save-and-restore logic so its stub injection no longer leaks into subsequently-run test modules, and a new TestHardRestrictionRetryAfter class covers normal, aware-datetime, expired, missing, and exception scenarios.

Confidence Score: 4/5

Safe to merge; the new Retry-After logic is fail-open and cannot cause a 500. The only concerns are an extra Firestore round-trip per rejection and a new blocking I/O call on the already-deprecated v1 async handler.

The feature works correctly and the tests are thorough. Two non-blocking observations prevent a clean score: the v2 path makes two sequential Firestore reads per hard-rejection when one would suffice, and the deprecated v1 async handler gains a new synchronous Firestore call that bypasses the thread-pool executor used consistently in v2.

backend/routers/sync.py — v1 blocking-IO inconsistency and v2 double Firestore read on the rejection path.

Important Files Changed

Filename Overview
backend/utils/fair_use.py Adds get_hard_restriction_retry_after_seconds — reads Firestore state, strips tzinfo via .replace(tzinfo=None) (same pattern as is_hard_restricted), and returns seconds remaining; fail-open on exception. Timezone stripping is technically unsafe for non-UTC aware datetimes.
backend/routers/sync.py Wires Retry-After header into both v1 and v2 429 responses via _hard_restriction_headers. V2 path correctly uses run_blocking; v1 adds a new blocking Firestore call to an async handler. V2 also issues two sequential Firestore reads per rejection.
backend/tests/unit/test_sync_fair_use_gate.py Adds isolation logic to restore sys.modules after the test-file's stub injection, preventing pollution of later test suites. New TestHardRestrictionRetryAfter covers the key cases (normal, aware datetime, expired, missing, exception).

Sequence Diagram

sequenceDiagram
    participant Client
    participant SyncV1 as sync_local_files (v1, async)
    participant SyncV2 as sync_local_files_v2 (async)
    participant FairUse as fair_use helpers
    participant Firestore

    Client->>SyncV1: POST /v1/sync-local-files
    SyncV1->>FairUse: is_hard_restricted(uid) [blocking, no run_blocking]
    FairUse->>Firestore: get_fair_use_state(uid) [read 1]
    Firestore-->>FairUse: state
    FairUse-->>SyncV1: True (restricted)
    SyncV1->>FairUse: _hard_restriction_headers(uid) [blocking, no run_blocking]
    FairUse->>Firestore: get_fair_use_state(uid) [read 2]
    Firestore-->>FairUse: state (restrict_until)
    FairUse-->>SyncV1: Retry-After N
    SyncV1-->>Client: 429 + Retry-After + Deprecation headers

    Client->>SyncV2: POST /v2/sync-local-files
    SyncV2->>FairUse: "run_blocking -> is_hard_restricted(uid)"
    FairUse->>Firestore: get_fair_use_state(uid) [read 1]
    Firestore-->>FairUse: state
    FairUse-->>SyncV2: True (restricted)
    SyncV2->>FairUse: "run_blocking -> _hard_restriction_headers(uid)"
    FairUse->>Firestore: get_fair_use_state(uid) [read 2]
    Firestore-->>FairUse: state (restrict_until)
    FairUse-->>SyncV2: Retry-After N
    SyncV2-->>Client: 429 + Retry-After
Loading

Comments Outside Diff (1)

  1. backend/routers/sync.py, line 1323-1328 (link)

    P2 New blocking I/O call added to async v1 handler without run_blocking

    The v1 endpoint is async def but _hard_restriction_headers(uid, …) now makes a synchronous fair_use_db.get_fair_use_state(uid) Firestore read directly on the event-loop thread (no executor). The v2 path correctly wraps the same call with await run_blocking(critical_executor, _hard_restriction_headers, uid), so there is an inconsistency. The existing is_hard_restricted(uid) call on line 1323 is already a known pre-existing blocker, but this PR deliberately adds a second one. For a deprecated endpoint the practical risk is low, but it is inconsistent with the v2 approach and with the project's stated goal of keeping the async-blocker backlog from growing.

Reviews (1): Last reviewed commit: "Add Retry-After to sync fair-use restric..." | Re-trigger Greptile

Comment thread backend/routers/sync.py Resolved
Comment thread backend/utils/fair_use.py Resolved

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

Backend enhancement (Retry-After on sync fair-use restrictions) — approve only per policy.

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

Retry-After on sync fair-use restrictions — approve only (re-approve)

@tianmind-studio
tianmind-studio force-pushed the codex/sync-fair-use-retry-after branch from df5829d to d535712 Compare June 23, 2026 06:34

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

Re-approved on new commits; approve-only per area policy. (auto-review)

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the careful follow-up here. I re-reviewed the current head and this looks good to merge from the maintainer-review side: the sync hard-restriction path now returns Retry-After without adding the extra Firestore read that earlier feedback flagged, keeps the v1 deprecation headers, handles timezone-aware restrict_until values correctly, and includes focused unit coverage. The relevant backend unit tests pass locally (52 passed).

Git-on-my-level added a commit that referenced this pull request Jun 28, 2026
## Summary
- Add `private_cloud_sync_enabled` to `CreateConversation` and propagate
the user's private-cloud setting through v1/v2 file sync segment
processing.
- Preserve the current main-branch private-cloud chunk storage behavior
while forwarding data-protection metadata and finalizing v1 audio
metadata after chunk upload.
- Cover the new conversation creation path, v1
private-cloud/data-protection wiring, and v2 background forwarding path
with unit tests.
- Refresh sync v2 test fixtures to use timestamp-shaped segment paths
and align the storage executor worker-count assertion/docs with the
current 128-worker config.
- Harden the related sync/conversation tests for Windows/lightweight
local runs by stubbing optional SDK imports and avoiding a real
multipart parser dependency where the test only needs to exercise the
endpoint coroutine.

## Current status
- Rebased on `main` at `cc06c20fae75e88b15e220d57402f6f47591dd72`.
- Current head: `962e7f6f55b6856cddab89aca86fcb9266c9d1c0`.
- GitHub compare reports this branch as ahead 10 / behind 0; PR is
mergeable.

## Validation
- From `backend/`:
`D:\codex-omi-work\.venvs\omi-backend-vad-refresh\Scripts\python.exe -m
pytest tests\unit\test_sync_transcription_prefs.py
tests\unit\test_sync_v2.py tests\unit\test_conversation_model_split.py
tests\unit\test_sync_silent_failure.py
tests\unit\test_sync_cloud_tasks.py -q --tb=short`
  - 329 passed, 28 warnings
- `D:\codex-omi-work\.venvs\omi-backend-vad-refresh\Scripts\python.exe
-m py_compile models\conversation.py routers\sync.py
tests\unit\test_sync_transcription_prefs.py tests\unit\test_sync_v2.py
tests\unit\test_conversation_model_split.py
tests\unit\test_sync_silent_failure.py`
- `D:\codex-omi-work\.venvs\omi-backend-vad-refresh\Scripts\python.exe
-m black --line-length 120 --skip-string-normalization --check
models\conversation.py routers\sync.py
tests\unit\test_sync_transcription_prefs.py tests\unit\test_sync_v2.py
tests\unit\test_conversation_model_split.py
tests\unit\test_sync_silent_failure.py`
  - 6 files would be left unchanged
- `PYTHONUTF8=1
D:\codex-omi-work\.venvs\omi-backend-vad-refresh\Scripts\python.exe
backend\scripts\scan_async_blockers.py`
- exit 0; existing async-blocker backlog reported, no new sync.py
blocker
- `git diff --check origin/main...HEAD`
- `scripts/pre-commit` with the backend Windows venv and local Dart SDK
on `PATH`

## Not run
- `tests\unit\test_sync_fair_use_gate.py` in this branch: its Windows
lightweight import isolation is handled in #7893 to avoid duplicating
the same test-file changes across PRs.
@tianmind-studio
tianmind-studio force-pushed the codex/sync-fair-use-retry-after branch from d535712 to 927f0b1 Compare June 29, 2026 02:20
@tianmind-studio
tianmind-studio force-pushed the codex/sync-fair-use-retry-after branch from 927f0b1 to 497fdc2 Compare June 29, 2026 02:57
@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks for this — solid implementation, and the refresh cleanly resolves the two earlier concerns:

  • Single Firestore read: get_hard_restriction_status(uid) returns both the restricted flag and the retry-after window from one state fetch, so the double-read on the rejection path is gone for both v1 and v2.
  • Timezone correctness: _as_naive_utc converts through astimezone(timezone.utc) before dropping tzinfo, which handles non-UTC aware datetimes correctly (the prior .replace(tzinfo=None) would have been wrong for those).

Minor notes (non-blocking):

  • The public get_hard_restriction_retry_after_seconds helper is not consumed by either sync endpoint (they use get_hard_restriction_status directly); worth a one-line note or a trim if it is not intended as a reusable API.
  • v1's call still runs synchronously on the event loop — pre-existing, not introduced here, just noting the v1/v2 asymmetry persists.

The change is fail-open: the 429 still blocks when Retry-After cannot be computed, so enforcement cannot be weakened by this. Since it touches fair-use enforcement, leaving the final approval to a maintainer.

@Git-on-my-level Git-on-my-level added the needs-maintainer-review Needs a human maintainer to sign off before merge label Jun 29, 2026
@Git-on-my-level
Git-on-my-level merged commit 0173e95 into BasedHardware:main Jun 29, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-maintainer-review Needs a human maintainer to sign off before merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants