Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(model_hub): repair the selection that outlives its row, and tell the reader

cyh5eda4f9e704c
diff --git a/docs/plans/model-hub-credential-address-repair.md b/docs/plans/model-hub-credential-address-repair.md
index eb8f5b57b..fa2cb1d16 100644
--- a/docs/plans/model-hub-credential-address-repair.md
+++ b/docs/plans/model-hub-credential-address-repair.md
@@ -124,17 +124,28 @@ back, in this precedence, to decide what it asks for
| `scope_settings.settings_json` → `routing.{model,model_override,opencode_model,claude_model,codex_model}` | A channel's routing override; read **before** the column | Renamed |
| `scope_settings.model` | The same override, column form | Renamed |
| `agents.model` | The Vibe Agent's own model | Renamed |
+| `run_definitions.metadata_json` → `session_settings_snapshot.model` | A reclaimed Session's pin, held for the Session that replaces it | Renamed |
| `agent_runs.model` | A record of a call that was made | **Not** renamed |
| `skill_usage_daily.model` | A metering key | **Not** renamed |
-The split is selection versus record. The first four decide a future request;
+The split is selection versus record. The first five decide a future request;
leaving one addressed keeps the Agent broken after the catalog is repaired —
the failure only changes from a double-addressed `model_not_found` to a
`mapping_target_unavailable`. The last two describe calls already made, and
rewriting them would restate history.
-`run_definitions` has no model column at all: a scheduled run resolves its
-model live through its Agent, so it inherits the repair for free.
+The snapshot is the one selection with no row of its own, and the reason a
+"`run_definitions` has no model column" reading of the schema is not enough.
+`session_reclaim` writes it precisely *because* the column does not exist: a
+`create_once` Task whose Session was torn down would otherwise re-resolve
+against scope defaults and silently change model, so the pin is parked in
+definition metadata and `_rebind_create_once_session` writes it back onto the
+replacement Session. An addressed snapshot therefore re-seeds the value on a
+row created *after* the config witness was cleared, where no later demand runs
+the repair again. Soft-deleted definitions are included: the rename path skips
+them because it keeps live bindings correct, while this repair is making the
+address absent from storage, and a row that is only marked deleted still
+stores it.
The hub proves which addresses are addresses; it does not own these rows. It
hands the proven set to `repair_model_selections`, which the controller wires
@@ -164,6 +175,37 @@ resolving against, which names nothing the repaired one does not); and among two
repaired entries meeting only because the address came off, the first wins,
which is discovery's own policy.
+### A reader already holding the answer
+
+The settings store is the other thing a committed row does not reach.
+`V2SettingsStore` serves channel routing from memory and reloads only when
+`runtime_settings_revision` differs from the one it observed
+(`v2_settings.py:531`), so a repair that rewrites `scope_settings` and stops
+there is half a repair: the IM turn keeps resolving the address the store
+cached at load, and the next same-scope save writes it back to disk. The
+repair therefore publishes `mark_runtime_settings_changed` in its own
+transaction, so a reader sees the repaired rows and the new revision together
+or neither.
+
+Only a scope movement publishes. An Agent's model and a Session's pin are read
+from their row on every turn — `VibeAgentStore` holds no cache — and that
+revision gates the settings domain alone, so republishing for them would make
+every live store reload for a change it does not hold.
+
+Together with the backend refresh above, this is the whole set of live readers:
+the engine projection, the running backend's catalog, and the settings store.
+
+**Why these two were missed, and the shape that finds them.** Both gaps are one
+class — *a copy of a selection that outlives the row it was read from*, whether
+it outlives it in another table or in memory. `core.vibe_agents`'s
+`_rebind_agent_references` already solves exactly this class for a renamed
+Agent, and its reach is the checklist: every persisted copy of the identifier
+(`agent_sessions`, `agent_runs`, `scope_settings` column **and**
+`settings_json`, `run_definitions` column **and** `metadata_json`), plus the
+settings revision. Enumerating the schema found the four columns; only the
+rename precedent finds the snapshot and the revision. A future identifier
+migration should start from that function, not from the column list.
+
### An addressed menu entry never routed
Renaming a menu id looks like it could move which Source a turn lands on, so it
@@ -314,6 +356,11 @@ tries again.
- all three selections a turn resolves lose the address, including every key a
scope's routing payload can spell one under;
+- a reclaimed Session's `session_settings_snapshot` loses it too — soft-deleted
+ definitions included — while everything the snapshot is not survives the
+ rewrite;
+- a repaired scope publishes a new `runtime_settings_revision`, and a repair
+ that moved no scope leaves it alone;
- an identity no address proves is left alone, including a foreign minted
address and the upstream slashes;
- a second pass finds nothing left to move, an empty proof set touches nothing,
diff --git a/storage/model_selection_addresses.py b/storage/model_selection_addresses.py
index 0933c6478..ff4fa5439 100644
--- a/storage/model_selection_addresses.py
+++ b/storage/model_selection_addresses.py
@@ -1,16 +1,25 @@
"""Take a credential's address out of persisted model selections.
-A model id is a *selection* in these tables, not a record of one: a turn reads
+A model id is a *selection* in these stores, not a record of one: a turn reads
them back to decide what it asks for. The precedence a turn resolves is the
session's pin, then the channel's routing override, then the Vibe Agent's own
model, so all three are selections and all three can hold an id an older
release offered — the menu is where a user picked one, and every one of these
-rows is a copy of what the menu said at the time.
+rows is a copy of what the menu said at the time. A reclaimed session's
+settings snapshot is a fourth: a selection with no row left to sit on, held
+until the Session that replaces it is created.
Repairing the Model Hub catalog alone would leave them naming a model that no
longer exists under that name. Repairing them is the other half of the same
write: one id, every place it is a key.
+``core.vibe_agents._rebind_agent_references`` already solves this shape for a
+renamed Agent, and its reach is the one this call matches: every persisted copy
+of the identifier, plus the settings revision that tells a live reader its
+cache is stale. A write that lands in the database but not in the revision is
+half a repair — ``V2SettingsStore.maybe_reload`` never looks, so the turn keeps
+resolving the address out of memory.
+
A run's recorded model and a usage ledger's key are deliberately *not* here.
Those are records of a call that was made, not inputs to one that will be, and
rewriting them would restate history.
@@ -32,7 +41,9 @@ from sqlalchemy.engine import Engine
from core.handlers.model_hub.identifiers import model_id_without_credential_addresses
from storage.db import get_cached_sqlite_engine
-from storage.models import agent_sessions, agents, scope_settings
+from storage.models import agent_sessions, agents, run_definitions, scope_settings
+from storage.session_reclaim import SESSION_SETTINGS_SNAPSHOT_KEY
+from storage.settings_revision import mark_runtime_settings_changed
logger = logging.getLogger(__name__)
@@ -74,6 +85,7 @@ def remove_credential_addresses_from_selections(
return 0
engine = engine or get_cached_sqlite_engine()
moved = 0
+ scope_moved = 0
with engine.begin() as connection:
for table, key, column in _SELECTION_COLUMNS:
rows = connection.execute(
@@ -89,7 +101,19 @@ def remove_credential_addresses_from_selections(
update(table).where(key == row_key).values({column.key: identity})
)
moved += 1
- moved += _repaired_routing_payloads(connection, known)
+ if table is scope_settings:
+ scope_moved += 1
+ routing_moved = _repaired_routing_payloads(connection, known)
+ moved += routing_moved
+ scope_moved += routing_moved
+ moved += _repaired_session_snapshots(connection, known)
+ if scope_moved:
+ # Published in the same transaction, so a reader sees the repaired
+ # rows and the new revision together or neither. Without it the
+ # settings store keeps serving what it cached at load: the IM turn
+ # resolves the stale override, and the next same-scope save writes
+ # it back.
+ mark_runtime_settings_changed(connection)
return moved
@@ -139,3 +163,64 @@ def _repaired_routing_payloads(connection: Any, known: frozenset[str]) -> int:
)
moved += changed
return moved
+
+
+def _repaired_session_snapshots(connection: Any, known: frozenset[str]) -> int:
+ """Rewrite the model a reclaimed Session's settings snapshot still pins.
+
+ ``run_definitions`` carries no model column, so a ``create_once`` Task that
+ outlived its Session keeps the selection here and
+ ``_rebind_create_once_session`` writes it straight onto the replacement
+ Session. A snapshot left addressed re-seeds the exact value this repair
+ removed, onto a row created after the catalog stopped offering it, and
+ nothing runs the repair a second time.
+
+ Soft-deleted definitions are included. The rename path skips them because
+ it keeps live bindings pointed at the right Agent; this one makes the
+ address absent from storage, and a row that is only marked deleted still
+ stores it.
+ """
+
+ rows = connection.execute(
+ select(run_definitions.c.id, run_definitions.c.metadata_json)
+ ).all()
+ moved = 0
+ for definition_id, raw in rows:
+ if not isinstance(raw, str) or not raw:
+ continue
+ try:
+ payload = json.loads(raw)
+ except (TypeError, ValueError):
+ logger.debug(
+ "model hub: unreadable definition metadata for %s", definition_id
+ )
+ continue
+ snapshot = (
+ payload.get(SESSION_SETTINGS_SNAPSHOT_KEY)
+ if isinstance(payload, dict)
+ else None
+ )
+ if not isinstance(snapshot, dict):
+ continue
+ value = snapshot.get("model")
+ if not isinstance(value, str) or not value:
+ continue
+ identity = model_id_without_credential_addresses(value, known)
+ if identity == value:
+ continue
+ connection.execute(
+ update(run_definitions)
+ .where(run_definitions.c.id == definition_id)
+ .values(
+ metadata_json=json.dumps(
+ {
+ **payload,
+ SESSION_SETTINGS_SNAPSHOT_KEY: {**snapshot, "model": identity},
+ },
+ ensure_ascii=False,
+ separators=(",", ":"),
+ )
+ )
+ )
+ moved += 1
+ return moved
diff --git a/tests/test_model_selection_addresses.py b/tests/test_model_selection_addresses.py
index 16f724688..e0be3ec12 100644
--- a/tests/test_model_selection_addresses.py
+++ b/tests/test_model_selection_addresses.py
@@ -5,6 +5,11 @@ columns hold a *copy* of one of those ids — the Vibe Agent's model, a channel'
routing override, and a session's pin — and a turn reads them back in that
precedence to decide what it asks for. Repairing only the catalog would leave
them naming a model that no longer exists under that name.
+
+Two of these outlive the row they were read from: a reclaimed Session's
+settings snapshot re-seeds its selection onto the Session that replaces it, and
+the settings store answers a turn from memory until the revision tells it to
+look again. A repaired database neither of them hears about is half a repair.
"""
from __future__ import annotations
@@ -19,7 +24,15 @@ from storage.importer import ensure_sqlite_state
from storage.model_selection_addresses import (
remove_credential_addresses_from_selections,
)
-from storage.models import agent_sessions, agents, scope_settings, scopes
+from storage.models import (
+ agent_sessions,
+ agents,
+ run_definitions,
+ scope_settings,
+ scopes,
+)
+from storage.session_reclaim import SESSION_SETTINGS_SNAPSHOT_KEY
+from storage.settings_revision import read_runtime_settings_revision
ADDRESS = "avibe-dc0395a1b2c3d4e5f60718"
OTHER_ADDRESS = "avibe-0123456789abcdef01234567"
@@ -97,6 +110,29 @@ def _add_session(connection, session_id: str, model: str | None) -> None:
)
+def _add_definition(
+ connection,
+ definition_id: str,
+ *,
+ snapshot: dict | None,
+ deleted: bool = False,
+) -> None:
+ metadata = {"note": "kept"}
+ if snapshot is not None:
+ metadata[SESSION_SETTINGS_SNAPSHOT_KEY] = snapshot
+ connection.execute(
+ insert(run_definitions).values(
+ id=definition_id,
+ definition_type="scheduled",
+ enabled=1,
+ deleted_at=NOW if deleted else None,
+ metadata_json=json.dumps(metadata),
+ created_at=NOW,
+ updated_at=NOW,
+ )
+ )
+
+
def test_every_selection_a_turn_resolves_loses_the_address(engine) -> None:
"""The Agent's model, the channel override, and the session pin all move.
@@ -228,3 +264,101 @@ def test_a_payload_that_cannot_be_read_does_not_stop_the_others(engine) -> None:
assert remove_credential_addresses_from_selections({ADDRESS}, engine=engine) == 1
with engine.connect() as connection:
assert connection.execute(select(agents.c.model)).scalar_one() == "gpt-5.5"
+
+
+def test_a_reclaimed_session_snapshot_cannot_re_seed_the_address(engine) -> None:
+ """The one selection with no row of its own still loses the address.
+
+ ``run_definitions`` has no model column, so a ``create_once`` Task that
+ outlived its Session carries the pin in this snapshot and the rebind writes
+ it onto the replacement Session. Left addressed it would re-seed the value
+ on a row created after the repair, with nothing to run the repair again.
+ """
+
+ with engine.begin() as connection:
+ _add_definition(
+ connection,
+ "definition-1",
+ snapshot={
+ "session_id": "session-gone",
+ "agent_name": "claude",
+ "model": f"{ADDRESS}/gpt-5.5",
+ "reasoning_effort": "high",
+ },
+ )
+ # Terminal for the rename path, still storage for this one.
+ _add_definition(
+ connection,
+ "definition-2",
+ snapshot={"session_id": "session-gone-too", "model": f"{ADDRESS}/opus"},
+ deleted=True,
+ )
+ _add_definition(connection, "definition-3", snapshot=None)
+
+ moved = remove_credential_addresses_from_selections({ADDRESS}, engine=engine)
+
+ assert moved == 2
+ with engine.connect() as connection:
+ stored = {
+ row.id: json.loads(row.metadata_json)
+ for row in connection.execute(
+ select(run_definitions.c.id, run_definitions.c.metadata_json)
+ )
+ }
+ assert stored["definition-1"][SESSION_SETTINGS_SNAPSHOT_KEY] == {
+ "session_id": "session-gone",
+ "agent_name": "claude",
+ "model": "gpt-5.5",
+ "reasoning_effort": "high",
+ }
+ assert stored["definition-2"][SESSION_SETTINGS_SNAPSHOT_KEY]["model"] == "opus"
+ # Everything the snapshot is not must survive the rewrite untouched.
+ assert stored["definition-1"]["note"] == "kept"
+ assert SESSION_SETTINGS_SNAPSHOT_KEY not in stored["definition-3"]
+
+
+def test_a_repaired_scope_publishes_a_revision_for_the_live_reader(engine) -> None:
+ """The settings store answers from memory until the revision moves.
+
+ ``V2SettingsStore.maybe_reload`` is the only thing that reloads it, and it
+ only looks when ``runtime_settings_revision`` differs. A repair that
+ rewrote the row and not the revision leaves the IM turn resolving the
+ address it cached, and the next same-scope save writes it back.
+ """
+
+ with engine.begin() as connection:
+ _add_scope(
+ connection,
+ "scope-1",
+ model=f"{ADDRESS}/gpt-5.5",
+ routing={"agent_name": "claude", "model": f"{ADDRESS}/gpt-5.5"},
+ )
+ with engine.connect() as connection:
+ before = read_runtime_settings_revision(connection)
+
+ assert remove_credential_addresses_from_selections({ADDRESS}, engine=engine) == 2
+
+ with engine.connect() as connection:
+ after = read_runtime_settings_revision(connection)
+ assert after is not None
+ assert after != before
+
+
+def test_a_repair_that_moved_no_scope_does_not_disturb_the_revision(engine) -> None:
+ """Only the settings domain is behind that revision.
+
+ An Agent's model and a Session's pin are read from the row on every turn,
+ so republishing for them would make every live store reload for a change
+ it does not hold.
+ """
+
+ with engine.begin() as connection:
+ _add_agent(connection, "agent-1", f"{ADDRESS}/gpt-5.5")
+ _add_session(connection, "session-1", f"{ADDRESS}/gpt-5.5")
+ with engine.connect() as connection:
+ before = read_runtime_settings_revision(connection)
+
+ assert remove_credential_addresses_from_selections({ADDRESS}, engine=engine) == 2
+
+ with engine.connect() as connection:
+ assert read_runtime_settings_revision(connection) == before