The release-validation milestone, and the thing it had to settle first was whether any of the earlier evidence meant what it said. M8 measured a deployment enforcing a 4,096-token input window while the application budgeted 16,384. Every request returned 200. What Ollama does with the excess is drop the oldest tokens, and the oldest tokens here are the system block — the narrator's rules and the campaign canon. A hundred-turn certification against that server would have looked perfect and proved nothing, which is why this milestone could not begin with a hundred turns. So the application asks now. Ollama's window is a property of how a model was loaded rather than of the request — sending num_ctx is accepted, ignored, and worse, reloads the model at the server's own default — so the only honest move is to find out and then tell the truth about it. /api/ps reports what a resident model is being served with, /api/show what an unloaded one will load with, both on the same host inference already uses, through the same endpoint policy and the same TLS trust store. A verified window is a ceiling on the budget; an unverified one leaves the budget alone and is recorded as unverified in the turn's own provenance, so an old turn can be asked afterwards whether it was built against a checked window. There is no third behaviour, and in particular no hard-coded 4,096: a number the server did not say would be right on one machine and wrong on the next. The proof that this is doing something is a campaign whose canon sits at the front of the prompt, 120 turns of history, and a 4,096-token window. The canon is still there afterwards and the oldest history is gone. The same campaign built the old way produces a prompt more than twice the window — the defect, reproduced, so the fix is measured against it rather than asserted. Two defects the validation found on its own, and they are the same defect twice: something was true and nobody was told. A manual state correction of four changes with one bad reference applied three, returned 201, and said nothing — while recording the refusal on the audit row nobody reads. It came to light because the identity diagnostic's own fixture was refused that way and the whole run proceeded on a campaign with no scene, which would have read as a model failure. And the narration-length setting moved no number: brief, medium and long each became one English sentence, while the numeric hint the model actually reads was derived from the global reply cap and said the same thing for all three. Both now say what they did. The other two post-M8 findings are closed as well. The tab said AI D&D, which no document had ever claimed it did not; it says Interactive Story now, with the open campaign first, and the name is the owner's decision rather than a find-and-replace to something narrower than the engine. After an Undo the reader could not tell where they had landed; the control row now ends with "Moment 11 · later story ahead", from the server's own answer, in the word the transcript already uses, with none of head, branch or depth anywhere near it. The identity diagnostic exists and the root cause does not. That campaign was destroyed, so no cause can be established — what M11 owes the finding is something that can classify the next occurrence, and a diagnostic that makes only the judgements a program can honestly make: duplicate keys, shared names, protagonist drift, state and context disagreeing. Whether prose misattributed a line is left to a person reading it beside its prompt, because a regex cannot read dialogue and one that pretended to would produce exactly the confident wrong answer this finding is about. Its detectors are proved to fire against a planted second Alice. Two entities may still share a display name. That was checked first, as the finding asked, and left permitted: a mother and a daughter, or a stranger giving a false name, are ordinary fiction, and refusing them to guard against a model mistake would refuse the wrong thing. What was missing was that it happened silently. It is reported now. Evidence, not inference: a hundred accepted turns against a real narrator with genuine process restarts; a real browser against the built SPA; a container with no network at all; a campaign moved into a data directory that never existed. Each was discarded and re-run whenever the product changed under it, and the runs that were thrown away are listed in the report with the reason, along with ten defects in the harnesses themselves — because a harness that has only ever agreed with itself is not evidence, and two of M8's five harness defects were masking real ones. No dependency was added, removed or upgraded. No acceptance test was retired, relaxed or reclassified. M11 is implemented and verified; it is not accepted, and there is no release tag. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Qyn3oRd4D6pi72nKBG725B
249 lines
11 KiB
Python
249 lines
11 KiB
Python
"""The model settings, and the connection test that tells you why they don't work.
|
|
|
|
There is one settings row, belonging to the one local user. It describes an
|
|
Ollama: where it is, which model to narrate with, which to embed with, and how
|
|
long to wait for it.
|
|
|
|
Upstream let this row name any OpenAI-compatible endpoint and carry an
|
|
encrypted API key for it. M2 narrowed both: `endpoints.py` decides which
|
|
addresses may be named, and there is no key field, because Ollama does not use
|
|
one and this build has no cloud provider to carry a key for.
|
|
"""
|
|
|
|
import httpx
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
from starlette.concurrency import run_in_threadpool
|
|
|
|
from .. import auth, contextwindow, endpoints, models, schemas, tlstrust
|
|
from ..database import get_db
|
|
from ..providers.openai_compatible import CONNECT_TIMEOUT
|
|
|
|
router = APIRouter(prefix="/api/settings", tags=["settings"])
|
|
|
|
#: The connection test is a listing, not a generation, so it never waits on a
|
|
#: model load and does not need the turn engine's patience.
|
|
TEST_TIMEOUT = 15.0
|
|
|
|
|
|
def get_settings(db: Session, user: models.User) -> models.Settings:
|
|
"""Returns the settings row, creating it on first access."""
|
|
settings = (
|
|
db.query(models.Settings).filter(models.Settings.user_id == user.id).first()
|
|
)
|
|
if settings is None:
|
|
settings = models.Settings(user_id=user.id)
|
|
db.add(settings)
|
|
db.commit()
|
|
return settings
|
|
|
|
|
|
@router.get("", response_model=schemas.SettingsOut)
|
|
def read_settings(
|
|
db: Session = Depends(get_db),
|
|
user: models.User = Depends(auth.get_current_user),
|
|
):
|
|
return get_settings(db, user)
|
|
|
|
|
|
@router.put("", response_model=schemas.SettingsOut)
|
|
async def update_settings(
|
|
payload: schemas.SettingsUpdate,
|
|
db: Session = Depends(get_db),
|
|
user: models.User = Depends(auth.get_current_user),
|
|
):
|
|
settings = get_settings(db, user)
|
|
fields = payload.model_dump(exclude_unset=True)
|
|
|
|
if "endpoint_url" in fields:
|
|
# Refused here so the user finds out while they are looking at the
|
|
# field, rather than on their next turn. The provider re-checks before
|
|
# every request regardless; this is the friendly half of the same rule.
|
|
reason = await run_in_threadpool(
|
|
endpoints.rejection_reason, fields["endpoint_url"]
|
|
)
|
|
if reason is not None:
|
|
raise HTTPException(400, f"That endpoint can't be used — {reason}.")
|
|
|
|
if any(
|
|
field in fields and fields[field] != getattr(settings, field)
|
|
for field in ("endpoint_url", "model")
|
|
):
|
|
# M11: a different server or a different model is a different window.
|
|
# What was verified about the old pair says nothing about the new one,
|
|
# and a stale ceiling is the one thing this must never apply.
|
|
contextwindow.cache_clear()
|
|
|
|
embedding_model_changed = (
|
|
"embedding_model" in fields
|
|
and fields["embedding_model"] != settings.embedding_model
|
|
)
|
|
for field, value in fields.items():
|
|
setattr(settings, field, value)
|
|
if embedding_model_changed:
|
|
# Vectors from the old model have a different dimensionality/space;
|
|
# clear them so the post-turn task re-embeds with the new model.
|
|
#
|
|
# Both columns, and the flag. This is the one place that clears vectors
|
|
# in bulk rather than through memorybank.set_vector, and when the
|
|
# vectors moved to embedding_blob it kept nulling the old JSON column
|
|
# alone. The blob survived, `embedded` stayed true, and
|
|
# `_embed_pending`, which selects rows where `embedded IS FALSE`, never
|
|
# found the rows. The bank kept ranking against the previous model's
|
|
# vectors.
|
|
owned = (
|
|
db.query(models.Adventure.id)
|
|
.filter(models.Adventure.user_id == user.id)
|
|
.scalar_subquery()
|
|
)
|
|
db.query(models.Memory).filter(models.Memory.adventure_id.in_(owned)).update(
|
|
{"embedding_blob": None, "embedded": False}, synchronize_session=False
|
|
)
|
|
# No cache invalidation needed, and deliberately none added: clearing
|
|
# `embedded` drops these rows out of the catalogue query, so retrieval
|
|
# stops asking for them, and by the time _embed_pending puts one back
|
|
# it has gone through set_vector, which evicts that entry. The rule
|
|
# holds: anything that removes a memory from play corrects itself.
|
|
db.commit()
|
|
return settings
|
|
|
|
|
|
async def list_endpoint_models(endpoint_url: str) -> dict:
|
|
"""Fetches the endpoint's `/models` listing, and doubles as the connection test.
|
|
|
|
Returns `{"ok": False, "detail": ...}` rather than raising, because every
|
|
caller wants to show the reason rather than fail the page.
|
|
|
|
The failure cases are told apart on purpose. "Ollama isn't running", "that
|
|
address isn't allowed", "the certificate doesn't verify" and "it answered,
|
|
but with an error" need four different things done about them, and a single
|
|
"connection failed" leaves the user guessing which they have.
|
|
"""
|
|
reason = await run_in_threadpool(endpoints.rejection_reason, endpoint_url)
|
|
if reason is not None:
|
|
return {
|
|
"ok": False, "kind": "rejected",
|
|
"detail": f"That endpoint can't be used — {reason}.",
|
|
}
|
|
|
|
url = endpoint_url.rstrip("/") + "/models"
|
|
try:
|
|
async with httpx.AsyncClient(
|
|
timeout=httpx.Timeout(TEST_TIMEOUT, connect=CONNECT_TIMEOUT),
|
|
verify=tlstrust.ssl_context(),
|
|
) as client:
|
|
resp = await client.get(url)
|
|
except httpx.ConnectError as exc:
|
|
# A TLS failure arrives as a ConnectError too, and it needs a different
|
|
# answer from "nothing is listening": install the CA, don't start Ollama.
|
|
if "CERTIFICATE_VERIFY" in str(exc).upper() or "SSL" in str(exc).upper():
|
|
return {
|
|
"ok": False, "kind": "tls",
|
|
"detail": (
|
|
"The endpoint's TLS certificate could not be verified. If it "
|
|
"uses a private or self-signed CA, install that CA on this "
|
|
"machine so the system trusts it. Certificate checking is "
|
|
"not optional."
|
|
),
|
|
}
|
|
return {
|
|
"ok": False, "kind": "unreachable",
|
|
"detail": f"Could not connect to {endpoint_url} — is Ollama running there?",
|
|
}
|
|
except httpx.TimeoutException:
|
|
return {
|
|
"ok": False, "kind": "timeout",
|
|
"detail": f"{endpoint_url} did not answer within {TEST_TIMEOUT:.0f}s.",
|
|
}
|
|
except httpx.HTTPError as exc:
|
|
return {"ok": False, "kind": "error", "detail": f"Connection failed: {exc}"}
|
|
|
|
if resp.status_code != 200:
|
|
return {
|
|
"ok": False, "kind": "http",
|
|
"detail": f"HTTP {resp.status_code}: {resp.text[:300]}",
|
|
}
|
|
|
|
models_available: list[str] = []
|
|
try:
|
|
data = resp.json()
|
|
models_available = [m.get("id", "?") for m in data.get("data", [])]
|
|
except (ValueError, AttributeError, TypeError):
|
|
pass # The body is not JSON or has an unexpected shape. The endpoint
|
|
# is still reachable.
|
|
return {"ok": True, "models": models_available}
|
|
|
|
|
|
def _window_warning(window: contextwindow.Window, settings: models.Settings) -> str | None:
|
|
"""What to tell the reader about the window, or None when nothing is wrong.
|
|
|
|
Three cases, and they need three different things done about them, so they
|
|
say three different things (the same reasoning as the connection test's own
|
|
four failure kinds).
|
|
"""
|
|
budget = settings.context_token_budget
|
|
if not window.verified:
|
|
return (
|
|
f"The context window this server will give '{settings.model}' could not "
|
|
f"be checked — {window.detail}. The story budget is {budget:,} tokens; "
|
|
"if the server's window is smaller than that it silently drops the "
|
|
"oldest part of the prompt, which here is the narrator's rules and the "
|
|
"campaign canon. See DEVELOPMENT.md, 'The context window your Ollama "
|
|
"actually enforces'."
|
|
)
|
|
if window.tokens < budget:
|
|
ceiling = (
|
|
f" The model itself can go up to {window.model_max:,}."
|
|
if window.model_max and window.model_max > window.tokens else ""
|
|
)
|
|
return (
|
|
f"This server gives '{settings.model}' {window.tokens:,} tokens, which is "
|
|
f"less than the {budget:,}-token story budget. Prompts are being built to "
|
|
f"{window.tokens:,} so nothing is silently truncated — the campaign simply "
|
|
f"gets less history than the setting asks for.{ceiling} To use the whole "
|
|
"budget, load the model with a larger window (DEVELOPMENT.md)."
|
|
)
|
|
return None
|
|
|
|
|
|
@router.post("/test")
|
|
async def test_connection(
|
|
db: Session = Depends(get_db),
|
|
user: models.User = Depends(auth.get_current_user),
|
|
):
|
|
"""Checks the endpoint the turn engine would use, and lists its models."""
|
|
settings = get_settings(db, user)
|
|
result = await list_endpoint_models(settings.endpoint_url)
|
|
if result.get("ok") and settings.model:
|
|
# M11: while we have the server's attention, ask what window it will
|
|
# give this model. This is where a reader can act on the answer — the
|
|
# model picker is on the same screen as the budget — and it is the
|
|
# difference between "your prompts are being truncated" being visible
|
|
# here and being invisible until the narrator forgets the canon.
|
|
# Cached, deliberately. The model-status badge calls this endpoint on
|
|
# every page load, so an uncached probe would be two extra requests to
|
|
# the inference host per page view for an answer that changes only when
|
|
# an operator reloads a model. Changing the endpoint or the model clears
|
|
# the cache (`update_settings`), which covers the case a reader can
|
|
# actually cause; the detail line always says where the number came from.
|
|
window = await contextwindow.probe(settings.endpoint_url, settings.model)
|
|
result = result | {"window": {
|
|
"verified": window.verified,
|
|
"tokens": window.tokens,
|
|
"source": window.source,
|
|
"model_max": window.model_max,
|
|
"detail": window.detail,
|
|
"budget": settings.context_token_budget,
|
|
"warning": _window_warning(window, settings),
|
|
}}
|
|
if result.get("ok") and settings.model and settings.model not in result["models"]:
|
|
# Reachable, but pointed at a model that is not installed there — the
|
|
# commonest way for a correct endpoint to still fail every turn.
|
|
return result | {
|
|
"warning": (
|
|
f"{settings.endpoint_url} is reachable, but has no model named "
|
|
f"'{settings.model}'. Pull it there, or pick one from the list."
|
|
)
|
|
}
|
|
return result
|