Skip to content

fix(conversations): compute duration from the transcript span on the backend discard gate and macOS - #13047

Merged
Git-on-my-level merged 9 commits into
mainfrom
fix/conversation-fragment-consolidation
Sep 8, 2026
Merged

Git-on-my-level merged 9 commits into
mainfrom
fix/conversation-fragment-consolidation

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Sep 8, 2026 •

Copy link
Copy Markdown
Member

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_at
precedes the previous record's finished_at, because they all share one capture
socket:

Conversation started_at created_at finished_at macOS showed mobile showed
Review Comments And Fix CI 23:27:11 23:41:02 23:41:43 14m 31s 17s
Conversational PM Strategy 23:27:35 23:43:43 23:46:49 19m 13s 1m 24s
Cleaner Chat UI 23:29:01 23:50:55 23:53:15 24m 13s 46s
Reassesses Tooling 23:29:48 23:59:17 00:05:08 35m 19s 2m 12s
Excited About Agent Nexus 23:32:05 00:07:09 00:08:05 36m 0s 18s
Astra's Cost 23:32:33 00:14:01 00:15:18 42m 45s 8s

The same day, 8s / 17s / 18s dictation scraps were kept instead of discarded.

Root cause

Conversation.started_at for a live-socket conversation is the streaming-session
origin — the STT stream offset plus the socket's first-audio-byte wall time
(backend/routers/listen/transcripts.py) — not the moment this conversation's
speech began. It drifts tens of minutes behind wall clock across a long socket,
so finished_at - started_at measures the age of the socket, not the
conversation. Two consumers computed exactly that:

  1. macOS display. ServerConversation.durationInSeconds returned
    finished_at - started_at whenever both timestamps existed, which is always,
    so the row and the detail header showed the session age. (It also read
    transcriptSegments.last rather than the maximum end on its fallback path,
    under-reporting an out-of-order tail.) Mobile already computes the transcript
    span and showed the truth (Bug conversation durations  #4056).
  2. The backend discard gate. process_conversation._get_structured passed the
    same wall duration to should_discard_conversation, whose prompt only applies
    its stricter "under 2 minutes" bar when duration_seconds < 120. An 8-second
    scrap 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.py is the single
authority: conversation_duration_seconds returns the transcript span — the
largest validated segment end — when the record has usable segments, and the
wall window (clamped at zero) only for transcript-free records such as photo-only
captures. Segments with blank text, non-finite start/end, or end < start
are 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_structured now calls the helper for the discard gate's duration_seconds.
utils/conversations/ARCHITECTURE.md records the new boundary.

deterministic_minimum.py was checked and does not recompute a discard duration.
The two other finished_at - started_at sites in process_conversation.py (the
pre-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.durationInSeconds prefers the transcript span with
the same validation and falls back to the wall window only when no segment can
answer. formattedDuration and all three callers (ConversationRowView,
ConversationDetailView, AuthService) are unchanged.

No recordFallback on the Swift 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 records that fallback
once, at the seam that owns the record.

Parity. contracts/parity/conversation_duration.json pins the rule with
vectors all three platforms run through their own production code — the backend
helper, ServerConversation.getDurationInSeconds (Dart), and
ServerConversation.durationInSeconds (Swift). The backend leg also validates
the 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 wall
window 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_at clock work below.

Explicitly deferred (not in this PR)

  1. Repair the provider→capture clock as one contract (receiver.py,
    streaming.py, vad_gate.py::WallTimeMapper, transcripts.py::process_loop)
    behind LISTEN_CAPTURE_CLOCK_V2_ENABLED. This PR does not change started_at
    derivation or any persisted timestamp.
  2. Exclude Omi-owned push-to-talk mic frames and Omi playback from ambient
    desktop capture (AppState+Transcription.swift;
    SystemAudioCaptureService.swift has an empty process exclusion list).
  3. Desktop ambient idle-timeout trial (5 min) and shadow continuation decisions.
  4. Coverage-based meeting-record supersede with reversible pointers.
  5. Converge the Flutter getter onto the validated-segment rule (Divergence
    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

  • INV-MEM-4 (canonical promotion is the sole Long-term authority) — matched
    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_seconds handed to should_discard_conversation, which
    decides whether a conversation is summarized at all — upstream of, and with no
    authority over, canonical memory admission.
  • INV-TASK-2 (capture proposes only where a Suggested surface exists) —
    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). A
duration 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_at on a live-socket capture is the streaming-session origin,
so finished_at - started_at reports how long the socket has been open and every
conversation 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.json and
backend/tests/unit/test_discard_gate_duration_input.py.

No existing class fit. The 29 scope-matched candidates from
scripts/pr-preflight --suggest are about omitted mirror members, re-derived
day-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_SECRET set from the
suite's test value):

  • 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 assert 2565.0 == 8.0,
    so the regression test is not vacuous.
  • python -m pytest tests/unit/test_parity_contracts.py — 16 passed
  • 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 tests/unit/test_lazy_conversation_processing.py together with the new modules
    in one process — 78 passed. The new fixture stubs utils.metrics and
    utils.observability.* and warms the jsonschema/rpds and
    pydantic.root_model imports at collection, because a second module that
    fresh-loads process_conversation otherwise dies on evicted third-party
    imports and duplicate Prometheus registration.
  • python scripts/check_module_stub_pollution.py — 1159 files, 0 violations
  • python scripts/scan_import_time_side_effects.py — 982 files, 0 violations
  • The changed-file backend lane, selected exactly as scripts/run-unit-ci.sh
    does (scripts/select_backend_unit_tests.py --changed-files → 62 files) and
    run through bash test.sh — all 30 tests in the three touched test modules
    passed. 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, and test_live_stt_failure.py. No
    assertion 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 than
    hidden: 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 (unchanged
    behavior, run as a regression check)
  • The full app/test.sh was not run: this worktree has no
    lib/firebase_options_*.dart or lib/env/*_env.g.dart, which that script
    requires.

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, Apple
Swift version 6.2.4, target arm64-apple-macosx26.0. A local pass is not proof
the pinned CI toolchain agrees.

  • 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").
  • desktop/macos/scripts/swiftlint-wrapper.sh lint — 1634 files, 0 violations
  • desktop/macos/scripts/swift-format-wrapper.sh format -i applied to both
    changed Swift files

Contract gates:

  • OMI_PR_BODY_FILE=.pr-body.md make preflight — PR preflight passed: 39
    checks in 140.05s
    , including product-file-line-count-ratchet,
    product-invariants, failure-class-protocol, desktop-changelog-entry,
    desktop-test-quality, backend-module-isolation, and backend-import-purity.
  • No Line-Count-Exception is needed:
    backend/utils/conversations/process_conversation.py stays 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 is
where the gate's input is actually computed.

🤖 Generated with Claude Code

Review in cubic

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 13 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread backend/utils/conversations/duration.py Resolved
Git-on-my-level and others added 6 commits September 8, 2026 13:51
…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
Git-on-my-level force-pushed the fix/conversation-fragment-consolidation branch from 4877836 to 125c566 Compare September 8, 2026 07:20
… 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.
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