Skip to content

fix(sync): add missing record_usage to sync endpoints + deprecate v1 - #7125

Merged
beastoin merged 8 commits into
mainfrom
fix/sync-record-usage-7123
May 2, 2026
Merged

beastoin merged 8 commits into
mainfrom
fix/sync-record-usage-7123

Conversation

@beastoin

@beastoin beastoin commented May 2, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Adds record_usage(uid, transcription_seconds=..., speech_seconds=...) to both v1 sync_local_files() and v2 _process_segments_background() after successful segment processing
  • Marks v1 POST /v1/sync-local-files as deprecated with Deprecation: true header, successor-version link, and warning log
  • Removes v1 client code — deleted syncLocalFiles() from Flutter app, removed its export from WAL interfaces

Context

PR #5863 originally added record_usage to sync endpoints. PR #5875 reverted it. PR #5878 re-added fair-use gates but did not re-add record_usage, leaving sync transcription invisible to the subscription credit system. Basic-plan users could sync without usage being counted toward their monthly limit.

Changes

File Change
backend/routers/sync.py Import record_usage, add calls in v1 and v2 paths, deprecate v1 endpoint with headers on all response paths
backend/tests/unit/test_sync_record_usage.py 19 structural tests for record_usage placement and v1 deprecation
backend/test.sh Add new test file to CI
app/lib/backend/http/api/conversations.dart Remove v1 syncLocalFiles() function
app/lib/services/wals/wal_interfaces.dart Remove v1 export
app/lib/services/wals/storage_sync.dart Update comment to reference v2

Live test evidence

L1 — v1 endpoint with real audio (PCM16 3s)

$ curl -D- -X POST "http://localhost:8700/v1/sync-local-files" \
  -H "Authorization: Bearer ADMIN_KEY123test-uid" \
  -F "files=@audio_phonemic_pcm16_16000_1_fs160_1777697725.bin"

HTTP/1.1 200 OK
deprecation: true
link: </v2/sync-local-files>; rel="successor-version"
{"new_memories":[],"updated_memories":[]}

Backend log:

WARNING:routers.sync:sync: deprecated v1 sync-local-files called uid=123 files=1 user_agent=curl/8.5.0
INFO:routers.sync:sync_local_files len(segmented_paths) 0 speech_seconds=0

L1 — v2 endpoint with same audio (no deprecation headers)

$ curl -D- -X POST "http://localhost:8700/v2/sync-local-files" \
  -H "Authorization: Bearer ADMIN_KEY123test-uid" \
  -F "files=@audio_phonemic_pcm16_16000_1_fs160_1777697725.bin"

HTTP/1.1 200 OK
(no deprecation headers)
{"new_memories":[],"updated_memories":[]}

L2 — Client cannot use v1

  • syncLocalFiles() function removed from conversations.dart
  • Export removed from wal_interfaces.dart
  • All callers use syncLocalFilesV2() exclusively
  • grep -rn "syncLocalFiles\b" app/lib/ | grep -v V2 returns empty

Review cycle changes

  • Round 1: Added _V1_DEPRECATION_HEADERS constant and headers= param to all HTTPException raises in v1
  • Round 2: Wrapped shared-helper calls in try/except to re-raise with deprecation headers. Moved record_usage after all-segments-failed guard.
  • Round 3: Removed v1 client code per manager feedback.

Test plan

  • Boot check passes (no import/syntax errors)
  • Real curl test: v1 returns Deprecation: true header with audio file
  • Real curl test: v2 works without deprecation headers
  • record_usage only runs when successful_segments > 0
  • All v1 response paths (200, 207, 429, 500, 400) carry deprecation headers
  • v1 client code removed — no Flutter/Desktop callers can use v1
  • 19 unit tests pass in test_sync_record_usage.py

Risks

  • record_usage calls Firestore — wrapped in try/except so failure is logged but doesn't break sync
  • v1 backend endpoint kept for backward compatibility with old app versions still in the wild

Closes #7123

🤖 Generated with Claude Code

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-apps

greptile-apps Bot commented May 2, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR re-adds record_usage to both the v1 and v2 sync paths (previously dropped in PR #5878) and deprecates the v1 endpoint with Deprecation: true headers and a warning log.

  • P1: In both v1 and v2, record_usage is called before the "all segments failed" guard — subscription credits are debited even when every transcription attempt fails.
  • P1: The Deprecation: true header set on the injected Response object is silently dropped for HTTPException-based responses (hard-restrict 429, all-fail 500); only the explicit JSONResponse(headers=...) paths carry the header correctly.

Confidence Score: 3/5

Not 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

Filename Overview
backend/routers/sync.py Adds record_usage to v1 and v2 sync paths and deprecates v1; two P1 bugs: usage is charged even when all segments fail (both paths), and Deprecation headers are silently dropped on HTTPException responses.

Sequence Diagram

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

Comments Outside Diff (1)

  1. backend/routers/sync.py, line 1165 (link)

    P2 response parameter shadowed by local dict

    The response: Response FastAPI parameter is reassigned here to a plain dict. The deprecation headers were already written to the original Response object before this line, so the 200 return works today because FastAPI holds its own reference to the injected object. However, any future response.headers[...] call after this line would silently operate on a dict and lose the header. Renaming the local dict (e.g., memo_result = {…}) would eliminate the ambiguity.

Reviews (1): Last reviewed commit: "fix(sync): add missing record_usage to s..." | Re-trigger Greptile

Comment thread backend/routers/sync.py Outdated
Comment on lines +1239 to +1245
# 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}')

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

Comment thread backend/routers/sync.py Outdated
Comment on lines 1107 to 1108
if is_hard_restricted(uid):
raise HTTPException(status_code=429, detail="Account temporarily restricted due to fair-use policy")

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

Comment thread backend/routers/sync.py Outdated
Comment on lines +1392 to +1398
# 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}')

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

beastoin and others added 4 commits May 2, 2026 04:27
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]>
@beastoin

beastoin commented May 2, 2026

Copy link
Copy Markdown
Collaborator Author

Live Test Evidence

L1 — Backend standalone

Boot check: beast omi dev boot-check --full — uvicorn starts, health endpoint responds on :8700.

v1 deprecation headers (all response paths):

$ curl -D- -X POST "http://localhost:8700/v1/sync-local-files" -H "Authorization: Bearer ADMIN_KEY123test-uid" -F "files=@/dev/null;filename=1714500000.bin"

HTTP/1.1 400 Bad Request
deprecation: true
link: </v2/sync-local-files>; rel="successor-version"

v2 no deprecation headers (correct — not deprecated):

$ curl -D- -X POST "http://localhost:8700/v2/sync-local-files" -H "Authorization: Bearer ADMIN_KEY123test-uid" -F "files=@/dev/null;filename=1714500000.bin"

HTTP/1.1 400 Bad Request
(no deprecation headers)

Unit tests: 19/19 passed in test_sync_record_usage.py

L2 — Integrated

Backend-only change with no response format changes. v2 endpoint (used by all clients) behavior is unchanged — record_usage is a fire-and-forget side effect wrapped in try/except. App compatibility preserved.

by AI for @beastoin

beastoin and others added 3 commits May 2, 2026 04:57
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]>
@beastoin

beastoin commented May 2, 2026

Copy link
Copy Markdown
Collaborator Author

lgtm

@beastoin
beastoin merged commit 080b78b into main May 2, 2026
2 checks passed
@beastoin
beastoin deleted the fix/sync-record-usage-7123 branch May 2, 2026 07:42
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.

fix(sync): add missing record_usage to sync-local-files + deprecate v1 endpoint

1 participant