Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 64 additions & 31 deletions src/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
import secrets
import time
import tomllib
from collections import OrderedDict
from contextlib import contextmanager
from functools import lru_cache
from pathlib import Path

import orjson
Expand Down Expand Up @@ -650,9 +650,14 @@ def _size(n: int) -> str:


# Keyed by limit, because the limit changes how much work the walk does and therefore what
# the answer contains. Bounded by construction: _cursor clamps to 0..MAX_LIMIT, so this
# holds at most a couple of hundred entries even if every caller asks for a different one.
_rooms_cache: OrderedDict[int, tuple[tuple, float, dict]] = OrderedDict()
# the answer contains — and by the stamp and the time bucket that say whether an entry is
# still good, because an entry that is no longer valid is not one to find and invalidate,
# it is a key nobody asks for (see _rooms_stamp, and store._time_bucket for the clock half).
#
# The limit alone was bounded by construction — _cursor clamps to 0..MAX_LIMIT — but the
# stamp and the bucket both turn over, so the key space is now open and the LRU bound is
# what closes it: at most MAX_ROOMS_CACHE walks, live and superseded mixed, and never more.
# A superseded entry is not evicted when its stamp moves, it just stops being looked up.
MAX_ROOMS_CACHE = 64


Expand All @@ -670,11 +675,18 @@ def _rooms_stamp() -> tuple:
This is what makes the cache correct rather than merely quick, and the ordering is the
whole argument: store.append, the create path and the reaper all bump these counters
*after* the record is on disk (or gone from it), so a stamp read before the walk can
never be newer than the data the walk sees. A stale entry is therefore always detected,
never be newer than the data the walk sees. A stale view is therefore never served,
whatever order two concurrent requests interleaved in — a /rooms request that walks the
pre-write state while a writer is still in fsync, the reaper or the create lock caches
that view under the *old* stamp and the next request rejects it. Nothing has to
invalidate anything for that to hold, which is why it survives a second worker.
that view under the *old* stamp, and the stamp is part of the cache key, so a request
that reads the new stamp is not looking it up. It does not have to be found and
rejected: it is simply not on the way to any later answer. Nothing has to invalidate
anything for that to hold, which is why it survives a second worker — and it is why
this is now the whole mechanism rather than half of one. Keying on the stamp instead of
storing it beside the value is also what leaves no read-then-validate window between
finding an entry and using it, so there is nothing here for a concurrent eviction to
race (the bug class of #376/#229). What it costs is that a superseded entry is not
reclaimed when its stamp moves; MAX_ROOMS_CACHE is what bounds that.

That argument holds for every key here, and `messages` is deliberately not one of them.
It is a single global lifetime counter, not per-room, so one message anywhere aged out
Expand All @@ -699,8 +711,11 @@ def _rooms_stamp() -> tuple:

The clock is also the backstop under a lying stamp. `_bump` is best effort by design —
an unwritable .counters must never fail a write that already landed — so a bump can go
missing, and a hit needs the stamp to match AND the entry to be inside the window. A
lost bump therefore costs at most one window, never a permanently stale listing.
missing, and a hit needs the stamp to match AND the time bucket to match — both of them
key material, so a miss on either is a miss. A lost bump therefore costs at most one
window, never a permanently stale listing. See store._time_bucket for why cutting the
window on a boundary can only expire an entry sooner than its own insertion would have,
which is the direction that keeps this docstring's promise rather than weakening it.
"""
counted = store.counters(config.ROOT)
# ROOT rides along for the reason _note_stats_cache stamps it: the entries are keyed by
Expand Down Expand Up @@ -735,19 +750,13 @@ def _note_stats() -> dict:
return view


def _rooms_view(limit: int) -> dict:
"""The /rooms payload for `limit`, from cache when one is both fresh and still valid.
def _rooms_payload(limit: int) -> dict:
"""The /rooms walk for `limit`, uncached — everything a cache entry is made of.

Deliberately caching the *store walk* and not the rendered response: the text and JSON
renderings differ, and the budget footer is per-caller, so a response cache would have
to key on both and would still be wrong for the footer.
Split out so the cache is one decorator and the disabled path is one call: with
ROOMS_CACHE_SECONDS at 0 this runs and nothing is stored, which is the same "no reuse"
the old guarded read/insert pair gave and is now unmistakable at a glance.
"""
now = time.monotonic()
stamp = _rooms_stamp() # before the walk, never after — see _rooms_stamp
if config.ROOMS_CACHE_SECONDS > 0:
hit = _rooms_cache.get(limit)
if hit and hit[0] == stamp and now - hit[1] < config.ROOMS_CACHE_SECONDS:
return hit[2]
view = store.room_stats(config.ROOT, limit=limit)
# Notes had no capacity surface at all: /kv/<ns> lists one namespace and namespaces are
# unenumerable by design, so nothing showed how full the global note cap was. Aggregate
Expand All @@ -764,20 +773,44 @@ def _rooms_view(limit: int) -> dict:
view["engagement"]["windowed_note_to_message_ratio"] = (
round(view["notes"]["total"] / seen, 4) if seen else None
)
if config.ROOMS_CACHE_SECONDS > 0:
# pop-then-insert, not move_to_end: assigning an existing key leaves the entry
# where it already was, which may be the front, and a concurrent evictor's popitem
# takes it from there — turning the move_to_end that used to follow into a
# KeyError. Reachable now that entries outlive a write: a caller cycling ?limit=
# keeps the cache full, so the evictor runs while another request is re-walking,
# and /rooms is sync, so two of them overlap in Starlette's threadpool.
_rooms_cache.pop(limit, None)
_rooms_cache[limit] = (stamp, now, view)
while len(_rooms_cache) > MAX_ROOMS_CACHE:
_rooms_cache.popitem(last=False)
return view


@lru_cache(maxsize=MAX_ROOMS_CACHE)
def _rooms_walk(limit: int, stamp: tuple, bucket: int) -> dict:
"""_rooms_payload under an LRU, keyed on everything that decides whether it is current.

There is no read-then-validate and no pop-then-insert here to get wrong. The pair that
used to bracket this function — a get, a stamp comparison, then a pop, an insert and an
eviction loop — was two unguarded read-modify-writes on shared state, and every fix for
them was a rearrangement of the same unguarded sequence. lru_cache is documented
threadsafe, so the bookkeeping stays coherent however Starlette's threadpool interleaves
two /rooms requests, and no part of the argument for that rests on GIL scheduling.

The dict it returns is shared by every caller that gets this entry, as it always was:
_rooms_payload finishes building it before it is stored, and `rooms` only reads it.
"""
return _rooms_payload(limit)


def _rooms_view(limit: int) -> dict:
"""The /rooms payload for `limit`, from cache when one is both fresh and still valid.

Deliberately caching the *store walk* and not the rendered response: the text and JSON
renderings differ, and the budget footer is per-caller, so a response cache would have
to key on both and would still be wrong for the footer.

Zero means no reuse, and it means it for entries already in the cache too: the knob is
read here, per call, and at zero the walk goes straight past the cache rather than
trying to expire what is in it.
"""
stamp = _rooms_stamp() # before the walk, never after — see _rooms_stamp
ttl = config.ROOMS_CACHE_SECONDS
if ttl <= 0:
return _rooms_payload(limit)
return _rooms_walk(limit, stamp, store._time_bucket(time.monotonic(), ttl))


def rooms(request: Request) -> Response:
left, retry = take(request, "read", RATE_READ)
if retry:
Expand Down
112 changes: 79 additions & 33 deletions src/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@
import tempfile
import time
import unicodedata
from collections import OrderedDict
from collections.abc import Iterator
from collections.abc import Iterator, Sequence
from contextlib import contextmanager
from datetime import UTC, datetime
from functools import lru_cache
Expand Down Expand Up @@ -974,7 +973,7 @@ def room_window(root: Path, room: str) -> tuple[int, list[str]]:
return top, nicks


def _unanswered(nicks: list[str]) -> int:
def _unanswered(nicks: Sequence[str]) -> int:
"""How many of a window's messages nobody else spoke after (`nicks` is newest-first).

A message is answered when some *later* message in the window carries a different nick.
Expand All @@ -988,7 +987,7 @@ def _unanswered(nicks: list[str]) -> int:
return run


def _engagement(nicks: list[str]) -> dict:
def _engagement(nicks: Sequence[str]) -> dict:
"""Per-room §II.2.2 aggregates over one scanned window. `window` is how many messages the
ratios are over, so a reader can tell 1.0-of-3 from 1.0-of-200."""
n = len(nicks)
Expand All @@ -1001,7 +1000,7 @@ def _engagement(nicks: list[str]) -> dict:
}


def _rollup(windows: list[list[str]]) -> dict:
def _rollup(windows: list[Sequence[str]]) -> dict:
"""Service-level §II.2.2 aggregates: one ratio pooled over every scanned window, not a mean
of per-room ratios, so a three-message room cannot outweigh a two-hundred-message one.
Nicks are pooled globally too — one bot talking to itself in forty rooms should read as low
Expand All @@ -1028,40 +1027,86 @@ def list_rooms(root: Path) -> list[str]:
return sorted(n for n in names if _listable(n))


# (top, nicks) per room, validated against the (mtime_ns, size) stat the overview walk
# already does — so a walk re-reads only the rooms a write actually changed. LRU-bounded.
def _time_bucket(now: float, ttl: float) -> int:
"""A coarse clock for a cache whose validity window is part of its key.

The memo caches here and in app.py all answer "is this entry still good?" — and the way
they answer it is to put the answer in the key: an entry that is no longer valid is not
an entry that has to be found and invalidated, it is a key nobody asks for any more.
A stamp does that for structural change; this does it for a TTL. An entry keyed on
`int(now // ttl)` is valid until the next multiple of `ttl`, so it expires at or before
`now + ttl` and never after it: an entry that carried its own expiry got the whole
window measured from its own insertion, this one gets the tail of the window it landed
in. So the published staleness bound (ROOMS_CACHE_SECONDS, NOTE_STATS_CACHE_SECONDS)
still holds — a boundary can only move an expiry earlier, which costs a walk, never
later, which would cost correctness. What it costs is that an entry made just before a
boundary is thrown away almost at once: averaged over where insertions fall, an entry
lives half a window rather than a whole one. That is why the bucket is the whole window
and not a subdivision of it — halving the hit rate is the price already paid, and a
finer bucket would only pay it again for staleness nothing here asked to be tighter.

`ttl <= 0` is not this function's case: zero means "no cache at all", which every caller
handles by bypassing its cache entirely rather than by asking for a bucket here. Passing
it would be a division by zero, and that is deliberate — a caller that reaches this with
a disabled TTL has a bug, and a silent 0 would hand it one shared eternal bucket.
"""
return int(now // ttl)


# (top, nicks) per room, keyed on the (mtime_ns, size) stat the overview walk already does —
# so a walk re-reads only the rooms a write actually changed.
#
# The stat is part of the KEY, not a stamp stored beside the value and checked against it.
# That is what retires this cache's bug class (#376, #229): there is no get-then-promote and
# no read-modify-write for a concurrent eviction to fall into, so no interleaving of two
# threadpool threads can raise, lose an update, or serve a value against the wrong stat.
# functools.lru_cache is documented threadsafe — its bookkeeping stays coherent under
# concurrent calls — and nothing here relies on GIL scheduling for that.
#
# The accepted cost: an entry whose stat is dead is never deleted, only stopped being asked
# for, so it lingers until the LRU evicts it. That is bounded by maxsize — the bound this
# cache always needed — so a churning store holds up to _WINDOW_MEMO_MAX windows, live and
# dead mixed, and never more. `root` is a str for the reason the old key stringified it: a
# Path hashes case-insensitively on some platforms, and two stores must never share an entry.
_WINDOW_MEMO_MAX = 512
_window_memo: OrderedDict[tuple, tuple] = OrderedDict()


def _cached_window(root: Path, name: str, stamp: tuple) -> tuple[int, list[str]]:
key = (str(root), name)
hit = _window_memo.get(key)
if hit and hit[0] == stamp:
_window_memo.move_to_end(key)
return hit[1]
view = room_window(root, name)
_window_memo[key] = (stamp, view)
_window_memo.move_to_end(key)
while len(_window_memo) > _WINDOW_MEMO_MAX:
_window_memo.popitem(last=False)
return view
@lru_cache(maxsize=_WINDOW_MEMO_MAX)
def _cached_window(root: str, name: str, stamp: tuple) -> tuple[int, tuple[str, ...]]:
top, nicks = room_window(Path(root), name)
# A tuple, not the list room_window builds: one entry is handed to every thread that
# asks for it and outlives all of them, so it must not be something a caller can mutate.
return top, tuple(nicks)


# Topic previews, valid while topics_written holds (bumped only by a `topic` note); reaper
# deletions age out with NOTE_STATS_CACHE_SECONDS, like the note gauge in app.py.
_topics_memo: tuple = ((), 0.0, {})
# deletions age out with NOTE_STATS_CACHE_SECONDS, like the note gauge in app.py — as a
# bucket in the key, so validity is once again the key rather than a slot to be reset.
#
# One entry per room, where this was a single dict slot shared by every caller. The slot was
# reset unconditionally by any caller whose stamp or expiry did not match, so two /rooms
# requests straddling one topic write did not merely miss each other once: each of them
# makes one lookup per shown room, and every one of those lookups reset the other's slot
# again, so neither ever hit and both re-read all ~50 topics (#515). Per-room keys under one
# LRU cannot thrash that way — a stamp the other caller is not using is a key it never
# touches — and the bound is the same order the slot held, one walk's worth of rooms.
_TOPICS_MEMO_MAX = 512


@lru_cache(maxsize=_TOPICS_MEMO_MAX)
def _topics_memo(root: str, room: str, stamp: tuple, bucket: int) -> str | None:
return topic(Path(root), room)


def _cached_topic(root: Path, room: str, stamp: tuple, now: float) -> str | None:
global _topics_memo
def _cached_topic(root: str, room: str, stamp: tuple, now: float) -> str | None:
ttl = config.NOTE_STATS_CACHE_SECONDS # per call, so 0 disables an existing entry too
if ttl <= 0 or _topics_memo[0] != stamp or now >= _topics_memo[1]:
_topics_memo = (stamp, now + ttl, {})
cache = _topics_memo[2]
if room not in cache:
cache[room] = topic(root, room)
return cache[room]
# ...and disables it by going round the cache, not by emptying it: an entry made while
# the knob was positive is never served once it is zero, which is the documented
# behaviour of reading the knob per call. Nothing is evicted for that, so flipping the
# knob back does not pay for a re-read either.
if ttl <= 0:
return topic(Path(root), room)
return _topics_memo(root, room, stamp, _time_bucket(now, ttl))


def room_stats(root: Path, limit: int = 50) -> dict:
Expand All @@ -1086,18 +1131,19 @@ def room_stats(root: Path, limit: int = 50) -> dict:
entries.sort(reverse=True)
shown = []
windows = []
topics_stamp = (counters(root)["topics_written"], str(root))
root_key = str(root) # hoisted: it is the first element of both memo keys, per room
topics_stamp = (counters(root)["topics_written"], root_key)
mono = time.monotonic()
for mtime, size, name, mtime_ns in entries[: max(1, min(int(limit), MAX_LIMIT))]:
top, nicks = _cached_window(root, name, (mtime_ns, size))
top, nicks = _cached_window(root_key, name, (mtime_ns, size))
windows.append(nicks)
shown.append(
{
"room": name,
"last_seq": top,
"bytes": size,
"idle_seconds": max(0, int(now - mtime)),
"topic": _cached_topic(root, name, topics_stamp, mono),
"topic": _cached_topic(root_key, name, topics_stamp, mono),
**_engagement(nicks),
}
)
Expand Down
16 changes: 8 additions & 8 deletions sz-baseline.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"core_total": 2240,
"core_total": 2229,
"caps": {
"core/app.py": 1017,
"core/config.py": 62,
Expand All @@ -10,10 +10,10 @@
},
"files": {
"core/app.py": {
"raw_lines": 1937,
"code_lines": 1017,
"raw_lines": 1970,
"code_lines": 1014,
"comment_lines": 270,
"tokens_per_line": 7.75
"tokens_per_line": 7.74
},
"core/config.py": {
"raw_lines": 353,
Expand All @@ -34,10 +34,10 @@
"tokens_per_line": 8.48
},
"core/store.py": {
"raw_lines": 2206,
"code_lines": 933,
"comment_lines": 474,
"tokens_per_line": 7.35
"raw_lines": 2252,
"code_lines": 925,
"comment_lines": 503,
"tokens_per_line": 7.37
},
"extra/manifest.py": {
"raw_lines": 1885,
Expand Down
22 changes: 18 additions & 4 deletions tests/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,31 @@


@pytest.fixture()
def client(tmp_path):
def client(tmp_path, monkeypatch):
"""One shared app, a fresh ROOT per test: config.override re-binds the knob (and app's
copy of it) for exactly this test, where the old fixture re-imported app against a
CHAT_ROOT env var. The limiter buckets and the /rooms cache are process state a fresh
import used to reset for free, so they are cleared here instead."""
CHAT_ROOT env var. The limiter buckets and the three memo caches behind /rooms are
process state a fresh import used to reset for free, so they are cleared here instead.

Their clock is pinned here too. Cache validity is part of the cache key now (see
store._time_bucket), so the boundary between one window and the next is a key change —
and unpinned those boundaries are cut on a free-running clock, which lands one inside
roughly one test in every ROOMS_CACHE_SECONDS of suite time. A test that pins a 60s
window "far above anything it spends" would still miss on those, for a reason no test
body could name. Anchoring the buckets to the moment the fixture ran puts a fast test
inside bucket 0 for the whole of it, and leaves a test that wants a window to pass
saying so out loud."""
import app as app_module
import config
import limit
import store

origin = time.monotonic()
monkeypatch.setattr(store, "_time_bucket", lambda now, ttl: int((now - origin) // ttl))
app_module._buckets.clear()
app_module._rooms_cache.clear()
app_module._rooms_walk.cache_clear()
store._cached_window.cache_clear()
store._topics_memo.cache_clear()
app_module._identities.clear()
app_module._proxy_evidence["proxied_requests"] = 0
# The duplicate ring is the same kind of process state the buckets are: a fresh
Expand Down
Loading