Files
UmbraAudio/umbraaudio/source_units.py
B.D. Murphy 829a03b89f Action the controller alignment proposal: source_unit_key + phase reports
The controller (oldbox) sent a data-model alignment proposal and asked for six
additive changes on this node, the validation protocol, and an honest report.
Six of the seven changes are done; the seventh is declared missing rather than faked.

Stage 0 - reachability verified exactly as documented: health 200, heartbeat 401
(the correct answer - auth is refusing), missing Host 400. Nothing else was sent.

source_unit_key (controller 5.1, the blocking item)
  umbraaudio/source_units.py. sha256("uk1" | chapter_source_text_sha256 |
  occurrence | text_sha256). Nothing positional in the key: "occurrence"
  disambiguates repeated text in document order.
  - 18,181/18,181 units keyed across all four projects, 0 collisions
  - chapter 1 renumbered +100 -> 0 keys changed (the load-bearing proof)
  - backfill 10,015 rows in 0.11s, second run stamps 0 (idempotent)
  - alignment phase 3: 200/200 probe units resolved with used_index: false
  - tolerates the older projects that have no chapters.chapter_index
  Recorded at generation time in chapter_builder, BEFORE the rows are read and
  BEFORE the marker is written, so every path that renders audio also produces
  identity and the clip can name its source unit.

5.7 recorded: utterance_index is KEPT as a display ordinal and made
  non-load-bearing. spec 21 §10.

Blob hashes and effect chain (5.2)
  Markers now carry the full sha256 of the delivered bytes and the effects that
  produced them. Verified the existing order is already correct - write_marker
  runs AFTER apply_effects - and closed the remaining hole: a changed trait list
  changed the hash with no recorded cause. sha256 verification is opt-in, since
  hashing every file on every validation pass would re-read gigabytes.

Vocabularies published (5.4) - umbraaudio/definitions.py, 19 sets, 126 values,
  each value carrying whether it is 'declared' (spec/controller) or 'extracted'
  (read out of code), so a diff shows a difference of meaning, not of wording.

Alignment report tool (6.6) - scripts/alignment_report.py --phase all. Emits the
  controller's envelope with the per-phase evidence shapes, and obeys the two
  rules they set: no evidence means blocked, never pass; a field we cannot produce
  is null PLUS a finding, never omitted. Phase 2 is deliberately 'fail' - the
  three-way store disagreement is real, and a pass there would be a check that
  passed by doing nothing.

Fingerprint discipline (5.5) - the drift detector reported its OWN fingerprint
  change when source_unit_key was added rather than hiding it. Node profile
  updated with the new fingerprints and an honest note that they moved.

Node report extended - per-project source-unit-key coverage, per-voice-asset
  sha256 + object_key, definition_set_version, controller stage reached.

Six gaps found in the proposal (spec 21 §11), including the one they invited plus
five more. The sharpest: "hash at generation" ignores that audio is
post-processed afterwards, and our key is anchored to chapters.source_text - a
second copy of the manuscript - so any change to chapter storage silently
invalidates every key in that chapter.

5.6 deliberately NOT faked: personality has no versioned artifact here, only
  unversioned LLM prose in speakers.json. Reported as phase 6b finding B-03
  instead, because wrapping unversioned inputs in a version field would produce
  artifacts claiming a lineage they do not have.

Answered the controller's two open questions (infra/controller-handoff-2026-10-03.md):
forward-only link for a revealed recurring character, and yes - a new edition may
contradict a frozen state, since this node's correction path IS a regeneration.

Full suite 484 passed / 8 failed - the same 8 pre-existing and unrelated failures.
ruff clean on every file touched. The parallel session's chapter_builder hunk
(helper_url) was filtered out of the commit and left intact in the working tree.
2026-10-02 20:16:06 -07:00

205 lines
7.8 KiB
Python

"""Content-addressed source-unit identity (``source_unit_key``).
Why this exists
---------------
Utterances are currently identified by ``utterance_index``, which is *position*.
Re-segmentation renumbers a chapter, and ``DELETE /api/utterance/{id}`` renumbers the
rest of the chapter and renames files on disk. ``specs/18-UmbraTrans.md`` §3.3 forbids
mutable indices as durable cross-language IDs, and ``specs/20`` §E.1 requires a
content-addressed key recorded at generation time with filenames unchanged.
The key
-------
``uk1`` version, byte order, hex-encoded SHA-256::
sha256(b"uk1\\x00" + chapter_text_sha256 + b"\\x00" + occurrence + b"\\x00" + text_sha256)
* ``chapter_text_sha256`` - SHA-256 of ``chapters.source_text``. This substitutes for a
source-revision id: it is self-verifying, so no revision table is needed, and any edit to
the chapter invalidates exactly the units whose text changed.
* ``occurrence`` - 0-based count of *earlier* utterances in the same chapter with an
identical text hash, in document order. Disambiguates repeated lines ("Yes.") without
depending on the index itself.
* ``text_sha256`` - SHA-256 of the utterance text, exact.
Properties this deliberately has
---------------------------------
* **No index in the key.** Renumbering cannot change it.
* **Index-independent resolution.** Given a key, the row is found by primary key lookup;
``utterance_index`` is never needed (controller validation phase 3).
* **Per-project agnostic.** Two projects with the same chapter text and the same utterance
text produce the same key. That is intentional (content identity), and it means the
controller must salt per tenant at ingest if isolation requires it - flagged as a finding
rather than silently namespaced here.
* **Idempotent.** Recomputing over an unchanged chapter reproduces every key exactly.
This is additive. It adds one nullable column, changes no filename, and does not participate
in ``is_current`` staleness decisions.
"""
from __future__ import annotations
import hashlib
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
import sqlite3
from collections.abc import Iterable, Sequence
# Bump if the derivation ever changes; existing keys stay valid and readable.
KEY_VERSION = "uk1"
COLUMN = "source_unit_key"
def _sha256(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def chapter_text_sha256(source_text: str | None) -> str:
"""Hash a chapter's source text. ``None``/empty still hashes (deterministically)."""
return _sha256((source_text or "").encode("utf-8"))
def text_sha256(text: str | None) -> str:
"""Hash an utterance's exact text."""
return _sha256((text or "").encode("utf-8"))
def compute_source_unit_key(chapter_sha: str, text: str, occurrence: int) -> str:
"""Derive one key. ``occurrence`` disambiguates repeated text within a chapter."""
payload = b"\x00".join(
(
KEY_VERSION.encode("ascii"),
chapter_sha.encode("ascii"),
str(occurrence).encode("ascii"),
text_sha256(text).encode("ascii"),
)
)
return _sha256(payload)
def assign_keys_for_chapter(chapter_sha: str, texts: Sequence[str]) -> list[str]:
"""Return the key for every utterance of one chapter, in document order."""
seen: dict[str, int] = {}
keys: list[str] = []
for text in texts:
t_sha = text_sha256(text)
occurrence = seen.get(t_sha, 0)
seen[t_sha] = occurrence + 1
keys.append(compute_source_unit_key(chapter_sha, text, occurrence))
return keys
def ensure_column(conn: sqlite3.Connection) -> bool:
"""Add ``source_unit_key`` if absent. Returns True when it added the column."""
cols = {row[1] for row in conn.execute("PRAGMA table_info(utterances)")}
if COLUMN in cols:
return False
conn.execute(f"ALTER TABLE utterances ADD COLUMN {COLUMN} TEXT")
conn.execute(f"CREATE INDEX IF NOT EXISTS idx_utterances_source_unit ON utterances({COLUMN})")
conn.commit()
return True
def _chapter_order_sql(conn: sqlite3.Connection) -> str:
"""Order chapters by display order, tolerating a missing ``chapter_index``.
Two of the four live projects carry an older schema shape (see
``manifest.md`` §1.3), so this must not assume the column exists.
"""
cols = {row[1] for row in conn.execute("PRAGMA table_info(chapters)")}
order = "chapter_index, id" if "chapter_index" in cols else "id"
return f"SELECT id FROM chapters ORDER BY {order}"
def chapter_keys(conn: sqlite3.Connection, chapter_id: int) -> list[tuple[int, str]]:
"""Compute ``(utterance_id, key)`` for one chapter without writing anything."""
chapter = conn.execute(
"SELECT source_text FROM chapters WHERE id = ?", (chapter_id,)
).fetchone()
chapter_sha = chapter_text_sha256(chapter[0] if chapter else None)
rows = conn.execute(
"SELECT id, text FROM utterances WHERE chapter_id = ? ORDER BY utterance_index",
(chapter_id,),
).fetchall()
keys = assign_keys_for_chapter(chapter_sha, [r[1] or "" for r in rows])
return [(row[0], key) for row, key in zip(rows, keys, strict=True)]
def stamp_chapter(conn: sqlite3.Connection, chapter_id: int) -> int:
"""Write keys for one chapter. Returns how many rows changed."""
ensure_column(conn)
pairs = chapter_keys(conn, chapter_id)
changed = 0
for utterance_id, key in pairs:
cursor = conn.execute(
f"UPDATE utterances SET {COLUMN} = ? "
f"WHERE id = ? AND ({COLUMN} IS NULL OR {COLUMN} != ?)",
(key, utterance_id, key),
)
changed += cursor.rowcount if cursor.rowcount and cursor.rowcount > 0 else 0
conn.commit()
return changed
def ensure_chapter_keys(conn: sqlite3.Connection, chapter_id: int) -> int:
"""Fill only the keys that are missing for one chapter. Cheap, idempotent, safe.
Called at generation time so every path that produces audio also produces identity,
including paths this file knows nothing about.
"""
ensure_column(conn)
missing = conn.execute(
f"SELECT COUNT(*) FROM utterances WHERE chapter_id = ? AND {COLUMN} IS NULL",
(chapter_id,),
).fetchone()[0]
if not missing:
return 0
return stamp_chapter(conn, chapter_id)
def backfill(
conn: sqlite3.Connection, chapter_ids: Iterable[int] | None = None
) -> dict[str, int]:
"""Backfill every chapter (or a subset). Returns counts for the report."""
if chapter_ids is None:
ids = [row[0] for row in conn.execute(_chapter_order_sql(conn))]
else:
ids = list(chapter_ids)
ensure_column(conn)
stamped = 0
for chapter_id in ids:
stamped += stamp_chapter(conn, chapter_id)
total, filled = conn.execute(
f"SELECT COUNT(*), SUM(CASE WHEN {COLUMN} IS NOT NULL THEN 1 ELSE 0 END) FROM utterances"
).fetchone()
return {
"chapters": len(ids),
"rows_stamped": stamped,
"utterances_total": total or 0,
"utterances_with_key": filled or 0,
"utterances_without_key": (total or 0) - (filled or 0),
}
def key_report(conn: sqlite3.Connection) -> dict[str, Any]:
"""Read-only coverage report - evidence for controller validation phase 2/3."""
has_column = COLUMN in {
row[1] for row in conn.execute("PRAGMA table_info(utterances)")
}
if not has_column:
return {"column_present": False}
total, filled, distinct = conn.execute(
f"SELECT COUNT(*), SUM(CASE WHEN {COLUMN} IS NOT NULL THEN 1 ELSE 0 END), "
f"COUNT(DISTINCT {COLUMN}) FROM utterances"
).fetchone()
return {
"column_present": True,
"key_version": KEY_VERSION,
"utterances_total": total or 0,
"utterances_with_key": filled or 0,
"distinct_keys": distinct or 0,
"collisions": (filled or 0) - (distinct or 0),
}