M6: branch-safe context, summaries and long-term story memory
Aligns the inherited AI-DnD memory and context foundation with the history,
authority and state model M3-M5 established. Long stories now reach the narrator
through a bounded, lineage-safe, inspectable context rather than a growing
transcript.
This commit includes the corrective work that followed the independent review in
planning/reports/M6-IMPLEMENTATION-REPORT.md. The first implementation reported
E03 as passing and it was not; the report records that history rather than
hiding it.
What was already correct, and was kept rather than rebuilt
Memory lineage. Memories already carried (branch_id, depth) and retrieval
already filtered through the capped-path clause; the ten-step negative control
was measured passing against b7005e6 before any change here. M6 adds the
regression tests that pin it, plus provenance and authority on the result.
Summary lineage — both halves
A summary is a row carrying the coordinate of the last node it covers, and
eligibility is the same head-capped lineage clause memories use. That alone
was not enough: generation was seeded from adventures.story_summary, a
campaign-global column with no lineage, so after a divergence the summariser
was handed the abandoned line's prose and asked to update it. The row it
produced was correctly anchored and therefore looked safe while its sentences
described a story the reader had left.
Generation is now seeded from summaries.current — the same question the
context builder asks — so the input and the output are scoped by one rule.
adventures.story_summary remains a reader-facing mirror for the Plot panel and
the export bundle, kept in step when a summary is written and when the head
moves, and nothing authoritative reads it.
Retrieval redundancy
With a real embedding model, four near-identical memories crowded out the one
distinctive clue, which survived only because the default memory_top_k is 5.
Retrieval now drops a candidate that repeats one already chosen, never across
authority classes, at a threshold measured against the configured embedding
model. The clue is retrieved at top_k 5, 4 and 3. Ranking itself is unchanged;
the further factors CONTEXT-AND-MEMORY §20 contemplates remain unimplemented
and are recorded as such.
Memory authority, budgeting, observability
Memory.authority is accepted_story or heuristic, classified by the application
and marked in the prompt; retrieval never writes state. The reply is reserved
out of the context budget, and an impossible configuration fails clearly
instead of overflowing. Each derived pass records ok/idle/failed per campaign,
served by GET /adventures/{id}/derived and shown in Insights, so the M2
failure — a dead memory bank with a green suite — is visible if it recurs.
Provider-wiring tests mock no factory.
Also: two pre-existing test-suite leaks fixed; two fixtures that stored one
vector in every memory now use distinct ones, so lineage assertions stay
readable alongside redundancy suppression.
Planning: CONTEXT-AND-MEMORY, TECHNICAL-DESIGN, DATA-MODEL, V1-ACCEPTANCE-TESTS,
BUILD-MILESTONES, VERSION and planning/README updated to describe what exists,
including that a valid E03 test must regenerate a summary after diverging. The
M5 report was rotated to planning/archive/milestone-reports/. No new ADR — every
choice implements a decision the package had already settled.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PWU4gTfLYY6Qq9U7aa9Qw2
This commit is contained in:
co-authored by
Claude Opus 5
parent
b7005e6fdd
commit
a6e9c7a32b
@@ -0,0 +1,837 @@
|
||||
"""M6: branch-safe context, summaries and long-term story memory.
|
||||
|
||||
The acceptance contract for this milestone is F01-F08 plus the E-series lineage
|
||||
tests that own the memory and summary consequences of branching. Each test below
|
||||
names the criterion it carries.
|
||||
|
||||
Two things are asserted throughout rather than assumed:
|
||||
|
||||
* **The assembled prompt, not the narration.** A model that fails to mention a
|
||||
leaked memory is not evidence that the memory did not leak, so every leak test
|
||||
reads the context the builder actually produced.
|
||||
* **The lineage chokepoint, not a reimplementation.** Memories and summaries are
|
||||
filtered by `lineage.Path.clause`, the same clause every read of the story
|
||||
goes through. A test that walked the tree itself could pass while the product
|
||||
leaked.
|
||||
|
||||
python -m pytest tests/test_context_memory.py -v
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
from fastapi import Depends
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import select
|
||||
|
||||
from app import auth, derived, limits, memorybank, models, summaries
|
||||
from app.context import builder, lineage
|
||||
from app.database import Base, SessionLocal, engine, get_db
|
||||
from app.main import app
|
||||
from app.providers import ProviderError
|
||||
from app.routers import adventures
|
||||
|
||||
from fakes import ScriptedProvider, state_block
|
||||
|
||||
|
||||
class StubEmbedder:
|
||||
"""A deterministic embedder. Distinct texts get distinguishable vectors."""
|
||||
|
||||
def __init__(self):
|
||||
self.calls = 0
|
||||
|
||||
async def embed(self, texts):
|
||||
self.calls += 1
|
||||
out = []
|
||||
for text in texts:
|
||||
lowered = text.lower()
|
||||
out.append([
|
||||
1.0,
|
||||
1.0 if "ledger" in lowered or "flagstone" in lowered else 0.0,
|
||||
1.0 if "chapel" in lowered else 0.0,
|
||||
])
|
||||
return out
|
||||
|
||||
|
||||
class StubSummariser:
|
||||
"""Stands in for the summariser so this file opens no sockets."""
|
||||
|
||||
async def complete(self, system, user, *, max_tokens=600):
|
||||
return "A summary of what has happened so far."
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client(monkeypatch):
|
||||
Base.metadata.create_all(bind=engine)
|
||||
memorybank._vector_cache.clear()
|
||||
setup = SessionLocal()
|
||||
user = models.User(is_guest=False, email="m6@example.com")
|
||||
setup.add(user)
|
||||
setup.flush()
|
||||
setup.add(models.Settings(
|
||||
user_id=user.id, api_key="enc:dummy", model="test-model",
|
||||
embedding_model="embed-test", context_token_budget=4000,
|
||||
max_output_tokens=400, memory_top_k=3,
|
||||
))
|
||||
adventure = models.Adventure(
|
||||
user_id=user.id, title="M6", memory_bank_enabled=True, auto_summarize=True,
|
||||
)
|
||||
setup.add(adventure)
|
||||
setup.flush()
|
||||
setup.add(models.Action(adventure_id=adventure.id, type="start",
|
||||
text="The road forks at the Crooked Lantern."))
|
||||
setup.commit()
|
||||
adv_id, user_id = adventure.id, user.id
|
||||
setup.close()
|
||||
|
||||
monkeypatch.setattr(limits, "check_row_cap", lambda *a, **k: None)
|
||||
monkeypatch.setattr(adventures.turns, "OpenAICompatibleProvider", ScriptedProvider)
|
||||
# Both derived providers are stubbed, not just the embedder (M6 review
|
||||
# finding M6-F3). With only the embedder replaced, the post-turn pass built
|
||||
# a real summariser against the default endpoint and every turn in this file
|
||||
# opened a socket to localhost:11434 — slow, dependent on what happens to be
|
||||
# listening, and the source of an abandoned-coroutine RuntimeWarning when
|
||||
# the TestClient event loop closed under it. Tests that deliberately
|
||||
# exercise real provider construction live in `test_provider_wiring.py`.
|
||||
monkeypatch.setattr(memorybank, "embedding_provider", lambda s: StubEmbedder())
|
||||
monkeypatch.setattr(memorybank, "summary_provider", lambda s: StubSummariser())
|
||||
app.dependency_overrides[auth.get_current_user] = (
|
||||
lambda db=Depends(get_db): db.get(models.User, user_id)
|
||||
)
|
||||
test_client = TestClient(app)
|
||||
test_client.adv_id = adv_id
|
||||
test_client.user_id = user_id
|
||||
try:
|
||||
yield test_client
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
memorybank._vector_cache.clear()
|
||||
Base.metadata.drop_all(bind=engine)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- helpers
|
||||
|
||||
def play(client, text, prose="The road bends onward past the treeline.", events=None):
|
||||
ScriptedProvider.replies = [f"{prose}\n{state_block(events or [])}"]
|
||||
r = client.post(f"/api/adventures/{client.adv_id}/actions",
|
||||
json={"type": "do", "text": text})
|
||||
assert r.status_code == 200, r.text[:300]
|
||||
assert '"error"' not in r.text, r.text[:300]
|
||||
|
||||
|
||||
def head_of(client):
|
||||
with SessionLocal() as db:
|
||||
adventure = db.get(models.Adventure, client.adv_id)
|
||||
return adventure.head_branch_id, adventure.head_depth
|
||||
|
||||
|
||||
def context_report(client) -> dict:
|
||||
"""The prompt the app would send now, assembled through the real builder."""
|
||||
r = client.get(f"/api/adventures/{client.adv_id}/context")
|
||||
assert r.status_code == 200, r.text[:300]
|
||||
return r.json()
|
||||
|
||||
|
||||
def prompt_text(report: dict) -> str:
|
||||
return "\n".join(s["text"] for s in report["sections"])
|
||||
|
||||
|
||||
def plant_memory(client, text, *, authority=None, at_depth=None):
|
||||
"""Attaches an embedded memory to a live node, as the real pass would."""
|
||||
with SessionLocal() as db:
|
||||
adventure = db.get(models.Adventure, client.adv_id)
|
||||
depth = adventure.head_depth if at_depth is None else at_depth
|
||||
node = db.execute(
|
||||
select(models.Action).where(
|
||||
models.Action.adventure_id == client.adv_id,
|
||||
lineage.path_of(db, adventure).uncapped().clause(models.Action),
|
||||
models.Action.depth == depth,
|
||||
)
|
||||
).scalars().first()
|
||||
assert node is not None, f"no live node at depth {depth}"
|
||||
memory = models.Memory(
|
||||
adventure_id=client.adv_id, text=text,
|
||||
branch_id=node.branch_id, depth=node.depth,
|
||||
source_start=node.depth, source_end=node.depth,
|
||||
authority=authority or memorybank.classify_authority(text),
|
||||
)
|
||||
memorybank.set_vector(memory, asyncio.run(StubEmbedder().embed([text]))[0])
|
||||
db.add(memory)
|
||||
db.commit()
|
||||
return memory.id
|
||||
|
||||
|
||||
def eligible_memory_texts(client) -> list[str]:
|
||||
"""What the retrieval filter would consider, through the real clause."""
|
||||
with SessionLocal() as db:
|
||||
adventure = db.get(models.Adventure, client.adv_id)
|
||||
return list(db.execute(
|
||||
select(models.Memory.text).where(
|
||||
models.Memory.adventure_id == client.adv_id,
|
||||
lineage.path_of(db, adventure).clause(models.Memory),
|
||||
models.Memory.forgotten.is_(False),
|
||||
)
|
||||
).scalars().all())
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- F01
|
||||
|
||||
def test_f01_recent_turns_stay_in_the_prompt(client):
|
||||
"""F01. The immediately preceding turns are what conversational coherence
|
||||
is made of, so they have to actually be there."""
|
||||
play(client, "ask Mara about the key", prose="Mara turns the silver key over.")
|
||||
play(client, "wait for her answer", prose="'I found it at the chapel,' she says.")
|
||||
|
||||
story = prompt_text(context_report(client))
|
||||
|
||||
assert "Mara turns the silver key over." in story
|
||||
assert "'I found it at the chapel,' she says." in story
|
||||
assert "ask Mara about the key" in story
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- F02
|
||||
|
||||
def test_f02_an_old_clue_survives_outside_recent_history(client):
|
||||
"""F02. A distinctive clue is planted, the story runs on past it, and the
|
||||
clue comes back through memory rather than through the whole transcript."""
|
||||
play(client, "search the floor",
|
||||
prose="Aldric pries up the third flagstone and hides the ledger beneath it.")
|
||||
plant_memory(client, "Aldric hid the ledger beneath the third flagstone.")
|
||||
for i in range(22):
|
||||
play(client, f"walk on {i}", prose=f"[{i}] " + "The road runs on. " * 60)
|
||||
|
||||
report = context_report(client)
|
||||
story = prompt_text(report)
|
||||
|
||||
# It has fallen out of the verbatim history.
|
||||
history_text = "\n".join(
|
||||
s["text"] for s in report["sections"]
|
||||
if s["label"] in ("history", "recent_history")
|
||||
)
|
||||
assert "third flagstone" not in history_text, (
|
||||
"the fixture did not push the clue out of recent history"
|
||||
)
|
||||
# But it is still available to the narrator, through memory.
|
||||
assert "third flagstone" in story
|
||||
assert any("flagstone" in m["text"] for m in report["memories"]["used"])
|
||||
# And not by sending the whole story.
|
||||
assert report["history"]["included"] < report["history"]["total"]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- F03
|
||||
|
||||
def test_f03_the_prompt_stays_bounded_as_the_story_grows(client):
|
||||
"""F03. Input must not grow with the transcript."""
|
||||
play(client, "begin", prose="The road bends. " * 40)
|
||||
for i in range(6):
|
||||
play(client, f"on {i}", prose=f"[{i}] " + "The road bends. " * 40)
|
||||
short = context_report(client)
|
||||
for i in range(24):
|
||||
play(client, f"further {i}", prose=f"[{i}] " + "The road bends. " * 40)
|
||||
long = context_report(client)
|
||||
|
||||
assert long["history"]["total"] > short["history"]["total"] * 2, "fixture too small"
|
||||
budget = long["tokens"]["budget"]
|
||||
assert long["tokens"]["total"] <= budget
|
||||
# Four times the story must not be four times the prompt.
|
||||
assert long["tokens"]["total"] < short["tokens"]["total"] * 2
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- F04
|
||||
|
||||
def test_f04_the_reply_budget_is_reserved(client):
|
||||
"""F04. The configured reply length stays available whatever the story."""
|
||||
for i in range(20):
|
||||
play(client, f"on {i}", prose=f"[{i}] " + "The road bends. " * 40)
|
||||
|
||||
report = context_report(client)
|
||||
with SessionLocal() as db:
|
||||
settings = db.query(models.Settings).filter_by(user_id=client.user_id).first()
|
||||
max_output = settings.max_output_tokens
|
||||
|
||||
assert report["tokens"]["output_reserve"] >= max_output
|
||||
assert report["tokens"]["total"] + max_output <= report["tokens"]["budget"], (
|
||||
"the assembled input left no room for the reply"
|
||||
)
|
||||
|
||||
|
||||
def test_f04_a_budget_too_small_for_the_reply_is_refused(client):
|
||||
"""Section 9: fail clearly rather than build a prompt known to overflow."""
|
||||
play(client, "begin")
|
||||
with SessionLocal() as db:
|
||||
adventure = db.get(models.Adventure, client.adv_id)
|
||||
settings = db.query(models.Settings).filter_by(user_id=client.user_id).first()
|
||||
settings.context_token_budget = 200
|
||||
settings.max_output_tokens = 4000
|
||||
db.commit()
|
||||
with pytest.raises(builder.ContextOverflow) as exc:
|
||||
builder.build_context(adventure, settings)
|
||||
# The message has to say what to change.
|
||||
assert "context budget" in str(exc.value)
|
||||
assert "reserved for the reply" in str(exc.value)
|
||||
|
||||
|
||||
def test_f04_an_impossible_budget_fails_the_turn_without_losing_the_story(client):
|
||||
"""The refusal reaches the reader as a failed turn, not a 500."""
|
||||
play(client, "begin", prose="The lantern swings.")
|
||||
with SessionLocal() as db:
|
||||
settings = db.query(models.Settings).filter_by(user_id=client.user_id).first()
|
||||
settings.context_token_budget = 200
|
||||
settings.max_output_tokens = 4000
|
||||
db.commit()
|
||||
|
||||
ScriptedProvider.replies = ["should never be reached"]
|
||||
r = client.post(f"/api/adventures/{client.adv_id}/actions",
|
||||
json={"type": "do", "text": "carry on"})
|
||||
assert r.status_code == 200
|
||||
assert "context budget" in r.text
|
||||
# The story that already existed is untouched.
|
||||
actions = client.get(f"/api/adventures/{client.adv_id}").json()["actions"]
|
||||
assert any("The lantern swings." in a["text"] for a in actions)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- F05
|
||||
|
||||
def test_f05_the_inspector_shows_every_component_m6_owns(client):
|
||||
"""F05, for the components this milestone owns."""
|
||||
play(client, "begin", prose="Aldric sets the key down.",
|
||||
events=[{"type": "create_entity", "entity": "aldric",
|
||||
"entity_type": "character", "name": "Aldric"}])
|
||||
plant_memory(client, "Aldric hid the ledger beneath the third flagstone.")
|
||||
with SessionLocal() as db:
|
||||
adventure = db.get(models.Adventure, client.adv_id)
|
||||
summaries.record(db, adventure, "The party reached the Crooked Lantern.")
|
||||
db.commit()
|
||||
play(client, "carry on")
|
||||
|
||||
report = context_report(client)
|
||||
labels = {s["label"] for s in report["sections"]}
|
||||
|
||||
assert "narrator" in labels, "narrator/system rules"
|
||||
assert "narrative_state" in labels, "current authoritative state"
|
||||
assert "story_summary" in labels, "the summary used"
|
||||
assert "used_memories" in labels, "retrieved memories"
|
||||
assert "history" in labels, "recent history"
|
||||
# Model and settings.
|
||||
assert report["settings"]["model"] == "test-model"
|
||||
assert report["settings"]["max_output_tokens"] == 400
|
||||
# Token accounting, per component and in total.
|
||||
assert all(isinstance(s["tokens"], int) for s in report["sections"])
|
||||
for key in ("total", "budget", "output_reserve", "protected", "available_for_history"):
|
||||
assert key in report["tokens"], key
|
||||
# Summary provenance.
|
||||
assert report["summary"]["depth"] is not None
|
||||
# Derived-work health.
|
||||
assert isinstance(report["derived"], list)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- F06
|
||||
|
||||
def test_f06_a_retrieved_memory_is_traceable_to_its_source(client):
|
||||
"""F06. "Where did this memory come from?" must be answerable."""
|
||||
play(client, "search the floor", prose="Aldric hides the ledger.")
|
||||
memory_id = plant_memory(client, "Aldric hid the ledger beneath the third flagstone.")
|
||||
play(client, "carry on")
|
||||
|
||||
used = context_report(client)["memories"]["used"]
|
||||
entry = next(m for m in used if m["id"] == memory_id)
|
||||
|
||||
assert entry["source"]["branch_id"] is not None
|
||||
assert entry["source"]["depth"] is not None
|
||||
assert entry["source"]["source_start"] is not None
|
||||
# And the coordinate names a real node of this campaign's accepted history.
|
||||
with SessionLocal() as db:
|
||||
node = db.execute(
|
||||
select(models.Action).where(
|
||||
models.Action.adventure_id == client.adv_id,
|
||||
models.Action.branch_id == entry["source"]["branch_id"],
|
||||
models.Action.depth == entry["source"]["depth"],
|
||||
)
|
||||
).scalars().first()
|
||||
assert node is not None, "the memory's provenance points at no action"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- F07
|
||||
|
||||
def test_f07_a_heuristic_memory_is_labelled_and_is_not_state(client):
|
||||
"""F07. An inference may be recalled; it may not become canon."""
|
||||
play(client, "watch her", prose="Mara glances at the door.",
|
||||
events=[{"type": "create_entity", "entity": "mara",
|
||||
"entity_type": "character", "name": "Mara"}])
|
||||
plant_memory(client, "Mara seemed nervous around Captain Vale.")
|
||||
play(client, "carry on")
|
||||
|
||||
report = context_report(client)
|
||||
used = report["memories"]["used"]
|
||||
entry = next(m for m in used if "Captain Vale" in m["text"])
|
||||
assert entry["authority"] == "heuristic"
|
||||
|
||||
story = prompt_text(report)
|
||||
assert "[inferred]" in story, "the prompt does not mark the inference"
|
||||
assert "interpretation, not established fact" in story
|
||||
|
||||
# And it did not become authoritative state.
|
||||
document = client.get(f"/api/adventures/{client.adv_id}/state").json()["document"]
|
||||
facts = [f["predicate"] for f in document["facts"]]
|
||||
assert not any("Vale" in f for f in facts), "a heuristic memory became a fact"
|
||||
|
||||
|
||||
def test_the_application_classifies_authority_not_the_model(client):
|
||||
"""The classifier is the application's, and it is inspectable."""
|
||||
assert memorybank.classify_authority(
|
||||
"Aldric promised Mara he would return before dawn.") == "accepted_story"
|
||||
assert memorybank.classify_authority(
|
||||
"Mara seemed uneasy when Captain Vale was mentioned.") == "heuristic"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- F08
|
||||
|
||||
def test_f08_a_failing_memory_pass_keeps_the_story_and_is_visible(client):
|
||||
"""F08. Derived work fails softly, and audibly."""
|
||||
play(client, "begin", prose="The lantern swings.",
|
||||
events=[{"type": "create_entity", "entity": "aldric",
|
||||
"entity_type": "character", "name": "Aldric"}])
|
||||
before_state = client.get(f"/api/adventures/{client.adv_id}/state").json()["document"]
|
||||
|
||||
class Broken:
|
||||
async def complete(self, *a, **k):
|
||||
raise ProviderError("the summariser is unreachable")
|
||||
|
||||
async def embed(self, texts):
|
||||
raise ProviderError("the embedder is unreachable")
|
||||
|
||||
with SessionLocal() as db:
|
||||
adventure = db.get(models.Adventure, client.adv_id)
|
||||
# Enough uncovered story that the memory pass is genuinely due.
|
||||
for depth in range(20):
|
||||
db.add(models.Action(adventure_id=adventure.id, type="do",
|
||||
text=f"filler {depth}"))
|
||||
db.commit()
|
||||
# Read the head *after* the fixture's own writes, so what this test measures
|
||||
# is the effect of the failing derived pass and nothing else.
|
||||
before_head = head_of(client)
|
||||
|
||||
import app.memorybank as mb
|
||||
real_summary, real_embed = mb.summary_provider, mb.embedding_provider
|
||||
mb.summary_provider = lambda s: Broken()
|
||||
mb.embedding_provider = lambda s: Broken()
|
||||
try:
|
||||
asyncio.run(mb.run_post_turn(client.adv_id))
|
||||
finally:
|
||||
mb.summary_provider, mb.embedding_provider = real_summary, real_embed
|
||||
|
||||
# The accepted story, its state and the head all survived.
|
||||
actions = client.get(f"/api/adventures/{client.adv_id}").json()["actions"]
|
||||
assert any("The lantern swings." in a["text"] for a in actions)
|
||||
after_state = client.get(f"/api/adventures/{client.adv_id}/state").json()["document"]
|
||||
assert after_state["entities"].keys() == before_state["entities"].keys()
|
||||
assert head_of(client) == before_head
|
||||
|
||||
# The failure is findable.
|
||||
status = client.get(f"/api/adventures/{client.adv_id}/derived").json()
|
||||
assert "memory" in status["failing"], status
|
||||
detail = next(r for r in status["status"] if r["kind"] == "memory")
|
||||
assert "unreachable" in detail["detail"]
|
||||
assert detail["failures"] >= 1
|
||||
|
||||
# And the story continues.
|
||||
play(client, "carry on", prose="The door opens.")
|
||||
assert any("The door opens." in a["text"]
|
||||
for a in client.get(f"/api/adventures/{client.adv_id}").json()["actions"])
|
||||
|
||||
|
||||
def test_f08_a_recovered_pass_clears_the_failure(client):
|
||||
"""Derived work can be retried: the next healthy run clears the record."""
|
||||
with SessionLocal() as db:
|
||||
derived.failed(db, client.adv_id, derived.SUMMARY,
|
||||
ProviderError("the summariser is unreachable"))
|
||||
db.commit()
|
||||
assert client.get(f"/api/adventures/{client.adv_id}/derived").json()["failing"] \
|
||||
== ["summary"]
|
||||
|
||||
with SessionLocal() as db:
|
||||
derived.succeeded(db, client.adv_id, derived.SUMMARY)
|
||||
db.commit()
|
||||
|
||||
status = client.get(f"/api/adventures/{client.adv_id}/derived").json()
|
||||
assert status["failing"] == []
|
||||
row = next(r for r in status["status"] if r["kind"] == "summary")
|
||||
assert row["status"] == "ok" and row["failures"] == 0
|
||||
|
||||
|
||||
# ------------------------------------------------------- E02 / E03 lineage
|
||||
#
|
||||
# The memory half of this was already correct at the M5 baseline: memories carry
|
||||
# a `(branch_id, depth)` coordinate and retrieval filters them through the
|
||||
# capped lineage. These tests pin that behaviour so a later change cannot lose
|
||||
# it. The summary half was not: before M6 the rolling summary was one column
|
||||
# with no coordinate, and it leaked across a divergence. That is what
|
||||
# `app/summaries.py` fixes, and what E03 below measures.
|
||||
|
||||
SECRET_A = "Aldric hid the ledger beneath the third flagstone."
|
||||
SECRET_B = "The party swore an oath in the drowned chapel."
|
||||
|
||||
|
||||
def test_e02_the_ten_step_memory_negative_control(client):
|
||||
"""E02, exactly as the milestone brief numbers it."""
|
||||
# 1-2. Establish the fact and let a memory be made from it.
|
||||
play(client, "search the floor", prose="Aldric pries up the flagstone.")
|
||||
plant_memory(client, SECRET_A)
|
||||
|
||||
# 3. Retrievable on that valid line.
|
||||
assert SECRET_A in eligible_memory_texts(client)
|
||||
assert SECRET_A in prompt_text(context_report(client))
|
||||
|
||||
# 4-5. Undo to before it: no longer eligible.
|
||||
client.post(f"/api/adventures/{client.adv_id}/undo")
|
||||
client.post(f"/api/adventures/{client.adv_id}/undo")
|
||||
assert SECRET_A not in eligible_memory_texts(client)
|
||||
assert SECRET_A not in prompt_text(context_report(client))
|
||||
|
||||
# 6-7. Redo: eligible again, and no re-embedding was needed.
|
||||
client.post(f"/api/adventures/{client.adv_id}/redo")
|
||||
client.post(f"/api/adventures/{client.adv_id}/redo")
|
||||
assert SECRET_A in eligible_memory_texts(client)
|
||||
with SessionLocal() as db:
|
||||
assert db.execute(
|
||||
select(models.Memory.embedded).where(
|
||||
models.Memory.adventure_id == client.adv_id)
|
||||
).scalars().first() is True, "the memory was re-embedded rather than reused"
|
||||
|
||||
# 8-9. Undo again and diverge onto a new continuation.
|
||||
client.post(f"/api/adventures/{client.adv_id}/undo")
|
||||
client.post(f"/api/adventures/{client.adv_id}/undo")
|
||||
play(client, "take the other road", prose="A different road opens.")
|
||||
|
||||
# 10. Still stored, never in the active prompt.
|
||||
with SessionLocal() as db:
|
||||
assert db.query(models.Memory).filter_by(adventure_id=client.adv_id).count() == 1
|
||||
assert SECRET_A not in eligible_memory_texts(client)
|
||||
assert SECRET_A not in prompt_text(context_report(client))
|
||||
|
||||
|
||||
def test_e02_the_same_control_through_a_save_point_restore(client):
|
||||
"""E02 again, reached by restoring a Save Point rather than by Undo."""
|
||||
play(client, "begin", prose="The lantern swings.")
|
||||
r = client.post(f"/api/adventures/{client.adv_id}/checkpoints",
|
||||
json={"name": "Before the ledger"})
|
||||
assert r.status_code in (200, 201), r.text[:200]
|
||||
save_point = r.json()
|
||||
|
||||
play(client, "search the floor", prose="Aldric pries up the flagstone.")
|
||||
plant_memory(client, SECRET_A)
|
||||
assert SECRET_A in prompt_text(context_report(client))
|
||||
|
||||
r = client.post(
|
||||
f"/api/adventures/{client.adv_id}/checkpoints/{save_point['id']}/restore")
|
||||
assert r.status_code == 200, r.text[:200]
|
||||
|
||||
assert SECRET_A not in eligible_memory_texts(client)
|
||||
assert SECRET_A not in prompt_text(context_report(client))
|
||||
|
||||
# Diverging from the restored position keeps it out for good.
|
||||
play(client, "a different road", prose="A different road opens.")
|
||||
assert SECRET_A not in prompt_text(context_report(client))
|
||||
with SessionLocal() as db:
|
||||
assert db.query(models.Memory).filter_by(adventure_id=client.adv_id).count() == 1
|
||||
|
||||
|
||||
def test_e03_an_abandoned_summary_is_retained_but_never_used(client):
|
||||
"""E03. The failure this milestone fixes, measured in the prompt.
|
||||
|
||||
Before M6 the summary was a single column with a lineage cursor but no
|
||||
lineage of its own, and the builder injected it unconditionally. Undo plus a
|
||||
divergence therefore left the narrator reading sentences about a story the
|
||||
reader was no longer on.
|
||||
"""
|
||||
play(client, "begin", prose="The lantern swings.")
|
||||
play(client, "go to the chapel", prose="The chapel door gives.")
|
||||
with SessionLocal() as db:
|
||||
adventure = db.get(models.Adventure, client.adv_id)
|
||||
summaries.record(db, adventure, SECRET_B, trigger="interval",
|
||||
model_name="test-model")
|
||||
db.commit()
|
||||
|
||||
# Eligible on the line that produced it.
|
||||
assert SECRET_B in prompt_text(context_report(client))
|
||||
assert context_report(client)["summary"]["trigger"] == "interval"
|
||||
|
||||
# Undo before the summarized stretch, then diverge.
|
||||
client.post(f"/api/adventures/{client.adv_id}/undo")
|
||||
client.post(f"/api/adventures/{client.adv_id}/undo")
|
||||
play(client, "take the other road", prose="A different road opens.")
|
||||
|
||||
report = context_report(client)
|
||||
assert SECRET_B not in prompt_text(report), "an abandoned summary reached the prompt"
|
||||
assert report["summary"] is None or SECRET_B not in report["summary"].get("preview", "")
|
||||
|
||||
# Retained, not deleted — and visible as retained.
|
||||
status = client.get(f"/api/adventures/{client.adv_id}/derived").json()
|
||||
stored = [row for row in status["summaries"] if SECRET_B in row["preview"]]
|
||||
assert stored, "the abandoned summary was deleted rather than retained"
|
||||
assert stored[0]["eligible"] is False
|
||||
|
||||
|
||||
def test_e03_a_summary_becomes_eligible_again_on_redo(client):
|
||||
"""The negative control needs its positive half: Redo restores the line, so
|
||||
the summary written on it is usable again."""
|
||||
play(client, "begin", prose="The lantern swings.")
|
||||
play(client, "go to the chapel", prose="The chapel door gives.")
|
||||
with SessionLocal() as db:
|
||||
adventure = db.get(models.Adventure, client.adv_id)
|
||||
summaries.record(db, adventure, SECRET_B)
|
||||
db.commit()
|
||||
assert SECRET_B in prompt_text(context_report(client))
|
||||
|
||||
client.post(f"/api/adventures/{client.adv_id}/undo")
|
||||
client.post(f"/api/adventures/{client.adv_id}/undo")
|
||||
assert SECRET_B not in prompt_text(context_report(client))
|
||||
|
||||
client.post(f"/api/adventures/{client.adv_id}/redo")
|
||||
client.post(f"/api/adventures/{client.adv_id}/redo")
|
||||
assert SECRET_B in prompt_text(context_report(client))
|
||||
|
||||
|
||||
def test_a_summary_the_reader_typed_is_anchored_too(client):
|
||||
"""A hand-written summary is still a summary. It would otherwise survive a
|
||||
divergence that its generated equivalent correctly does not."""
|
||||
play(client, "begin", prose="The lantern swings.")
|
||||
play(client, "go to the chapel", prose="The chapel door gives.")
|
||||
r = client.patch(f"/api/adventures/{client.adv_id}",
|
||||
json={"story_summary": SECRET_B})
|
||||
assert r.status_code == 200, r.text[:200]
|
||||
assert SECRET_B in prompt_text(context_report(client))
|
||||
|
||||
client.post(f"/api/adventures/{client.adv_id}/undo")
|
||||
client.post(f"/api/adventures/{client.adv_id}/undo")
|
||||
play(client, "the other road", prose="A different road opens.")
|
||||
|
||||
assert SECRET_B not in prompt_text(context_report(client))
|
||||
|
||||
|
||||
def test_e01_and_e04_state_and_scene_are_unchanged_by_m6(client):
|
||||
"""M5's lineage behaviour must not regress while context selection changes."""
|
||||
play(client, "establish", prose="Mara arrives.", events=[
|
||||
{"type": "create_entity", "entity": "mara", "entity_type": "character",
|
||||
"name": "Mara"}])
|
||||
play(client, "she learns", prose="Mara learns the code.", events=[
|
||||
{"type": "add_fact", "subject": "mara", "predicate": "knows the vault code",
|
||||
"fact_id": "vault"}])
|
||||
document = client.get(f"/api/adventures/{client.adv_id}/state").json()["document"]
|
||||
assert "knows the vault code" in [f["predicate"] for f in document["facts"]]
|
||||
|
||||
client.post(f"/api/adventures/{client.adv_id}/undo")
|
||||
client.post(f"/api/adventures/{client.adv_id}/undo")
|
||||
play(client, "a different road", prose="A different road opens.")
|
||||
|
||||
document = client.get(f"/api/adventures/{client.adv_id}/state").json()["document"]
|
||||
assert "knows the vault code" not in [f["predicate"] for f in document["facts"]]
|
||||
assert "vault code" not in prompt_text(context_report(client))
|
||||
|
||||
|
||||
# ------------------------------------------- authority conflicts (section 8)
|
||||
|
||||
def test_a_memory_cannot_outrank_a_manual_correction(client):
|
||||
"""Section 8. A withdrawn assertion may survive as history; it may not be
|
||||
presented as current truth, whatever a memory says about it."""
|
||||
play(client, "establish", prose="Mara arrives.", events=[
|
||||
{"type": "create_entity", "entity": "mara", "entity_type": "character",
|
||||
"name": "Mara"}])
|
||||
play(client, "she learns", prose="Mara learns where the key was found.", events=[
|
||||
{"type": "add_fact", "subject": "mara",
|
||||
"predicate": "knows where the key was found", "fact_id": "mara-knows"}])
|
||||
# A memory that records the same thing, written before the correction.
|
||||
plant_memory(client, "Mara knows where the key was found.")
|
||||
|
||||
r = client.post(f"/api/adventures/{client.adv_id}/state/corrections", json={
|
||||
"events": [{"type": "invalidate_fact", "fact_id": "mara-knows",
|
||||
"reason": "Mara never learned where the silver key was found."}],
|
||||
"note": "Mara never learned where the silver key was found.",
|
||||
})
|
||||
assert r.status_code in (200, 201), r.text[:200]
|
||||
|
||||
report = context_report(client)
|
||||
sections = {s["label"]: s["text"] for s in report["sections"]}
|
||||
|
||||
# The authoritative state says it is withdrawn, in the prompt itself.
|
||||
assert "No longer true" in sections["narrative_state"]
|
||||
assert "Mara never learned" in sections["narrative_state"]
|
||||
# The state section does not carry it among the facts that stand.
|
||||
established = sections["narrative_state"].split("No longer true")[0]
|
||||
assert "knows where the key was found" not in established
|
||||
# The memory is subordinate: it is not state, and it is not canon.
|
||||
document = client.get(f"/api/adventures/{client.adv_id}/state").json()["document"]
|
||||
active = [f["predicate"] for f in document["facts"]
|
||||
if f.get("status") != "invalidated"]
|
||||
assert "knows where the key was found" not in active
|
||||
|
||||
|
||||
# ---------------------------------------------------- derived rebuildability
|
||||
|
||||
def test_derived_data_can_be_deleted_and_rebuilt(client):
|
||||
"""Section 16. Authoritative history must not depend on derived rows."""
|
||||
play(client, "begin", prose="The lantern swings.", events=[
|
||||
{"type": "create_entity", "entity": "aldric", "entity_type": "character",
|
||||
"name": "Aldric"}])
|
||||
plant_memory(client, SECRET_A)
|
||||
with SessionLocal() as db:
|
||||
adventure = db.get(models.Adventure, client.adv_id)
|
||||
summaries.record(db, adventure, SECRET_B)
|
||||
db.commit()
|
||||
|
||||
before_actions = [a["text"] for a in
|
||||
client.get(f"/api/adventures/{client.adv_id}").json()["actions"]]
|
||||
before_state = client.get(f"/api/adventures/{client.adv_id}/state").json()["document"]
|
||||
before_head = head_of(client)
|
||||
|
||||
# Remove every derived row.
|
||||
with SessionLocal() as db:
|
||||
db.query(models.Memory).filter_by(adventure_id=client.adv_id).delete()
|
||||
db.query(models.Summary).filter_by(adventure_id=client.adv_id).delete()
|
||||
db.commit()
|
||||
|
||||
after_actions = [a["text"] for a in
|
||||
client.get(f"/api/adventures/{client.adv_id}").json()["actions"]]
|
||||
after_state = client.get(f"/api/adventures/{client.adv_id}/state").json()["document"]
|
||||
assert after_actions == before_actions, "deleting derived data changed the transcript"
|
||||
assert after_state == before_state, "deleting derived data changed the state"
|
||||
assert head_of(client) == before_head
|
||||
# The story still plays with no derived data at all.
|
||||
play(client, "carry on", prose="The door opens.")
|
||||
|
||||
# And derived data can be written again.
|
||||
plant_memory(client, SECRET_A)
|
||||
with SessionLocal() as db:
|
||||
adventure = db.get(models.Adventure, client.adv_id)
|
||||
summaries.record(db, adventure, SECRET_B)
|
||||
db.commit()
|
||||
assert SECRET_A in prompt_text(context_report(client))
|
||||
assert SECRET_B in prompt_text(context_report(client))
|
||||
|
||||
|
||||
# ------------------------------------------- E03 regenerated after divergence
|
||||
#
|
||||
# M6 review finding M6-F1. The original E03 test proved only that the *old*
|
||||
# summary row becomes ineligible after a divergence, and passed while the defect
|
||||
# was live: the summariser seeded itself from `adventures.story_summary`, a
|
||||
# campaign-global mirror with no lineage, so the summary it generated on the new
|
||||
# line inherited the abandoned line's prose. The row was correctly anchored; its
|
||||
# contents were not.
|
||||
#
|
||||
# The regression below plays far enough on the new line to force a *new* summary
|
||||
# to be generated, which is the step that was missing.
|
||||
|
||||
E03_SENTINEL = "ABANDONED-CHAPEL-OATH-9930"
|
||||
|
||||
|
||||
class CarryingSummariser:
|
||||
"""A summariser that behaves like a real one.
|
||||
|
||||
It carries the summary it was given forward and folds in the new events, so
|
||||
"did abandoned content reach this summary?" has an exact answer. The
|
||||
per-block memory prompt is answered separately, echoing the sentinel only
|
||||
for blocks that genuinely contain it.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.summary_seeds = []
|
||||
|
||||
async def complete(self, system, user, *, max_tokens=600):
|
||||
if "Current story summary:" not in user:
|
||||
return f"MEM[{E03_SENTINEL}]" if E03_SENTINEL in user else "MEM[dry road]"
|
||||
current = user.split("Current story summary:\n", 1)[1].split("\n\nNew events")[0]
|
||||
events = user.split("New events since the last update:\n", 1)[1].split(
|
||||
"\n\nUpdated summary:")[0]
|
||||
self.summary_seeds.append(current.strip())
|
||||
carried = "" if current.strip() == "(none yet)" else current.strip() + " "
|
||||
return (carried + events.strip().replace("\n", " "))[:1500]
|
||||
|
||||
async def embed(self, texts):
|
||||
return [[1.0, 0.0, 0.0] for _ in texts]
|
||||
|
||||
|
||||
def test_e03_a_summary_generated_after_divergence_carries_no_abandoned_content(client):
|
||||
"""M6-F1. The failure the original E03 test could not see.
|
||||
|
||||
Every step of the review's reproduction, in order, with the positive control
|
||||
first — a summary that does not exist proves nothing about what it omits.
|
||||
"""
|
||||
summariser = CarryingSummariser()
|
||||
import app.memorybank as mb
|
||||
real_summary, real_embed = mb.summary_provider, mb.embedding_provider
|
||||
mb.summary_provider = lambda s: summariser
|
||||
mb.embedding_provider = lambda s: summariser
|
||||
try:
|
||||
# 1-2. Path A, long enough to generate a summary, with the sentinel on it.
|
||||
for i in range(20):
|
||||
play(client, f"a{i}", prose=f"They swear the {E03_SENTINEL}. [{i}]")
|
||||
asyncio.run(mb.run_post_turn(client.adv_id))
|
||||
|
||||
# 3. POSITIVE CONTROL: the sentinel really is in the path-A summary.
|
||||
report_a = context_report(client)
|
||||
summary_a = next((s["text"] for s in report_a["sections"]
|
||||
if s["label"] == "story_summary"), "")
|
||||
assert summary_a, "no summary was generated on path A; the rest proves nothing"
|
||||
assert E03_SENTINEL in summary_a, "the fixture did not put the sentinel in the summary"
|
||||
assert E03_SENTINEL in prompt_text(report_a)
|
||||
with SessionLocal() as db:
|
||||
adventure = db.get(models.Adventure, client.adv_id)
|
||||
path_a_summary_id = summaries.current(db, adventure).id
|
||||
|
||||
# 4. Move the head below every turn that mentions the sentinel.
|
||||
while head_of(client)[1] > 0:
|
||||
if client.post(f"/api/adventures/{client.adv_id}/undo").status_code != 200:
|
||||
break
|
||||
|
||||
# 5-6. Diverge, and play far enough that a NEW summary is generated.
|
||||
# Seeds recorded from here on are the ones that matter: on path A the
|
||||
# summariser is *supposed* to be seeded with the sentinel, because the
|
||||
# sentinel is on path A.
|
||||
summariser.summary_seeds.clear()
|
||||
for i in range(20):
|
||||
play(client, f"b{i}", prose=f"A dry road, nothing sworn. [{i}]")
|
||||
asyncio.run(mb.run_post_turn(client.adv_id))
|
||||
|
||||
report_b = context_report(client)
|
||||
summary_b_row = report_b["summary"]
|
||||
summary_b = next((s["text"] for s in report_b["sections"]
|
||||
if s["label"] == "story_summary"), "")
|
||||
|
||||
# 7. A new summary really was generated on the new line.
|
||||
assert summary_b_row is not None, "no summary is eligible on path B"
|
||||
assert summary_b_row["id"] != path_a_summary_id, (
|
||||
"path B reused path A's summary row rather than generating one"
|
||||
)
|
||||
|
||||
# 8. No path-A story is on path B's lineage, so anything from it is a leak.
|
||||
with SessionLocal() as db:
|
||||
adventure = db.get(models.Adventure, client.adv_id)
|
||||
carried_over = db.query(models.Action).filter(
|
||||
models.Action.adventure_id == client.adv_id,
|
||||
lineage.path_of(db, adventure).clause(models.Action),
|
||||
models.Action.text.like(f"%{E03_SENTINEL}%"),
|
||||
).count()
|
||||
assert carried_over == 0, "the fixture left path-A story on path B's lineage"
|
||||
|
||||
# 9-10. The sentinel is in neither the new summary nor the whole prompt.
|
||||
assert E03_SENTINEL not in summary_b, (
|
||||
"the summary generated on path B carries the abandoned line's content"
|
||||
)
|
||||
assert E03_SENTINEL not in prompt_text(report_b), (
|
||||
"abandoned content reached the active narrator prompt"
|
||||
)
|
||||
|
||||
# And it was never even *offered* the abandoned prose: the fix is at the
|
||||
# input, not a filter over the output.
|
||||
assert summariser.summary_seeds, "no summary was generated on path B"
|
||||
assert not any(E03_SENTINEL in seed for seed in summariser.summary_seeds), (
|
||||
"the summariser was seeded with content from the abandoned line"
|
||||
)
|
||||
|
||||
# 11. The old summary is retained, and reported as retained-but-ineligible.
|
||||
listing = client.get(f"/api/adventures/{client.adv_id}/derived").json()
|
||||
old = [row for row in listing["summaries"] if row["id"] == path_a_summary_id]
|
||||
assert old, "the abandoned summary row was deleted rather than retained"
|
||||
assert old[0]["eligible"] is False
|
||||
finally:
|
||||
mb.summary_provider, mb.embedding_provider = real_summary, real_embed
|
||||
@@ -0,0 +1,202 @@
|
||||
"""M6: the read paths this milestone touches must not grow a query per row.
|
||||
|
||||
M5 spent a review finding on an N+1 in the action list. M6 adds three things
|
||||
that could each reintroduce one — a memory's provenance, a summary's source
|
||||
coordinates, and the derived-work status — so each is measured here rather than
|
||||
argued about.
|
||||
|
||||
The assertions are on *growth*, not on an exact count. A fixed number would
|
||||
break on any unrelated query and teach the next person to raise the number; what
|
||||
matters is that doubling the rows does not double the queries.
|
||||
|
||||
python -m pytest tests/test_context_performance.py -v
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
from fastapi import Depends
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import event
|
||||
|
||||
from app import auth, limits, memorybank, models, summaries
|
||||
from app.database import Base, SessionLocal, engine, get_db
|
||||
from app.main import app
|
||||
from app.routers import adventures
|
||||
|
||||
from fakes import ScriptedProvider, state_block
|
||||
|
||||
|
||||
class StubEmbedder:
|
||||
async def embed(self, texts):
|
||||
return [[1.0, 0.0, 0.0] for _ in texts]
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def sql_log():
|
||||
statements: list[str] = []
|
||||
|
||||
def record(conn, cursor, statement, parameters, context, executemany):
|
||||
statements.append(statement)
|
||||
|
||||
event.listen(engine, "before_cursor_execute", record)
|
||||
try:
|
||||
yield statements
|
||||
finally:
|
||||
event.remove(engine, "before_cursor_execute", record)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client(monkeypatch):
|
||||
Base.metadata.create_all(bind=engine)
|
||||
memorybank._vector_cache.clear()
|
||||
setup = SessionLocal()
|
||||
user = models.User(is_guest=False, email="perf@example.com")
|
||||
setup.add(user)
|
||||
setup.flush()
|
||||
setup.add(models.Settings(
|
||||
user_id=user.id, api_key="enc:dummy", model="test-model",
|
||||
embedding_model="embed-test", context_token_budget=8000,
|
||||
max_output_tokens=400, memory_top_k=5,
|
||||
))
|
||||
adventure = models.Adventure(
|
||||
user_id=user.id, title="Perf", memory_bank_enabled=True, auto_summarize=True,
|
||||
)
|
||||
setup.add(adventure)
|
||||
setup.flush()
|
||||
setup.add(models.Action(adventure_id=adventure.id, type="start", text="A road."))
|
||||
setup.commit()
|
||||
adv_id, user_id = adventure.id, user.id
|
||||
setup.close()
|
||||
|
||||
monkeypatch.setattr(limits, "check_row_cap", lambda *a, **k: None)
|
||||
monkeypatch.setattr(adventures.turns, "OpenAICompatibleProvider", ScriptedProvider)
|
||||
monkeypatch.setattr(memorybank, "embedding_provider", lambda s: StubEmbedder())
|
||||
app.dependency_overrides[auth.get_current_user] = (
|
||||
lambda db=Depends(get_db): db.get(models.User, user_id)
|
||||
)
|
||||
test_client = TestClient(app)
|
||||
test_client.adv_id = adv_id
|
||||
test_client.user_id = user_id
|
||||
try:
|
||||
yield test_client
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
memorybank._vector_cache.clear()
|
||||
Base.metadata.drop_all(bind=engine)
|
||||
|
||||
|
||||
def _grow(client, *, turns, memories, summary_rows):
|
||||
with SessionLocal() as db:
|
||||
adventure = db.get(models.Adventure, client.adv_id)
|
||||
for i in range(turns):
|
||||
db.add(models.Action(adventure_id=adventure.id,
|
||||
type="ai" if i % 2 else "do",
|
||||
text=f"[{i}] The road bends onward. " * 6))
|
||||
db.commit()
|
||||
with SessionLocal() as db:
|
||||
adventure = db.get(models.Adventure, client.adv_id)
|
||||
for i in range(memories):
|
||||
memory = models.Memory(
|
||||
adventure_id=adventure.id, text=f"Memory {i}: something happened.",
|
||||
branch_id=adventure.head_branch_id, depth=adventure.head_depth,
|
||||
source_start=0, source_end=adventure.head_depth,
|
||||
)
|
||||
memorybank.set_vector(memory, [1.0, 0.0, 0.0])
|
||||
db.add(memory)
|
||||
for i in range(summary_rows):
|
||||
summaries.record(db, adventure, f"Summary {i}.")
|
||||
db.commit()
|
||||
|
||||
|
||||
def _count(sql_log, client) -> int:
|
||||
sql_log.clear()
|
||||
r = client.get(f"/api/adventures/{client.adv_id}/context")
|
||||
assert r.status_code == 200, r.text[:200]
|
||||
return len(sql_log)
|
||||
|
||||
|
||||
def test_assembling_context_does_not_cost_a_query_per_memory(client, sql_log):
|
||||
"""A memory's provenance is fetched in the same read as its text, so more
|
||||
memories must not mean more queries."""
|
||||
_grow(client, turns=10, memories=5, summary_rows=1)
|
||||
small = _count(sql_log, client)
|
||||
_grow(client, turns=0, memories=25, summary_rows=0)
|
||||
large = _count(sql_log, client)
|
||||
|
||||
assert large <= small + 2, (
|
||||
f"{small} queries with 5 memories, {large} with 30 — "
|
||||
"the context read is paying per memory"
|
||||
)
|
||||
|
||||
|
||||
def test_assembling_context_does_not_cost_a_query_per_summary(client, sql_log):
|
||||
"""Only the eligible summary is read, however many are retained."""
|
||||
_grow(client, turns=10, memories=2, summary_rows=2)
|
||||
small = _count(sql_log, client)
|
||||
_grow(client, turns=0, memories=0, summary_rows=30)
|
||||
large = _count(sql_log, client)
|
||||
|
||||
assert large <= small + 2, (
|
||||
f"{small} queries with 2 summaries, {large} with 32 — "
|
||||
"the context read is paying per summary"
|
||||
)
|
||||
|
||||
|
||||
def test_assembling_context_does_not_cost_a_query_per_turn(client, sql_log):
|
||||
"""The history window is one read, not one per action."""
|
||||
_grow(client, turns=10, memories=2, summary_rows=1)
|
||||
small = _count(sql_log, client)
|
||||
_grow(client, turns=60, memories=0, summary_rows=0)
|
||||
large = _count(sql_log, client)
|
||||
|
||||
assert large <= small + 2, (
|
||||
f"{small} queries at 10 turns, {large} at 70 — "
|
||||
"the context read is paying per turn"
|
||||
)
|
||||
|
||||
|
||||
def test_the_derived_status_endpoint_does_not_pay_per_summary(client, sql_log):
|
||||
"""The listing resolves the eligible summary once, not once per row."""
|
||||
_grow(client, turns=6, memories=1, summary_rows=3)
|
||||
sql_log.clear()
|
||||
assert client.get(f"/api/adventures/{client.adv_id}/derived").status_code == 200
|
||||
small = len(sql_log)
|
||||
|
||||
_grow(client, turns=0, memories=0, summary_rows=30)
|
||||
sql_log.clear()
|
||||
assert client.get(f"/api/adventures/{client.adv_id}/derived").status_code == 200
|
||||
large = len(sql_log)
|
||||
|
||||
assert large <= small + 1, (
|
||||
f"{small} queries with 3 summaries, {large} with 33"
|
||||
)
|
||||
|
||||
|
||||
def test_the_context_size_stops_growing_once_the_budget_is_reached(client):
|
||||
"""The companion to the query counts: more story, not more prompt.
|
||||
|
||||
Measured from a story that already fills the budget. Comparing a short story
|
||||
to a long one only shows that the prompt grew, which it is supposed to do
|
||||
until it reaches the ceiling; what F03 is about is that it stops there.
|
||||
"""
|
||||
_grow(client, turns=140, memories=3, summary_rows=1)
|
||||
filled = client.get(f"/api/adventures/{client.adv_id}/context").json()
|
||||
budget = filled["tokens"]["budget"]
|
||||
assert filled["tokens"]["total"] > budget * 0.5, (
|
||||
"the fixture never filled the budget, so this proves nothing"
|
||||
)
|
||||
|
||||
_grow(client, turns=280, memories=0, summary_rows=0)
|
||||
doubled = client.get(f"/api/adventures/{client.adv_id}/context").json()
|
||||
|
||||
assert doubled["history"]["total"] > filled["history"]["total"] * 2, "fixture too small"
|
||||
assert doubled["tokens"]["total"] <= budget
|
||||
# Three times the story, and the prompt does not move.
|
||||
assert doubled["tokens"]["total"] <= filled["tokens"]["total"] + 50, (
|
||||
f"{filled['tokens']['total']} -> {doubled['tokens']['total']} tokens "
|
||||
f"while the story went from {filled['history']['total']} to "
|
||||
f"{doubled['history']['total']} actions"
|
||||
)
|
||||
# And it is bounded by the budget rather than by the length of the story.
|
||||
assert doubled["history"]["included"] < doubled["history"]["total"]
|
||||
@@ -0,0 +1,238 @@
|
||||
"""M6 section 13: context assembly and derived work against a real model.
|
||||
|
||||
The M6 equivalent of `test_narrative_realistic.py`, and it exists for the same
|
||||
reason: memory and summary extraction can look correct against a tiny synthetic
|
||||
prompt and behave differently under a full application context — a real narrator
|
||||
instruction, real authoritative state, enough recent story to exercise
|
||||
budgeting, a summary, and several memories.
|
||||
|
||||
**What is asserted, and what is not.** These tests do not assert that the model
|
||||
writes a good summary or picks the right memory. No test can, and a threshold
|
||||
would fail when a model is swapped rather than when the code breaks. They assert
|
||||
that the *application* stays correct around whatever the model produces:
|
||||
|
||||
* the prompt stays inside its budget and keeps the reply reserve;
|
||||
* a summary the model generates is anchored to the story it covers;
|
||||
* a failure is recorded rather than swallowed;
|
||||
* nothing from an abandoned line reaches the prompt.
|
||||
|
||||
Model behaviour is recorded as evidence and printed, not asserted.
|
||||
|
||||
## Running it
|
||||
|
||||
Skipped unless an endpoint is configured, so the ordinary suite stays local,
|
||||
deterministic and offline:
|
||||
|
||||
AIDND_TEST_ENDPOINT=http://127.0.0.1:11434/v1 \\
|
||||
AIDND_TEST_MODEL=qwen2.5:3b-instruct \\
|
||||
AIDND_TEST_EMBED_MODEL=nomic-embed-text \\
|
||||
python -m pytest tests/test_context_realistic.py -v -s
|
||||
|
||||
The endpoint is read from the environment and never written down here, and the
|
||||
same endpoint policy the rest of the product enforces applies: loopback or a
|
||||
trusted-LAN address, TLS verified, no cloud.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
|
||||
import pytest
|
||||
from fastapi import Depends
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app import auth, limits, memorybank, models, summaries
|
||||
from app.database import Base, SessionLocal, engine, get_db
|
||||
from app.main import app
|
||||
from app.routers import adventures
|
||||
|
||||
from fakes import ScriptedProvider, state_block
|
||||
|
||||
ENDPOINT = os.environ.get("AIDND_TEST_ENDPOINT", "")
|
||||
MODEL = os.environ.get("AIDND_TEST_MODEL", "")
|
||||
EMBED_MODEL = os.environ.get("AIDND_TEST_EMBED_MODEL", "nomic-embed-text")
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not (ENDPOINT and MODEL),
|
||||
reason="set AIDND_TEST_ENDPOINT and AIDND_TEST_MODEL to run against a real model",
|
||||
)
|
||||
|
||||
CANON = {
|
||||
"rules": ["The Crooked Lantern is the only inn in the valley."],
|
||||
"forbidden": ["No character may use magic."],
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client(monkeypatch):
|
||||
Base.metadata.create_all(bind=engine)
|
||||
memorybank._vector_cache.clear()
|
||||
setup = SessionLocal()
|
||||
user = models.User(is_guest=False, email="m6live@example.com")
|
||||
setup.add(user)
|
||||
setup.flush()
|
||||
setup.add(models.Settings(
|
||||
user_id=user.id, api_key="enc:dummy", endpoint_url=ENDPOINT, model=MODEL,
|
||||
summary_model=MODEL, embedding_model=EMBED_MODEL,
|
||||
context_token_budget=8192, max_output_tokens=700, memory_top_k=4,
|
||||
model_timeout_seconds=600,
|
||||
))
|
||||
adventure = models.Adventure(
|
||||
user_id=user.id, title="The Crooked Lantern",
|
||||
memory_bank_enabled=True, auto_summarize=True, campaign_canon=CANON,
|
||||
)
|
||||
setup.add(adventure)
|
||||
setup.flush()
|
||||
setup.add(models.Action(adventure_id=adventure.id, type="start",
|
||||
text="Rain hammers the road outside the Crooked Lantern."))
|
||||
setup.commit()
|
||||
adv_id, user_id = adventure.id, user.id
|
||||
setup.close()
|
||||
|
||||
monkeypatch.setattr(limits, "check_row_cap", lambda *a, **k: None)
|
||||
app.dependency_overrides[auth.get_current_user] = (
|
||||
lambda db=Depends(get_db): db.get(models.User, user_id)
|
||||
)
|
||||
test_client = TestClient(app)
|
||||
test_client.adv_id = adv_id
|
||||
test_client.user_id = user_id
|
||||
try:
|
||||
yield test_client
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
memorybank._vector_cache.clear()
|
||||
Base.metadata.drop_all(bind=engine)
|
||||
|
||||
|
||||
def play_scripted(client, text, prose, events=None):
|
||||
"""A turn with a known outcome, so the fixture is deterministic."""
|
||||
real = adventures.turns.OpenAICompatibleProvider
|
||||
adventures.turns.OpenAICompatibleProvider = ScriptedProvider
|
||||
ScriptedProvider.replies = [f"{prose}\n{state_block(events or [])}"]
|
||||
try:
|
||||
r = client.post(f"/api/adventures/{client.adv_id}/actions",
|
||||
json={"type": "do", "text": text})
|
||||
assert r.status_code == 200, r.text[:300]
|
||||
finally:
|
||||
adventures.turns.OpenAICompatibleProvider = real
|
||||
|
||||
|
||||
def context(client) -> dict:
|
||||
r = client.get(f"/api/adventures/{client.adv_id}/context")
|
||||
assert r.status_code == 200, r.text[:300]
|
||||
return r.json()
|
||||
|
||||
|
||||
def test_a_real_summary_is_generated_and_anchored(client):
|
||||
"""The summariser runs against the real model, and what it writes is
|
||||
anchored to the story it read rather than to a column."""
|
||||
play_scripted(client, "step inside", "Aldric shakes the rain from his coat.", [
|
||||
{"type": "create_entity", "entity": "aldric", "entity_type": "character",
|
||||
"name": "Aldric"},
|
||||
{"type": "create_entity", "entity": "mara", "entity_type": "character",
|
||||
"name": "Mara"},
|
||||
])
|
||||
for i in range(18):
|
||||
play_scripted(client, f"talk on {i}",
|
||||
f"Mara pours another measure and tells him about the road north. "
|
||||
f"The lantern gutters. [{i}]")
|
||||
|
||||
asyncio.run(memorybank.run_post_turn(client.adv_id))
|
||||
|
||||
with SessionLocal() as db:
|
||||
adventure = db.get(models.Adventure, client.adv_id)
|
||||
rows = summaries.all_for(db, adventure)
|
||||
eligible = summaries.current(db, adventure)
|
||||
status = {r["kind"]: r["status"] for r in
|
||||
__import__("app.derived", fromlist=["report"]).report(db, client.adv_id)}
|
||||
|
||||
print(json.dumps({
|
||||
"model": MODEL, "embedding_model": EMBED_MODEL,
|
||||
"summaries_written": len(rows),
|
||||
"derived_status": status,
|
||||
"summary_preview": (eligible.text[:300] if eligible else None),
|
||||
}, indent=2, sort_keys=True))
|
||||
|
||||
assert status.get("summary") == "ok", f"the summariser failed: {status}"
|
||||
assert rows, "no summary was written"
|
||||
assert eligible is not None
|
||||
# Anchored, not floating: it names the stretch of story it covers.
|
||||
assert eligible.depth is not None
|
||||
assert eligible.branch_id is not None
|
||||
assert eligible.model_name == MODEL
|
||||
# And it reaches the prompt.
|
||||
assert eligible.text[:40] in "\n".join(s["text"] for s in context(client)["sections"])
|
||||
|
||||
|
||||
def test_the_prompt_stays_bounded_and_reserves_the_reply_under_real_context(client):
|
||||
"""Budgeting, measured on a realistic prompt rather than a synthetic one."""
|
||||
play_scripted(client, "step inside", "Aldric shakes the rain from his coat.", [
|
||||
{"type": "create_entity", "entity": "aldric", "entity_type": "character",
|
||||
"name": "Aldric"},
|
||||
])
|
||||
for i in range(40):
|
||||
play_scripted(client, f"on {i}",
|
||||
f"[{i}] " + "The lantern swings and the rain keeps on. " * 20)
|
||||
asyncio.run(memorybank.run_post_turn(client.adv_id))
|
||||
|
||||
report = context(client)
|
||||
print(json.dumps({
|
||||
"model": MODEL,
|
||||
"budget": report["tokens"]["budget"],
|
||||
"input_tokens": report["tokens"]["total"],
|
||||
"output_reserve": report["tokens"]["output_reserve"],
|
||||
"protected": report["tokens"]["protected"],
|
||||
"available_for_history": report["tokens"]["available_for_history"],
|
||||
"actions_included": report["history"]["included"],
|
||||
"actions_total": report["history"]["total"],
|
||||
"memories_used": len(report["memories"]["used"]) if report["memories"] else 0,
|
||||
}, indent=2, sort_keys=True))
|
||||
|
||||
assert report["tokens"]["total"] <= report["tokens"]["budget"]
|
||||
assert report["tokens"]["total"] + 700 <= report["tokens"]["budget"], (
|
||||
"the real prompt left no room for the configured reply"
|
||||
)
|
||||
assert report["history"]["included"] < report["history"]["total"], (
|
||||
"the whole transcript was sent"
|
||||
)
|
||||
|
||||
|
||||
def test_a_real_turn_still_generates_with_memory_and_summary_present(client):
|
||||
"""The end-to-end shape: a real narrator turn on a campaign that has a
|
||||
generated summary, retrieved memories and authoritative state."""
|
||||
play_scripted(client, "step inside", "Aldric shakes the rain from his coat.", [
|
||||
{"type": "create_entity", "entity": "aldric", "entity_type": "character",
|
||||
"name": "Aldric"},
|
||||
])
|
||||
for i in range(18):
|
||||
play_scripted(client, f"talk {i}",
|
||||
f"They talk of the road north while the fire burns down. [{i}]")
|
||||
asyncio.run(memorybank.run_post_turn(client.adv_id))
|
||||
|
||||
# A real turn, through the real provider.
|
||||
r = client.post(f"/api/adventures/{client.adv_id}/actions",
|
||||
json={"type": "do", "text": "ask Mara what lies north"})
|
||||
assert r.status_code == 200, r.text[:300]
|
||||
assert '"error"' not in r.text, r.text[:400]
|
||||
|
||||
with SessionLocal() as db:
|
||||
action = (db.query(models.Action)
|
||||
.filter_by(adventure_id=client.adv_id, type="ai")
|
||||
.order_by(models.Action.id.desc()).first())
|
||||
snapshot = action.context_snapshot
|
||||
text = action.text
|
||||
|
||||
labels = [s["label"] for s in snapshot["sections"]]
|
||||
print(json.dumps({
|
||||
"model": MODEL,
|
||||
"sections": labels,
|
||||
"input_tokens": snapshot["tokens"]["total"],
|
||||
"output_reserve": snapshot["tokens"]["output_reserve"],
|
||||
"reply_chars": len(text),
|
||||
}, indent=2, sort_keys=True))
|
||||
|
||||
assert "narrator" in labels
|
||||
assert "history" in labels
|
||||
# The reply is a story, not protocol.
|
||||
assert "```state" not in text
|
||||
assert '"events"' not in text
|
||||
@@ -108,7 +108,12 @@ def actions_loaded():
|
||||
|
||||
# ------------------------------------------------------- the prompt is equal
|
||||
|
||||
@pytest.mark.parametrize("budget", [1024, 4096, 8192, 16384, 65536])
|
||||
# The smallest budget here is the tightest one this fixture can still build a
|
||||
# prompt for. M6 reserves the reply out of the context budget, so 1024 with an
|
||||
# 800-token reply and 750 tokens of protected prompt is no longer a
|
||||
# configuration that produces a prompt — it raises `ContextOverflow`, which
|
||||
# `test_a_budget_too_small_for_the_reply_is_refused` covers.
|
||||
@pytest.mark.parametrize("budget", [2048, 4096, 8192, 16384, 65536])
|
||||
def test_window_builds_the_same_prompt_as_the_whole_story(story, budget, monkeypatch):
|
||||
db, adventure, settings = story
|
||||
settings.context_token_budget = budget
|
||||
|
||||
@@ -216,8 +216,13 @@ def test_prompt_stays_inside_the_budget_on_a_long_story(story):
|
||||
db.expire_all()
|
||||
adventure = db.get(models.Adventure, adventure.id)
|
||||
|
||||
# A large reply budget, so the length hint is long enough for a missing
|
||||
# reservation to show. M6 reserves the reply out of the context budget, so
|
||||
# the budget has to be large enough to hold both — 2048 with a 2400-token
|
||||
# reply is a configuration that cannot produce a prompt at all, and now
|
||||
# says so rather than silently overflowing.
|
||||
settings.max_output_tokens = 2400
|
||||
settings.context_token_budget = 2048
|
||||
settings.context_token_budget = 8192
|
||||
|
||||
_, _, report = builder.build_context(adventure, settings)
|
||||
assert report["history"]["included"] < 120, "budget was never actually filled"
|
||||
|
||||
@@ -20,6 +20,7 @@ exactly as `test_branch_clause.py` builds it.
|
||||
python -m pytest tests/test_memory_nodes.py -v
|
||||
"""
|
||||
import asyncio
|
||||
import math
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -138,11 +139,26 @@ def forked():
|
||||
nodes[f"C{depth}"] = add_node(db, adventure, c, depth, "C")
|
||||
db.flush()
|
||||
|
||||
# Distinct vectors, equally similar to the query.
|
||||
#
|
||||
# These tests are about *lineage visibility* — which memories a branch can
|
||||
# see. They used to store the same vector in every memory, which was
|
||||
# harmless until M6 added redundancy suppression: four identical vectors are
|
||||
# four copies of one statement as far as retrieval is concerned, so they
|
||||
# collapsed to one and the lineage assertions could no longer be read.
|
||||
#
|
||||
# Each vector below sits at the same angle from the query `(1, 0, 0)`, so
|
||||
# ranking between them is unchanged, and far enough apart from each other
|
||||
# (pairwise cosine -0.28 to 0.36) that none suppresses another.
|
||||
memories = {
|
||||
"shared": add_memory(db, adventure, "on the shared trunk", nodes["A3"]),
|
||||
"sibling": add_memory(db, adventure, "on A's own continuation", nodes["A5"]),
|
||||
"b": add_memory(db, adventure, "on B", nodes["B5"]),
|
||||
"c": add_memory(db, adventure, "on C", nodes["C7"]),
|
||||
"shared": add_memory(db, adventure, "on the shared trunk", nodes["A3"],
|
||||
vector=(0.6, 0.8, 0.0)),
|
||||
"sibling": add_memory(db, adventure, "on A's own continuation", nodes["A5"],
|
||||
vector=(0.6, -0.8, 0.0)),
|
||||
"b": add_memory(db, adventure, "on B", nodes["B5"],
|
||||
vector=(0.6, 0.0, 0.8)),
|
||||
"c": add_memory(db, adventure, "on C", nodes["C7"],
|
||||
vector=(0.6, 0.0, -0.8)),
|
||||
}
|
||||
adventure.head_branch_id = c.id
|
||||
adventure.head_depth = 7
|
||||
@@ -162,6 +178,21 @@ def switch_to(db, adventure, branch_id, tip):
|
||||
db.commit()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def restore_embedding_provider():
|
||||
"""Puts `memorybank.embedding_provider` back after every test here.
|
||||
|
||||
`retrieved` below replaces it by assignment. Until M6 nothing restored it,
|
||||
so a stub outlived the module and was still installed when a later file ran
|
||||
(`tests/test_provider_wiring.py`, which asserts on the real factory).
|
||||
"""
|
||||
real = memorybank.embedding_provider
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
memorybank.embedding_provider = real
|
||||
|
||||
|
||||
def retrieved(adventure, settings) -> set[str]:
|
||||
memorybank.embedding_provider = lambda s: StubEmbedder()
|
||||
result = asyncio.run(
|
||||
@@ -381,6 +412,8 @@ def deeply_forked():
|
||||
memory_top_k=50,
|
||||
))
|
||||
|
||||
_spread = 2 * math.pi / 14
|
||||
|
||||
def story(title, forks):
|
||||
adventure = models.Adventure(
|
||||
user_id=user.id, title=title, script_state={}, memory_bank_enabled=True,
|
||||
@@ -404,8 +437,20 @@ def deeply_forked():
|
||||
nodes.append(add_node(db, adventure, branch, depth, "n"))
|
||||
depth += 1
|
||||
db.flush()
|
||||
_placed: list = []
|
||||
for node in nodes[5::6]: # one memory per six actions, as the pass makes them
|
||||
add_memory(db, adventure, f"memory at {node.depth}", node)
|
||||
# A distinct direction per memory, all at the same angle from the
|
||||
# query, so ranking between them is unaffected and M6's redundancy
|
||||
# suppression does not collapse fourteen distinct memories into one.
|
||||
# This test measures bytes fetched, not deduplication.
|
||||
#
|
||||
# Fourteen directions spread evenly around the circle orthogonal to
|
||||
# the query are 2*pi/14 apart; the small shared component keeps the
|
||||
# closest pair at cosine ~0.905, below the 0.93 redundancy bar.
|
||||
angle = _spread * len(_placed)
|
||||
_placed.append(node)
|
||||
add_memory(db, adventure, f"memory at {node.depth}", node,
|
||||
vector=(0.2, 0.98 * math.cos(angle), 0.98 * math.sin(angle)))
|
||||
adventure.head_branch_id = branch.id
|
||||
adventure.head_depth = depth - 1
|
||||
return adventure
|
||||
|
||||
@@ -36,6 +36,23 @@ class StubEmbedder:
|
||||
return [list(self.vector) for _ in texts]
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def restore_embedding_provider():
|
||||
"""Puts `memorybank.embedding_provider` back after every test here.
|
||||
|
||||
The helpers below replace it by assignment rather than through monkeypatch,
|
||||
and until M6 nothing put it back — so whichever test ran last left a stub
|
||||
installed for the rest of the session. That was invisible while every other
|
||||
memory test stubbed it too, and surfaced the moment M6 added a test that
|
||||
asserts on the real factory (`tests/test_provider_wiring.py`).
|
||||
"""
|
||||
real = memorybank.embedding_provider
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
memorybank.embedding_provider = real
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def db():
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
@@ -29,7 +29,7 @@ import os
|
||||
|
||||
import pytest
|
||||
|
||||
from app import models, worldstate
|
||||
from app import models, summaries, worldstate
|
||||
from app import narrative
|
||||
from app.context import builder
|
||||
from app.database import Base, SessionLocal, engine
|
||||
@@ -97,7 +97,6 @@ def story():
|
||||
user_id=user.id, title="A", scenario_id=scenario.id, script_state={},
|
||||
memory="The hero hunts bandits.",
|
||||
ai_instructions="Write in second person.",
|
||||
story_summary="The hero left the village.",
|
||||
world_state=worldstate.instantiate(SCHEMA),
|
||||
narrative_state=NARRATIVE,
|
||||
# Phase 18. Set here so that every test in this file runs with a
|
||||
@@ -113,6 +112,11 @@ def story():
|
||||
db.add(models.Action(adventure_id=adventure.id,
|
||||
type="ai" if i % 2 else "do",
|
||||
text=f"[{i}] The road bends onward past the treeline."))
|
||||
db.flush()
|
||||
# M6: the summary is a row anchored to the story it covers, not a column.
|
||||
# `build_context` reads whichever summary is eligible for the current head,
|
||||
# so a test that wants one in the prompt has to record one.
|
||||
summaries.record(db, adventure, "The hero left the village.")
|
||||
db.commit()
|
||||
db.expire_all()
|
||||
adventure = db.get(models.Adventure, adventure.id)
|
||||
@@ -195,7 +199,7 @@ def test_live_sections_are_still_charged_to_the_budget(story):
|
||||
settings = db.get(models.Settings, settings.id)
|
||||
|
||||
_, _, lean = builder.build_context(adventure, settings)
|
||||
adventure.story_summary = "The hero left the village. " * 150
|
||||
summaries.record(db, adventure, "The hero left the village. " * 150)
|
||||
db.commit()
|
||||
_, _, fat = builder.build_context(adventure, settings)
|
||||
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
"""M6: the provider construction path, exercised for real.
|
||||
|
||||
M2 shipped with the entire memory bank dead and the full suite green. The
|
||||
summariser and the embedder were built from `Settings` attributes that had moved,
|
||||
the resulting `AttributeError` was raised inside a fire-and-forget task, and
|
||||
every memory test had stubbed the factories out — so nothing anywhere noticed
|
||||
(`BUILD-MILESTONES.md`, note from M2).
|
||||
|
||||
These tests exist so that cannot happen twice. **Nothing here mocks a provider
|
||||
factory.** They call the real factories with a real `Settings` row read back out
|
||||
of the database, and assert that the configured values arrive at the object that
|
||||
consumes them. A renamed or removed column fails here loudly instead of killing
|
||||
the memory bank quietly.
|
||||
|
||||
Network is never touched: constructing a provider makes no request. The one test
|
||||
that would make one is skipped unless a trusted-LAN endpoint is configured, and
|
||||
it is reported separately from these.
|
||||
|
||||
python -m pytest tests/test_provider_wiring.py -v
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from app import endpoints, memorybank, models
|
||||
from app.database import Base, SessionLocal, engine
|
||||
from app.providers import OpenAICompatibleProvider, ProviderError
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def settings():
|
||||
"""A real Settings row, round-tripped through the database.
|
||||
|
||||
Round-tripping matters: a column that was renamed in the model but still
|
||||
referenced by a factory fails on the read, which is the failure this module
|
||||
is here to produce.
|
||||
"""
|
||||
Base.metadata.create_all(bind=engine)
|
||||
db = SessionLocal()
|
||||
user = models.User(is_guest=False, email="wiring@example.com")
|
||||
db.add(user)
|
||||
db.flush()
|
||||
row = models.Settings(
|
||||
user_id=user.id,
|
||||
api_key="enc:dummy",
|
||||
endpoint_url="http://127.0.0.1:11434/v1",
|
||||
model="narrator-model",
|
||||
summary_model="summariser-model",
|
||||
embedding_model="embedding-model",
|
||||
api_mode="chat",
|
||||
model_timeout_seconds=123,
|
||||
max_output_tokens=456,
|
||||
context_token_budget=4096,
|
||||
)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
row_id = row.id
|
||||
db.close()
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db.get(models.Settings, row_id)
|
||||
finally:
|
||||
db.close()
|
||||
Base.metadata.drop_all(bind=engine)
|
||||
|
||||
|
||||
# ------------------------------------------------- the real construction path
|
||||
|
||||
def test_the_summary_provider_is_built_from_the_configured_values(settings):
|
||||
"""Every value the summariser needs reaches the provider that uses it."""
|
||||
provider = memorybank.summary_provider(settings)
|
||||
|
||||
assert isinstance(provider, OpenAICompatibleProvider)
|
||||
assert provider.base_url == "http://127.0.0.1:11434/v1"
|
||||
assert provider.model == "summariser-model"
|
||||
assert provider.api_mode == "chat"
|
||||
assert provider.read_timeout == 123
|
||||
|
||||
|
||||
def test_the_summary_provider_falls_back_to_the_narrator_model(settings):
|
||||
"""An empty summary model means "use the main one", not "use nothing"."""
|
||||
settings.summary_model = ""
|
||||
assert memorybank.summary_provider(settings).model == "narrator-model"
|
||||
|
||||
|
||||
def test_the_embedding_provider_is_built_from_the_configured_values(settings):
|
||||
provider = memorybank.embedding_provider(settings)
|
||||
|
||||
assert isinstance(provider, OpenAICompatibleProvider)
|
||||
assert provider.base_url == "http://127.0.0.1:11434/v1"
|
||||
assert provider.model == "embedding-model"
|
||||
|
||||
|
||||
def test_the_narrator_provider_is_built_from_the_configured_values(settings):
|
||||
"""The turn path builds its own provider; the same values have to reach it."""
|
||||
provider = OpenAICompatibleProvider(
|
||||
settings.endpoint_url, settings.model, settings.api_mode,
|
||||
settings.model_timeout_seconds,
|
||||
)
|
||||
assert provider.base_url == "http://127.0.0.1:11434/v1"
|
||||
assert provider.model == "narrator-model"
|
||||
assert provider.api_mode == "chat"
|
||||
assert provider.read_timeout == 123
|
||||
|
||||
|
||||
@pytest.mark.parametrize("attribute", [
|
||||
"endpoint_url", "model", "summary_model", "embedding_model", "api_mode",
|
||||
"model_timeout_seconds", "max_output_tokens", "context_token_budget",
|
||||
])
|
||||
def test_every_settings_attribute_the_providers_read_still_exists(settings, attribute):
|
||||
"""The named guard against M2's failure.
|
||||
|
||||
Each attribute here is one a factory or the context builder reads. If a
|
||||
migration renames one, this fails by name instead of the memory bank dying
|
||||
in a task nobody is watching.
|
||||
"""
|
||||
assert hasattr(settings, attribute), (
|
||||
f"Settings.{attribute} is gone; something that builds a provider reads it"
|
||||
)
|
||||
|
||||
|
||||
def test_building_a_provider_makes_no_request(settings):
|
||||
"""Construction is inert, so these tests are safe to run offline."""
|
||||
import socket
|
||||
|
||||
def refuse(*args, **kwargs): # pragma: no cover - only runs on a failure
|
||||
raise AssertionError("provider construction opened a socket")
|
||||
|
||||
real = socket.socket.connect
|
||||
socket.socket.connect = refuse
|
||||
try:
|
||||
memorybank.summary_provider(settings)
|
||||
memorybank.embedding_provider(settings)
|
||||
finally:
|
||||
socket.socket.connect = real
|
||||
|
||||
|
||||
# ------------------------------------------------------- the endpoint policy
|
||||
|
||||
def test_the_embedding_path_enforces_the_same_endpoint_policy(settings):
|
||||
"""M6 section 18. Embedding inputs are story text, and they go to the same
|
||||
kind of endpoint under the same rule as a narrator prompt.
|
||||
|
||||
Asserted through the real `embed()` rather than by reading the source: a
|
||||
check that exists but is not reached would pass a source inspection.
|
||||
"""
|
||||
import asyncio
|
||||
|
||||
provider = OpenAICompatibleProvider("https://api.openai.com/v1", "embedding-model")
|
||||
with pytest.raises(ProviderError) as exc:
|
||||
asyncio.run(provider.embed(["a line of someone's story"]))
|
||||
assert "can't be used" in str(exc.value)
|
||||
|
||||
|
||||
def test_the_policy_refuses_a_public_address_for_embeddings():
|
||||
"""The rule is the address, not the name of the caller."""
|
||||
assert endpoints.rejection_reason("https://api.openai.com/v1/embeddings")
|
||||
assert endpoints.rejection_reason("http://8.8.8.8:11434/v1/embeddings")
|
||||
# And permits the local endpoints the product is built for.
|
||||
assert endpoints.rejection_reason("http://127.0.0.1:11434/v1/embeddings") is None
|
||||
|
||||
|
||||
def test_no_cloud_or_remote_vector_service_is_configured_anywhere():
|
||||
"""M6 section 18: no new network path. Checked against the source, because
|
||||
the point is that no such code exists to be exercised."""
|
||||
import pathlib
|
||||
|
||||
forbidden = (
|
||||
"api.openai.com", "api.anthropic.com", "pinecone", "weaviate",
|
||||
"qdrant", "chromadb", "cohere.ai", "huggingface.co/api",
|
||||
)
|
||||
root = pathlib.Path(__file__).resolve().parent.parent / "app"
|
||||
offenders = []
|
||||
for path in root.rglob("*.py"):
|
||||
text = path.read_text()
|
||||
for needle in forbidden:
|
||||
# `endpoints.py` names cloud hosts in order to refuse them.
|
||||
if needle in text and path.name != "endpoints.py":
|
||||
offenders.append(f"{path.name}: {needle}")
|
||||
assert not offenders, offenders
|
||||
|
||||
|
||||
# ------------------------------------------------- the live endpoint, if any
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not os.environ.get("AIDND_TEST_ENDPOINT"),
|
||||
reason="set AIDND_TEST_ENDPOINT and AIDND_TEST_MODEL to run against a real model",
|
||||
)
|
||||
def test_the_real_construction_path_reaches_a_real_endpoint():
|
||||
"""The wiring test with the network attached.
|
||||
|
||||
Reported separately from the tests above: this one proves the constructed
|
||||
provider can actually talk to the configured endpoint, which is the half a
|
||||
unit test cannot show. It uses the ordinary endpoint policy — no TLS
|
||||
weakening, no allowlist bypass.
|
||||
"""
|
||||
import asyncio
|
||||
|
||||
endpoint = os.environ["AIDND_TEST_ENDPOINT"]
|
||||
model = os.environ.get("AIDND_TEST_EMBED_MODEL", "nomic-embed-text")
|
||||
assert endpoints.rejection_reason(endpoint) is None, (
|
||||
"the configured test endpoint is refused by the policy"
|
||||
)
|
||||
Base.metadata.create_all(bind=engine)
|
||||
db = SessionLocal()
|
||||
try:
|
||||
user = models.User(is_guest=False, email="live@example.com")
|
||||
db.add(user)
|
||||
db.flush()
|
||||
row = models.Settings(
|
||||
user_id=user.id, api_key="enc:dummy", endpoint_url=endpoint,
|
||||
model=os.environ.get("AIDND_TEST_MODEL", ""), embedding_model=model,
|
||||
)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
provider = memorybank.embedding_provider(row)
|
||||
vectors = asyncio.run(provider.embed(["Aldric hid the ledger."]))
|
||||
finally:
|
||||
db.close()
|
||||
Base.metadata.drop_all(bind=engine)
|
||||
|
||||
assert len(vectors) == 1
|
||||
assert len(vectors[0]) > 8, "the endpoint returned no usable vector"
|
||||
@@ -126,6 +126,7 @@ def pre_tree():
|
||||
# another table still points at. Any future table that references these
|
||||
# has to be added to the front of this list.
|
||||
for table in ("state_events", "state_proposals", "checkpoints",
|
||||
"summaries", "derived_status",
|
||||
"actions", "memories", "branches", "adventures"):
|
||||
conn.execute(text(f"DROP TABLE IF EXISTS {table}"))
|
||||
for ddl in PRE_TREE_DDL:
|
||||
@@ -600,6 +601,7 @@ def pre_split():
|
||||
Base.metadata.create_all(bind=engine)
|
||||
with engine.begin() as conn:
|
||||
for table in ("state_events", "state_proposals", "checkpoints",
|
||||
"summaries", "derived_status",
|
||||
"actions", "memories", "branches", "adventures"):
|
||||
conn.execute(text(f"DROP TABLE IF EXISTS {table}"))
|
||||
for ddl in PRE_TREE_DDL:
|
||||
|
||||
Reference in New Issue
Block a user