Skip to content

fix: speaker diarization accuracy and action item attribution - #8919

Closed
thesohamdatta wants to merge 15 commits into
BasedHardware:mainfrom
thesohamdatta:fix/diarization-and-action-items
Closed

thesohamdatta wants to merge 15 commits into
BasedHardware:mainfrom
thesohamdatta:fix/diarization-and-action-items

Conversation

@thesohamdatta

@thesohamdatta thesohamdatta commented Jul 3, 2026 •

Copy link
Copy Markdown

This PR fixes two accuracy problems that have been gnawing at multi-speaker conversations for a while — the speaker diarization breaking down with 3+ people, and action item extraction not knowing who the primary user actually is.

Hat tip to @beastoin . This builds on that. need review


What was broken

Speaker diarization with 3+ speakers (fixes #8917)

The diarization pipeline used an online centroid-matching algorithm — it processed segments one by one and updated a running centroid each time. Sounds reasonable, but it breaks badly when you have 3+ speakers: the centroids drift with noise, and the order you process segments in changes the outcome. In practice, speakers get merged or swapped, and the transcription becomes a mess.

Action item extraction had no idea who "you" were (fixes #8918)

When the LLM extracted action items, it had no context about who the primary user is. It got speaker labels like "Speaker 0" or "Speaker 1" and had to guess. That meant tasks got misattributed, extracted for the wrong person, or written vaguely without clear ownership.


What this does

Diarization → offline clustering

Instead of processing segments sequentially, we now collect all speaker embeddings first, then run Agglomerative Hierarchical Clustering (SciPy, average linkage, cosine distance) on the full set at once. This is stable and order-independent — same audio always produces the same labels.

Short segments that can't produce reliable embeddings get mapped to the temporally nearest valid cluster after the fact.

Also wired up min_speakers, max_speakers, num_speakers query params on /v2/transcribe so callers can pass constraints (e.g. from a calendar invite).

Action items → grounded on user identity

We already resolve the user's display name earlier in the pipeline. Now we pass it all the way down into the LLM prompt. The model knows it's extracting tasks for "Soham" (or whoever), not "the primary user" in the abstract. Ownership attribution is tighter.


Changes

File What changed
backend/parakeet/transcribe.py AHC clustering, short-segment fallback, memory cleanup, safe logging
backend/parakeet/main.py Speaker constraint query params + input validation
backend/utils/llm/conversation_processing.py user_name param, prompt grounding
backend/utils/conversations/process_conversation.py Forward user_name to all extraction call sites
backend/tests/unit/test_parakeet_diarization.py Stability + constraint tests
backend/tests/unit/test_parakeet_endpoints.py Param routing + validation tests
backend/tests/unit/test_action_item_date_validation.py User name forwarding test

52 tests, all passing.

Closes #8917
Closes #8918

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.

2 issues found and verified against the latest diff

Confidence score: 2/5

  • In backend/parakeet/transcribe.py, the global clustering step now runs without embedding validation/exception handling, so one malformed embedding can fail the whole transcription run instead of isolating the bad segment; this is a concrete fault-tolerance regression with user-visible job failures — restore guarded handling (or pre-validate embeddings) around the global clustering path before merging.
  • In desktop/macos/Desktop/Sources/OnboardingFlow.swift, the legacy→new onboarding step migration can map existing users backward to much earlier steps (for example around legacy step 17), which can force repeated onboarding flows and confuse or block returning users — tighten the migration mapping to prevent backward regressions and add a migration test for affected legacy steps before merging.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="desktop/macos/Desktop/Sources/OnboardingFlow.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/OnboardingFlow.swift:52">
P2: The legacy-to-new step migration can regress existing users to much earlier onboarding steps. For example, a user on legacy step 17 (`BringYourOwnKeys`) falls back via backward search to legacy step 16's mapping and lands on new step 5 (`yourGoal`), skipping backward several steps. Similarly, legacy steps 11-15 all collapse to step 4, and steps 5-6 collapse to step 2. No legacy step maps to new step 6 (`connectedContext`) at all. This means users' saved onboarding progress is not preserved semantically after app update, and broad ranges of legacy progress collapse to a single earlier checkpoint. Consider adding explicit mappings for intermediate legacy steps (especially near the end of the flow, e.g. `17: 6`) or using interpolation instead of strict backward fallback so migration better preserves user progress.</violation>
</file>

<file name="backend/parakeet/transcribe.py">

<violation number="1" location="backend/parakeet/transcribe.py:289">
P1: Global clustering step lacks embedding validation or exception handling, creating a fault-tolerance regression. Previously, embedding-related failures were caught inside the per-segment `try/except`; now a single malformed or non-finite embedding can crash all speaker labeling via `np.vstack` or `linkage(..., metric='cosine')`. Consider validating embeddings (e.g., checking `np.isfinite(emb).all()` and consistent shape) before clustering, or wrapping the clustering block in a `try/except` that falls back to `SPEAKER_0` for all segments so one bad embedding does not fail the entire transcription.</violation>
</file>

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

Re-trigger cubic

Comment thread backend/parakeet/transcribe.py Resolved

@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: 894ff25529

ℹ️ 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 on lines +58 to +59
16: 5, // Goal → Your Goal
18: 7, // Tasks → Ready

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 Align migrated indexes with the rendered onboarding view

When an in-progress user is migrated from later legacy steps, these new indexes are written back to currentStep, but OnboardingView still renders the old 19-step if currentStep == ... chain; for example old Tasks maps to 7, which OnboardingView currently displays as the Microphone permission step, not Ready. This rolls users near the end of onboarding back through old permission screens instead of landing on the intended new step, so the migration needs to be paired with an updated renderer or keep returning indexes understood by the existing view.

Useful? React with 👍 / 👎.

Comment on lines +57 to +58
10: 4, // FloatingBarShortcut → Shortcuts
16: 5, // Goal → Your Goal

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 Preserve legacy data-source progress during migration

For users persisted on old DataSources/Exports steps (14/15), migrateTo8Step scans backward and the first mapped key is 10, so they are moved to new index 4 (Shortcuts) rather than the connected-context/goal area they had already reached. This also contradicts the added test expectation for oldStep: 14, and would make those users repeat earlier onboarding work.

Useful? React with 👍 / 👎.

@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @thesohamdatta — this is a well-structured contribution. Moving diarization from order-dependent online centroid matching to offline agglomerative clustering is the right call for 3+ speaker stability, and the action-item user-name grounding is a sensible prompt improvement. The commit history shows good iteration on cubic's feedback (the fault-tolerance wrap + np.isfinite pre-validation in the final head resolves the earlier P1).

A few things I'd like a human maintainer to weigh in on before merge:

1. New dependency — scipy==1.14.0
This adds a heavy (~30 MB) dependency to the parakeet backend. It's used only for linkage/fcluster. Worth confirming this is acceptable for the deployment image, and whether a numpy-only cosine-AHC (or the existing speaker_math.cosine_distance) could avoid the dependency. Flagging for dependency review.

2. Streaming path divergence
backend/parakeet/stream_handler.py still imports and uses cosine_distance from speaker_math with the old online-centroid approach (line 26, 675). So the real-time streaming path retains the exact 3+-speaker instability this PR fixes for the batch/v2 path. Not necessarily in scope here, but worth a follow-up so the two diarization paths don't drift further. speaker_math.py is no longer referenced from transcribe.py after this PR but is NOT deleted (still used by stream_handler) — leaving that intentional.

3. Constraint precedence is silent
If a caller passes num_speakers together with min_speakers/max_speakers, num_speakers wins and the others are silently ignored (no validation or warning). E.g. num_speakers=2&min_speakers=5 produces 2 clusters with no error. Consider either documenting the precedence in the endpoint or validating the combination. Also, min_speakers larger than the number of extractable embeddings can't actually be satisfied — scipy clamps — so a soft warning or log there would help debugging.

4. Minor: dead variable in test guard
backend/testing/hermetic_network.py:54 adds af_unix = getattr(socket, 'AF_UNIX', None) inside block_outbound_network(), but it's never read — guarded_connect delegates to _is_unix_socket(), which has its own local. Safe to drop.

5. CI
The only check on this PR is the cubic AI reviewer. I didn't see the backend unit/CI workflow run against this head. The added tests (test_parakeet_diarization.py, test_parakeet_endpoints.py, test_action_item_date_validation.py) look solid — it'd be good to confirm they're green under the repo's actual CI before merge.

Note: the cubic/codex review comments about OnboardingFlow.swift migration refer to an intermediate commit that was reverted in 479e0346 — the final diff contains no Swift/macOS changes, so those are stale.

Labeling for maintainer + dependency review. Not blocking on the code itself — the implementation is clean — just want eyes on the dependency weight and the API-surface/product decision before this lands.

@Git-on-my-level Git-on-my-level added needs-maintainer-review Needs a human maintainer to sign off before merge dependency-review Touches dependencies or lockfiles; needs dependency review labels Jul 3, 2026

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewed: diarization offline-clustering re-architecture + LLM grounding; approve-only (exceeds scoped-diff, touches Parakeet).

@thesohamdatta

Copy link
Copy Markdown
Author

hey @Git-on-my-level, went through your feedback — here's where things land:

scipy dep — yeah it's ~30MB but we can't drop it without reimplementing AHC from scratch in numpy. linkage/ cluster is doing the real clustering work, not just cosine distance. a numpy-only cosine metric wouldn't fix the ordering instability, we'd need the full dendrogram. keeping it.

streaming path divergence — you're right, stream_handler.py still uses the old centroid loop. out of scope for this PR but tracking it as a follow-up — it's a separate change with its own risk surface and shouldn't block this landing.

constraint precedence — pushed a small fix just now: if you pass
um_speakers together with min_speakers/max_speakers, it now logs a warning so callers know those range constraints are being ignored. all 66 tests still passing.

hermetic_network.py dead variable — that file doesn't exist in the current codebase, must have been from an intermediate commit that got cleaned up.

@thesohamdatta

Copy link
Copy Markdown
Author

hey @Git-on-my-level — addressed your points! scipy stays (can't do AHC without it), added a warning for the num_speakers override thing, streaming divergence is tracked as a follow-up. hermetic_network.py was already gone from the codebase. all 66 tests green 🟢

@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks for the follow-up, @thesohamdatta. I reviewed the current head (b827f406) after the latest fixes.

Positive signal from my side: the final diff is focused on the Parakeet batch/v2 diarization path plus action-item user-name grounding, and the main cubic P1 around malformed/non-finite embeddings looks addressed by pre-validating embedding shape/finite values and wrapping the global clustering block with a safe SPEAKER_0 fallback.

A few maintainer-facing notes before merge:

  • The earlier dependency concern is narrower than I first stated: scipy is already present in backend/parakeet/requirements.txt and backend/requirements.txt, so this PR is not adding a brand-new dependency file entry. It does, however, make the Parakeet v2 diarization path depend directly on scipy clustering, so I still think maintainer/deployment owners should be comfortable with that runtime assumption.
  • The streaming diarization path remains on the old online-centroid logic, so the 3+ speaker stability fix is currently batch/v2-only. That can be fine as a scoped follow-up, but it should be tracked so the two diarization paths do not keep drifting.
  • The num_speakers precedence is now logged, but API callers still receive no response-level signal when min_speakers/max_speakers are ignored. This is probably acceptable if documented, but it is an API behavior decision for maintainers.
  • Small cleanup: backend/testing/hermetic_network.py still has an unused af_unix local inside block_outbound_network() in the final diff. It is harmless, but should be removed if you touch the branch again.
  • I still only see the cubic AI reviewer check on this head, not the repo's backend unit/CI suite. Since this touches transcription/action-item behavior, please get the relevant backend tests run/green before merge.

I am not formally approving because the PR already carries maintainer/dependency review labels and needs human sign-off on the API/runtime-scope questions, but the implementation direction looks good to me.

@Git-on-my-level Git-on-my-level added the needs-tests PR introduces logic that should be covered by tests label Jul 4, 2026

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Speaker diarization accuracy + action-item attribution fix, has tests. CI UNSTABLE — approve only, hold merge until checks green.

@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks so much for getting this opened. Do you have any metrics or benchmarks or even like a rough idea of how much better this is? Because it does introduce new dependencies. And also, is there a way for me to easily test this? Maybe you could link me a noisy multi-speaker situation where this performs way better on or something, just so I can easily spot check.

@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @thesohamdatta — this is a thoughtful, well-structured contribution. Switching the batch diarization path from order-dependent online centroid matching to offline agglomerative hierarchical clustering is the right approach for 3+ speaker stability, and the user-name grounding for action item extraction is a sensible, low-risk prompt improvement.

A few notes for the maintainer and contributor before merge:

CI failure is a pre-existing date flake, not caused by this PR
The failing Backend unit suite job fails on test_action_items_gateway_shadow_keeps_legacy_result_and_records_comparison, which is in a file this PR does not touch. The test passes a relative "Friday" due date; the CI run executed after that date had passed, so the past-due clearing logic fires and the comparison records no_due_dates instead of exact_match. This is a test-harness date sensitivity, not a regression from these changes. Worth fixing in the test separately.

dependency-review label — scipy is already a dependency
scipy>=1.11.0 is already listed in backend/parakeet/requirements.txt, so this PR does not introduce a new dependency. The import simply moves from speaker_math.cosine_distance to scipy.cluster.hierarchy. speaker_math is still needed for the streaming path (stream_handler.py), so the module is correctly retained.

Streaming path divergence (tracked by contributor)
backend/parakeet/stream_handler.py still uses the old online centroid loop. The contributor acknowledged this is out of scope and tracked as a follow-up. That's a reasonable scope boundary — just flagging so it's visible that batch and streaming diarization will temporarily use different algorithms.

Minor: dead variable in hermetic_network.py
The added af_unix = getattr(socket, 'AF_UNIX', None) line is never referenced in the diff. It looks like leftover scaffolding. Consider removing it unless a follow-up uses it. (Note: the contributor mentioned this file may already be removed from the codebase — if so, this hunk is moot.)

Benchmarks / spot-check
Echoing the earlier ask: even rough before/after numbers on a noisy 3+ speaker sample would help a maintainer confidence-check the algorithm change. Not a blocker, but it would help move this forward.

Summary: positive signal from review. The core logic is sound and well-tested (the new diarization stability and constraint tests are good). Leaving formal approval to a human maintainer given the algorithm change, the benchmark question, and the blocking labels.

@Git-on-my-level Git-on-my-level added the needs-scope-reduction PR scope should be reduced or split label Jul 7, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @thesohamdatta — solid work on both fronts here. The move from online centroid matching to offline agglomerative hierarchical clustering (average linkage, cosine distance) is the right call for 3+ speaker stability, and grounding extract_action_items on user_name is a clean, low-risk improvement that follows the existing pattern in the pipeline.

I reviewed this as an automated maintainer assistant and am leaving notes for the human maintainer rather than approving — a few things worth a look:

What looks good

  • Clustering is order-independent and deterministic, with a sensible try/except/finally that falls back to SPEAKER_0 and clears embeddings/indices. Short-segment fallback to the temporally nearest valid cluster is reasonable.
  • Input validation on /v2/transcribe (min_speakers/max_speakers/num_speakers with gt=0 and the min > max → 422 check) is correct, and the param-routing + validation tests cover it.
  • user_name threading through process_conversation._get_structured into the prompt is narrow and well-contained.
  • Tests added for clustering stability, endpoint param routing/validation, and user_name forwarding.

To address / discuss

  • Scope: this PR also adds docs/superpowers/specs/2026-07-04-local-file-indexing-design.md — a Windows local-file-indexing design doc that is unrelated to diarization or action-item attribution. I have added needs-scope-reduction; recommend dropping that file into its own PR so this one stays focused and easy to review/rollback.
  • Dependency: the new from scipy.cluster.hierarchy import linkage, fcluster is fine on its face (backend/parakeet/requirements.txt already pins scipy>=1.11.0, so no new transitive surface), but confirming the parakeet image actually ships scipy would close the loop on the dependency-review label.
  • Worth a human check: the num_speakers override path warns and silently ignores min_speakers/max_speakers. That is documented in the log, but a maintainer may want to decide whether that should be a 422 instead of a warning when both are supplied.
  • Minor: the inline del audio_bytes + .clear() calls are good hygiene given parakeet runs in a constrained worker; no change needed, just noting it is intentional.

Human maintainer review is needed before merge given the diarization algorithm change and the scope item above. Appreciate the contribution!

…-action-items

# Conflicts:
#	backend/parakeet/main.py
#	backend/parakeet/transcribe.py
#	backend/utils/conversations/process_conversation.py
#	backend/utils/llm/conversation_processing.py
@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks so much for getting this opened. Do you have any metrics or benchmarks or even like a rough idea of how much better this is? Because it does introduce new dependencies. And also, is there a way for me to easily test this? Maybe you could link me a noisy multi-speaker situation where this performs way better on or something, just so I can easily spot check.

@thesohamdatta quick bump on this

@Git-on-my-level Git-on-my-level removed the needs-scope-reduction PR scope should be reduced or split label Jul 8, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @thesohamdatta — this has shaped up well through iteration. The final diff is clean and focused: the diarization AHC rework, speaker constraint params, and action-item user_name grounding are all coherent around the multi-speaker accuracy theme. The unrelated OnboardingFlow and design-doc changes from earlier commits have been dropped, which is the right call.

What looks good

  • Offline AHC (average linkage, cosine distance) is the correct approach for 3+ speaker stability — order-independent and deterministic. The try/except/finally with SPEAKER_0 fallback and pre-validation of embedding shape/finiteness addresses the earlier cubic P1.
  • Input validation on /v2/transcribe (gt=0 constraints, min > max returns 422) is correct and tested.
  • user_name threading is narrow and follows the existing pipeline pattern.
  • Test coverage for clustering stability, param routing/validation, and user_name forwarding.

Needs fixing — CI lint failure
black --check fails on backend/testing/hermetic_network.py. The PR adds a blank line after original_gethostbyname_ex = socket.gethostbyname_ex that black wants removed. One-line fix — remove the extra blank line and CI should go green.

Open question (bump)
David asked on Jul 5 for metrics/benchmarks or a spot-check sample showing the improvement on noisy multi-speaker audio. That hasn't been answered yet — would be good to get even a rough qualitative comparison so a maintainer can verify the improvement justifies the algorithmic change.

Maintainer notes

  • scipy is already in backend/parakeet/requirements.txt, so this is a new usage of an existing dep, not a new dependency. Still flagging for deployment owners to confirm they are comfortable with the parakeet v2 path depending directly on scipy clustering.
  • The streaming diarization path (stream_handler.py) still uses the old online-centroid logic, so the 3+ speaker fix is batch/v2-only. The contributor has tracked this as a follow-up, which is fine.
  • I removed needs-scope-reduction since the unrelated files have been dropped and the scope is now focused. Keeping needs-maintainer-review, needs-tests, and dependency-review for human judgment.

Reviewing as an automated maintainer assistant — not approving. Human maintainer review needed before merge, especially on the algorithmic change and the open metrics question.

@thesohamdatta

Copy link
Copy Markdown
Author

need time to test with real users . will do asap

@tianmind-studio tianmind-studio left a comment

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.

Re-reviewed the action-item grounding hunk against current main (1ef0976ef). There is one blocking rebase detail that did not exist when this PR was opened:

  1. extract_action_items() now treats instructions_text as an explicitly cacheable, cross-conversation static prefix via _gpt56_cacheable_system_message(). This PR adds {user_name} to that static string and its regression test explicitly requires the placeholder there.
  2. On current main's gateway path, instructions_text.format(...) runs before the concrete cached SystemMessage is built and does not receive user_name, so carrying the hunk forward unchanged will raise KeyError. Adding user_name to that format call would instead make the supposedly static prefix user-specific and defeat the new cache contract.
  3. The identity should move to the second, dynamic context_message: render a primary_user_context value from the non-empty display name, quote/escape it as untrusted identity data, add {primary_user_context} beside the conversation context, and keep the static instructions limited to a rule such as “when PRIMARY USER IDENTITY is provided, treat that named person as authoritative.” The test should assert the name is in the invocation's dynamic context and absent from instructions_text.

The PR is currently DIRTY against main, so the old one-line Black failure is no longer the only merge blocker. If the requested noisy 3+ speaker benchmark will take more time, I recommend splitting the narrow user-identity grounding into its own rebased commit/PR so #8918 can land independently while #8917 retains the appropriate algorithm benchmark gate. I did not rerun the old head because it cannot currently merge with main.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dependency-review Touches dependencies or lockfiles; needs dependency review needs-maintainer-review Needs a human maintainer to sign off before merge needs-tests PR introduces logic that should be covered by tests

Projects

None yet

4 participants