Repository navigation
Sync: fair-use gates with lock-on-exhaustion (v2, clean) - #5878
Conversation
Allows sync endpoint to pass lock state through to process_conversation when user credits are exhausted. Locked conversations can be unlocked after payment. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Adds optional source param (default 'realtime') for logging which path recorded speech — sync vs realtime. Does not affect Redis keys. Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Pre-check: block hard-restricted users (429) - Credit check: if exhausted, still process but lock conversation - Speech tracking: record VAD speech duration to Redis via fair-use - Soft cap check: trigger lock if caps exceeded - Pass is_locked through process_segment to CreateConversation Co-Authored-By: Claude Opus 4.6 <[email protected]>
25 tests covering: speech source param, precomputed soft caps, VAD duration computation, hard restriction gate, CreateConversation lock propagation, sync.py code structure, and boundary values. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Greptile SummaryThis PR adds fair-use gates to the Key issues found:
Confidence Score: 3/5
Important Files Changed
Sequence DiagramsequenceDiagram
participant Client
participant SyncRouter as sync.py /v1/sync-local-files
participant FairUse as utils/fair_use.py
participant Redis
participant DB as conversations_db
participant ProcessSeg as process_segment()
Client->>SyncRouter: POST /v1/sync-local-files (files)
SyncRouter->>FairUse: is_hard_restricted(uid)
FairUse->>Redis: get enforcement stage + speech totals
Redis-->>FairUse: stage / totals
alt stage == restrict AND over cap
FairUse-->>SyncRouter: True
SyncRouter-->>Client: 429 Restricted
else
FairUse-->>SyncRouter: False
SyncRouter->>SyncRouter: should_lock = not has_transcription_credits(uid)
SyncRouter->>SyncRouter: VAD segmentation → compute speech_ms
SyncRouter->>FairUse: record_speech_ms(uid, total_speech_ms, source='sync')
FairUse->>Redis: HINCRBY bucket + ZADD zset
SyncRouter->>FairUse: get_rolling_speech_ms(uid)
Redis-->>SyncRouter: speech totals
SyncRouter->>FairUse: check_soft_caps(uid, speech_totals)
FairUse-->>SyncRouter: triggered_caps []
alt triggered_caps non-empty
SyncRouter->>SyncRouter: should_lock = True
end
Note over SyncRouter: ⚠️ trigger_classifier_if_needed called<br/>without await + wrong arg (speech_totals vs triggered_caps)
SyncRouter->>ProcessSeg: process_segment(path, uid, response, source, is_locked)
alt new conversation
ProcessSeg->>DB: process_conversation(..., is_locked=is_locked)
else existing conversation + is_locked
ProcessSeg->>DB: update_conversation(uid, id, {is_locked: True})
end
SyncRouter-->>Client: {new_memories, updated_memories}
end
Last reviewed commit: "Add test_sync_fair_u..." |
| if triggered_caps: | ||
| should_lock = True | ||
| logger.info(f'sync: soft caps triggered for {uid}: {triggered_caps}') | ||
| trigger_classifier_if_needed(uid, speech_totals) |
There was a problem hiding this comment.
Coroutine never executed + wrong argument type
trigger_classifier_if_needed is an async def function. Calling it without await (or asyncio.create_task) inside this async endpoint silently creates a coroutine object that is never executed — the classifier is effectively dead for the entire sync path. Python may emit a RuntimeWarning: coroutine 'trigger_classifier_if_needed' was never awaited but the call will complete without any error or enforcement action.
On top of that, the second argument is speech_totals — a dict with keys daily_ms/three_day_ms/weekly_ms — but the function signature expects triggered_caps: list. If the coroutine were somehow awaited, it would eventually call escalate_enforcement(uid, triggered_caps, ...) which does:
triggered_caps[0]['trigger'].value if triggered_caps else 'daily'On a non-empty dict, triggered_caps is truthy, so triggered_caps[0] would raise KeyError: 0.
Compare with the correct pattern already used in transcribe.py:485:
asyncio.create_task(trigger_classifier_if_needed(uid, triggered_caps, session_id))The fix should mirror that pattern and also move the call inside the if triggered_caps block (since triggering the classifier without a cap violation is meaningless):
| trigger_classifier_if_needed(uid, speech_totals) | |
| if triggered_caps: | |
| should_lock = True | |
| logger.info(f'sync: soft caps triggered for {uid}: {triggered_caps}') | |
| asyncio.create_task(trigger_classifier_if_needed(uid, triggered_caps)) |
This replaces lines 779-782 (the if triggered_caps block + standalone classifier call).
| class TestSoftCapBoundary: | ||
| """Test check_soft_caps at exact boundary values.""" | ||
|
|
||
| @patch.object(fair_use_mod, 'FAIR_USE_ENABLED', True) | ||
| @patch.object(fair_use_mod, 'FAIR_USE_KILL_SWITCH', False) | ||
| @patch.object(fair_use_mod, 'FAIR_USE_EXEMPT_UIDS', set()) | ||
| @patch.object(fair_use_mod, 'FAIR_USE_DAILY_SPEECH_MS', 7200000) | ||
| @patch.object(fair_use_mod, 'get_rolling_speech_ms') | ||
| def test_exactly_at_cap_does_not_trigger(self, mock_speech): |
There was a problem hiding this comment.
Test never validates the "does not trigger" assertion
test_exactly_at_cap_does_not_trigger stores the return value in result but only asserts that mock_speech was not called. Since speech_totals is always provided in this test, get_rolling_speech_ms (the mock) is never called regardless of whether caps triggered or not — so mock_speech.assert_not_called() always passes even if check_soft_caps returned violations.
The test as written would pass even if the boundary condition were >= instead of >, which is precisely the case it was meant to guard.
| class TestSoftCapBoundary: | |
| """Test check_soft_caps at exact boundary values.""" | |
| @patch.object(fair_use_mod, 'FAIR_USE_ENABLED', True) | |
| @patch.object(fair_use_mod, 'FAIR_USE_KILL_SWITCH', False) | |
| @patch.object(fair_use_mod, 'FAIR_USE_EXEMPT_UIDS', set()) | |
| @patch.object(fair_use_mod, 'FAIR_USE_DAILY_SPEECH_MS', 7200000) | |
| @patch.object(fair_use_mod, 'get_rolling_speech_ms') | |
| def test_exactly_at_cap_does_not_trigger(self, mock_speech): | |
| result = fair_use_mod.check_soft_caps('user1', speech_totals=precomputed) | |
| # At cap exactly — triggers only when OVER | |
| assert result == [], f"Expected no caps triggered at exact threshold, got: {result}" | |
| mock_speech.assert_not_called() |
Local Dev Backend Live Test EvidenceEnvironment:
Test 1: Full HTTP endpoint uploads (5 uploads) ✅Test 2: Fair-use speech tracking ✅All uploads show VAD detected ~12s of speech from the 28.3s audio file. Test 3: Redis Cloud accumulation ✅Test 4: Fair-use functions (inline test) ✅Test 5: Syntax verification ✅All 43 router files pass Summary
by AI for @beastoin |
…args - Add asyncio.create_task() since trigger_classifier_if_needed is async - Pass triggered_caps (list) instead of speech_totals (dict) - Only call classifier when caps are actually triggered Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Greptile review fixesP0 (fixed): P1 (fixed): by AI for @beastoin |
Live Test Evidence v2 — All code paths verified (including classifier)Setup: Upload 1: Soft caps trigger + classifier fires ✅
Upload 2: Multiple caps trigger ✅
"coroutine never awaited" check ✅Summary
by AI for @beastoin |
|
lgtm |
## Summary - Removed `should_lock = True` from the soft cap trigger block in `sync.py` - Soft cap triggers now only run the classifier async (matching `transcribe.py` behavior) - Added structural test to prevent regression ## Root Cause PR #5878 incorrectly set `should_lock = True` when soft caps triggered in the sync endpoint. This caused unlimited users exceeding the 2h daily soft cap via sync to get all conversations immediately locked — bypassing the graduated enforcement system (WARNING → THROTTLE → RESTRICT). The equivalent code in `transcribe.py` (WebSocket) correctly only triggers the classifier without locking. ## Impact With `FAIR_USE_ENABLED=true` in production, any user exceeding the daily soft cap through sync had their conversations locked immediately, regardless of subscription tier or classifier result. ## Test plan - [x] 26/26 unit tests pass (including new structural test) - [x] `py_compile` verified on all router files - [ ] Deploy and verify no locked conversations for unlimited sync users 🤖 Generated with [Claude Code](https://claude.com/claude-code)
…bug (#5901) ## Summary Migration script to unlock conversations, memories, and action items incorrectly locked by the sync soft cap bug (PR #5878, fixed in PR #5896). Script at `backend/scripts/unlock_soft_cap_locked.py` — reads UIDs from a file, verifies paid subscription (unlimited/pro), then unlocks all 3 collections. Dry-run by default. ## Usage (Cloud Run job) ```bash python scripts/unlock_soft_cap_locked.py --uids-file /tmp/impacted_uids.txt # dry-run python scripts/unlock_soft_cap_locked.py --uids-file /tmp/impacted_uids.txt --execute # apply ``` ## Impact - 8 users identified from prod logs, 6 are paid (unlimited), 2 basic (skipped) - 692 total items to unlock (649 conversations, 17 memories, 26 action items) Closes #5899
…re#5878) ## Summary - Add fair-use gates to `/v1/sync-local-files` endpoint - Block hard-restricted users (429) - Lock conversations (not block) when credits exhausted — user pays to unlock - Track VAD speech duration to Redis for rolling window caps - Trigger soft cap check and LLM classifier after speech recording - Add `is_locked` field to `CreateConversation` model for lock propagation through `process_conversation` - Add `source` parameter to `record_speech_ms` for sync vs realtime traceability ## Files changed (no transcribe.py) - `models/conversation.py` — `is_locked: bool = False` on `CreateConversation` - `routers/sync.py` — fair-use imports, `should_lock` flag, `is_locked` propagation - `utils/fair_use.py` — `source` param on `record_speech_ms` - `tests/unit/test_sync_fair_use_gate.py` — 25 unit tests - `test.sh` — add test to runner ## How locking works 1. `should_lock = not has_transcription_credits(uid)` — checks subscription credits 2. If soft caps triggered, `should_lock = True` 3. `is_locked` passed to `CreateConversation` → propagates to `Conversation`, memories, action items via `process_conversation` 4. Existing conversations updated with `is_locked=True` via `update_conversation` 5. User pays → `payment.py` calls `unlock_all_conversations/memories/action_items` ## Verification - 25/25 unit tests pass - All 43 router files pass syntax check (including transcribe.py) - Clean branch from main — zero changes to transcribe.py ## Test plan - [x] All 25 unit tests pass - [x] All router files syntax-verified via `py_compile` - [x] `is_locked` propagation tested through `CreateConversation` → `Conversation` - [x] Boundary tests: exactly-at-cap, 1ms-over, zero-speech - [x] Code structure tests: no 402, has should_lock, has is_hard_restricted Replaces reverted PR BasedHardware#5863 with clean implementation. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
…rdware#5896) ## Summary - Removed `should_lock = True` from the soft cap trigger block in `sync.py` - Soft cap triggers now only run the classifier async (matching `transcribe.py` behavior) - Added structural test to prevent regression ## Root Cause PR BasedHardware#5878 incorrectly set `should_lock = True` when soft caps triggered in the sync endpoint. This caused unlimited users exceeding the 2h daily soft cap via sync to get all conversations immediately locked — bypassing the graduated enforcement system (WARNING → THROTTLE → RESTRICT). The equivalent code in `transcribe.py` (WebSocket) correctly only triggers the classifier without locking. ## Impact With `FAIR_USE_ENABLED=true` in production, any user exceeding the daily soft cap through sync had their conversations locked immediately, regardless of subscription tier or classifier result. ## Test plan - [x] 26/26 unit tests pass (including new structural test) - [x] `py_compile` verified on all router files - [ ] Deploy and verify no locked conversations for unlimited sync users 🤖 Generated with [Claude Code](https://claude.com/claude-code)
…bug (BasedHardware#5901) ## Summary Migration script to unlock conversations, memories, and action items incorrectly locked by the sync soft cap bug (PR BasedHardware#5878, fixed in PR BasedHardware#5896). Script at `backend/scripts/unlock_soft_cap_locked.py` — reads UIDs from a file, verifies paid subscription (unlimited/pro), then unlocks all 3 collections. Dry-run by default. ## Usage (Cloud Run job) ```bash python scripts/unlock_soft_cap_locked.py --uids-file /tmp/impacted_uids.txt # dry-run python scripts/unlock_soft_cap_locked.py --uids-file /tmp/impacted_uids.txt --execute # apply ``` ## Impact - 8 users identified from prod logs, 6 are paid (unlimited), 2 basic (skipped) - 692 total items to unlock (649 conversations, 17 memories, 26 action items) Closes BasedHardware#5899
…asedHardware#7125) * fix(sync): add missing record_usage to sync endpoints + deprecate v1 record_usage(uid, transcription_seconds, speech_seconds) was removed in PR BasedHardware#5875 revert and never re-added in BasedHardware#5878, leaving sync-local-file transcription invisible to the subscription credit system. Adds record_usage calls after segment processing in both v1 sync_local_files() and v2 _process_segments_background(). Marks v1 POST /v1/sync-local-files as deprecated — no Flutter or Desktop clients use it (all callers migrated to v2). Adds Deprecation header and warning log for monitoring remaining traffic. Closes BasedHardware#7123 Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(sync): add deprecation headers to all v1 response paths HTTPException paths in v1 sync-local-files were missing Deprecation headers because FastAPI drops response.headers on exceptions. Add headers param to all HTTPException raises and use a shared constant. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(sync): handle shared-helper HTTPExceptions and move record_usage after failure check - Wrap retrieve_file_paths/decode_files_to_wav calls in v1 with try/except to re-raise HTTPExceptions with deprecation headers (shared helpers can't have deprecation headers directly since v2 also uses them) - Move record_usage after the all-segments-failed guard so usage is only recorded when at least one segment succeeded - Apply same pattern to v2 background worker Co-Authored-By: Claude Opus 4.6 <[email protected]> * test(sync): add tests for record_usage placement and v1 deprecation 19 structural tests verifying: - record_usage import at module level - v1: record_usage called after all-segments-failed guard, not under fair_use_restrict_dg, wrapped in try/except with error logging - v2: record_usage after failed_segments check, guarded by successful_segments > 0, before mark_job_completed - v1 deprecation: deprecated=True, warning log, headers constant, all HTTPExceptions and JSONResponses carry deprecation headers, shared helper exceptions re-raised with headers Co-Authored-By: Claude Opus 4.6 <[email protected]> * chore(test): add test_sync_record_usage.py to test.sh Co-Authored-By: Claude Opus 4.6 <[email protected]> * refactor(app): remove deprecated v1 syncLocalFiles function v1 POST /v1/sync-local-files is deprecated on the backend. Remove the unused client function — all callers already use syncLocalFilesV2. Co-Authored-By: Claude Opus 4.6 <[email protected]> * refactor(app): remove v1 syncLocalFiles from WAL exports Co-Authored-By: Claude Opus 4.6 <[email protected]> * docs(app): update comment to reference v2 sync endpoint Co-Authored-By: Claude Opus 4.6 <[email protected]> --------- Co-authored-by: Claude Opus 4.6 <[email protected]>
Summary
/v1/sync-local-filesendpointis_lockedfield toCreateConversationmodel for lock propagation throughprocess_conversationsourceparameter torecord_speech_msfor sync vs realtime traceabilityFiles changed (no transcribe.py)
models/conversation.py—is_locked: bool = FalseonCreateConversationrouters/sync.py— fair-use imports,should_lockflag,is_lockedpropagationutils/fair_use.py—sourceparam onrecord_speech_mstests/unit/test_sync_fair_use_gate.py— 25 unit teststest.sh— add test to runnerHow locking works
should_lock = not has_transcription_credits(uid)— checks subscription creditsshould_lock = Trueis_lockedpassed toCreateConversation→ propagates toConversation, memories, action items viaprocess_conversationis_locked=Trueviaupdate_conversationpayment.pycallsunlock_all_conversations/memories/action_itemsVerification
Test plan
py_compileis_lockedpropagation tested throughCreateConversation→ConversationReplaces reverted PR #5863 with clean implementation.
🤖 Generated with Claude Code