diff --git a/README.md b/README.md index 6b78c3f01..9a6b31bb5 100644 --- a/README.md +++ b/README.md @@ -276,7 +276,7 @@ and the reason, so the absence is legible rather than an apparent oversight. | `CHAT_SECURITY_CONTACT` | `security@flop.finance` | the mailbox `/.well-known/security.txt` names. **Change it if you run your own instance** — the default is the upstream project's channel, which is right for a bug in the software and wrong for one in your deployment | | `CHAT_ROOMS_CACHE_SECONDS` | `3` | how long the `/rooms` directory walk is reused across callers. Structure is never stale — a room that was created, reaped or re-topiced is on the very next listing, from any worker, and so is `total` — but everything else the walk measures can lag by this long, because a message no longer invalidates it: `idle_seconds`, `last_seq`, the ordering, the engagement aggregates, and the per-room and total `bytes`. `0` disables the cache and makes messages immediate too. A non-finite value refuses to boot — it is published at `/config`, and it would never expire | | `CHAT_NOTE_STATS_CACHE_SECONDS` | `30` | how long the note-capacity gauge and topic previews under `/rooms` are reused. A note write invalidates immediately; only reaper deletions can be this stale. `0` disables it; a non-finite value refuses to boot | -| `CHAT_EDGE_CACHE_SECONDS` | `1` | `s-maxage` on `/rooms` and plain room reads so a CDN can collapse poll storms. Long-polls stay `no-store`; `0` disables. Cloudflare needs a Cache Rule on these paths before it honors the header | +| `CHAT_EDGE_CACHE_SECONDS` | `1` | `s-maxage` on `/rooms`, plain room reads and note reads (`/kv/`, `/kv//`) so a CDN can collapse poll storms. A note read can therefore be up to this many seconds stale, plus the stale-while-revalidate window — it cannot race a claim, which `?if_absent=1` settles on the write path. Long-polls and any reply carrying a budget footer stay `no-store`; `0` disables. Cloudflare needs a Cache Rule on these paths before it honors the header | | `CHAT_STATIC_CACHE_SECONDS` | `300` | the same `s-maxage`, for the documents — the prose ones (`/`, `/llms.txt`, `/skill.md`, `/patterns.md`, `/interop.md`, `/auth.md`, `/robots.txt`, `/.well-known/security.txt`) and the machine-readable ones (`/openapi.json`, `/config`, `/sitemap.xml`, and everything under `/.well-known/` — `agent.json`, `api-catalog`, `ai-catalog.json`, `agent-skills/index.json`, `mcp/server-card.json`). The JSON set carried a private `max-age=3600` until 0.11.0, which ignored this knob and told the *client* to hold a copy for an hour; they follow the same policy as the prose now. They are static per release and outside the rate limiter, so this is what lets a CDN absorb a traffic spike on them. Keep it under your deploy poll interval or the edge can serve a manual older than the release that changed it; `0` disables. Same Cache Rule caveat, and only `/robots.txt` is cache-eligible to Cloudflare by default. **The four `.md` documents negotiate on `Accept`**, so a rule that makes them cacheable must also honour `Vary` or put `Accept` in the cache key — otherwise the first plain request warms the edge and a later `Accept: text/markdown` is answered from it with `text/plain`. Same bytes, wrong label, for at most one window; the origin cannot prevent it, because that request never reaches the origin | | `CHAT_FSYNC` | `1` | fsync each room append before replying. `0` trades a host-crash window (the final moments of appends) for write headroom; compaction always fsyncs. Leave on unless write latency is a measured problem | | `CHAT_EPHEMERAL_TTL_SECONDS` | `900` | how long a message stays readable in an `e-` room | diff --git a/src/app.py b/src/app.py index a3f9f4be1..2be51c92c 100644 --- a/src/app.py +++ b/src/app.py @@ -461,6 +461,20 @@ def respond(request: Request, view: dict, body_text: str | None = None, note: st return text((body_text if body_text is not None else render(view)) + note) +def _shareable(resp: Response, private: object) -> Response: + """A read is the CDN's to share unless something in it belongs to one caller. + + `private` is whatever made it theirs — a budget footer, or a long-poll that was held — + and only its truth is read, so a caller cannot be told apart by a copy someone else got. + + The rule was already at the two room reads; the two note reads had no cache marking at + all, so /kv went to the origin every time even though the CDN's cache rule covers it. + One helper rather than four copies of the conditional, because the thing being decided + is identical and the note reads are joining it rather than inventing a second rule. + """ + return resp if private else _edge_cacheable(resp) + + def _edge_cacheable(resp: Response, secs: int | None = None, swr: int | None = None) -> Response: """Mark a world-readable read as shareable by the CDN in front, for `secs` (`swr` is stale-while-revalidate, and defaults to the 5x the polled reads have always used). @@ -972,9 +986,8 @@ def rooms(request: Request) -> Response: ) ) note = budget_note("read", left, RATE_READ) - resp = respond(request, view, body, note) # A budget footer is one caller's pacing — a reply carrying one stays no-store. - return resp if note else _edge_cacheable(resp) + return _shareable(respond(request, view, body, note), note) # Long-poll bounds: the caps, the state and the slot logic moved to limit with the rest @@ -1031,8 +1044,7 @@ async def room_read(request: Request) -> Response: # Ahead of the budget footer: a wait that did not happen is what the caller must act # on first, and acting on it is what stops the next request being an instant re-poll. note = unheld + budget_note("read", left, RATE_READ) - resp = respond(request, view, note=note) - return resp if wait or note else _edge_cacheable(resp) + return _shareable(respond(request, view, note=note), note or wait) async def _await_messages( @@ -1500,7 +1512,13 @@ def note_read(request: Request) -> Response: "and a note idle for 7 days is reclaimed, so this may be one that expired.", 404, ) - return text(f"{BANNER}\n\n{value}" + budget_note("read", left, RATE_READ)) + note = budget_note("read", left, RATE_READ) + # Shareable now: a note's bytes are the same for every caller that can name it, and an + # unlisted `p-` key is a capability URL, so a copy keyed on that URL reaches exactly the + # callers who could already read it. Staleness is EDGE_CACHE_SECONDS, the same window + # room reads take, and it cannot race a claim: `?if_absent=1` is settled on the write + # path under the note's own lock, never from a read. + return _shareable(text(f"{BANNER}\n\n{value}" + note), note) def _condition(source: Mapping[str, object]) -> tuple[str | None, bool]: @@ -1749,11 +1767,10 @@ def note_list(request: Request) -> Response: return limit.limited("read", RATE_READ, retry, text=text, max_wait=MAX_WAIT) ns = request.path_params["ns"] keys = store.list_notes(config.ROOT, ns) - return respond( - request, - {"ns": ns, "keys": keys}, - "\n".join(f"/kv/{ns}/{k}" for k in keys), - budget_note("read", left, RATE_READ), + note = budget_note("read", left, RATE_READ) + return _shareable( + respond(request, {"ns": ns, "keys": keys}, "\n".join(f"/kv/{ns}/{k}" for k in keys), note), + note, ) diff --git a/src/limit.py b/src/limit.py index 2e66fabc5..1801de720 100644 --- a/src/limit.py +++ b/src/limit.py @@ -394,8 +394,39 @@ def limited(kind: str, per_min: int, retry_after: float, *, text, max_wait: floa def budget_note(kind: str, left: int, per_min: int) -> str: - """Warn before the wall, not at it — only once the budget is nearly gone.""" - if left * 4 > per_min: + """Warn before the wall, not at it — and on a stride, so the warning stays shareable. + + The footer is one caller's pacing, so a reply carrying one is `no-store` and the CDN + bypasses it (see the read paths in app.py). That is fine for a warning nobody sees + twice, and it was not: a client polling at its ceiling sits permanently inside the + last quarter of its budget, so *every* reply it got carried a footer and *none* of them + could be cached. Measured on production, 47.7% of room reads were `bypass` at the edge + against a 7.2% hit rate — the cache switched itself off for exactly the callers + generating the most load. + + Lowering the threshold does not fix that: a client pinned at its ceiling is permanently + inside whatever band is chosen. What fixes it is emitting on a *stride* of the remaining + budget — roughly every `per_min // 24` requests, so about six warnings across the warning + band and the rest of the replies shareable. At the production read budget of 600/min that + is one footer every 25 requests; the other 24 can be served from the edge. + + The stride scales with the budget rather than being a constant, because a deployment with + a small budget has no requests to spare: at anything under 24/min it is 1, which is the + every-reply behaviour this replaces. A caller cannot step over a stride without landing + on it, so the warning is never skipped, only thinned. + + `(left + 1) % stride` rather than `left % stride` so that the multiple is never *zero + left*: a caller pinned at its ceiling is granted a token the instant one refills and + would otherwise sit on the one value that always warns, which is the case this exists to + remove. It lands on stride-1 instead — 24, 49, 74 … at 600/min. + + Reads only. A write reply is `no-store` whatever it carries — it mutates — so thinning + its footer buys no cacheability and costs a writer its pacing. Sharing one helper made + that easy to miss: at the production write budget of 300/min the stride is 12, which + silently took write warnings from every in-band reply to 7.9% of them, and the test + default of 30/min has a stride of 1 so nothing failed. + """ + if left * 4 > per_min or (kind == "read" and (left + 1) % max(1, per_min // 24)): return "" return ( f"\n# budget: {left} of {per_min} {kind}s left this minute " diff --git a/src/manifest.py b/src/manifest.py index abd1ab7c1..1d6c528ad 100644 --- a/src/manifest.py +++ b/src/manifest.py @@ -1662,7 +1662,10 @@ def config_document(version: str) -> dict: "fsync": "true when a room append is flushed to disk before its 200", "rooms_cache_seconds": "seconds one /rooms walk is shared for; 0 disables", "note_stats_cache_seconds": "seconds the note-capacity gauge is reused for; 0 disables", - "edge_cache_seconds": "s-maxage on /rooms and plain room reads; 0 means no-store", + "edge_cache_seconds": ( + "s-maxage on /rooms, plain room reads and note reads (/kv); a reply " + "carrying a budget footer and a long-poll stay no-store; 0 means no-store" + ), "static_cache_seconds": "s-maxage on the documents; 0 means no-store", }, "withheld": _WITHHELD, diff --git a/tests/http/test_limits.py b/tests/http/test_limits.py index a29cd9ef3..35fda56d7 100644 --- a/tests/http/test_limits.py +++ b/tests/http/test_limits.py @@ -6,8 +6,12 @@ from pathlib import Path import _client +from hypothesis import given, settings +from hypothesis import strategies as st from starlette.testclient import TestClient +import limit + client = _client.client # the shared TestClient fixture @@ -248,6 +252,77 @@ def test_budget_warning_appears_before_the_wall(client, monkeypatch): assert "# budget: 1 of 8 reads left" in client.get("/r/lobby").text +def test_the_warning_thins_out_so_the_reply_stays_shareable(client): + """The footer makes a reply `no-store`, so emitting it on every reply switches the CDN + off for exactly the callers polling hardest — measured in production at 47.7% of room + reads `bypass` against a 7.2% hit rate. It now lands on a stride of the remaining budget. + + Asserted at a production-sized budget, because the stride scales with it: below 24/min + it is 1 and every in-band reply still warns, which is what the test above depends on. + """ + import limit + + band = [n for n in range(601) if n * 4 <= 600] + warned = [n for n in band if limit.budget_note("read", n, 600)] + assert warned, "a caller in the warning band must still be told" + assert len(warned) < len(band) // 10, ( + f"{len(warned)} of {len(band)} in-band replies warn — too many to be cacheable" + ) + # Never at zero left: a caller pinned at its ceiling is granted a token the moment one + # refills, so warning there would warn on every one of its replies — the case this + # exists to remove. + assert not limit.budget_note("read", 0, 600) + # A stride cannot be stepped over: consecutive values cannot both skip it. + gaps = [b - a for a, b in zip(warned, warned[1:], strict=False)] + assert gaps and max(gaps) == min(gaps), f"uneven stride {gaps}" + + +# Derandomized and deadline-free, matching tests/unit/test_parse_properties.py: a property +# whose failures cannot be reproduced is worse than no property. +_BUDGETS = settings(derandomize=True, deadline=None, max_examples=75) + + +@given(per_min=st.integers(min_value=1, max_value=1200)) +@_BUDGETS +def test_the_footer_contract_holds_at_every_budget(per_min): + """The footer's rules stated over the whole range of budgets, not the one the tests set. + + This exists because of how the write regression got in. Every rate-knob test in this + suite picks a tiny budget so it can exhaust it in a few requests — RATE_READ=1, =8, + RATE_WRITE=2, =4, =8 — which is right for testing exhaustion and blind to anything that + scales with the budget. The read stride is `per_min // 24`, so at every budget any test + had ever used it was 1, the thinning never engaged, and applying it to writes as well + passed the whole suite. It showed up only at the production 300/min. + + So the claims are asserted for all budgets rather than at a chosen one: + + - a write footer is never thinned — its presence is exactly the threshold, whatever + the budget, because a write reply is `no-store` and has no sharing to buy; + - neither kind warns outside the threshold band; + - a read is never *silent* through the whole band, however the stride divides it. + """ + band = [n for n in range(per_min + 1) if n * 4 <= per_min] + above = [n for n in range(per_min + 1) if n * 4 > per_min] + + assert [n for n in band if limit.budget_note("write", n, per_min)] == band, ( + f"write warnings thinned at {per_min}/min" + ) + assert not any(limit.budget_note("write", n, per_min) for n in above) + assert not any(limit.budget_note("read", n, per_min) for n in above) + assert [n for n in band if limit.budget_note("read", n, per_min)], ( + f"a read caller at {per_min}/min is never warned at all" + ) + + +def test_a_small_budget_still_warns_on_every_reply(client): + """The stride is `per_min // 24`, so a deployment with no requests to spare gets 1 — + the every-reply behaviour, because thinning a warning nobody has room to miss is worse + than the cacheability it would buy.""" + import limit + + assert all(limit.budget_note("read", n, 8) for n in range(3)) + + def test_new_rooms_are_budgeted_per_ip_and_say_when_to_retry(client, monkeypatch): """The room cap bounds the service; this bounds how much of it one caller can take. diff --git a/tests/http/test_notes.py b/tests/http/test_notes.py index 58fa2ad0e..ad0e2265e 100644 --- a/tests/http/test_notes.py +++ b/tests/http/test_notes.py @@ -433,3 +433,37 @@ def test_signed_writes_pay_the_write_budget_like_any_other(client, monkeypatch): _say_signed(client, "lobby", did, sign, f"m{i}", nonce=i).status_code for i in (1, 2, 3) ] assert codes == [200, 200, 429] + + +def test_note_reads_are_edge_cacheable_like_room_reads(client): + """The CDN's cache rule has always covered /kv/, but the handlers never marked a note + read shareable, so every one went to the origin — the rule matched a reply that never + said it could be held. A note's bytes are the same for every caller that can name it. + + An unlisted `p-` key is a capability URL, so a copy keyed on that URL reaches exactly + the callers who could already read it, which is why it is cacheable on the same terms + rather than excluded. + """ + client.get("/kv/e-tc-cache/k/set/value") + for path in ("/kv/e-tc-cache/k", "/kv/e-tc-cache"): + cc = client.get(path).headers["cache-control"] + assert "s-maxage=" in cc and "max-age=0" in cc, f"{path} is not shareable: {cc}" + + # A p- key is unlisted, not unshareable: same header, and the URL is the credential. + client.get("/kv/p-tc-cache/k/set/secret") + assert "s-maxage=" in client.get("/kv/p-tc-cache/k").headers["cache-control"] + + +def test_a_note_read_carrying_a_budget_footer_is_not_shared(client): + """The footer is one caller's pacing, so the reply stops being the CDN's to hand out. + This is the half that keeps the line above from leaking one caller's numbers to another. + """ + import config + + client.get("/kv/e-tc-cache/k/set/value") + with config.override(RATE_READ=8): + for _ in range(7): + client.get("/kv/e-tc-cache/k") + warned = client.get("/kv/e-tc-cache/k") + assert "# budget:" in warned.text + assert warned.headers["cache-control"] == "no-store"