Skip to content

Commit ea8e2d8

Browse files
fix(migrations): guard the three ALTERs init_db's reconciliation pre-empts
A sessions database last written by an older release could never reach v48. init_db runs _reconcile_legacy_base_tables BEFORE migrate(): it diffs every existing table against the final schema and ADDs the missing columns, and those ALTERs auto-commit. Three migrations then added the same column unguarded on a table an earlier version created: v37 practice_attempts.topic / .concept (table from v24 -> v24..v36) v32 context_session_projects.assignment_kind (v31) v44 context_capture_runs.withdrawn (v34..v43) The ALTER failed with "duplicate column name", migrate() rolled the sequence back -- but the reconciliation's columns survived the rollback, so every later migrate() (session-maint embed, session-export, any studyloop command) failed identically with user_version stuck. Andy's v30 database on the Mac Mini: "Migrating database from version 30 to 48 ... v37 ... duplicate column name: topic". The reconciliation's docstring claimed "migrations themselves are column-guarded"; learner_schema.install even guards parked_topics on exactly that reasoning, four lines below the unguarded practice_attempts ALTERs. All three now check the column is absent first, which also recovers databases already left in the stuck state. The docstring now states the real contract. Tests (test_init_db_legacy): for every schema version 0..47, a database stopped at that version converges through init_db; and the same database after the old final-shape widening converges through a bare migrate() -- the session-maint path, and the exact state of the stuck database. Before the fix 40 of those 96 cases failed (24 topic, 14 withdrawn, 2 assignment_kind).
1 parent a9c2f7d commit ea8e2d8

6 files changed

Lines changed: 172 additions & 11 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,23 @@ experience may change before `1.0.0`.
119119

120120
### Fixed
121121

122+
- A sessions database last written by an older release could never reach the
123+
current schema. `init_db`'s legacy reconciliation adds every final-shape
124+
column to the tables that already exist *before* the migrations run, and
125+
three migrations then `ALTER TABLE ... ADD COLUMN` the same column
126+
unguarded: v37 (`practice_attempts.topic`/`concept`, so any database at
127+
v24–v36), v32 (`context_session_projects.assignment_kind`, v31) and v44
128+
(`context_capture_runs.withdrawn`, v34–v43). The ALTER failed with
129+
`duplicate column name`, the whole sequence rolled back, and because the
130+
reconciliation's own ALTERs had already auto-committed, every later
131+
`migrate()` — `session-maint embed`, `session-export`, any `studyloop`
132+
command — failed the same way with `user_version` stuck (a v30 database
133+
reported "Migrating database from version 30 to 48 … duplicate column
134+
name: topic"). All three now check for the column first; databases already
135+
left in that state migrate on the next run. A test replays a database
136+
stopped at every schema version through `init_db`, and the same database
137+
after the old reconciliation touched it through `migrate()`, so an
138+
unguarded ALTER cannot ship again.
122139
- A database stopped at exactly v5 in rollback-journal mode failed to migrate
123140
with `cannot change into wal mode from within a transaction`: the
124141
pragma-only v6 migration was executed inside `migrate()`'s `BEGIN

‎packages/agent-session-tools/src/agent_session_tools/context/learner_schema.py‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,18 @@
2222

2323
def install(conn: sqlite3.Connection) -> None:
2424
conn.execute(NOTES_DDL)
25-
conn.execute("ALTER TABLE practice_attempts ADD COLUMN topic TEXT")
26-
conn.execute("ALTER TABLE practice_attempts ADD COLUMN concept TEXT")
25+
# Guarded: init_db's legacy reconciliation adds every final-shape column
26+
# to a table that already exists BEFORE the migrations run, so a database
27+
# stopped anywhere between v24 (practice_attempts created) and v36 reaches
28+
# this migration with both columns already present. Unguarded, the ALTER
29+
# failed with "duplicate column name: topic", the whole sequence rolled
30+
# back, and the database could never leave its old version.
31+
practice_columns = {
32+
r[1] for r in conn.execute("PRAGMA table_info(practice_attempts)")
33+
}
34+
for name in ("topic", "concept"):
35+
if name not in practice_columns:
36+
conn.execute(f"ALTER TABLE practice_attempts ADD COLUMN {name} TEXT")
2737
conn.execute(
2838
"CREATE INDEX IF NOT EXISTS idx_study_notes_status ON study_notes(status,created_at DESC)"
2939
)

‎packages/agent-session-tools/src/agent_session_tools/export_sessions.py‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -84,9 +84,17 @@ def _reconcile_legacy_base_tables(conn: sqlite3.Connection) -> None:
8484
columns — nullable, with the schema's default when it is a constant
8585
(SQLite cannot add a column with a non-constant default, nor
8686
retroactively enforce NOT NULL/PRIMARY KEY on a populated table).
87-
Migrations themselves are column-guarded, so replaying them over the
88-
reconciled shape is safe; tables the bootstrap will create from scratch
89-
are skipped. Existing rows are never touched.
87+
Tables the bootstrap will create from scratch are skipped. Existing rows
88+
are never touched.
89+
90+
This runs BEFORE ``migrate()``, and its ALTERs auto-commit, so a pending
91+
migration meets a table that already carries the column it is about to
92+
add. Every migration that ``ALTER TABLE ... ADD COLUMN`` on a table an
93+
earlier version created must therefore check the column is absent first;
94+
``test_init_db_legacy`` replays a database stopped at every version to
95+
enforce it. An unguarded one fails with ``duplicate column name``, the
96+
sequence rolls back, these ALTERs survive the rollback, and the database
97+
is stuck below the current version until the migration is guarded.
9098
"""
9199
pristine = sqlite3.connect(":memory:")
92100
try:

‎packages/agent-session-tools/src/agent_session_tools/migrations.py‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1391,9 +1391,12 @@ def migrate_v31(conn: sqlite3.Connection) -> None:
13911391
def migrate_v32(conn: sqlite3.Connection) -> None:
13921392
import hashlib
13931393

1394-
conn.execute(
1395-
"ALTER TABLE context_session_projects ADD COLUMN assignment_kind TEXT NOT NULL DEFAULT 'explicit' CHECK(assignment_kind IN ('explicit','root_policy','sync'))"
1396-
)
1394+
# Guarded: init_db's legacy reconciliation may have added this column to a
1395+
# v31 database before the migrations ran (see learner_schema.install).
1396+
if "assignment_kind" not in _table_columns(conn, "context_session_projects"):
1397+
conn.execute(
1398+
"ALTER TABLE context_session_projects ADD COLUMN assignment_kind TEXT NOT NULL DEFAULT 'explicit' CHECK(assignment_kind IN ('explicit','root_policy','sync'))"
1399+
)
13971400
conn.execute(
13981401
"CREATE TABLE context_policy_state(id INTEGER PRIMARY KEY CHECK(id=1),digest TEXT NOT NULL,applied_at TEXT)"
13991402
)

‎packages/agent-session-tools/src/agent_session_tools/replication/withdrawal_schema.py‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,15 @@
22

33

44
def install(conn):
5-
conn.execute(
6-
"ALTER TABLE context_capture_runs ADD COLUMN withdrawn INTEGER NOT NULL DEFAULT 0"
7-
)
5+
# Guarded: init_db's legacy reconciliation may have added this column to a
6+
# v34..v43 database before the migrations ran (see learner_schema.install).
7+
capture_columns = {
8+
r[1] for r in conn.execute("PRAGMA table_info(context_capture_runs)")
9+
}
10+
if "withdrawn" not in capture_columns:
11+
conn.execute(
12+
"ALTER TABLE context_capture_runs ADD COLUMN withdrawn INTEGER NOT NULL DEFAULT 0"
13+
)
814
conn.execute("""CREATE TABLE context_replica_permissions (
915
peer TEXT NOT NULL REFERENCES context_replica_peers(peer),
1016
direction TEXT NOT NULL CHECK(direction IN ('in','out')),

‎packages/agent-session-tools/tests/test_init_db_legacy.py‎

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,24 @@
1010
"""
1111

1212
import sqlite3
13+
from pathlib import Path
1314

1415
import pytest
1516

17+
from agent_session_tools.migrations import (
18+
CURRENT_VERSION,
19+
MIGRATIONS,
20+
get_user_version,
21+
migrate,
22+
set_user_version,
23+
)
24+
1625
pytestmark = []
1726

27+
SCHEMA_PATH = (
28+
Path(__file__).parent.parent / "src" / "agent_session_tools" / "schema.sql"
29+
)
30+
1831
LEGACY_SCHEMA = """
1932
CREATE TABLE IF NOT EXISTS study_sessions (id TEXT PRIMARY KEY, started_at TEXT);
2033
CREATE TABLE IF NOT EXISTS sessions (
@@ -62,3 +75,107 @@ def test_init_db_on_legacy_db_is_repeatable(legacy_db_path):
6275
assert conn.execute("SELECT id FROM sessions").fetchone()[0] == "legacy1"
6376
finally:
6477
conn.close()
78+
79+
80+
def _database_stopped_at(tmp_path: Path, version: int) -> Path:
81+
"""A sessions.db exactly as a fresh install left it at schema ``version``.
82+
83+
schema.sql plus migrations 1..version, with ``user_version`` recorded --
84+
the shape of a database last touched by an older release.
85+
"""
86+
db = tmp_path / f"sessions-v{version}.db"
87+
conn = sqlite3.connect(db)
88+
try:
89+
conn.executescript(SCHEMA_PATH.read_text())
90+
for v in range(1, version + 1):
91+
MIGRATIONS[v][1](conn)
92+
set_user_version(conn, v)
93+
conn.execute(
94+
"INSERT INTO sessions(id,source,created_at) VALUES ('kept','kiro','2024-01-01')"
95+
)
96+
conn.commit()
97+
finally:
98+
conn.close()
99+
return db
100+
101+
102+
def _widen_to_final_shape(conn: sqlite3.Connection) -> None:
103+
"""What ``_reconcile_legacy_base_tables`` did before the fix.
104+
105+
It diffed every live table against the *final* schema and ADDed each
106+
missing column -- including columns a not-yet-applied migration was
107+
about to add itself. Those ALTERs auto-committed before ``migrate()``
108+
ran and then survived its rollback, so a database it touched once was
109+
left with the columns present and ``user_version`` unchanged.
110+
"""
111+
pristine = sqlite3.connect(":memory:")
112+
try:
113+
pristine.executescript(SCHEMA_PATH.read_text())
114+
migrate(pristine)
115+
tables = [
116+
row[0]
117+
for row in pristine.execute(
118+
"SELECT name FROM sqlite_master WHERE type='table'"
119+
)
120+
]
121+
for table in tables:
122+
live = {row[1] for row in conn.execute(f'PRAGMA table_info("{table}")')}
123+
if not live:
124+
continue
125+
for _, name, ctype, _, default, pk in pristine.execute(
126+
f'PRAGMA table_info("{table}")'
127+
).fetchall():
128+
if name in live or pk:
129+
continue
130+
ddl = f'ALTER TABLE "{table}" ADD COLUMN "{name}" {ctype}'
131+
if default is not None and "(" not in str(default):
132+
ddl += f" DEFAULT {default}"
133+
conn.execute(ddl)
134+
conn.commit()
135+
finally:
136+
pristine.close()
137+
138+
139+
@pytest.mark.parametrize("version", range(CURRENT_VERSION))
140+
def test_init_db_converges_a_database_stopped_at_any_version(tmp_path, version):
141+
"""Every release's schema must migrate forward through ``init_db``.
142+
143+
The legacy reconciliation runs *before* the migrations. If it adds a
144+
column a pending migration adds unguarded, that migration fails with
145+
``duplicate column name`` and the whole sequence rolls back -- which is
146+
how a v30 database (practice_attempts from v24, ``topic`` added by v37)
147+
could never reach v48.
148+
"""
149+
from agent_session_tools.export_sessions import init_db
150+
151+
conn = init_db(str(_database_stopped_at(tmp_path, version)))
152+
try:
153+
assert get_user_version(conn) == CURRENT_VERSION
154+
assert conn.execute("SELECT id FROM sessions").fetchone()[0] == "kept"
155+
finally:
156+
conn.close()
157+
158+
159+
@pytest.mark.parametrize("version", range(CURRENT_VERSION))
160+
def test_migrate_recovers_a_database_the_old_reconciliation_already_widened(
161+
tmp_path, version
162+
):
163+
"""Databases the old reconciliation touched are stuck until migrations tolerate it.
164+
165+
Such a database already carries every final-shape column while its
166+
``user_version`` still says ``version``. ``session-maint embed`` calls
167+
``migrate()`` directly on it (no reconciliation), so the pending
168+
migrations themselves must skip a column that is already there.
169+
"""
170+
db = _database_stopped_at(tmp_path, version)
171+
conn = sqlite3.connect(db)
172+
try:
173+
_widen_to_final_shape(conn)
174+
assert get_user_version(conn) == version
175+
176+
migrate(conn)
177+
178+
assert get_user_version(conn) == CURRENT_VERSION
179+
assert conn.execute("SELECT id FROM sessions").fetchone()[0] == "kept"
180+
finally:
181+
conn.close()

0 commit comments

Comments
 (0)