Skip to content

feat(memos): the voice embedding, its vector and the sample purge - #1559

Merged
hrustalq merged 3 commits into
devfrom
feat/1557-voice-embedding
Dec 3, 2026
Merged

hrustalq merged 3 commits into
devfrom
feat/1557-voice-embedding

Conversation

@hrustalq

@hrustalq hrustalq commented Dec 3, 2026

Copy link
Copy Markdown
Owner

Closes #1557

Refs #1403
Refs #1400

The voice queue now means something: one enrollment job decodes the stored sample, refuses a recording that holds more than one voice, computes the pinned model's 192-d embedding, writes the one VoiceProfile vertex, purges every version of the sample and records voice.enrolled. The only route change is the 503 the doc's § Fallback requires.

The artifact is built, never committed

scripts/export-voice-model.py is onnx_export.py's Wrapper verbatim — speechbrain's compute_features → mean_var_norm → embedding_model, input_names=['wav'], output_names=['emb'], a dynamic time axis, opset 17 — with the checkpoint landing in a throwaway savedir. Dockerfile.api gains a voice-model stage that installs the probe's versions from the CPU wheel index (the default index pulls gigabytes of CUDA into a stage that needs none) and copies ecapa.onnx + ecapa.onnx.data into runtime at apps/api/models/; the pair must sit together because ORT resolves the external weights by the model path. apps/api/models/ is gitignored and .dockerignored. Nothing is fetched from huggingface.co at runtime.

onnxruntime-node is a runtime dependency, imported dynamically inside embed() only: AppModule imports this module for available(), and the API process must not load a 228 MB native session to answer a 503.

The graph, the decode, the vector

  • voice.embedding.ts: one memoized InferenceSession (a rejected creation is dropped so the next job retries it), [1, T] in, emb checked for [1, 192], L2-normalised before it leaves the module (COSINE ignores scale, but a re-export must not silently change every stored vector's magnitude). available() is two existsSync calls — the graph and its .data.
  • Decode goes through a temp file, never stdout: execFile's 1 MB maxBuffer is below one 60 s sample (3.8 MB), so a pipe would fail at the last second of a legitimate enrollment. Fewer than 16 000 decoded samples is an error, not an embedding.
  • writeVoiceProfile deletes this profileId's vertex (both predicates) and then CREATE VERTEX … SET … embedding = :embedding with the array bound, the upsertRevisionChunks parameter form. No UPDATE … UPSERT WHERE profileId: the type's unique index is on profileId alone while the delete carries both, and delete-then-create is what provably replaces a re-enroll. A crash between the two leaves a profile with no vector — never matchable, re-enrollable.
  • ensureVoiceProfiles is ensureNoteChunks's memoized bootstrap: VOICE_PROFILE_DDL, the schema:types assertion with the permission hint, ensureVectorIndex('VoiceProfile', 192), a rejected attempt dropped so the next enrollment retries. The processor calls it before its first write; the API never writes a vector.

The one-voice check is measured

Halves of ≈10 s each through the real graph, over the probe's nine clips and every different-speaker splice:

cosine
lowest same-speaker half-cosine (ru_chulsky_a) 0.7835
highest different-speaker half-cosine (ru_chulsky_a first half + ru_ponomarenko_b second half) 0.2842
gap 0.4993
VOICE_SINGLE_VOICE_MIN (middle, rounded) 0.53

A sample below it is refused with reason: 'multiple-voices', and the refusal deletes the row and the sample — a refused enrollment leaves no trace.

The job and its corrections to 2.2a

  • The payload gains key: the extension is deliberately not stored on the row, so the route hands the worker the object it just wrote. (Queue is empty in every deployment — the flag is off — so no in-flight job needs migrating.)
  • attempts: 3 with exponential backoff (delay: 2000): a model-load race or a storage hiccup retries, and a refusal is not retried into anything because the row is already gone.
  • The processor re-reads both gates on execution (the shared voiceGateOpen, not a second copy): a workspace that switched recognition off between the POST and the job voids the enrollment — vector, every sample version, then the row. A failure (missing artifact, storage) throws and leaves row and sample for the retry. A refusal voids; a failure leaves both.

Evidence

  • make verify: exit 0 (lint, typecheck, dependency-cruiser, contracts, api 5515/5515, web, admin, ui).
  • The real graph, through the built module: 192 floats, norm 1.000000; same speaker ru_milena_a×ru_milena_b 0.963807; different speaker ru_milena_a×ru_ponomarenko_a 0.232657, ×en_daniel_a 0.070518; halves same speaker 0.9294, spliced 0.2258; ≈165 ms per 20 s clip warm (453 ms first call, session creation included).
  • The build stage, built here (docker build --target voice-model): succeeds. Two exports of the same pinned checkpoint gave 652,226 B and 651,395 B with different sha256s (77bf89b2… and ab5d2c8c…) — the .onnx file is not byte-reproducible — while the weights are 83,418,688 B at sha256 1144f64778640fa8f18b52ea475d33fb38549ee3c67c1cbdebd32fe3d4f86024, byte-identical to the probe's. Rather than claim a byte match, I measured functional parity: each rebuilt graph and the probe's 711,847 B artifact (9c1910c7…) embed the nine clips at cosine 1.000000 on all nine. The Appendix's graph hash therefore records the probe's export; its weight hash is the reproducible one, and it is what says the checkpoint is right.
  • The runtime image, built here (docker build --target runtime, linux/arm64, 2.61 GB): the pair lands at /app/apps/api/models owned by node, and the module inside the image answers available() true, 192 floats at norm 1.000000, same speaker 0.963807, different speaker 0.232658, halves 0.9294 — the same numbers as on the laptop. That exercises the COPY --from=voice-model, the onnxruntime-node install in the production closure, ffmpeg and the default model path together.
  • Pins: torch==2.15.0, torchaudio==2.11.0 (2.11.1 is not on the CPU index; 2.11.0 is the nearest release it carries), speechbrain==1.1.2, onnx==1.23.2, onnxscript==0.7.2. onnxruntime-node is pinned at 1.31.1: 1.32.0 does not exist on npm (the probe's 1.32.0 is the Python package's version). The checkpoint is pinned to the Appendix's commit (0f99f2d0…) through speechbrain's FetchConfig.

#1403's acceptance criteria this closes

criterion verdict evidence
A bad sample is refused with a reason; no raw audio remains after processing met 2.2a refuses at the route (duration, level); this PR adds the worker's multiple-voices refusal and purges the sample prefix on every success and refusal (voice.processor.spec.ts, the measured table above).
Enroll, re-enroll and delete work; a deleted profile leaves no vector met 2.2a's routes; this PR writes the vector with delete-then-create (vector-search.spec.ts: the two statements, the bound array, no UPSERT), and the delete paths purge the vector before the row (voice.spec.ts).
With the workspace feature off, enrollment is unavailable and no profile is written met 2.2a closes the routes with 404; the processor re-reads the gates and voids a job that outlived the switch (voice.processor.spec.ts, three closed-gate cases).
A second user cannot enroll for another; an admin sees only enrolled/not enrolled, never the vector open — 2.3 the admin boundary is the absence of a user id on the route (2.2a); the count/list surface is the Settings screen.
Specs cover consent version, deletion, cross-workspace isolation and the admin boundary partly — 2.3 consent version, deletion and cross-workspace isolation are covered (2.2a + this PR); the admin-boundary specs land with the surface.
make verify met exit 0, above.

Divergences

  • error.voice.unavailable, not a new error.voice.modelUnavailable. 2.2a already shipped that key with exactly the 503 copy ("this server cannot compute a voice signature. Nothing was stored") and nothing read it; adding a second identical key in two languages would have left one dead. The reason string is model-unavailable, as decided.
  • make api-client was run, contrary to the brief's "no make api-client": the premise ("no contract type moves") does not hold, because AUDIT_ACTIONS is a contract union that openapi.json and the api-client's schema.d.ts embed. The regenerated diff is only the voice.enrolled member (4 enum sites in the OpenAPI document, 4 union lines in the client); contract-schemas.json and the docs reference are unchanged. 2.2a regenerated the same four files for voice.consent.
  • The worker module is voice-worker.module.ts + worker.module.ts, not MemosWorkerModule — voice has had its own module side since 2.2a.
  • The job payload gains key, as above — a correction to 2.2a's producer named in the commit.
  • .dockerignore: scripts/ was excluded wholesale; it now excludes only scripts/*.mjs, because the voice-model stage copies scripts/export-voice-model.py in, and apps/api/models is excluded from the context (a local artifact must never be streamed to the daemon).
  • A stale-promise sweep: voice.constants.ts, voice.producer.ts, voice.module.ts, voice.service.ts, graph.service.ts (deleteVoiceProfile), admin-health.service.ts, packages/contracts and § Operations of doc 89 all said the processor/embedding/voice.enrolled "arrives with feat(memos): call participants 2.2 — the ONNX voice embedding, the profile vector and the sample purge #1557"; each now says what shipped.

Review

Two independent reviewers over the committed range — one per axis, sliced by area — with every blocking finding fixed or rebutted.

Found and fixed

  • The two-voice test fixture was silence, not a second voice. Its second half was all zeros, so the refusal was proved on "signal vs nothing" rather than on two live voices. It now points the second half the other way (−3), and the embedded vectors for both halves carry magnitude. (voice.processor.spec.ts)
  • The audit row's "no biometric" assertion stringified only params. A vector in another field of the entry would have passed. The assertion now checks the whole row. (voice.processor.spec.ts)
  • The lockfile carried a re-resolved vitest peer note (@types/node@24.13.3 where dev had 25.9.5) picked up by the dependency add. Reverted; pnpm install --frozen-lockfile accepts it and the diff carries only the new dependency's subtree.
  • The checkpoint followed mutable main. from_hparams was fetching whatever the model repo's default branch held, so a rebuild could silently change the weights behind a stored vector. It is now pinned to the commit doc 89's Appendix measured, via speechbrain's FetchConfig(revision=…). The stage was rebuilt on the pin: weights hash unchanged, the nine clips still match the probe's artifact at cosine 1.000000.
  • onnxruntime-node's postinstall was silently ignored by pnpm (a warning on every install). It is now named in ignoredBuiltDependencies: the script only fetches the CUDA execution-provider binaries, the CPU ones ship in the tarball, and downloading them into every runner and image would be pure waste. If a GPU build is ever wanted, that entry moves to onlyBuiltDependencies in the same change.

Rejected, with the reason

  • "torchaudio 2.11.0 requires torch 2.11.x, so the voice-model stage cannot resolve." The stage was built here: Successfully installed … torch-2.15.0+cpu torchaudio-2.11.0+cpu. The reviewer inferred the pairing from the version numbers; the CPU index's actual dependency metadata accepted the pins, and the whole export ran.
  • "The inventory diff is scope creep and its changelog describes work that does not exist." The reviewer's slice held only the inventory files, so the code it expected was in the sibling slices (all of which passed). Every one of those files is on feat(memos): call participants 2.2 — the ONNX voice embedding, the profile vector and the sample purge #1557's own deliverable list; the admin-health comment is the mandated stale-promise correction.

Deferred, named rather than hidden

  • The .onnx graph file is not byte-reproducible. Two exports of the same pinned checkpoint produced 652,226 B and 651,395 B with different hashes; both are opset 18, ir 10, 277 nodes / 234 initializers, and both embed the nine clips at cosine 1.000000 against the probe's 711,847 B export. The Appendix's graph hash therefore records the probe's macOS export, not a build target; the weights hash (1144f647…) is reproducible, and it is the one that says the checkpoint is right.
  • A re-enroll that lands while its job is still pending is folded into that job (jobId = profileId). The pending job embeds the sample its own key names — an object that still exists, because only the post-write purge removes sample objects — and its prefix purge then removes whatever the newer enrollment wrote. Row, vector and purge stay consistent; the newest sample is not the one embedded. The window is a re-enroll before the first job runs; the feature is off in every deployment today.
  • The one-voice floor is measured on clean 20 s probe clips. A real enrollment with a long silent half is the first thing to re-measure (doc 89 § Method already says these numbers are a floor, and phase 5 owns real recordings). No VAD was added, per § Method.
  • The runtime image was built after this body's first draft (see Evidence); the voice-model stage alone was the bounded proof the task asked for.

One `voice` job now becomes one 192-d vector: the ECAPA-TDNN graph the probe
measured (#1412) runs in-process through onnxruntime-node, the stored sample
is decoded to 16 kHz mono PCM, a half-to-half cosine refuses a recording with
two voices, the vector replaces any previous one on the `VoiceProfile` vertex,
every version of the sample object is purged, and `voice.enrolled` is recorded
with the consent version and nothing biometric.

The graph is built by `Dockerfile.api`'s `voice-model` stage: 84 MB of weights
never enter git, and nothing is fetched from huggingface.co at runtime. The
runtime import is dynamic, so the API process answers its 503 with two
`existsSync` calls instead of loading a native session for an answer it does
not need the model to give.

The one-voice floor is measured, not guessed. Over the nine probe clips the
lowest same-speaker half-cosine is 0.7835 and the highest different-speaker one
(the first half of one speaker spliced onto the second half of another) is
0.2842; VOICE_SINGLE_VOICE_MIN sits at the middle of that gap, 0.53.

The job carries the sample key — the row deliberately has no extension — the
producer gains three attempts with exponential backoff, and the processor
re-reads both workspace gates on execution: a closed gate voids the enrollment,
a multi-voice refusal deletes the row and the sample, and a failure leaves both
for the retry.

Refs #1403
… whole-row check

`pnpm-workspace.yaml` names `onnxruntime-node` in `ignoredBuiltDependencies`:
its postinstall only fetches the CUDA execution-provider binaries — the CPU
ones ship in the tarball — so the install must skip it rather than download
them into every runner and image.

The processor spec's two-voice PCM now points its second half the other way
instead of at silence, so the refusal is proved on two live voices; and the
audit assertion stringifies the whole row, not only `params`, so a vector in
another field would fail it.

The lockfile keeps the vitest snapshot it had before the dependency was added
(pnpm had re-resolved a peer note; a frozen install accepts either).
`from_hparams` followed the model repo's `main`, so a rebuild could silently
change the weights behind an already-stored vector. The revision is now the
commit doc 89's Appendix measured (0f99f2d0…), passed through speechbrain's
`FetchConfig`. Rebuilt on top of it: the weights still hash to the probe's
1144f6… and the nine clips embed at cosine 1.000000 against the probe's
artifact.

The graph file itself is not byte-reproducible: two exports of the same pinned
checkpoint differ (652,226 B and 651,395 B, different sha256s), so the
Appendix's `.onnx` hash records the probe's export, not a build target.
@hrustalq
hrustalq merged commit 3b44292 into dev Dec 3, 2026
2 checks passed
@hrustalq
hrustalq deleted the feat/1557-voice-embedding branch December 3, 2026 19:50
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