Repository navigation
fix(sync): add missing record_usage to sync endpoints + deprecate v1 - #7125
Conversation
record_usage(uid, transcription_seconds, speech_seconds) was removed in PR #5875 revert and never re-added in #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 #7123 Co-Authored-By: Claude Opus 4.6 <[email protected]>
Greptile SummaryThis PR re-adds
Confidence Score: 3/5Not safe to merge as-is — two P1 defects affect billing correctness and the stated deprecation header contract. Two independent P1 bugs: (1) users charged for entirely-failed transcription batches in both v1 and v2, and (2) Deprecation headers missing from HTTPException error responses despite the PR test plan explicitly requiring them on all status codes. backend/routers/sync.py — specifically the record_usage placement relative to the all-fail check, and the HTTPException deprecation header gaps. Important Files Changed
Sequence DiagramsequenceDiagram
participant Client
participant v1 as POST /v1/sync-local-files
participant v2bg as _process_segments_background
participant RU as record_usage()
participant FS as Firestore
Client->>v1: upload files
v1->>v1: set Deprecation header on Response obj
v1->>v1: VAD segmentation
alt hard-restrict gate
v1-->>Client: HTTPException 429 (Deprecation header LOST)
end
alt DG budget exhausted
v1-->>Client: JSONResponse 429 (Deprecation: true OK)
end
v1->>v1: process segments
v1->>RU: record_usage() called before all-fail check
RU->>FS: update_hourly_usage
alt all segments failed
v1-->>Client: HTTPException 500 (Deprecation header LOST, credits already charged)
end
alt partial failure
v1-->>Client: JSONResponse 207 (Deprecation: true OK)
end
v1-->>Client: 200 OK (Deprecation: true OK)
Client->>v2bg: background job
v2bg->>v2bg: process segments
v2bg->>RU: record_usage() called before all-fail check
RU->>FS: update_hourly_usage
v2bg->>v2bg: mark_job_completed / mark_job_failed
|
| # Record subscription usage (transcription credits) | ||
| try: | ||
| usage_seconds = int(total_speech_seconds) | ||
| if usage_seconds > 0: | ||
| record_usage(uid, transcription_seconds=usage_seconds, speech_seconds=usage_seconds) | ||
| except Exception as e: | ||
| logger.error(f'sync: usage record error for {uid}: {e}') |
There was a problem hiding this comment.
Usage recorded before all-fail guard
record_usage is called unconditionally before the "all segments failed → 500" check at line 1265. If every segment fails processing, subscription credits are still debited even though no transcription succeeded. The call should be placed after confirming at least one segment succeeded (i.e., after the if total_segments > 0 and successful_segments == 0: raise HTTPException(...) block).
| if is_hard_restricted(uid): | ||
| raise HTTPException(status_code=429, detail="Account temporarily restricted due to fair-use policy") |
There was a problem hiding this comment.
Deprecation headers lost on HTTPException responses
Headers set on the injected response: Response object (lines 1103–1104) are not forwarded when FastAPI raises an HTTPException — the exception handler builds a fresh response, discarding the injected object's headers. This means the hard-restrict HTTPException(status_code=429) path and the all-fail HTTPException(status_code=500) path will never carry Deprecation: true, contradicting the PR's stated test plan. The DG-budget 429 and partial-fail 207 are fine because they use explicit JSONResponse(headers=...), but this path is not.
| # Record subscription usage (transcription credits) | ||
| try: | ||
| usage_seconds = int(total_speech_seconds) | ||
| if usage_seconds > 0: | ||
| record_usage(uid, transcription_seconds=usage_seconds, speech_seconds=usage_seconds) | ||
| except Exception as e: | ||
| logger.error(f'sync_v2: usage record error for {uid}: {e}') |
There was a problem hiding this comment.
v2: usage recorded even when all segments fail
Same pattern as v1 — in _process_segments_background, record_usage is called before any check on failed_segments. If every segment fails, mark_job_completed is still called with failed_segments == total_segments and the job result shows complete failure, but subscription credits have already been debited. The call should be guarded so it only executes when successful_segments > 0.
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]>
…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]>
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]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Live Test EvidenceL1 — Backend standaloneBoot check: v1 deprecation headers (all response paths): v2 no deprecation headers (correct — not deprecated): Unit tests: 19/19 passed in L2 — IntegratedBackend-only change with no response format changes. v2 endpoint (used by all clients) behavior is unchanged — by AI for @beastoin |
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]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
lgtm |
Summary
record_usage(uid, transcription_seconds=..., speech_seconds=...)to both v1sync_local_files()and v2_process_segments_background()after successful segment processingPOST /v1/sync-local-filesas deprecated withDeprecation: trueheader, successor-version link, and warning logsyncLocalFiles()from Flutter app, removed its export from WAL interfacesContext
PR #5863 originally added
record_usageto sync endpoints. PR #5875 reverted it. PR #5878 re-added fair-use gates but did not re-addrecord_usage, leaving sync transcription invisible to the subscription credit system. Basic-plan users could sync without usage being counted toward their monthly limit.Changes
backend/routers/sync.pyrecord_usage, add calls in v1 and v2 paths, deprecate v1 endpoint with headers on all response pathsbackend/tests/unit/test_sync_record_usage.pybackend/test.shapp/lib/backend/http/api/conversations.dartsyncLocalFiles()functionapp/lib/services/wals/wal_interfaces.dartapp/lib/services/wals/storage_sync.dartLive test evidence
L1 — v1 endpoint with real audio (PCM16 3s)
Backend log:
L1 — v2 endpoint with same audio (no deprecation headers)
L2 — Client cannot use v1
syncLocalFiles()function removed fromconversations.dartwal_interfaces.dartsyncLocalFilesV2()exclusivelygrep -rn "syncLocalFiles\b" app/lib/ | grep -v V2returns emptyReview cycle changes
_V1_DEPRECATION_HEADERSconstant andheaders=param to allHTTPExceptionraises in v1record_usageafter all-segments-failed guard.Test plan
Deprecation: trueheader with audio filerecord_usageonly runs whensuccessful_segments > 0test_sync_record_usage.pyRisks
record_usagecalls Firestore — wrapped in try/except so failure is logged but doesn't break syncCloses #7123
🤖 Generated with Claude Code