Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
37 changes: 27 additions & 10 deletions src/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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)
Comment thread
sv marked this conversation as resolved.
Resolved


def _condition(source: Mapping[str, object]) -> tuple[str | None, bool]:
Expand Down Expand Up @@ -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,
)


Expand Down
29 changes: 27 additions & 2 deletions src/limit.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,8 +394,33 @@ 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.
"""
if left * 4 > per_min or (left + 1) % max(1, per_min // 24):
return ""
Comment thread
sv marked this conversation as resolved.
Resolved
return (
f"\n# budget: {left} of {per_min} {kind}s left this minute "
Expand Down
34 changes: 34 additions & 0 deletions tests/http/test_limits.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,40 @@ 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}"


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.

Expand Down
34 changes: 34 additions & 0 deletions tests/http/test_notes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Loading