Files
turnstone/tests/test_migration_071.py
T
Patrick Buckley 480a1426b3 Fail-closed history-commit handoff (#1005)
* fix(session): fail-closed history-commit handoff (#981)

The deleted-workstream discovery is now a terminal, ws_id-keyed latch:
keyed conversation commits refuse admission once the durable parent is
gone (convergence finalizers and force-abandon are exempt), history
handoff refuses to mint a proof token so /history fails closed with a
503 instead of silently wiping the pane, and the SSE stream carries a
workstream_gone resync reason. Discarded commits leave a forensic log
of commit keys and roles, never content.

Conversation rows gain a commit_key (migration 071): keyed saves are
idempotent under retry, validated against the full commit identity, and
refused when they would cross a workstream deletion. The prune orphan
category now requires a NULL alias plus a two-hour updated grace, with
cutoffs computed at discovery time and carried into both dialects'
rechecks.

The mid-turn interjection queue is owner-partitioned with no per-site
mode flags: pops take the acting principal's and unowned rows, other
participants' rows are structurally retained, and enforcement lives at
queue admission plus the shared before_spawn gates. The retraction
ledger is bounded by open pop windows: pops open a window atomically
with the queue delete, restores close their ids atomically with the
ledger consume, every other exit closes through one helper, and misses
for unheld ids record nothing. The workstream-gone latch refuses
unattended wakes at all three gates (watcher spawn, claim, delivery
pre-pop), and the retry dispatcher regained its pre-envelope
cancel/error convergence net.

Persistence-state reporting derives through the session bound to each
UI instead of a registry lookup by id that failed open to healthy
during tombstone retention. The dashboard roster no longer re-inserts
ghost entries from trailing activity events, the history tool-outcome
scan tolerates interleaved non-turn rows, and the shared
handoff-deadline handle owns its own retirement.

Single-sourced across call sites: keyed-commit row values, attachment
save wrappers, tail-truncation and conflict-resolution bodies for both
storage dialects; worker-slot lifecycle field sets; the direct-commit
admission frame; queued-row layout accessors; the string-aware comment
stripper shared by every JS harness suite.

Refs #981 #964

* fix(session): sweep handoff fixes to their sibling surfaces

The interactive replay loop treated a system row as a tool-batch
boundary, so every tool result after an interleaved row vanished from
that pane while the coordinator rendered the same history correctly.
Only a conversational turn ends the batch window now, matching the
shared outcome index.

Accepted user turns clear the composer's attachment chips on the same
viewer policy that settles optimistic bubbles rather than on having
matched a local bubble, so a workstream created with an upload no
longer keeps a chip for an attachment the create dispatch already
consumed. The coordinator's raced-Stop arm emits the stream-end hook it
inherits alongside the idle state, leaving no unfinalized bubble or
unflushed tool output. Ending a session surfaces a failure toast when
the request never lands or answers with a non-JSON body.

The per-second persistence reconcile now probes each session without
blocking: a workstream whose generation and handoff locks are held is
skipped until the next pass instead of contending the locks every
commit needs. The one-shot repair that gates workstream creation at
capacity keeps a definite probe — it has no next pass, and the sessions
likeliest to be contended are the ones whose unresolved journals
emptied its candidate list.

Single-sourced: the attachment lane builds its conversation row through
the shared commit-identity builder; the ordinary worker exit releases
its slot through the lifecycle owner; both operator surfaces snapshot
their counters through one non-consuming helper; the replay preamble
loses its per-kind wrappers and its config hook; the browser harness
suites share one brace walker; and each in-flight history attempt is
one record carrying both its abort controller and its deadline.

Refs #981 #964
2026-08-11 04:18:36 -07:00

180 lines
6.7 KiB
Python

"""Migration coverage for idempotent conversation commit keys."""
from __future__ import annotations
import contextlib
import importlib
from pathlib import Path
from types import SimpleNamespace
from typing import TYPE_CHECKING, Any
import pytest
import sqlalchemy as sa
from alembic import command
from alembic.config import Config
if TYPE_CHECKING:
from collections.abc import Iterator
_MIGRATIONS_DIR = str(
Path(__file__).resolve().parent.parent / "turnstone" / "core" / "storage" / "migrations"
)
def _alembic_cfg(db_path: Path) -> Config:
cfg = Config()
cfg.set_main_option("script_location", _MIGRATIONS_DIR)
cfg.set_main_option("sqlalchemy.url", f"sqlite:///{db_path}")
return cfg
class TestMigration071:
def test_upgrade_preserves_legacy_rows_and_enforces_scoped_key_uniqueness(
self, tmp_path: Path
) -> None:
db_path = tmp_path / "071-up.db"
cfg = _alembic_cfg(db_path)
command.upgrade(cfg, "070")
engine = sa.create_engine(f"sqlite:///{db_path}")
try:
with engine.begin() as conn:
conn.execute(
sa.text(
"INSERT INTO conversations (ws_id, timestamp, role, content) "
"VALUES ('legacy', '2026-01-01T00:00:00', 'assistant', 'same'), "
"('legacy', '2026-01-01T00:00:01', 'assistant', 'same')"
)
)
command.upgrade(cfg, "071")
with engine.begin() as conn:
assert (
conn.execute(
sa.text("SELECT COUNT(*) FROM conversations WHERE commit_key IS NULL")
).scalar_one()
== 2
)
# NULL keeps append-only legacy semantics under the unique index.
conn.execute(
sa.text(
"INSERT INTO conversations "
"(ws_id, timestamp, role, content, commit_key) VALUES "
"('legacy', '2026-01-01T00:00:02', 'assistant', 'same', NULL)"
)
)
conn.execute(
sa.text(
"INSERT INTO conversations "
"(ws_id, timestamp, role, content, commit_key) VALUES "
"('keyed-a', '2026-01-01T00:00:03', 'assistant', 'a', 'key-1'), "
"('keyed-b', '2026-01-01T00:00:04', 'assistant', 'b', 'key-1')"
)
)
with pytest.raises(sa.exc.IntegrityError):
conn.execute(
sa.text(
"INSERT INTO conversations "
"(ws_id, timestamp, role, content, commit_key) VALUES "
"('keyed-a', '2026-01-01T00:00:05', 'assistant', 'dup', 'key-1')"
)
)
finally:
engine.dispose()
@pytest.mark.parametrize("invalid_index", [False, True])
def test_postgresql_upgrade_is_restart_safe_and_repairs_invalid_index(
self,
monkeypatch: pytest.MonkeyPatch,
invalid_index: bool,
) -> None:
migration = importlib.import_module(
"turnstone.core.storage.migrations.versions.071_conversations_commit_key"
)
class _Result:
def __init__(self, value: bool) -> None:
self.value = value
def scalar_one_or_none(self) -> bool:
return self.value
class _Bind:
dialect = SimpleNamespace(name="postgresql")
def __init__(self) -> None:
self.queries: list[str] = []
self.invalid_index = invalid_index
def execute(self, statement: Any) -> _Result:
self.queries.append(str(statement))
return _Result(self.invalid_index)
class _Context:
@contextlib.contextmanager
def autocommit_block(self) -> Iterator[None]:
yield
class _Op:
def __init__(self, bind: _Bind) -> None:
self.bind = bind
self.ddl: list[str] = []
def get_bind(self) -> _Bind:
return self.bind
def get_context(self) -> _Context:
return _Context()
def execute(self, statement: str) -> None:
self.ddl.append(statement)
if statement.startswith(("DROP INDEX", "CREATE UNIQUE INDEX")):
self.bind.invalid_index = False
bind = _Bind()
fake_op = _Op(bind)
monkeypatch.setattr(migration, "op", fake_op)
# Running twice models a revision left unstamped after either durable
# DDL operation. Both statements remain safe on the second attempt.
migration.upgrade()
migration.upgrade()
assert (
fake_op.ddl.count("ALTER TABLE conversations ADD COLUMN IF NOT EXISTS commit_key TEXT")
== 2
)
creates = [statement for statement in fake_op.ddl if statement.startswith("CREATE UNIQUE")]
assert len(creates) == 2
assert all("CONCURRENTLY IF NOT EXISTS" in statement for statement in creates)
drops = [statement for statement in fake_op.ddl if statement.startswith("DROP INDEX")]
assert len(drops) == (1 if invalid_index else 0)
assert bind.queries and all("NOT i.indisvalid" in query for query in bind.queries)
def test_downgrade_then_upgrade_round_trip(self, tmp_path: Path) -> None:
db_path = tmp_path / "071-roundtrip.db"
cfg = _alembic_cfg(db_path)
command.upgrade(cfg, "071")
command.downgrade(cfg, "070")
engine = sa.create_engine(f"sqlite:///{db_path}")
try:
columns = {c["name"] for c in sa.inspect(engine).get_columns("conversations")}
indexes = {i["name"] for i in sa.inspect(engine).get_indexes("conversations")}
assert "commit_key" not in columns
assert "uq_conversations_ws_commit_key" not in indexes
finally:
engine.dispose()
command.upgrade(cfg, "071")
engine = sa.create_engine(f"sqlite:///{db_path}")
try:
columns = {c["name"] for c in sa.inspect(engine).get_columns("conversations")}
indexes = {i["name"]: i for i in sa.inspect(engine).get_indexes("conversations")}
assert "commit_key" in columns
assert bool(indexes["uq_conversations_ws_commit_key"]["unique"])
assert "commit_key IS NOT NULL" in str(
indexes["uq_conversations_ws_commit_key"]["dialect_options"]["sqlite_where"]
)
finally:
engine.dispose()