Skip to content

Sync: fair-use gates with lock-on-exhaustion (v2, clean) - #5878

Merged
beastoin merged 7 commits into
mainfrom
fix/sync-fair-use-gate-5854-v2
Mar 21, 2026
Merged

beastoin merged 7 commits into
mainfrom
fix/sync-fair-use-gate-5854-v2

Conversation

@beastoin

Copy link
Copy Markdown
Collaborator

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

  • All 25 unit tests pass
  • All router files syntax-verified via py_compile
  • is_locked propagation tested through CreateConversation → Conversation
  • Boundary tests: exactly-at-cap, 1ms-over, zero-speech
  • Code structure tests: no 402, has should_lock, has is_hard_restricted

Replaces reverted PR #5863 with clean implementation.

🤖 Generated with Claude Code

beastoin and others added 5 commits March 21, 2026 09:20
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]>
@greptile-apps

greptile-apps Bot commented Mar 21, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds fair-use gates to the /v1/sync-local-files endpoint: a hard-restrict pre-check (HTTP 429), credit-exhaustion locking (conversations are locked rather than blocked so users can pay to unlock), VAD-based speech duration tracking to Redis, soft-cap detection, and is_locked propagation through CreateConversation → Conversation. The source parameter added to record_speech_ms correctly limits its scope to logging only.

Key issues found:

  • Critical — classifier never runs in sync path (backend/routers/sync.py:782): trigger_classifier_if_needed is an async def but is called as a plain function without await or asyncio.create_task. The coroutine is created but immediately discarded — the LLM classifier is silently skipped on every sync upload. Additionally, speech_totals (a dict) is passed as the second argument instead of triggered_caps (a list), which would raise KeyError: 0 inside escalate_enforcement if the coroutine were ever executed. The correct pattern is already established in transcribe.py:485: asyncio.create_task(trigger_classifier_if_needed(uid, triggered_caps, session_id)).
  • Test gap (test_sync_fair_use_gate.py:TestSoftCapBoundary::test_exactly_at_cap_does_not_trigger): The test claims to verify that usage exactly at the daily cap does not trigger enforcement, but never asserts on the return value of check_soft_caps. The only assertion (mock_speech.assert_not_called()) is trivially true whenever speech_totals is pre-supplied, so the boundary condition (> vs >=) is not actually validated.

Confidence Score: 3/5

  • The core locking/blocking logic is correct, but the LLM classifier is silently dead on the sync path due to a missing await and wrong argument — this is a P0 functional bug that must be fixed before merge.
  • The hard-restrict gate, credit-exhaustion lock, and is_locked propagation all work correctly and are well-tested. However, trigger_classifier_if_needed is called without await/asyncio.create_task and with the wrong argument type (speech_totals dict vs triggered_caps list), meaning the LLM classifier enforcement is completely non-functional for the sync code path. This breaks a stated goal of the PR and bypasses graduated enforcement for sync users. The fix is targeted (two lines), but the bug itself is P0 — it silently disables a security/fairness mechanism.
  • backend/routers/sync.py line 782 requires a targeted fix before merge.

Important Files Changed

Filename Overview
backend/routers/sync.py Adds fair-use gates to /v1/sync-local-files: hard-restrict check (429), credit-exhaustion lock flag, VAD speech duration tracking, and soft-cap detection. Contains a critical bug: trigger_classifier_if_needed is called without await/asyncio.create_task and receives speech_totals (dict) instead of triggered_caps (list), making the classifier permanently silenced on the sync path.
backend/utils/fair_use.py Adds source parameter to record_speech_ms for logging/traceability; parameter is correctly documented as having no effect on Redis keys. Change is minimal and correct.
backend/models/conversation.py Adds is_locked: bool = False field to CreateConversation; Conversation already has the field, so propagation via **kwargs unpacking works correctly.
backend/tests/unit/test_sync_fair_use_gate.py 25 unit tests covering gate logic, lock propagation, and boundary conditions. test_exactly_at_cap_does_not_trigger has a missing assertion on the return value — it only checks that Redis was not called, meaning the boundary condition (> vs >=) is not actually verified.
backend/test.sh Adds the new test file to the unit test runner. Straightforward and correct.

Sequence Diagram

sequenceDiagram
    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
Loading

Last reviewed commit: "Add test_sync_fair_u..."

Comment thread backend/routers/sync.py Outdated
if triggered_caps:
should_lock = True
logger.info(f'sync: soft caps triggered for {uid}: {triggered_caps}')
trigger_classifier_if_needed(uid, speech_totals)

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.

P0 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):

Suggested change
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).

Comment on lines +283 to +291
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):

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.

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

Suggested change
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()

@beastoin

Copy link
Copy Markdown
Collaborator Author

Local Dev Backend Live Test Evidence

Environment:

  • LOCAL_DEVELOPMENT=true, FAIR_USE_ENABLED=true
  • Real Redis Cloud (redis-10797.c62.us-east-1-4.ec2.redns.redis-cloud.com:10797)
  • Real Firestore (based-hardware project)
  • Local Silero VAD (no hosted VAD dependency)
  • Real espeak-ng speech audio → Opus .bin (28.3s, frame_size=160)

Test 1: Full HTTP endpoint uploads (5 uploads) ✅

Upload 1: HTTP 200 — {"updated_memories":[],"new_memories":[]}
Upload 2: HTTP 200 — {"updated_memories":[],"new_memories":[]}
Upload 3: HTTP 200 — {"updated_memories":[],"new_memories":[]}
Upload 4: HTTP 200 — {"updated_memories":[],"new_memories":[]}
Upload 5: HTTP 200 — {"updated_memories":[],"new_memories":[]}

Test 2: Fair-use speech tracking ✅

All uploads show record_speech_ms with source=sync:

INFO:routers.sync:sync_local_files len(segmented_paths) 1 speech_seconds=12
INFO:utils.fair_use:fair_use: record_speech_ms uid=123 ms=12183 source=sync

VAD detected ~12s of speech from the 28.3s audio file.

Test 3: Redis Cloud accumulation ✅

fair_use:bucket:123 →
  29568095 → 168000  (uploads 1-4, first minute bucket)
  29568096 → 48732   (uploads crossing minute boundary)
  29568097 → 24366   (upload 5)
Total: 241,098ms across 3 minute-buckets
TTL: ~691,192s (8 days — matching FAIR_USE_REDIS_RETENTION_SECONDS)

Test 4: Fair-use functions (inline test) ✅

is_hard_restricted('123') → False (no enforcement state)
has_transcription_credits('123') → True (should_lock = False)
record_speech_ms(uid, 28000, source='sync') → Recorded to Redis
get_rolling_speech_ms('123') → daily=168000ms, 3day=168000ms, weekly=168000ms
check_soft_caps('123') → [] (under daily cap of 7200000ms)

Test 5: Syntax verification ✅

All 43 router files pass py_compile — including transcribe.py (untouched in this PR).

Summary

Gate Status Evidence
Hard restriction (429) ✅ is_hard_restricted checked, passes for normal user
Credit check → should_lock ✅ has_transcription_credits checked, should_lock=False
Speech tracking (Redis) ✅ 241s accumulated across 5 uploads with source=sync
Soft cap check ✅ No caps triggered (under 7200000ms daily limit)
Lock propagation ✅ is_locked passes through CreateConversation (unit tested)
Backend boots ✅ Full uvicorn startup, HTTP 200 on all uploads
All routers syntax OK ✅ 43/43 files pass py_compile

by AI for @beastoin

beastoin and others added 2 commits March 21, 2026 09:51
…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]>
@beastoin

Copy link
Copy Markdown
Collaborator Author

Greptile review fixes

P0 (fixed): trigger_classifier_if_needed is async def — was called without await, creating a never-executed coroutine. Also was passing speech_totals (dict) instead of triggered_caps (list). Fixed: asyncio.create_task(trigger_classifier_if_needed(uid, triggered_caps)), only called when caps are triggered.

P1 (fixed): test_exactly_at_cap_does_not_trigger stored result but never asserted on it. Added assert result == [] to actually validate the boundary condition.


by AI for @beastoin

@beastoin

Copy link
Copy Markdown
Collaborator Author

Live Test Evidence v2 — All code paths verified (including classifier)

Setup: FAIR_USE_DAILY_SPEECH_MS=5000 (5s, intentionally low to trigger caps), FAIR_USE_CLASSIFIER_COOLDOWN_SECONDS=5, real Redis Cloud, local Silero VAD.

Upload 1: Soft caps trigger + classifier fires ✅

HTTP 200
INFO:routers.sync:sync_local_files len(segmented_paths) 1 speech_seconds=12
INFO:utils.fair_use:fair_use: record_speech_ms uid=123 ms=12183 source=sync
INFO:routers.sync:sync: soft caps triggered for 123: [{'trigger': <SoftCapTrigger.DAILY: 'daily'>, 'speech_ms': 12183, 'threshold_ms': 5000}]
INFO:utils.llm.fair_use_classifier:fair_use: no conversations to classify for 123
ERROR:utils.fair_use:fair_use: classifier/escalation error for 123: 403 Missing or insufficient permissions.
  • Soft cap triggered: 12183ms > 5000ms daily cap ✅
  • asyncio.create_task worked: classifier actually executed (no "coroutine never awaited" warning) ✅
  • Classifier ran: fair_use_classifier.py invoked, found no conversations for test user ✅
  • Escalation attempted: hit 403 (expected — local SA lacks Firestore write to fair_use_state) ✅

Upload 2: Multiple caps trigger ✅

INFO:routers.sync:sync: soft caps triggered for 123: [
  {'trigger': <SoftCapTrigger.DAILY: 'daily'>, 'speech_ms': 24366, 'threshold_ms': 5000},
  {'trigger': <SoftCapTrigger.THREE_DAY: '3day'>, 'speech_ms': 24366, 'threshold_ms': 15000}
]
INFO:utils.llm.fair_use_classifier:fair_use: no conversations to classify for 123
  • Daily AND 3-day caps triggered ✅
  • Classifier ran again (cooldown=5s expired) ✅

"coroutine never awaited" check ✅

$ grep "coroutine.*never.*awaited" /tmp/backend_live_test.log
(no matches — P0 fix confirmed working)

Summary

Code path Before P0 fix After P0 fix
record_speech_ms ✅ worked ✅ works
check_soft_caps ✅ worked ✅ works
trigger_classifier_if_needed ❌ silently dead (coroutine never awaited) ✅ executes via asyncio.create_task
escalate_enforcement ❌ never reached ✅ reached (403 expected in local dev)

by AI for @beastoin

@beastoin
beastoin merged commit f4bcc2d into main Mar 21, 2026
1 of 2 checks passed
@beastoin
beastoin deleted the fix/sync-fair-use-gate-5854-v2 branch March 21, 2026 10:11
@beastoin

Copy link
Copy Markdown
Collaborator Author

lgtm

beastoin added a commit that referenced this pull request Mar 22, 2026
## 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)
beastoin added a commit that referenced this pull request Mar 22, 2026
…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
Glucksberg pushed a commit to Glucksberg/omi-local that referenced this pull request Apr 28, 2026
…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)
Glucksberg pushed a commit to Glucksberg/omi-local that referenced this pull request Apr 28, 2026
…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)
Glucksberg pushed a commit to Glucksberg/omi-local that referenced this pull request Apr 28, 2026
…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
pull Bot pushed a commit to Mu-L/omi that referenced this pull request May 2, 2026
…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]>
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.

1 participant