Files
LLeMbas/src/lembas/db/migrations.py
T
Jaroslav Beneš 2f09d8363d Something can happen because time passed, and land somewhere worth reading
Nothing in LLeMbas ever happened on its own. Every reply was downstream of
somebody pressing Send, and the one exception -- jobs.wake, waking a chat when a
background job finishes -- was downstream of a command they had run. PLAN.md
never listed scheduling as unbuilt because services/chat.py:618 had recorded it
as a decision: "a scheduler is a whole new concern for a single-worker
application". This is that concern, taken on deliberately, plus the two places
its output goes.

Reports first, because it is useful with no scheduling at all. A report is not a
Chat with one Message in it: it has no turns and no reply, it is read top to
bottom, and it must be writable with no chat behind it -- being the fallback for
a run whose own chat has gone. As a Chat it would need a sidebar row per daily
report, a title that regenerates itself, a composer to suppress and a bubble with
a rewind button around something that is not a turn. The section's character is
enforced by absence: nothing under reports/ includes the composer or renders
chat/_message.html, so there is no sse-connect anywhere and nothing on those
pages *can* start a generation. The test reads that off the OpenAPI schema, not
by walking app.routes -- this FastAPI keeps an included router wrapped rather
than flattening it, so the walk finds nothing and the assertion passes for the
wrong reason.

rule.py is pure, total, and was finished before anything called it. No session,
no wall clock, nothing that raises: validate clamps what it recognises, drops
what it does not, and answers {} for prose -- at which point the caller shows the
manual form. It had to be that way because the compile step's output is model
output that becomes a *timer*, which is the sharpest case of hard rule 6 here.
The invariant, pinned: anything validate accepts has a computable next
occurrence. A schedule that can never fire looks exactly like a working one on
every screen it appears on.

Wall-clock and elapsed time are kept apart because they mean different things.
at.times are wall-clock in the owner's zone, so 15:00 stays 15:00 across a
daylight-saving change -- that is what "every Monday at 3PM" means. every is
elapsed real time, so six hours stays six hours across a 23- or 25-hour day --
that is what a timer means. Conflating them gets one of the two wrong twice a
year. A time inside the spring-forward gap fires at the first minute that exists;
left to zoneinfo's own resolution it lands an hour away wearing a wall-clock time
that did not happen, and a daily 02:30 report vanishing once a year on a machine
nobody watches is the failure this file is arranged around.

The ticker claims and commits *before* it fires. The other order is a hot loop: a
firing that raises is retried every tick for ever against whatever it was that
failed, and the only symptom is load. Its blanket except is copied from the
terminal reaper for a sharper reason -- a ticker that dies on one bad row stops
every schedule on the instance and says nothing at all. No request fails, no
reply errors, no dot appears. The reports simply stop.

Three rules that look like bugs from outside: a firing arriving while the chat is
still answering queues rather than starting a second reply, and past max_queued
is skipped with the reason on the row; Run now does not advance next_fire_at, or
testing a schedule silently consumes the run it was testing; resuming recomputes
from now, or a schedule paused for a month fires the instant it comes back, once
per occurrence it missed. Catching up lives in the sweep and not in a startup
hook, because a suspended host and a long stall reproduce "its time passed while
nothing was running" with no restart to hang one on.

services/wake.py is the lock discipline extracted rather than copied. A finished
job and a due schedule are the same problem, and both depend on there being no
await between the running_for check and the writes; two lock dictionaries for one
invariant is how one of them drifts. jobs.wake is now a caller that supplies
wording, and _completion_text stayed exactly where it was because tool.background
quotes its opening sentence.

A scheduled run has no reader, so ask_user is withdrawn from resolve_tools rather
than merely discouraged in core.unattended -- a rule living only in a system
message is one a page the model just read can argue with, and a parked question
holds the reply for the whole approval_timeout with nobody to answer it. For the
same reason a task chat may not be an agent chat in v1: Manual, Edit and Plan all
stop to ask on RISK_EXECUTE, so the only two outcomes would be unattended
execution and a reply that stalls. That deserves its own pass.

Messages is bounded in the request and unbounded on disk. Only the latest chunk
is sent; everything else stays exactly where it was written. Nothing is folded
into text and nothing is deleted -- the visible conversation is identical either
way, so destroying the older rows would buy only disk, against being irreversible
and losing every attachment and tool call in the range, and it would contradict
the rule compaction already holds. should_compact refuses this kind for the
matching reason: two mechanisms narrowing one transcript is how a summary ends up
summarising a summary. The history route is the mirror of thread_tail and keeps
its four properties; the fifth is its own, that prepending moves the scroll
position, so app.js records scrollHeight before the swap and adds the difference
back after.

An empty Chat.kind meant "both sides of the switch" and had been read as "no
filter" since there were only two of them. The sidebar passes "" precisely when
agent chats are switched off -- so the moment a third kind existed, every task
chat and every Messages conversation appeared in somebody's ordinary chat list,
on exactly the instances whose owners would never think to look. KINDS stays the
two-sided fork, because set_sidebar_kind validates against it and a third entry
there makes the tree filterable to a side with no button to leave it; ALL_KINDS
is what a row may be. Both narrowings are pinned, because they are two
implementations of one rule and only one of them is SQL.

Per-user timezone had to exist for any of this: harness.py:179 was telling every
reader the *server's* idea of the date, which is survivable while the answer is
prose and stops being survivable the moment somebody says "every Monday at 3" and
something has to work out when that is.

Three things were caught by a test being wrong rather than by the code being
wrong. The task-chat "no composer" assertions were passing against a page
rendering its no-models-configured branch. A permission test asserted the same
thing twice because the administrator bypasses every permission. And every
Messages test passed with default_model never called, because none of them
configured a model -- so the pair it returns was being assigned straight to
model_id, and SQLite refuses a tuple in a String column. The fixtures now say why
they exist.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 21:31:36 +02:00

234 lines
9.8 KiB
Python

"""Additive schema synchronisation.
This project has no Alembic, by design: it is SQLite-only and the schema is
created at startup. That was fine until the first live instance had data in it,
at which point adding a column to a model stopped being free -- ``create_all``
only creates missing *tables*, so a new column silently never appears and every
query mentioning it fails.
What this module does instead is derive the migration from the models: compare
each table's declared columns against what the database actually has, and
``ALTER TABLE ... ADD COLUMN`` for whatever is missing. That covers new tables
and new columns, which is essentially every schema change this project makes.
What it deliberately does NOT do:
* rename, drop or retype a column
* add a PRIMARY KEY or UNIQUE constraint to an existing table
* backfill anything requiring application logic
SQLite cannot do most of those with ALTER TABLE anyway; they need the
create-copy-swap dance. Anything in that category is a hand-written job and
should be added to MANUAL_STEPS below so it is at least visible.
"""
from __future__ import annotations
import logging
from typing import Any
from sqlalchemy import Engine, inspect, text
from sqlalchemy.schema import Column, Table
from lembas.db.base import Base
log = logging.getLogger(__name__)
# Schema changes that this module cannot perform. Kept as documentation so a
# failure has somewhere to point rather than being a mystery.
MANUAL_STEPS: list[str] = []
def _literal_default(column: Column) -> str | None:
"""A SQL literal to backfill an existing row's new column with.
SQLite refuses to add a NOT NULL column without a default, and refuses a
non-constant default. Python-side defaults (``default=dict``,
``default=utcnow``) are callables and cannot be expressed in DDL, so the
value is derived from the column type instead. New rows still get the real
Python default; this only fills the rows that already exist.
"""
default = column.default
if default is not None and not default.is_callable and not default.is_clause_element:
value: Any = default.arg
if isinstance(value, bool):
return "1" if value else "0"
if isinstance(value, (int, float)):
return str(value)
if isinstance(value, str):
escaped = value.replace("'", "''")
return f"'{escaped}'"
affinity = column.type.__class__.__name__.upper()
if "JSON" in affinity:
# MutableList columns must start as [] and MutableDict as {}; guessing
# wrong makes the first read blow up rather than return empty.
python_type = getattr(column.type, "python_type", None)
return "'[]'" if python_type is list else "'{}'"
if "BOOL" in affinity:
return "0"
if any(token in affinity for token in ("INT", "FLOAT", "NUMERIC", "DECIMAL")):
return "0"
if "DATE" in affinity or "TIME" in affinity:
return "CURRENT_TIMESTAMP"
if any(token in affinity for token in ("STRING", "TEXT", "VARCHAR", "CHAR")):
return "''"
return None
def _add_column_sql(table: Table, column: Column, dialect) -> str | None:
type_sql = column.type.compile(dialect)
default = _literal_default(column)
if not column.nullable and default is None:
log.error(
"cannot add NOT NULL column %s.%s: no usable default. Add it by hand.",
table.name,
column.name,
)
return None
parts = [f'ALTER TABLE "{table.name}" ADD COLUMN "{column.name}" {type_sql}']
if not column.nullable:
# SQLite refuses a NOT NULL column with no default, so existing rows
# have to be given something. That is the only reason a default is
# emitted at all.
parts.append("NOT NULL")
parts.append(f"DEFAULT {default}")
# A nullable column gets no default on purpose. Backfilling one would give
# existing rows a value the model does not consider absent -- an added
# foreign key would arrive as "" rather than NULL, and every "is this set?"
# check downstream would be wrong about rows that predate it.
return " ".join(parts)
# --- Full-text search --------------------------------------------------------
# The library stores are searched rather than listed, and LIKE over a few
# hundred documents ranks nothing and matches badly. SQLite ships FTS5, so the
# index costs no dependency and works offline like everything else here.
#
# These are the one part of the schema this module's model-diffing cannot
# derive: an FTS5 virtual table is not a SQLAlchemy model, has no columns to
# compare, and needs triggers to stay in step with the table it shadows. So it
# is written out -- but written out *idempotently*, with IF NOT EXISTS
# throughout, which keeps it the same kind of thing as the column sync: run it
# at every startup and it converges.
#
# `content=` makes each index external-content: the text is not stored twice,
# and the triggers below are what the FTS5 documentation calls for to keep an
# external-content index correct through updates and deletes.
FTS_INDEXES: tuple[tuple[str, str, tuple[str, ...]], ...] = (
("documents_fts", "documents", ("title", "description", "extracted_text")),
("notes_fts", "notes", ("title", "body")),
("skills_fts", "skills", ("name", "description", "body")),
("reports_fts", "reports", ("title", "summary", "body")),
)
def _fts_statements(index: str, table: str, columns: tuple[str, ...]) -> list[str]:
# `id` rides along UNINDEXED so a match can be turned straight back into an
# ORM row. The alternative is joining on rowid, which SQLAlchemy models do
# not expose and which changes under VACUUM.
columns = ("id", *columns)
column_list = ", ".join(columns)
declared = ", ".join(
f"{name} UNINDEXED" if name == "id" else name for name in columns
)
new_values = ", ".join(f"new.{name}" for name in columns)
old_values = ", ".join(f"old.{name}" for name in columns)
return [
f"CREATE VIRTUAL TABLE IF NOT EXISTS {index} USING fts5("
f"{declared}, content='{table}', content_rowid='rowid')",
# 'delete' rows carry the old values because an external-content index
# cannot look them up itself once the source row has gone.
f"""CREATE TRIGGER IF NOT EXISTS {index}_ai AFTER INSERT ON {table} BEGIN
INSERT INTO {index}(rowid, {column_list}) VALUES (new.rowid, {new_values});
END""",
f"""CREATE TRIGGER IF NOT EXISTS {index}_ad AFTER DELETE ON {table} BEGIN
INSERT INTO {index}({index}, rowid, {column_list})
VALUES ('delete', old.rowid, {old_values});
END""",
f"""CREATE TRIGGER IF NOT EXISTS {index}_au AFTER UPDATE ON {table} BEGIN
INSERT INTO {index}({index}, rowid, {column_list})
VALUES ('delete', old.rowid, {old_values});
INSERT INTO {index}(rowid, {column_list}) VALUES (new.rowid, {new_values});
END""",
]
def ensure_fts(engine: Engine) -> list[str]:
"""Create the search indexes and their triggers if they are missing.
Returns the indexes it created. A failure here is logged and swallowed:
search degrading to "finds nothing" is bad, but it is much better than the
application refusing to start.
"""
created: list[str] = []
inspector = inspect(engine)
known = set(inspector.get_table_names())
with engine.begin() as connection:
for index, table, columns in FTS_INDEXES:
if table not in known:
continue
fresh = index not in known
for statement in _fts_statements(index, table, columns):
connection.execute(text(statement))
if fresh:
# Backfill anything already in the table. Only on creation --
# the triggers keep it current from then on.
column_list = ", ".join(("id", *columns))
connection.execute(
text(
f"INSERT INTO {index}(rowid, {column_list}) "
f"SELECT rowid, {column_list} FROM {table}"
)
)
created.append(index)
return created
def sync_schema(engine: Engine) -> list[str]:
"""Bring the database up to the declared schema. Returns what it changed."""
import lembas.db.models # noqa: F401 (registers every table on the metadata)
changes: list[str] = []
inspector = inspect(engine)
known_tables = set(inspector.get_table_names())
for table in Base.metadata.sorted_tables:
if table.name not in known_tables:
changes.append(f"create table {table.name}")
# Creates anything missing; existing tables are left alone.
Base.metadata.create_all(bind=engine)
inspector = inspect(engine)
with engine.begin() as connection:
for table in Base.metadata.sorted_tables:
existing = {col["name"] for col in inspector.get_columns(table.name)}
for column in table.columns:
if column.name in existing:
continue
statement = _add_column_sql(table, column, engine.dialect)
if statement is None:
continue
connection.execute(text(statement))
changes.append(f"add column {table.name}.{column.name}")
log.info("schema: %s", statement)
try:
for index in ensure_fts(engine):
changes.append(f"create search index {index}")
except Exception: # noqa: BLE001 - search is not worth refusing to start over
log.exception("could not create the full-text search indexes")
if changes:
log.info("schema synchronised: %d change(s)", len(changes))
for step in MANUAL_STEPS:
log.warning("manual schema step still required: %s", step)
return changes