Skip to content

feat(listen): add demand ramp outcome and wire telemetry - #21923

Merged
Git-on-my-level merged 5 commits into
mainfrom
live-demand-telemetry
Oct 16, 2026
Merged

Git-on-my-level merged 5 commits into
mainfrom
live-demand-telemetry

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 16, 2026 •

Copy link
Copy Markdown
Member

Makes the listen 5% → 25% → 100% demand ramp measurable with a cohort pinned once per session, successful paid-provider wire seconds, decoded capture exposure, distinct exhausted sessions, failure detail, serving-lane time, and first-output/visible-return latency with censored-wait counts. Existing dashboards and alerts aggregate the additive labels; defaults and serving policy remain unchanged.

Admission is independent of optional instrumentation. Bootstrap initializes telemetry/recovery pins without requiring __init__, and never touches the receiver before component construction. Receiver construction applies its cohort to an optional lane meter. Missing or faulty attachments resolve to ineligible; metric label binding, mutation, construction, and callback errors cannot interrupt bootstrap, audio writes, transcript delivery, or teardown. Actual transport failures retain their original behavior.

Validation: 311 targeted cases across 11 files passed with explicit BACKEND_UNIT_TEST_FILE_LIST, nice -n 19, one worker, and file isolation. This includes the unchanged runtime bootstrap, parity-runtime, ready-provider, and speaker-embedding regressions; runtime image contracts; demand policy/handover, session outcomes, fallback, and provider selection. The 42 telemetry cases cover real runtimes with absent/faulty attachments and raising label binding or mutation. Grok fault injection checks both async vendor queues commit successful writes exactly once, Deepgram's installed SDK and SafeDeepgramSocket keep accepting later audio, client-state still reaches policy and following audio reaches STT, delivered transcripts remain transcribed across repeated deliveries, failover reaches the next provider or typed exhaustion, and the demand lifetime loop still returns to vendor. Tests use the repository's 1.0s CI CPU ceiling (the local default is 0.30s); no test timing allowlist or existing runtime regression tests were changed. test_app_client_schema_inventory is excluded as requested.

The cheap hermetic listen E2E selection passed 13 tests (120 deselected), exit 0, at this head. It is not a process-stack gauntlet result. Current Pyright reports 0 errors; PR metadata passed all 4 checks. make preflight passed all 34 selected checks, including source closure for 17 runtime images and the seven-file Firestore guard executed serially with a local execution-only runner override. The E2E process emitted a closed-stream logger warning at interpreter shutdown after its green summary.

Merged origin/main at 50737e86a7b2 via merge commit b520cf24da6; no rebase. Invalid client-state reports now preserve the last valid telemetry visibility and pending wait with a one-line change; routing still treats invalid reports as unknown. The owning pipeline guide documents metric definitions and the no-raise boundary. The coordination report data/run-2026-10-13-two-lane-nemotron/sol-demand-telemetry.md contains exact gate PromQL and a site-by-site Grok fixes section. No production writes, endpoint requests, deployment, or ramp.

Product invariants affected

none

Failure class

Failure-Class: none

This corrects a pre-merge integration regression in this telemetry PR. No existing failure-class definition matches the optional telemetry/bootstrap ordering mechanism, and no new production incident attribution is claimed.

Line-Count-Exception: backend/routers/listen/receiver.py | 2555 -> 2564 | Adapter-local capture and successful-write hooks delegate to shared no-raise telemetry primitives; unrelated lifecycle extraction is outside this additive telemetry PR.
Line-Count-Exception: backend/utils/stt/streaming.py | 2373 -> 2401 | Adapter-local capture and successful-write hooks delegate to shared no-raise telemetry primitives; unrelated lifecycle extraction is outside this additive telemetry PR.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-16T19:26:52.587439Z b89fee7 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b2d87ad01a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/utils/stt/streaming.py Outdated
Comment on lines +1443 to +1445
sample_rate: int = 16000,
) -> None:
self._demand_wire = WireAudioMeter('modulate', sample_rate)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Pass the negotiated sample rate to routed Modulate sockets

When connect_modulate() uses a configured registry endpoint, backend/utils/stt/live_target_connect.py:35 still constructs SafeModulateSocket without the negotiated sample_rate, so this meter silently assumes 16 kHz even though the query sent to Modulate uses the actual rate. For example, a successful 48 kHz write is reported as three times its real duration, corrupting the wire-audio comparison used for the ramp; update that in-tree constructor call along with this API change.

AGENTS.md reference: AGENTS.md:L34-L34

Useful? React with 👍 / 👎.

Comment thread backend/routers/listen/runtime.py Outdated
Comment on lines +426 to +428
telemetry = getattr(self, 'demand_telemetry', None)
if telemetry is not None:
telemetry.finish()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Finish output waits for custom-STT sessions

For a custom-STT session, _record_session_transcript_outcome() returns at line 414 before reaching this finish(), even though the receiver still calls telemetry.capture() for decoded audio and observe_visibility() for client-state reports. If such a session starts a first-output or visible-return wait and then closes without delivering text, its required no_output event is never emitted, biasing the censored-latency accounting for the ineligible cohort; finish this telemetry independently of the backend-STT outcome path.

Useful? React with 👍 / 👎.

Comment on lines +88 to +95
def observe_visibility(self, payload) -> None:
foreground, visible = payload.get('foreground'), payload.get('transcript_visible')
state = None
if type(foreground) is bool and type(visible) is bool and (foreground or not visible):
state = 'visible' if visible else 'hidden'
if state == 'visible' and self.visibility == 'hidden':
self.visible_at = monotonic()
self.output_event('visible_return', 'started')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Enforce the client-state report budget before recording waits

After a session reaches the existing 2,000-report limit, RealtimeDemandTracker.observe() and DemandPolicy.observe() reject or invalidate further client-state changes, but this new observer has no equivalent budget and is called before those checks. A buggy or hostile client can therefore keep alternating hidden and visible indefinitely, producing unbounded started/no_output visible-return events from one socket and skewing the ramp telemetry; apply the same report cap before changing this state.

Useful? React with 👍 / 👎.

@@ -12,11 +12,14 @@ def __init__(self, clock: Callable[[], float] = time.monotonic):
self.since: float | None = None
self.lane = 'vendor'
self.reason = 'baseline'

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Add the demand cohort to lane-switch telemetry

The new telemetry contract in backend/docs/listen_pusher_pipeline.mdx:4949 says the serving-lane metrics gain demand_cohort, but this field is only applied to lane seconds: DEMAND_SWITCHES is still emitted with just from_lane, to_lane, and reason. Consequently demand handovers cannot be separated from control or ineligible window/fallback transitions, so the switch counts cannot support the intended cohort comparison; propagate this pinned field into the switch counter as well.

Useful? React with 👍 / 👎.

Comment thread backend/routers/listen/receiver.py Outdated
Comment on lines +2281 to +2283
telemetry = getattr(self.host, 'demand_telemetry', None)
if telemetry is not None:
telemetry.capture(len(decoded) / (2 * request.sample_rate))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Count decoded multi-channel capture audio

For channels >= 2, the receive loop adds the result of _handle_multi_channel_audio() and immediately continues, so it never reaches this new telemetry.capture() call. Those sessions still create per-channel provider sockets whose successful writes increment omi_stt_provider_wire_audio_seconds_total, leaving the ineligible cohort with positive wire exposure but no corresponding capture exposure and making the documented wire-versus-capture comparison incorrect; record each successfully decoded channel's duration in the multi-channel path as well.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b89fee74df

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

WINDOW_CANARY_OUTCOME.labels(
arm='window' if window_allocation(self.request.uid) else 'control', outcome=outcome
).inc()
telemetry_call(self, 'demand_telemetry', 'finish')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Finalize demand exhaustion after receiver shutdown

When receive teardown exits before _drain_stt_sockets() (for example, because _teardown_body() raises), this call records the session as outcome="no" before receiver.finish() settles any pending or already-dead managed leg. That later settlement can emit an exhausted fallback—especially with recovery disabled—but DemandTelemetry.finished prevents correcting the completed-session counter, so the documented distinct exhausted-session metric undercounts exactly these abnormal teardown cases. Move demand telemetry finalization to the outer post-component seam alongside the routing-cohort finalization.

AGENTS.md reference: backend/AGENTS.md:L159-L159

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit a4cce4c into main Oct 16, 2026
54 of 56 checks passed
@Git-on-my-level
Git-on-my-level deleted the live-demand-telemetry branch October 16, 2026 19:41
Git-on-my-level added a commit that referenced this pull request Oct 17, 2026
## Demand-driven processing

Add default-off surface leases, immediate dispatch with tier priority
under contention through existing Cloud Tasks workers, open-time
promotion, and coalesced lazy memory/vector/task work. Expose
`process_recent_conversations` to app chat, shared Telegram/Linq chat
and hosted MCP with authenticated owner binding,
six-hour/twenty-obligation bounds and a shared rate limit.

Phone and Mac reporters renew explicit intent independently of audio
sockets. Mac intent measures the main window. The end-of-day hook is
omitted under David's updated 2026-10-16 KB rulings. Daytime merge
decisions and proactive notification priority remain unchanged.

## Product invariants affected

- INV-AUTH-1: lease reporting captures and revalidates the current
authorization generation; it never changes Firebase session state.
- INV-DATA-1: desktop deploy declarations retain the existing customer
identity/data-plane authority; only default-off demand controls are
added.
- INV-CAP-1: capture/intake and durable audio retention are preserved;
only processing dispatch changes.
- INV-MEM-4: lazy work uses the existing canonical memory writer and
privacy fences, without a second promotion authority.
- INV-TASK-2: lazy tasks use the existing suggestion/capture policy and
do not accept suggestions automatically.

Failure-Class: none
UI-Evidence: none -- changes report lifecycle intent; no rendered view
or navigation changes.

## Rollout plan

Config trains are documented in
`backend/docs/runbooks/demand-driven-processing.md`: default-off image
-> explicit owner client reporting and scheduler allowlist (0%) -> lazy
work -> agent tool -> 1% -> 5% with >=30 minutes of clean sentinel
readouts at each step -> 25/50/100 only after acceptance. No production
flag change or deployment is included.

Measure per-tier queue age, existing end-to-end finalization journeys,
retry/dead-letter and outbox repair counts, visible quality, memory/task
completeness and live p95. Qualification requires tier 0 <=1m, tier 1
p95 <=5m, tier 2 <=60m; newest 20m <=2m and newest hour <=4m on
simultaneous opens. Scheduling headroom is not a measured freshness
guarantee. Roll back admission flags while retaining workers/sweeps to
drain durable debt. No GPU/cost saving is claimed.

## Validation

- Targeted backend: **490 passed** across twelve targeted files using
the repository file-list runner, one worker and `nice -n 19`. Includes
tier assignment/promotion/drain/ceiling and idle-capacity dispatch,
shared outbox recovery, visible/lazy split, synthetic-owner ASGI auth,
registration/recovery-read avoidance, tool auth/bounds.
- Flutter `listen_client_state_test.dart`: 8 passed. Focused Mac
`ListenClientStateTests`: 9 passed, including URL normalization; the
final incremental run compiles the regenerated additive API types.
- Local HTTP smoke: real loopback HTTP -> production surface handler ->
fake Redis -> recorded Cloud Tasks; open intent promoted pending work to
tier 0. No live cloud acceptance is claimed.
- Full backend Pyright: 0 errors, 36,017 warnings; async blocker scan: 0
findings; changed production import scan: 0 violations.
- Schema inventory, full MCP transport/output schemas, prompt-cache
inventory and pusher config snapshots pass.
- Runtime fixture/renderer contracts: 219 passed; workflow actionlint:
both changed workflows pass. Runtime compose check and dev/prod
validators pass; source closure passes for all 17 images. OpenAPI and
generated Swift/TypeScript contracts regenerated; Dart model freshness
passes.
- Final-head repository preflight passed 83 selected checks;
final-head/push-hook receipts are recorded in the run handoff. Config
trains, metrics, rollback and load/quality gates are in the runbook.

## Limits

The earlier upstream daily-summary decoder inventory failure is fixed by
#21925, now integrated from main (`bfd3a973ed4`). The Grok fix commits
do not implement that unrelated client migration. Full CI is not claimed
green.

The tool promotes the caller's indexed recent debt and reports
`ready=false`; it does not scan Firestore for pre-rollout historical
work. Existing durable reconciliation owns unindexed debt. Full
peak-load and provider qualification are rollout gates. The newer KB
rulings remove item 5 from this PR; #21836 and lazy speaker refinement
remain separate work.

## Grok fixes

- Preserve production's 600-second trailing-edge sync settle when the
master switch is enabled, including tier 0/open promotion, Redis-loss
enqueue fallback and the durable worker claim. Appends continue to
extend one outbox obligation; invisible effects retain explicit-demand
bypass.
- Retain close/occlusion changes during in-flight Mac and phone reports.
Mac re-reads visibility after asynchronous header preparation; both
clients drain queued state changes after send and retry failed closes on
closed heartbeats without spinning.
- Only explicit boolean `surface_open` counts as listen intent. Released
iOS/Android/mobile/Mac telemetry remains unchanged when server flags
turn on.
- Targeted regression run: 490 backend tests passed across twelve files,
one file worker at a time via `BACKEND_UNIT_TEST_FILE_LIST`, `nice -n
19`. Mac lifecycle/race tests: 9 passed. Phone lifecycle/race tests: 8
passed. Detailed receipts are recorded in the run handoff.
- Merged main's #21923 telemetry (`a4cce4c3099`) while retaining strict
surface intent and both documentation sections; telemetry and demand
policy regression tests pass.
- Merged main's T0 config train (#21887, `acfcd8ed0d4`), regenerated
runtime/registry output, and verified all 96 demand defaults remain
off/empty/zero while every other runtime value exactly matches main.
Sync settle remains 600 seconds; 55 Helm/cohort/parity checks pass.
- Continue from the lead's `fb698130b3e` merge of main, without
rebasing. The two desktop deploy workflows retain only six additive
default-off env lines each; **David approved these exact workflow lines
in the final-main-sync instruction**. No merge, deploy or runtime
configuration change is included.

## Main sync 2026-10-17

Merged `origin/main` at `6e7007e3e35` without rebasing. Resolved eight
conflicts by retaining both additive config/registry/test sets and both
post-persistence processing paths. Demand mode retains its 59-minute
ceiling and 600-second trailing settle; upstream revision reuse alone
retains its 60-minute ceiling. Both enabled use the existing demand
headroom, covered by the four-way flag matrix and Redis/open-state
settle tests. No intentional change to Grok-approved semantics.

Targeted merge validation: **434 passed across nine files**, canonical
`BACKEND_UNIT_TEST_FILE_LIST` runner, `BACKEND_PYTEST_WORKERS=1`, `nice
-n 19`. All 96 demand defaults remain off/empty/zero and every other
runtime value matches main. The two workflow diffs remain exactly six
additive default-off lines each; David has approved these exact workflow
lines. Detailed conflict resolutions and final publication receipts are
appended to the run handoff.

## Final main sync

Merged `origin/main` at `3a4fe148259` without rebasing. The only
conflict was generated `backend/docs/feature-flag-registry.md`;
regenerated it from the merged sources with `--as-of 2026-09-24`, and
recomposed/checked runtime env. Seven key Grok-reviewed production files
are byte-identical to `66bdc353202`; all 96 demand defaults remain
off/empty/zero and every other runtime value matches main. No reviewed
semantic change.

**303 targeted tests passed across four files**, using
`BACKEND_UNIT_TEST_FILE_LIST`, `BACKEND_PYTEST_WORKERS=1` and `nice -n
19`, serially. The workflow edits remain exactly six additive
default-off `DEMAND_PROCESSING_*` lines in each approved file and are
unchanged from the Grok-reviewed head. **David's scoped approval is
recorded.** No PR merge or deployment is included. Final head and
publication receipts are appended under “Final main sync” in the run
handoff.

## Integration size exceptions


Line-Count-Exception: backend/database/conversations.py | 4107 -> 4120 |
Small blind metadata writer; avoids a new hot-path Firestore read and
stays with database ownership.

Line-Count-Exception: backend/routers/listen/receiver.py | 2618 -> 2632
| Small guarded ingestion hook reuses existing client_state; scheduling
lives in its own module.

Line-Count-Exception: backend/routers/users.py | 2576 -> 2598 | Small
typed authenticated lifecycle endpoint; all lease logic lives in the
demand module.

Line-Count-Exception:
backend/utils/conversations/process_conversation.py | 3566 -> 3592 |
Small integration seams retain canonical memory/task writer ownership;
scheduler and outbox worker are separate modules.

Line-Count-Exception: backend/utils/retrieval/agentic.py | 1993 -> 1999
| Register and gate one tool implemented in its own module.

Line-Count-Exception: backend/utils/sync/pipeline.py | 3385 -> 3391 |
Small flag/coalescing and explicit-demand hooks preserve the existing
sync owner.

Line-Count-Exception: app/lib/pages/home/page.dart | 1126 -> 1127 | One
startup hook starts the opt-in reporter even without a recording socket;
no view construction changes.

Line-Count-Exception: desktop/macos/Desktop/Sources/OmiApp.swift | 1683
-> 1684 | One startup hook starts the opt-in reporter after
environment/auth setup; implementation remains in ListenClientState.
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