94 files, +1,395 -6,578. Three files are new; twenty-four are gone. The milestone is subtraction, and what is left is the single-user local storyteller the specification describes. Removed in full: campaign scripting and its QuickJS sandbox; multi-user accounts, guest sessions, login, registration and the shared demo key; the visitor-analytics tables, dashboard and page beacon; the access log of sign-ins, addresses and devices; per-IP and per-user rate limiting and quotas; Render deployment config; Postgres and psycopg; cloud inference providers, the API-key field and the key encryption that existed to store it; session-cookie signing. None of it was hidden behind a flag — the routes are gone and answer 404. Two things were kept that the brief allowed keeping. The `users` table and its foreign keys stay as an internal ownership detail, because rewriting them out means a migration across most of the schema to delete a column that costs nothing; nothing creates a second user and no request carries an identity. Five inert tables and four inert columns stay for the same reason, so an M1 campaign database opens unchanged. The one addition is app/endpoints.py, which decides where a story may be sent. Loopback, RFC1918, link-local, unique-local and CGNAT — an explicit allowlist of networks, not a guess at what `ipaddress` means by "private", which calls the documentation ranges private and IPv6 loopback reserved. Every address a hostname resolves to must be in it, so a split answer does not squeak through, and the rule runs both when the endpoint is saved and before every outbound request, because a name that resolved to the LAN this morning can resolve elsewhere this afternoon. Known cloud hosts are named in the refusal so the error says why rather than looking like broken DNS. TLS is never traded against it: M1's shared trust context is intact on all four clients and there is no way to skip verification. The hardcoded 120-second model timeout is now a setting. That was not theoretical — on this GPU-less four-core host a cold load of qwen2.5:3b-instruct took 648.9 seconds to produce the first turn, while turns 2 to 5 of the same campaign took 3.6 to 13.1. Connect stays short at 10s so a wrong address still fails fast; the read timeout defaults to 300s and is bounded at 3600, because "wait longer" must stay a number. Two defects found while testing and fixed here. An unknown /api path fell through the SPA catch-all and came back as HTML with status 200, so a client asking for JSON parsed a web page instead of learning the route was gone. And AIDND_CORS_ORIGINS accepted "*", which on an unauthenticated loopback API would hand every page on the Internet a write handle on the campaign database; it now refuses to start. Verified rather than assumed. Offline, on a network with no route out and no DNS: five turns, retry with both takes retained, restart with an identical transcript digest, a failed model call leaving the accepted AI-turn count untouched, and a capture with zero non-loopback unicast packets. Against a real second machine on the LAN over HTTPS with a private CA: four turns, restart, and a capture showing 289 packets to the approved host, 344 loopback, zero anywhere else, zero DNS queries. Cloud and public endpoints refused with their reasons; no API key settable; every removed route 404. 604 backend tests pass, down from 648 by the fifteen retired with the subsystems they tested and up by the twenty-nine added for the endpoint policy and the removed surface. The scripting tests were not deleted: eight files used a JavaScript counter as instrumentation for the state snapshot and rollback machinery, which M2 does not touch, so the counter moved to the world-state engine and those tests still assert what they always did. Frontend lint and build are clean; the image builds, and its wheel-building stage is gone with quickjs. No M3 work. Undo is still destructive and there is still no Redo.
246 lines
8.8 KiB
Python
246 lines
8.8 KiB
Python
"""Tests for undo and retry rolling back the shared `world_state`
|
|
(plan/11-state-revert-and-retry-fix.md).
|
|
|
|
The state being rolled back was the scripting engine's `script_state` until
|
|
M2 removed campaign scripting. The machinery under test — `attempts.restore_state`,
|
|
`roll_back_before`, and the per-node outcome snapshot — is unchanged; only the
|
|
column it moves has. `world_state`/`world_state_after` is now the shared state
|
|
an adventure carries, so that is what these tests exercise.
|
|
|
|
Phase 14 SP4 reversed the snapshots. An action used to carry the state as
|
|
it stood before it ran, and rolling back read the snapshot off the action
|
|
being removed. Now it carries the state it left behind, and rolling back
|
|
reads that state off the node in front of it. This is the same value
|
|
reached from the other direction, and it is the only version a retry can
|
|
use, because attempts at one turn share a starting position and differ
|
|
only in their outcome.
|
|
|
|
Run from the backend dir: python -m pytest tests/test_state_revert.py -v
|
|
"""
|
|
|
|
# Point the app at a throwaway SQLite file before importing anything that
|
|
# binds the engine at import time. `app.database` reads `AIDND_DB_PATH`
|
|
# on import.
|
|
|
|
import pytest
|
|
from fastapi import HTTPException
|
|
|
|
from app import attempts, memorybank, models
|
|
from app.database import Base, SessionLocal, engine
|
|
from app.routers import adventures
|
|
|
|
|
|
@pytest.fixture()
|
|
def db():
|
|
Base.metadata.create_all(bind=engine)
|
|
session = SessionLocal()
|
|
try:
|
|
yield session
|
|
finally:
|
|
session.close()
|
|
Base.metadata.drop_all(bind=engine)
|
|
adventures.turns._active_turns.clear()
|
|
|
|
|
|
def _make_adventure(db, world_state):
|
|
user = models.User(is_guest=False)
|
|
db.add(user)
|
|
db.flush()
|
|
adv = models.Adventure(user_id=user.id, title="T", world_state=world_state)
|
|
db.add(adv)
|
|
db.flush()
|
|
return user, adv
|
|
|
|
|
|
def _add(db, adv, index, type_, text="x", state_after=None):
|
|
a = models.Action(
|
|
adventure_id=adv.id, type=type_, text=text,
|
|
world_state_after=state_after,
|
|
)
|
|
db.add(a)
|
|
db.flush()
|
|
return a
|
|
|
|
|
|
def _forget_snapshots(db, adv):
|
|
"""Blank every outcome, the way a row written before SP4 looks.
|
|
|
|
Straight SQL, because `tree.stamp_outcome` runs on every flush precisely so
|
|
that a node written through the ORM cannot end up without one.
|
|
"""
|
|
db.query(models.Action).filter_by(adventure_id=adv.id).update(
|
|
{"state_after": None, "world_state_after": None}, synchronize_session=False
|
|
)
|
|
db.commit()
|
|
db.expire_all()
|
|
|
|
|
|
# ---------------------------------------------------------------- undo
|
|
|
|
def test_undo_reverts_state_to_before_the_turn(db):
|
|
# A turn moved world_state from {gold:0} to {gold:10}. The node in
|
|
# front of the turn records where it started. The current state is
|
|
# the mutated one.
|
|
user, adv = _make_adventure(db, {"gold": 10})
|
|
_add(db, adv, 0, "start", state_after={"gold": 0})
|
|
_add(db, adv, 1, "do", state_after={"gold": 0})
|
|
_add(db, adv, 2, "ai", state_after={"gold": 10})
|
|
db.commit()
|
|
|
|
adventures.undo_turn(adv.id, db=db, adventure=adv)
|
|
|
|
assert adv.world_state == {"gold": 0}
|
|
assert [a.type for a in adv.actions] == ["start"]
|
|
|
|
|
|
def test_undo_of_bare_continue_uses_the_node_in_front(db):
|
|
# A "continue" turn has no player action, so the opening is what the story
|
|
# falls back to.
|
|
user, adv = _make_adventure(db, {"gold": 5})
|
|
_add(db, adv, 0, "start", state_after={"gold": 0})
|
|
_add(db, adv, 1, "ai", state_after={"gold": 5})
|
|
db.commit()
|
|
|
|
adventures.undo_turn(adv.id, db=db, adventure=adv)
|
|
|
|
assert adv.world_state == {"gold": 0}
|
|
assert [a.type for a in adv.actions] == ["start"]
|
|
|
|
|
|
def test_undo_leaves_state_untouched_when_snapshot_missing(db):
|
|
# A row the SP4 migration could not derive an outcome for: leave the live
|
|
# state alone rather than resetting it to nothing.
|
|
user, adv = _make_adventure(db, {"gold": 10})
|
|
_add(db, adv, 0, "start")
|
|
_add(db, adv, 1, "do")
|
|
_add(db, adv, 2, "ai")
|
|
_forget_snapshots(db, adv)
|
|
|
|
adventures.undo_turn(adv.id, db=db, adventure=adv)
|
|
|
|
assert adv.world_state == {"gold": 10}
|
|
|
|
|
|
def test_undo_raises_when_nothing_to_undo(db):
|
|
user, adv = _make_adventure(db, {})
|
|
_add(db, adv, 0, "start")
|
|
db.commit()
|
|
with pytest.raises(HTTPException) as exc:
|
|
adventures.undo_turn(adv.id, db=db, adventure=adv)
|
|
assert exc.value.status_code == 400
|
|
|
|
|
|
def test_undo_blocked_by_active_turn_lock(db):
|
|
user, adv = _make_adventure(db, {})
|
|
_add(db, adv, 0, "start")
|
|
_add(db, adv, 1, "ai", state_after={})
|
|
db.commit()
|
|
|
|
adventures.turns.acquire_turn_lock(adv.id) # a turn is "generating"
|
|
try:
|
|
with pytest.raises(HTTPException) as exc:
|
|
adventures.undo_turn(adv.id, db=db, adventure=adv)
|
|
assert exc.value.status_code == 409
|
|
# The failed undo must not have released someone else's lock.
|
|
assert adv.id in adventures.turns._active_turns
|
|
finally:
|
|
adventures.turns._active_turns.discard(adv.id)
|
|
|
|
|
|
def test_undo_prunes_memory_covering_removed_actions(db):
|
|
user, adv = _make_adventure(db, {})
|
|
for i in range(4):
|
|
_add(db, adv, i, "ai" if i % 2 else "do", state_after={})
|
|
# A memory summarizing actions up to index 3, which undo will delete.
|
|
covering = models.Memory(adventure_id=adv.id, text="m", source_start=0, source_end=3)
|
|
keep = models.Memory(adventure_id=adv.id, text="k", source_start=0, source_end=1)
|
|
db.add_all([covering, keep])
|
|
db.commit()
|
|
|
|
adventures.undo_turn(adv.id, db=db, adventure=adv) # removes indexes 2 & 3
|
|
|
|
texts = {m.text for m in adv.memories}
|
|
assert texts == {"k"}
|
|
|
|
|
|
# -------------------------------------------------------- withdrawing a node
|
|
|
|
def test_forget_node_withdraws_only_what_that_node_produced(db):
|
|
"""Phase 14 SP3: a memory attaches to the node where its block ends, so
|
|
removing a node is a lookup rather than a scan for memories that
|
|
reference actions the story no longer has."""
|
|
user, adv = _make_adventure(db, {})
|
|
_add(db, adv, 0, "do")
|
|
second = _add(db, adv, 1, "ai")
|
|
db.add_all([
|
|
models.Memory(adventure_id=adv.id, text="hangs off node 1",
|
|
source_start=0, source_end=1),
|
|
models.Memory(adventure_id=adv.id, text="hangs off node 0",
|
|
source_start=0, source_end=0),
|
|
])
|
|
db.commit()
|
|
|
|
removed = memorybank.forget_node(db, adv, second)
|
|
db.commit()
|
|
db.refresh(adv) # expire_on_commit=False: reload the memories collection
|
|
|
|
assert removed == 1
|
|
assert {m.text for m in adv.memories} == {"hangs off node 0"}
|
|
|
|
|
|
# ---------------------------------------------------------------- snapshot
|
|
|
|
def test_snapshot_outcome_is_an_independent_deep_copy(db):
|
|
_, adv = _make_adventure(db, {"nested": {"n": 1}})
|
|
node = models.Action(adventure_id=adv.id, type="ai", text="x")
|
|
attempts.snapshot_outcome(adv, node)
|
|
adv.world_state["nested"]["n"] = 99
|
|
assert node.world_state_after == {"nested": {"n": 1}} # unaffected by later mutation
|
|
|
|
|
|
def test_snapshot_outcome_handles_non_dict(db):
|
|
_, adv = _make_adventure(db, {})
|
|
adv.world_state = None
|
|
node = models.Action(adventure_id=adv.id, type="ai", text="x")
|
|
attempts.snapshot_outcome(adv, node)
|
|
assert node.world_state_after == {}
|
|
|
|
|
|
def test_restore_state_ignores_a_node_with_no_outcome(db):
|
|
_, adv = _make_adventure(db, {"gold": 7})
|
|
attempts.restore_state(adv, models.Action(adventure_id=adv.id, type="ai"))
|
|
assert adv.world_state == {"gold": 7}
|
|
attempts.restore_state(adv, None)
|
|
assert adv.world_state == {"gold": 7}
|
|
|
|
|
|
# ---------------------------------------------------------------- retry
|
|
|
|
def test_retry_restores_the_state_the_turn_started_from(db, monkeypatch):
|
|
# Retry must roll script_state back to what the node in front of the AI
|
|
# action left behind, so regeneration does not stack output mutations
|
|
# on top of the attempt being replaced.
|
|
user, adv = _make_adventure(db, {"gold": 20}) # 20 = double-applied bug value
|
|
_add(db, adv, 0, "start", state_after={"gold": 0})
|
|
_add(db, adv, 1, "do", state_after={"gold": 10})
|
|
_add(db, adv, 2, "ai", state_after={"gold": 20})
|
|
db.commit()
|
|
|
|
|
|
async def _noop(*a, **k):
|
|
if False:
|
|
yield # make it an async generator
|
|
monkeypatch.setattr(adventures.turns, "generate_turn", _noop)
|
|
|
|
adventures.retry_action(adv.id, request=None, db=db, user=user, adventure=adv)
|
|
|
|
assert adv.world_state == {"gold": 10}
|
|
# Nothing is written until a replacement actually arrives: the attempt on
|
|
# screen is left exactly as it was, and stays the live one.
|
|
assert [a.type for a in adv.actions] == ["start", "do", "ai"]
|
|
last = adv.actions[-1]
|
|
assert last.live is True
|
|
assert len(attempts.group(db, last)) == 1 # no sibling was filed
|
|
assert last.world_state_after == {"gold": 20} # its own outcome, untouched
|
|
adventures.turns._active_turns.discard(adv.id)
|