Repository navigation
feat(backend): persist bounded per-speaker voice-match scores (prod on) - #20722
Conversation
Carry existing capture, sync and resolution comparisons into internal conversation metadata for offline calibration, without changing identity or relevance decisions. Co-Authored-By: Codex <[email protected]>
Pin all six computing and persistence hosts on, bound stored score bytes, and omit optional evidence on codec faults or near-full documents. Keep enhanced-protection migrations safe when score re-encryption fails. Co-Authored-By: Codex <[email protected]>
…aker resolution Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
All reported issues were addressed across 24 files
You’re at about 95% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact [email protected].
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3aa3b966a5
ℹ️ 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".
Co-Authored-By: Codex <[email protected]>
Keep current transaction evidence, aggregate sync bridge donors, record manual capture decisions, and isolate optional score faults across identity, model and cache boundaries. Co-Authored-By: Codex <[email protected]>
Restore the exact main file; the merge hook had introduced unrelated formatting. Skip only the Dart reformatter for this byte-for-byte restoration, with no backend checks skipped. Co-Authored-By: Codex <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 705ebe039d
ℹ️ 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".
Allow isolated suites that stub utils packages to import model and speaker modules; optional reporting failures stay contained. Co-Authored-By: Codex <[email protected]>
Validate decoded score shapes, reclaim optional score storage at capacity, preserve donor evidence, aggregate merged resolution clusters, and record manual rejection without changing speaker decisions. Co-Authored-By: Codex <[email protected]>
…with speaker match scores Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6b7cef857e
ℹ️ 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".
Validate optional evidence before every Conversation model entry, reveal assignment result scores with the validated codec, and reclaim score blobs on partial transcript writes using the existing snapshot. Co-Authored-By: Codex <[email protected]>
Replace the optional resolution stage even when a successful rerun produces no comparisons, carry explicit empty evidence through encoding and processing merges, and retain concurrent capture/sync rows. Co-Authored-By: Codex <[email protected]>
…ores # Conflicts: # backend/docs/feature-flag-registry.md # config/feature-flags.yaml
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8e9a77e486
ℹ️ 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".
| contributions = [r for record in records for r in record.get(match_scores.FIELD) or []] | ||
| if contributions: | ||
| result[match_scores.FIELD] = match_scores.merge(None, contributions) |
There was a problem hiding this comment.
Scope unkeyed score rows before bridge aggregation
When a sync bridge absorbs conversations whose rows have an empty speaker_id_scope—as all resolution rows do—this flattening feeds them directly to merge(), whose key is (stage, scope, speaker_id). Equal resolution speaker IDs from different conversations therefore collide, silently replacing donor evidence. Fresh evidence beyond the prior donor-aggregation fix is that the new aggregate() helper assigns conversation:<id> provenance to unscoped rows, but this bridge bypasses that helper; aggregate the decoded records with the provenance-aware path before encoding.
Useful? React with 👍 / 👎.
| if match_scores.enabled(): | ||
| retained = [r for r in (conversation.speaker_match_scores or []) if r['stage'] != 'resolution'] | ||
| conversation.speaker_match_scores = match_scores.merge(retained, resolution.match_scores) |
There was a problem hiding this comment.
Clear stale resolution rows on early resolution exits
When a previously scored conversation reruns resolution but exits through _without_resolution—for example because changed segments are no longer audio-aligned or no usable embeddings remain—the return above bypasses this filtering, leaving the old resolution rows in the processing snapshot. The transaction then sees those rows as the new resolution stage, so even replace_resolution=True preserves evidence for the earlier transcript. Fresh evidence beyond the previous comparison-free-resolution fix is that the resolution is None and other _without_resolution paths still return before this newly added clearing block; clear the stage for every completed resolution attempt, including these early outcomes.
Useful? React with 👍 / 👎.
| try: | ||
| # Fixture suites install empty utils packages while importing models. | ||
| # Resolve optional telemetry only at the observation boundary. | ||
| import utils.observability.fallback as reporter |
There was a problem hiding this comment.
Move fallback reporting out of the config function
When score collection degrades, this function resolves the observability dependency dynamically and then swallows every import or reporting failure, so a missing or renamed telemetry module in a backend/pusher runtime silently removes the only fallback signal. It also bypasses the repository's required top-level import graph, making this cross-layer dependency harder to validate; move reporting to an allowed top-level owner or inject the callback while fixing the affected test stubs rather than importing inside the function.
AGENTS.md reference: backend/AGENTS.md:L159-L165
Useful? React with 👍 / 👎.
| USER_SELF_PERSON_ID if manual.get('is_user') else manual.get('person_id') | ||
| ) | ||
| row['status'] = 'user' if manual.get('is_user') else 'not_user' | ||
| self.match_scores = match_scores.merge(self.match_scores, [row]) |
There was a problem hiding this comment.
Bound live score rows per conversation instead of per session
During a listen connection that spans conversation rollovers or provider epochs, SpeakerMatcher survives until session teardown, so this shared list accumulates keys from earlier conversations/scopes. Once it contains 16 capture keys, merge() retains those first 16 and discards every new key; later conversation segments only attach rows whose scope matches their own, leaving those conversations with no capture evidence. Clear or partition the score buffer on rollover, or evict older scopes so the documented per-conversation cap is applied at persistence rather than across the whole listen session.
Useful? React with 👍 / 👎.
Persist bounded per-speaker voice-match evidence on existing conversation writes for future offline relevance evaluation.
Capture snapshots the existing arbitrated owner/person cosine comparisons in session memory; sync carries its existing pooled comparisons through internal segment dumps; resolution captures its existing 0.50 pooled-voice comparisons under resolved speaker IDs. Existing conversation writes aggregate a
speaker_match_scoresblob; transient per-segment score payloads are removed before storage. The in-memory Conversation holds it before relevance runs. Jev inputs, verdicts, thresholds and speaker assignments are unchanged.Rows record stage-local speaker ID/scope, owner distance, nearest non-owner person distance/ID, nearest-to-runner-up margin, embedded evidence seconds, decision/status, accepted ID, schema version and actual operating thresholds. Floats round to 3 decimals and unavailable/nonfinite values become null. Retain 16 rows per stage (48 total); scopes are capped at 128 characters. The stored field is additionally capped at 8,192 bytes including compression/encryption; worst-case added Firestore storage is 8,214 bytes, Document protobuf field growth is 8,224 bytes, and the complete CommitRequest protobuf body grows by at most 8,249 bytes including the update mask and length-prefix boundaries. Tail snapshots are trimmed as needed. Existing write snapshots suppress new scores and delete an already-stored score blob above the 900 KiB document budget, reclaiming the optional space with no extra reads. Separate stages preserve capture/sync evidence when resolution renumbers voices. Missing fields on old conversations remain absent. No backfill.
Optional score collection, generation, transfer, decode/merge/serialization/compression/encryption and size-estimation errors emit shared fallback telemetry while speaker decisions and content writes continue. Partial retention reports
scores_trimmed;scores_omittedmeans nothing new is stored. Every Conversation constructor, model_validate and factory entry drops raw or malformed optional score values before typed validation. Manual assignment returns its scores through the same validated UID-aware decode path, preventing post-commit assignment/rejection 500s; undecodable evidence is omitted. Model serialization and embedding-cache metadata also isolate optional faults. Manual capture decisions retain the existing comparison with the actual manual outcome. Processing transactions decode and merge the current stored scores ahead of stale capture/sync snapshot rows, replacing resolution rows with the processing result and re-encoding at the current transaction protection level. Failed optional merges leave the current stored blob intact. Sync bridges, manual conversation merges and Jev smart absorbs aggregate decoded donor rows before the existing codec/write. Unscoped donor keys receive conversation provenance so equal resolution IDs remain distinct. Malformed decoded shapes are dropped before typed Conversation construction. Resolution rows sum constituent embedded seconds and retain minimum per-candidate distances after identity-cluster merges; merged/scored counts and distance/margin aggregation tags distinguish this evidence from a fresh pooled comparison. The decision and margin still describe the original representative comparison. Manual rejection records no accepted identity and the manual_rejected outcome. Protection migrations delete old optional scores when re-encryption fails, preventing plaintext retention at enhanced protection. Partial text edits, manual assignments and translation materialization run the capacity guard against their already-read stored snapshot. Successful resolution with no comparisons clears stale resolution rows, including in the processing transaction: explicit empty score snapshots survive encoding, and explicit resolution metadata authorizes stage replacement. Score-only size growth is suppressed before commit; ordinary content/Firestore failures keep their existing semantics.No new collections, Firestore operations, model calls or audio replay. Resolution adds actual embedded PCM seconds to its existing encrypted embedding-cache header without changing the cache's transcript-duration validation; older cache entries report null evidence seconds. Tests verify reuse makes no additional embedding calls.
Privacy: although
speaker_resolutionis coarse plaintext metadata, distances linked to enrolled people are biometric-adjacent. Use the existing compressed JSON conversation codec with per-user encryption at enhanced protection, compressed bytes at standard protection, and re-encode with existing protection-level migration writes. This follows manual-speaker receipt protection rather than weakening it to plaintext metadata. Fields are SkipJsonSchema/excluded and available only in internal Python-mode dumps; JSON responses, live client projections, dict views and integration/webhook payloads omit them. The conversation-field trust pin explicitly classifies this as server-derived numeric evidence, not an untrusted display projection.Rollout: prod ON at merge+deploy on GKE backend-listen/pusher and Cloud Run backend, backend-sync, backend-sync-backfill and backend-integration. All six explicitly pin
SPEAKER_MATCH_SCORES_ENABLED=truein the production overlay; both production charts mirror it. The manifest and registry are regenerated. Backend-integration shares the main image and its developer processing routes; desktop-backend and jobs do not compute or persist this evidence. Rollback = flag off on all six hosts. Code defaults remain dev/local/offline on and unset prod off. No deployment is performed by this lane.Product invariants affected
Failure-Class: none
Reason: Optional encoded evidence was reaching typed response validation after a manual mutation committed. This change adds a shared fail-open model boundary and existing-owner decode/persistence guards; reviewed failure classes cover index maintenance, closed job keys and explicit-null persistence, rather than this optional conversation-evidence codec/model boundary.
Validation
Round 4 is
73c79f1dcb(raw-model and partial-write guards) and789a2c547f(empty-resolution persistence), then merged with origin/main after #20737 (feature-flags conflict kept both flags, registry regenerated). The score file passed 115 cases; it includes real FastAPI HTTP requests through the assignment and rejection handlers with valid and corrupt persisted score blobs at both protection levels, constructor/model_validate/factory fail-open cases, all three partial-write paths, and successful zero-comparison resolution persisted with/without other-stage rows. Initial fixture setup/body errors were corrected before this passing run.Final-source affected validation uses 95 file-isolated files, four workers,
not integration and not slow, and CI's 1.0-second CPU guard. Final affected run: 2,519 passed, 4 skipped, 5 deselected, exit 0, with no CPU-guard failures. The single final preflight passed all 45 checks in 223.75 seconds, exit 0. No preflight gates are unsatisfied. No entire backend unit suite is run; CI owns that validation. The enforced final-source typecheck passed: 0 errors, 13,004 warnings, exit 0. Google credentials are stripped and the test PATH omits kubectl/gcloud. The audit inventory contains 51 matching production call/definition lines, including MCP/chat projections that do not declare scores; the field-level before validator covers their factory and direct model entry points without uid-dependent decryption in models.Generated clients
The stale TypeScript/Swift clients on main were regenerated separately in #20737 (merged). This PR's numeric fields remain SkipJsonSchema/excluded and change no generated client.
Existing owner integration
Line-Count-Exception: backend/database/conversations.py | 3512 -> 3657 | Small integration hooks at existing persistence/session owners; numeric summary policy is extracted into a pure bounded helper rather than duplicating it.
Affected test command (Google credentials stripped; test PATH excludes kubectl/gcloud):
Validation log:
/private/tmp/speaker-match-scores-round3-affected.log. Preflight log:/private/tmp/speaker-match-scores-round3-preflight.log.Raw-model audit:
/private/tmp/speaker-match-scores-round3-raw-model-audit.txt.🤖 Generated with Claude Code