Something can happen because time passed, and land somewhere worth reading

Nothing in LLeMbas ever happened on its own. Every reply was downstream of
somebody pressing Send, and the one exception -- jobs.wake, waking a chat when a
background job finishes -- was downstream of a command they had run. PLAN.md
never listed scheduling as unbuilt because services/chat.py:618 had recorded it
as a decision: "a scheduler is a whole new concern for a single-worker
application". This is that concern, taken on deliberately, plus the two places
its output goes.

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jaroslav Beneš
2026-08-05 21:31:36 +02:00
parent 178742501d
commit 9ddc0a2103
63 changed files with 6773 additions and 67 deletions
+273
View File
@@ -0,0 +1,273 @@
"""Messages: one conversation that never ends, and a request that must.
The failure this file mostly guards against is not visible on screen at all —
a conversation whose request grows with it until the endpoint refuses, which is
what `_too_big` exists for elsewhere and what the live chunk prevents here.
The rest is the cursor, which has the same four traps as `thread_tail` going the
other way. A message that cannot be scrolled back to is a message that is gone.
"""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import select
from lembas.db.models import KIND_MESSAGES, Chat, Message, User
from lembas.services import messages as messages_service
@pytest.fixture(autouse=True)
def a_model_exists(db, registered):
"""Not scaffolding.
`for_user` seeds the conversation from `default_model`, which answers with a
*pair* — and with no model configured it answers None, so the whole of that
path is skipped and a bug in it cannot be seen. It was: the pair was
assigned straight to `model_id`, SQLite refused a tuple in a String column,
and every one of these tests passed anyway.
"""
from lembas.db.models import Connection, Model
from lembas.services.crypto import encrypt
connection = Connection(
name="Test", base_url="http://127.0.0.1:1", api_key_encrypted=encrypt("")
)
db.add(connection)
db.commit()
db.add(Model(connection_id=connection.id, model_id="test-model"))
db.commit()
return None
def _user(db) -> User:
return db.scalars(select(User).order_by(User.created_at)).first()
def _fill(db, chat: Chat, count: int, *, day: int = 1) -> list[Message]:
"""`count` alternating turns, a minute apart so the order is unambiguous."""
start = datetime(2026, 1, day, tzinfo=UTC)
rows = []
for index in range(count):
rows.append(
Message(
chat_id=chat.id,
role="user" if index % 2 == 0 else "assistant",
content=f"turn {index}",
created_at=start + timedelta(minutes=index),
complete=True,
)
)
db.add_all(rows)
db.commit()
return rows
# --- The conversation itself ------------------------------------------------------
def test_there_is_exactly_one_per_person(client: TestClient, db, registered):
"""Get-or-create, so a schedule can post here before anybody has opened the
page — the second deliberate exception to "chats are created lazily"."""
first = messages_service.for_user(db, _user(db))
second = messages_service.for_user(db, _user(db))
assert first.id == second.id
assert first.kind == KIND_MESSAGES
assert len(db.scalars(select(Chat).where(Chat.kind == KIND_MESSAGES)).all()) == 1
def test_it_is_not_in_the_chat_tree(client: TestClient, db, registered):
"""It has a section of its own. This is the kind-leakage trap again, from
the other side."""
from lembas.api.pages import sidebar_context
conversation = messages_service.for_user(db, _user(db))
listed = {c.id for c in sidebar_context(db, _user(db))["unfiled_chats"]}
assert conversation.id not in listed
# --- What reaches the model -------------------------------------------------------
def test_the_request_does_not_grow_with_the_conversation(
client: TestClient, db, registered
):
"""The whole point. A conversation meant to run for years cannot all be
sent, and a request that grows until the endpoint refuses it is the failure
nobody sees coming — there is nothing wrong on screen right up until it
stops working.
"""
from lembas.services import chat as chat_service
conversation = messages_service.for_user(db, _user(db))
_fill(db, conversation, 10)
short = chat_service.build_messages(db, conversation)
_fill(db, conversation, 300)
long = chat_service.build_messages(db, conversation)
assert len(short) == 10
assert len(long) == messages_service.LIVE_CHUNK
assert len(long) < len(short) + 300
def test_it_is_the_most_recent_turns_that_are_sent(client: TestClient, db, registered):
from lembas.services import chat as chat_service
conversation = messages_service.for_user(db, _user(db))
_fill(db, conversation, messages_service.LIVE_CHUNK + 20)
payload = chat_service.build_messages(db, conversation)
bodies = [entry["content"] for entry in payload]
assert bodies[-1] == f"turn {messages_service.LIVE_CHUNK + 19}"
assert "turn 0" not in bodies
def test_an_ordinary_chat_still_sends_everything(client: TestClient, db, registered):
"""The bound is one branch on one kind. A chat is not silently truncated."""
from lembas.services import chat as chat_service
ordinary = Chat(user_id=_user(db).id, model_id="m")
db.add(ordinary)
db.commit()
_fill(db, ordinary, messages_service.LIVE_CHUNK + 20)
assert len(chat_service.build_messages(db, ordinary)) == messages_service.LIVE_CHUNK + 20
def test_compaction_never_fires_on_it(client: TestClient, db, registered):
"""Two mechanisms narrowing one transcript is how a summary ends up
summarising a summary — and this one would be summarising turns that are
already outside the request."""
from lembas.services import compaction as compaction_service
conversation = messages_service.for_user(db, _user(db))
_fill(db, conversation, 200)
assert compaction_service.should_compact(db, conversation) is False
# --- Nothing is lost ---------------------------------------------------------------
def test_every_turn_is_kept_however_old(client: TestClient, db, registered):
"""Bounded in the request, unbounded on disk. Deliberately not folded into
text: the visible conversation would be identical either way, so the only
thing destroying the rows would buy is disk — against irreversibility."""
conversation = messages_service.for_user(db, _user(db))
_fill(db, conversation, 250)
assert messages_service.count(db, conversation) == 250
# --- Reading backwards --------------------------------------------------------------
def test_the_page_opens_on_the_latest_chunk(client: TestClient, db, registered):
conversation = messages_service.for_user(db, _user(db))
_fill(db, conversation, 120)
body = client.get("/messages").text
assert "turn 119" in body
assert "turn 0" not in body
assert "history-sentinel" in body
def test_a_short_conversation_has_no_sentinel(client: TestClient, db, registered):
conversation = messages_service.for_user(db, _user(db))
_fill(db, conversation, 5)
assert "history-sentinel" not in client.get("/messages").text
def test_scrolling_up_returns_the_page_before(client: TestClient, db, registered):
conversation = messages_service.for_user(db, _user(db))
rows = _fill(db, conversation, 200)
oldest_shown = rows[-messages_service.LIVE_CHUNK]
response = client.get(f"/api/messages/history?before={oldest_shown.id}")
assert response.status_code == 200
assert f"turn {200 - messages_service.LIVE_CHUNK - 1}" in response.text
# The turn it was asked to go before is not repeated.
assert f">turn {200 - messages_service.LIVE_CHUNK}<" not in response.text
def test_a_cursor_it_cannot_place_is_answered_with_204(
client: TestClient, db, registered
):
"""Never with "the oldest page": that would prepend a block the reader is
already looking at, and a duplicated transcript is something only a reload
can reconcile."""
conversation = messages_service.for_user(db, _user(db))
_fill(db, conversation, 100)
other = Chat(user_id=_user(db).id, model_id="m")
db.add(other)
db.commit()
stray = Message(chat_id=other.id, role="user", content="elsewhere")
db.add(stray)
db.commit()
assert client.get("/api/messages/history").status_code == 204
assert client.get("/api/messages/history?before=nope").status_code == 204
assert client.get(f"/api/messages/history?before={stray.id}").status_code == 204
def test_the_oldest_page_stops_rather_than_looping(client: TestClient, db, registered):
conversation = messages_service.for_user(db, _user(db))
rows = _fill(db, conversation, 3)
response = client.get(f"/api/messages/history?before={rows[0].id}")
assert response.status_code == 204
def test_two_turns_sharing_a_timestamp_are_each_returned_once(
client: TestClient, db, registered
):
"""The `id` tie-breaker. Under a bare `<`, a row sharing the cursor's
microsecond can never be reached — and a message that cannot be scrolled
back to is a message that is gone."""
conversation = messages_service.for_user(db, _user(db))
stamp = datetime(2026, 1, 1, tzinfo=UTC)
twins = [
Message(chat_id=conversation.id, role="user", content=f"same {i}", created_at=stamp)
for i in range(2)
]
db.add_all(twins)
db.commit()
# A later day, so the cursor is unambiguously after both twins -- otherwise
# the cursor shares their stamp and the test is about id ordering, which is
# random, rather than about the tie-breaker.
later = _fill(db, conversation, 2, day=2)
page = messages_service.older_than(db, conversation, later[0])
assert {m.content for m in page} == {"same 0", "same 1"}
def test_the_sentinel_names_its_own_target(client: TestClient, db, registered):
"""It sits on a page whose composer form carries `hx-target="#thread"`, and
htmx resolves that by walking up the DOM. The jobs chip demonstrated once
what an unstated target does to a transcript."""
conversation = messages_service.for_user(db, _user(db))
_fill(db, conversation, 120)
body = client.get("/messages").text
sentinel = next(chunk for chunk in body.split("<div") if "history-sentinel" in chunk)
assert 'hx-target="this"' in sentinel
assert 'hx-swap="outerHTML"' in sentinel
# And it is outside the composer's form, which is the other half of the same
# lesson: a descendant that fetches inherits the form's target.
assert body.index("history-sentinel") < body.index("composer__form")
def test_the_scroll_anchor_is_wired_up(client: TestClient, db, registered):
"""Prepending moves everything down by the height of what arrived, so
without this the reader is dragged up the page the instant the sentinel
fires — which reads as a browser bug rather than a feature."""
from pathlib import Path
source = Path("src/lembas/web/static/js/app.js").read_text()
assert "history-sentinel" in source
assert "htmx:beforeSwap" in source
assert "scrollHeight - heightBefore" in source