Repository navigation
fix(conversations): compute duration from the transcript span on the backend discard gate and macOS - #13047
Merged
Conversation
There was a problem hiding this comment.
All reported issues were addressed across 13 files
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
…script `started_at` on a live-socket conversation is the streaming-session origin — the STT stream offset plus the socket's first-audio-byte wall time — not the moment this conversation's speech began, so it drifts tens of minutes behind wall clock across a long socket. `_get_structured` computed `finished_at - started_at` and handed that to `should_discard_conversation`, whose prompt only applies its stricter "under 2 minutes" bar below 120s. An 8-second dictation scrap recorded 42 minutes into a socket therefore reached the model labelled 2565 seconds, the short-content rule never fired, and 8s / 17s / 18s scraps were kept (measured on a real account 2026-09-07). Adds `utils/conversations/duration.py` as the single authority for a conversation's duration: the transcript span (largest validated segment `end`) when the record has usable segments, the wall window only for transcript-free records such as photo-only captures. Segments with blank text, non-finite bounds, or `end < start` are ignored; a record whose segments all fail validation falls back to the wall window and records a `record_fallback` because that input is degraded. Mobile already ships this rule (`ServerConversation.getDurationInSeconds`, #4056); this is the backend half. No change to `started_at`/`finished_at` derivation or persistence, the discard prompt, its thresholds, or the calendar-overlap override. Verification (backend/.venv, Python 3.11.13): - `python -m pytest tests/unit/test_conversation_duration.py` — 13 passed - `python -m pytest tests/unit/test_discard_gate_duration_input.py` — 3 passed; reverting the `_get_structured` change fails it with `2565.0 != 8.0` - `python -m pytest tests/unit/test_discard_calendar_override.py tests/unit/test_process_conversation_free_tier_branch.py tests/unit/test_conversation_discard_revival.py` — 40 passed alongside the new module in one process (its fixture stubs `utils.metrics` / `utils.observability.*` so a second fresh load cannot duplicate-register Prometheus collectors) - `python scripts/check_module_stub_pollution.py` — 0 violations - `python scripts/scan_import_time_side_effects.py` — 0 violations Co-Authored-By: Claude Fable 5.1 <[email protected]>
…t the socket The macOS row and detail header read `finished_at - started_at`, which is the lifetime of the live capture socket rather than of this conversation, so six consecutive conversations measured on a real account 2026-09-07 showed 14m31s / 19m13s / 24m13s / 35m19s / 36m0s / 42m45s where mobile showed 17s / 1m24s / 46s / 2m12s / 18s / 8s. The worst case, an 8-second dictation scrap, rendered as "42m 45s". `ServerConversation.durationInSeconds` now prefers the transcript span (largest validated segment `end`, ignoring blank-text, non-finite, and reversed segments) and falls back to the wall window only when no segment can answer — matching `utils/conversations/duration.py` and the Flutter `getDurationInSeconds` (#4056). The old code also took `transcriptSegments.last` rather than the maximum `end`, so an out-of-order tail under-reported. `formattedDuration` and every caller are unchanged. A list response that omits `transcript_segments` still reports the wall window; that is the same answer mobile gives, and there is nothing else to measure. No `recordFallback` on the wall-window branch: `durationInSeconds` is a computed property evaluated on every row render, so emitting there would produce unbounded telemetry for a static condition. The backend helper records that fallback once, at the seam that owns the record. Toolchain: this Mac has Xcode 26.x while CI pins 16.4, so these results are the local toolchain's, not proof the pinned CI toolchain agrees. Verification (`swift-driver version: 1.135.3`, Apple Swift version 6.2.4, target arm64-apple-macosx26.0): - `xcrun swift build --build-tests --package-path Desktop` — Build complete - `./scripts/dev-feedback.py --once swift 'ConversationDurationTests'` — 13 tests, 0 failures - reverting `durationInSeconds` to its previous body fails all 13, including `("2565") is not equal to ("8")` and `("42m 45s") is not equal to ("8s")` Co-Authored-By: Claude Fable 5.1 <[email protected]>
… and macOS Conversation duration is exactly the class of rule the parity contracts exist for: one product rule, three implementations, and a silent divergence that showed 42m45s on macOS and 8s on mobile for the same 8-second capture. `contracts/parity/conversation_duration.json` holds the vectors the three platforms agree on — transcript span wins over the wall window, the span is the maximum segment `end` rather than the last element, a zero-length transcript is zero and not the window, and a transcript-free record falls back to the window. Each platform runs them through its own production code: `conversation_duration_seconds`, `ServerConversation.getDurationInSeconds`, and `ServerConversation.durationInSeconds`. The backend leg also checks the fixture is internally well-formed so a rotted vector cannot pass vacuously everywhere at once. Malformed inputs are deliberately outside the fixture and recorded as Divergence register entry 6: backend and macOS validate each segment and clamp a reversed wall window, while the Flutter getter takes the raw maximum `end` and returns a negative duration unclamped. Flutter is the losing platform; converging it means changing `app/lib/backend/schema/conversation.dart` and adding those vectors in the same PR. Verification: - `python -m pytest tests/unit/test_parity_contracts.py` — 16 passed - `flutter test test/parity/parity_contracts_test.dart` — 35 passed, 5 skipped (day-key cases outside the runner's zone offset); all 8 duration cases ran - `./scripts/dev-feedback.py --once swift 'ConversationDurationTests'` — 13 tests, 0 failures, including `testSharedDurationContractVectors` Co-Authored-By: Claude Fable 5.1 <[email protected]>
…duration Registers the class this PR's two fixes instance: a duration displayed to a user or fed to a policy decision must be measured from the content it describes, not from a capture-session timestamp that merely bounds it. The subtraction never fails, so the wrong number reaches a UI label and an LLM policy prompt with no error, no metric, and green per-platform tests. Its guard artifacts are the two surfaces added in this PR: the shared vectors in `contracts/parity/conversation_duration.json`, which every platform runs through its own production code, and `backend/tests/unit/test_discard_gate_duration_input.py`, which drives the real `_get_structured` seam and captures the value the discard gate receives. None of the 29 scope-matched existing definitions states this contract; the nearest are about omitted mirror members, re-derived day-bucket keys, and PTT capture start latency. Verification: `scripts/failure-class validate --pr-body-file .pr-body.md` Co-Authored-By: Claude Fable 5.1 <[email protected]>
- macOS: clamp the transcript span into Int range before Int(Double); a finite segment end beyond Int.max traps and crashes the client (P1) - backend: normalize naive timestamps to UTC before the wall-window subtraction; naive-minus-aware raised TypeError and silently dropped duration metadata from the discard prompt (P2) - docs: state that the wall-window fallback also covers records whose segments all fail validation, matching the malformed-doc branch (P3)
The pre-push gate formats changed files; this file was added unformatted in the parity-test commit.
Git-on-my-level
force-pushed
the
fix/conversation-fragment-consolidation
branch
from
September 8, 2026 07:20
4877836 to
125c566
Compare
…ment-consolidation
… boundary Double(Int.max) rounds up to 2^63, so Int(Double(Int.max)) traps — the clamp added in 9c09968 crashed the exact case it was meant to guard. Compare in Double space before converting; the clamp now returns Int.max.
This was referenced Sep 27, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What was measured
The same conversation reported 42m45s on macOS and 8s on mobile. Six consecutive
conversations on a real account, UTC 2026-09-07/08 — note that every
started_atprecedes the previous record's
finished_at, because they all share one capturesocket:
The same day, 8s / 17s / 18s dictation scraps were kept instead of discarded.
Root cause
Conversation.started_atfor a live-socket conversation is the streaming-sessionorigin — the STT stream offset plus the socket's first-audio-byte wall time
(
backend/routers/listen/transcripts.py) — not the moment this conversation'sspeech began. It drifts tens of minutes behind wall clock across a long socket,
so
finished_at - started_atmeasures the age of the socket, not theconversation. Two consumers computed exactly that:
ServerConversation.durationInSecondsreturnedfinished_at - started_atwhenever both timestamps existed, which is always,so the row and the detail header showed the session age. (It also read
transcriptSegments.lastrather than the maximumendon its fallback path,under-reporting an out-of-order tail.) Mobile already computes the transcript
span and showed the truth (Bug conversation durations #4056).
process_conversation._get_structuredpassed thesame wall duration to
should_discard_conversation, whose prompt only appliesits stricter "under 2 minutes" bar when
duration_seconds < 120. An 8-secondscrap arrived labelled 2565 seconds, so the short-content rule never fired.
Nothing failed along the way: the subtraction succeeds, no decode error or
exception is raised, and each platform's tests stayed green because each asserted
the number it computed.
What changed
Backend. New
backend/utils/conversations/duration.pyis the singleauthority:
conversation_duration_secondsreturns the transcript span — thelargest validated segment
end— when the record has usable segments, and thewall window (clamped at zero) only for transcript-free records such as photo-only
captures. Segments with blank text, non-finite
start/end, orend < startare ignored; when segments exist but none survives validation it falls back to
the wall window and calls the shared
record_fallback(
conversation_finalization,transcript_span→wall_clock,malformed_doc,degraded), because that input is degraded rather than absent._get_structurednow calls the helper for the discard gate'sduration_seconds.utils/conversations/ARCHITECTURE.mdrecords the new boundary.deterministic_minimum.pywas checked and does not recompute a discard duration.The two other
finished_at - started_atsites inprocess_conversation.py(thepre-finalization meeting cost gate at ~L2293 and the >30-minute important-
conversation notification at ~L2760) are not on the discard path and are
deliberately untouched.
macOS.
ServerConversation.durationInSecondsprefers the transcript span withthe same validation and falls back to the wall window only when no segment can
answer.
formattedDurationand all three callers (ConversationRowView,ConversationDetailView,AuthService) are unchanged.No
recordFallbackon the Swift wall-window branch:durationInSecondsis acomputed property evaluated on every row render, so emitting there would produce
unbounded telemetry for a static condition. The backend records that fallback
once, at the seam that owns the record.
Parity.
contracts/parity/conversation_duration.jsonpins the rule withvectors all three platforms run through their own production code — the backend
helper,
ServerConversation.getDurationInSeconds(Dart), andServerConversation.durationInSeconds(Swift). The backend leg also validatesthe fixture is internally well-formed so a rotted vector cannot pass vacuously
everywhere at once.
Known limitation
A list response may omit
transcript_segments; those rows still report the wallwindow because there is nothing else to measure. That is the same answer mobile
gives, so the platforms agree, and the desktop reconciliation policy retains
cached segments for any conversation that has been opened. Repairing it properly
belongs with the
started_atclock work below.Explicitly deferred (not in this PR)
receiver.py,streaming.py,vad_gate.py::WallTimeMapper,transcripts.py::process_loop)behind
LISTEN_CAPTURE_CLOCK_V2_ENABLED. This PR does not changestarted_atderivation or any persisted timestamp.
desktop capture (
AppState+Transcription.swift;SystemAudioCaptureService.swifthas an empty process exclusion list).register entry 6 in
contracts/parity/README.md).No feature flag on either side: both are defect corrections, and mobile already
ships the corrected rule unflagged.
Product invariants affected
because the diff touches
backend/utils/conversations/process_conversation.py.Not weakened: no intake route, consolidation decision, promotion receipt, or
Short-term/Long-term transition is touched. The only behavior change is the
value of
duration_secondshanded toshould_discard_conversation, whichdecides whether a conversation is summarized at all — upstream of, and with no
authority over, canonical memory admission.
matched for the same file. Not weakened: no capture-policy outcome, Candidate
creation, acceptance path, extraction prompt, or surface gate is touched. The
change cannot create, accept, or expire a Candidate; a more accurate duration
only makes the discard gate judge content correctly before extraction runs.
Failure-Class: new
Failure class
FC-capture-session-window-read-as-content-duration(added in this PR). Aduration that is displayed to a user or fed to a policy decision must be measured
from the content it describes, never from a capture-session timestamp that merely
bounds it.
started_aton a live-socket capture is the streaming-session origin,so
finished_at - started_atreports how long the socket has been open and everyconversation after the first in a session inherits the whole session's age; the
subtraction never fails, so the wrong number reaches a UI label and an LLM policy
prompt with no error, no metric, and green per-platform tests. Prevention is to
derive the duration from the content through one named authority per platform and
keep the capture-window timestamps only as the fallback for records with no
content to measure, with the cross-platform rule pinned by shared fixture vectors
so a divergence is a fixture edit rather than silent drift. Guard artifacts:
contracts/parity/conversation_duration.jsonandbackend/tests/unit/test_discard_gate_duration_input.py.No existing class fit. The 29 scope-matched candidates from
scripts/pr-preflight --suggestare about omitted mirror members, re-derivedday-bucket keys, and PTT capture start latency; none states the contract that a
policy or display duration must be measured from content rather than from a
bounding capture window.
Verification
Backend (
backend/.venv, Python 3.11.15,ENCRYPTION_SECRETset from thesuite's test value):
python -m pytest tests/unit/test_conversation_duration.py— 13 passedpython -m pytest tests/unit/test_discard_gate_duration_input.py— 3 passed.Reverting the
_get_structuredchange fails it withassert 2565.0 == 8.0,so the regression test is not vacuous.
python -m pytest tests/unit/test_parity_contracts.py— 16 passedpython -m pytest tests/unit/test_discard_calendar_override.py tests/unit/test_process_conversation_free_tier_branch.py tests/unit/test_conversation_discard_revival.py tests/unit/test_lazy_conversation_processing.pytogether with the new modulesin one process — 78 passed. The new fixture stubs
utils.metricsandutils.observability.*and warms thejsonschema/rpdsandpydantic.root_modelimports at collection, because a second module thatfresh-loads
process_conversationotherwise dies on evicted third-partyimports and duplicate Prometheus registration.
python scripts/check_module_stub_pollution.py— 1159 files, 0 violationspython scripts/scan_import_time_side_effects.py— 982 files, 0 violationsscripts/run-unit-ci.shdoes (
scripts/select_backend_unit_tests.py --changed-files→ 62 files) andrun through
bash test.sh— all 30 tests in the three touched test modulespassed. Four untouched files reported
status 1:test_byok_llm_logging.py,test_chat_file_gateway_stub_import_contract.py,test_backend_runtime_env_validator.py, andtest_live_stt_failure.py. Noassertion failed in any of them; each tripped the fast-unit CPU-duration guard
(0.30–0.36s against its 0.30s fail limit) on this machine while several pytest
processes ran in parallel. Re-running those files on their own
(
BACKEND_UNIT_TEST_FILE_LIST=...) passes 142 tests. Called out rather thanhidden: they are a local machine-speed artifact, not a regression from this
change, and none of them imports anything this PR touches.
Flutter (Flutter 3.44.5):
flutter test test/parity/parity_contracts_test.dart— 35 passed, 5 skipped(day-key cases outside the runner's zone offset); all 8 duration cases ran
flutter test test/unit/conversation_duration_test.dart— 6 passed (unchangedbehavior, run as a regression check)
app/test.shwas not run: this worktree has nolib/firebase_options_*.dartorlib/env/*_env.g.dart, which that scriptrequires.
macOS Swift — toolchain caveat: CI pins Xcode 16.4 and this Mac only has
Xcode 26.x, so these results come from
swift-driver version: 1.135.3, AppleSwift version 6.2.4, target
arm64-apple-macosx26.0. A local pass is not proofthe pinned CI toolchain agrees.
xcrun swift build --build-tests --package-path Desktop— Build complete./scripts/dev-feedback.py --once swift 'ConversationDurationTests'— 13tests, 0 failures
durationInSecondsto its previous body fails all 13, including("2565") is not equal to ("8")and("42m 45s") is not equal to ("8s").desktop/macos/scripts/swiftlint-wrapper.sh lint— 1634 files, 0 violationsdesktop/macos/scripts/swift-format-wrapper.sh format -iapplied to bothchanged Swift files
Contract gates:
OMI_PR_BODY_FILE=.pr-body.md make preflight— PR preflight passed: 39checks in 140.05s, including
product-file-line-count-ratchet,product-invariants,failure-class-protocol,desktop-changelog-entry,desktop-test-quality,backend-module-isolation, andbackend-import-purity.Line-Count-Exceptionis needed:backend/utils/conversations/process_conversation.pystays at 2950 lines,because the call-site comment was trimmed to a two-line pointer once the rule
and its rationale moved into
utils/conversations/duration.py's docstring.Not exercised end-to-end: the macOS change was verified by unit test only. No dev
named bundle was launched and no live conversation row was observed, so the
"exercised the real path" evidence for the desktop half is test-level. The
backend half is exercised through the production seam
_get_structured, which iswhere the gate's input is actually computed.
🤖 Generated with Claude Code