From 8f0bc6c86550eee4996aac5e72420ccf1ea45efe Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 11:46:34 -0600 Subject: [PATCH 1/3] feat(pm-console): ask GitHub by tag, and keep to the time it gives for asking again The edge reads pull requests, ranked issues and prompts from GitHub with the fleet's token, so it draws on the same hourly allowance the agents do. Twice on 2026-11-23 the agents used the hour up and the edge's reads failed until it turned (#13489). - Each answer to a read is kept under its address with GitHub's tag, and asked for again by that tag. GitHub answers "not modified" for a list that has not changed, and such a call does not count against the allowance. A screen left open asks for the same lists every minute or two: those calls now cost nothing unless something changed. - Turned away for calling too often, GitHub says when to ask again (retry-after, or the turn of the hour when nothing is left). That time is now kept to: nothing is asked of GitHub until it has come, where before the edge asked again every five minutes. It is never kept to for more than a little over an hour, and the owner's "try again now" lifts it. - Why a read failed now starts with that time, so the app can say when. - Health says how many of GitHub's answers were "not modified", so the saving can be seen from outside. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01YLT5K1QVuzZjfWGFhXSSNF --- pm-stack/console/edge/src/direct.ts | 165 +++++++++++++++- pm-stack/console/edge/src/edge.ts | 47 ++++- pm-stack/console/src/ops.ts | 9 +- pm-stack/console/test/direct.test.ts | 286 ++++++++++++++++++++++++++- pm-stack/console/test/edge.test.ts | 203 ++++++++++++++++++- 5 files changed, 691 insertions(+), 19 deletions(-) diff --git a/pm-stack/console/edge/src/direct.ts b/pm-stack/console/edge/src/direct.ts index 40152aca69..b325d6682c 100644 --- a/pm-stack/console/edge/src/direct.ts +++ b/pm-stack/console/edge/src/direct.ts @@ -42,14 +42,20 @@ export const DIRECT_ACTIONS = [ ] as const; /** One call this side made of GitHub or the queue store, and how it was - * answered: `status` 0 is no answer at all. `write` is anything that - * may have changed something. `limited` is a call turned away for - * being one too many just now, not for what the token may do. */ + * answered: `status` 0 is no answer at all, and 304 is GitHub saying + * the answer this side kept still stands. `write` is anything that may + * have changed something. `limited` is a call turned away for being + * one too many just now, not for what the token may do; `until` is + * when GitHub says it may be asked again, where it says. A call this + * side did not make, because GitHub had said not to ask before then, + * is recorded as the 429 it would have been: it was not sent, so it + * wrote nothing. */ export interface Outward { to: "github" | "queue"; write: boolean; status: number; limited?: boolean; + until?: number; } /** Which of the two each section this side reads is read from. */ @@ -70,10 +76,108 @@ export interface DirectSecrets { * address is used, and the queue store's is the one a machine reports. */ githubApi?: string; queueDb?: string; + /** What this side remembers of GitHub between calls: its answers by + * address, and when it said to ask again. Given by whoever outlives + * the classes (the edge's object); without it nothing is remembered. */ + github?: GitHubMemory; + /** The clock, where a test sets it. */ + now?: () => number; } const GITHUB_API = "https://api.github.com"; +/** One answer of GitHub's, with the tag GitHub gave it. */ +export interface KeptAnswer { + etag: string; + text: string; +} + +/** What is remembered of GitHub between calls. + * + * Its answers, each under the address it was asked at. Asked again with + * the answer's tag, GitHub says "not modified" for one that has not + * changed, and a call answered that way does not count against the + * account's allowance for the hour: the agents draw on that allowance + * too, and a screen left open asks for the same lists every minute. + * A tag belongs to the token it was given to; after a new token the + * old tags only get full answers again. + * + * And when it said to ask again, after turning a call away for being + * one too many: until then nothing is asked of it at all. */ +export interface GitHubMemory { + get(url: string): KeptAnswer | undefined; + set(url: string, answer: KeptAnswer): void; + delete(url: string): void; + /** Not to be asked before this time, in milliseconds; 0 when free to. */ + quietUntil: number; +} + +/** The longest this side stays quiet on GitHub's word: a little over + * the hour its allowance is counted by. A time further off than that + * is a header that cannot be right. */ +export const QUIET_MOST_MS = 65 * 60_000; + +/** GitHub's answers kept in memory: the one asked for longest ago is + * dropped first, once there are more than `most` or they hold more + * than `room` characters between them. One that would not fit on its + * own is not kept. */ +export function githubMemory(room = 12_000_000, most = 200): GitHubMemory & { held(): number; size(): number } { + const kept = new Map(); + let held = 0; + const cost = (url: string, answer: KeptAnswer) => url.length + answer.etag.length + answer.text.length; + const drop = (url: string) => { + const had = kept.get(url); + if (!had) return; + held -= cost(url, had); + kept.delete(url); + }; + return { + quietUntil: 0, + get(url) { + const had = kept.get(url); + if (!had) return undefined; + // Asked for: it is now the last to go. + kept.delete(url); + kept.set(url, had); + return had; + }, + set(url, answer) { + drop(url); + if (cost(url, answer) > room) return; + kept.set(url, answer); + held += cost(url, answer); + for (const oldest of kept.keys()) { + if (kept.size <= most && held <= room) break; + drop(oldest); + } + }, + delete: drop, + held: () => held, + size: () => kept.size, + }; +} + +/** When GitHub says a caller it turned away for calling too often may + * ask again, in milliseconds; undefined where it does not say. It says + * it one of two ways: `retry-after`, a number of seconds from now, or, + * when `x-ratelimit-remaining` is 0, `x-ratelimit-reset`, the second + * the allowance for the hour comes back. Never further off than + * QUIET_MOST_MS, and never in the past. */ +export function askAgainAt(headers: { get(name: string): string | null } | undefined, now: number): number | undefined { + const within = (at: number) => Math.min(Math.max(at, now), now + QUIET_MOST_MS); + const after = headers?.get("retry-after") ?? null; + if (after !== null && /^\d{1,9}$/.test(after.trim())) return within(now + Number(after.trim()) * 1000); + if (headers?.get("x-ratelimit-remaining")?.trim() === "0") { + const reset = headers.get("x-ratelimit-reset") ?? ""; + if (/^\d{1,12}$/.test(reset.trim())) return within(Number(reset.trim()) * 1000); + } + return undefined; +} + +/** Said at the front of why a call failed, when GitHub said when to + * ask again: the app reads the time back out of it (whySaid). */ +export const askAgainSaid = (until: number) => `GitHub says to ask again at ${new Date(until).toISOString()}: `; + /** One `fleet gh api` call as a GitHub REST call. `argv` is what follows * `api`: an optional `-X METHOD`, the path, `-f key=value` pairs, and * `--input -` for a JSON body on stdin. A failed call answers the way @@ -87,6 +191,8 @@ async function ghApi( fetchImpl: Fetch, origin: string, seen?: (call: Outward) => void, + memory?: GitHubMemory, + now: () => number = Date.now, ): Promise { if (!token) throw new OpError(502, "the edge has no GitHub token"); let method = "GET"; @@ -121,6 +227,19 @@ async function ghApi( body = JSON.stringify(Object.fromEntries(fields)); } const write = method !== "GET"; + // GitHub said not to ask before a time that has not come: it is not + // asked. Asking on while turned away is what it warns callers off, + // and each such call would be one more of the same answer. + if (memory && memory.quietUntil > now()) { + seen?.({ to: "github", write, status: 429, limited: true, until: memory.quietUntil }); + return { + code: 1, + stdout: "", + stderr: `${askAgainSaid(memory.quietUntil)}not asked, GitHub having turned this account away for calling too often (rate limit)`, + }; + } + // A list asked for before is asked for by its tag. + const had = write ? undefined : memory?.get(url); let res: Awaited>; try { res = await fetchImpl(url, { @@ -133,6 +252,7 @@ async function ghApi( "user-agent": "pm-console-edge", "x-github-api-version": "2022-11-28", ...(body === undefined ? {} : { "content-type": "application/json" }), + ...(had ? { "if-none-match": had.etag } : {}), }, ...(body === undefined ? {} : { body }), signal: AbortSignal.timeout(20_000), @@ -143,6 +263,12 @@ async function ghApi( seen?.({ to: "github", write, status: 0 }); return { code: 1, stdout: "", stderr: `GitHub could not be reached: ${(error as Error).message}` }; } + // Not modified: the answer kept from before still stands, and this + // call cost nothing of the hour's allowance. + if (res.status === 304 && had) { + seen?.({ to: "github", write, status: 304 }); + return { code: 0, stdout: had.text, stderr: "" }; + } // The body is read as JSON and written back out, so an empty answer // (a 204) stays empty and an error body keeps its own words for the // caller. @@ -157,9 +283,26 @@ async function ghApi( // it uses for a token that may not do the thing, and says which in // the body; a 429 is always the former. const limited = res.status === 429 || (res.status === 403 && /rate limit/i.test(text)); - seen?.({ to: "github", write, status: res.status, ...(limited ? { limited } : {}) }); + const until = limited ? askAgainAt(res.headers, now()) : undefined; + if (until !== undefined && memory) memory.quietUntil = Math.max(memory.quietUntil, until); + seen?.({ + to: "github", + write, + status: res.status, + ...(limited ? { limited } : {}), + ...(until === undefined ? {} : { until }), + }); if (!res.ok) { - return { code: 1, stdout: "", stderr: text === "" ? `GitHub answered http ${res.status}` : text }; + // What was kept under this address is no longer known to be what + // is there, if what is there is gone. + if (!write && (res.status === 404 || res.status === 410)) memory?.delete(url); + const why = text === "" ? `GitHub answered http ${res.status}` : text; + return { code: 1, stdout: "", stderr: until === undefined ? why : `${askAgainSaid(until)}${why}` }; + } + if (!write && memory) { + const etag = res.headers?.get("etag") ?? null; + if (etag) memory.set(url, { etag, text }); + else memory.delete(url); } return { code: 0, stdout: text, stderr: "" }; } @@ -171,7 +314,16 @@ export function edgeRun(config: Config, secrets: DirectSecrets, fetchImpl: Fetch return async (argv, opts) => { const [bin, verb, ...rest] = argv; if (bin === config.fleetBin && verb === "gh" && rest[0] === "api") { - return ghApi(rest.slice(1), opts?.stdin, secrets.githubToken, fetchImpl, origin, secrets.seen); + return ghApi( + rest.slice(1), + opts?.stdin, + secrets.githubToken, + fetchImpl, + origin, + secrets.seen, + secrets.github, + secrets.now, + ); } if (bin === config.fleetBin && verb === "secrets" && rest[0] === "get") { const name = rest[1]; @@ -220,7 +372,6 @@ export function directConfig(edge: EdgeConfig): Config { export interface DirectOptions extends DirectSecrets { fetchImpl?: Fetch; - now?: () => number; } export interface DirectClasses { diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index cb75e6098f..9a689fafc6 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -30,7 +30,9 @@ import { type DirectClasses, directClasses, directRead, + githubMemory, type Outward, + QUIET_MOST_MS, READ_FROM, } from "./direct.ts"; import { Devices, KeyedLimiter, Limiter } from "../../src/devices.ts"; @@ -270,6 +272,15 @@ export class Edge { /** This side's latest calls of GitHub and the queue store, numbered. */ private outward: (Outward & { n: number })[] = []; private outwardN = 0; + /** What this side remembers of GitHub between calls: its answers by + * address, asked for again by their tags, and when it said to ask + * again. Kept while this object lives; a restart only costs one full + * answer of each. */ + private github = githubMemory(); + /** GitHub's answers since this object started: all of them, and + * those that were "not modified", which cost nothing of the hour's + * allowance. For health: it is how the saving is seen from outside. */ + private githubAnswers = { all: 0, unchanged: 0 }; /** Actions this side's token was turned away for, and until when * they are left to a machine. */ private refused = new Map(); @@ -385,6 +396,9 @@ export class Edge { const tried = [...this.refusedKinds(), ...this.refusedReads().map((name) => `read.${name}`)]; this.refused.clear(); this.unread.clear(); + // The owner's word outweighs GitHub's "not before": if it is + // still turned away, the first call says so again. + this.github.quietUntil = 0; await this.saveAway(); return { tried }; }, @@ -854,7 +868,14 @@ export class Edge { queueDb: this.direct?.queueDb, fetchImpl: this.direct?.fetchImpl as never, now: this.now, + github: this.github, seen: (call) => { + // Counted: what GitHub answered (not what was held back here, + // which is recorded as the 429 it would have been, with its time). + if (call.to === "github" && call.status !== 0 && !(call.status === 429 && call.until !== undefined)) { + this.githubAnswers.all++; + if (call.status === 304) this.githubAnswers.unchanged++; + } this.outward.push({ ...call, n: ++this.outwardN }); if (this.outward.length > OUTWARD_KEPT) this.outward.splice(0, this.outward.length - OUTWARD_KEPT); }, @@ -937,15 +958,19 @@ export class Edge { /** Whether this side's token was turned away in a call since number * `from` (of these services only, if any are named), and if so for * how long what was being done is left to a machine: an hour when it - * may not do the thing (401, 403), a few minutes when it was only - * calling too often. Calls made at the same time by something else - * are counted too: that can only hand a machine something this side - * could have done, never keep from it what this side cannot. */ + * may not do the thing (401, 403); when it was only calling too + * often, until the time GitHub gave for asking again, and a few + * minutes where it gave none or a nearer one. Calls made at the same + * time by something else are counted too: that can only hand a + * machine something this side could have done, never keep from it + * what this side cannot. */ private away(from: number, to?: Outward["to"][]): number | null { const mine = this.outward.filter((call) => call.n > from && (to === undefined || to.includes(call.to))); if (mine.some((call) => (call.status === 401 || call.status === 403) && !call.limited)) return REFUSED_FOR_MS; - if (mine.some((call) => call.limited)) return LIMITED_FOR_MS; - return null; + const limited = mine.filter((call) => call.limited); + if (limited.length === 0) return null; + const until = Math.max(0, ...limited.map((call) => call.until ?? 0)); + return Math.min(QUIET_MOST_MS, Math.max(LIMITED_FOR_MS, until - this.now())); } /** Whether something was written since call number `from`, or may @@ -1457,6 +1482,16 @@ export class Edge { // it could not read as `read.
`. refused: [...this.refusedKinds(), ...this.refusedReads().map((name) => `read.${name}`)], selfCheck: this.selfCheckResult, + // What GitHub answered this side since it started, how many of + // those were "not modified" (which cost nothing of the hour's + // allowance), how many answers are kept to ask by, and until + // when GitHub said not to ask, if it has. + github: { + answers: this.githubAnswers.all, + unchanged: this.githubAnswers.unchanged, + kept: this.github.size(), + quietUntil: this.github.quietUntil > this.now() ? this.github.quietUntil : null, + }, hostSeen: this.hostSeen || null, // The commit the host's console is running, as it last said. hostVersion: this.hostVersion, diff --git a/pm-stack/console/src/ops.ts b/pm-stack/console/src/ops.ts index a78d61c99e..b336925ba5 100644 --- a/pm-stack/console/src/ops.ts +++ b/pm-stack/console/src/ops.ts @@ -24,7 +24,14 @@ export type Run = (argv: string[], opts?: { stdin?: string; timeoutMs?: number } export type Fetch = ( url: string, init: { method: string; headers: Record; body?: string; signal?: AbortSignal }, -) => Promise<{ ok: boolean; status: number; json(): Promise }>; +) => Promise<{ + ok: boolean; + status: number; + json(): Promise; + /** What the answer says of itself, where the caller reads it (the + * edge does, for GitHub's tag on an answer and when to ask again). */ + headers?: { get(name: string): string | null }; +}>; export type Row = Record; /** Queue priorities, most urgent first (the queue's design scale). */ export const PRIORITY_SCALE = [10, 20, 30, 40, 50, 70, 90] as const; diff --git a/pm-stack/console/test/direct.test.ts b/pm-stack/console/test/direct.test.ts index ab3e6d41e7..c2201789ce 100644 --- a/pm-stack/console/test/direct.test.ts +++ b/pm-stack/console/test/direct.test.ts @@ -3,21 +3,30 @@ // secret, and every other fleet verb is refused as the laptop's. // // Oracles: the exact request the stand-in fetch receives (method, URL, -// headers, body), and the exact RunResult the classes see back. +// headers, body), and the exact RunResult the classes see back. For +// what is remembered of GitHub: a stand-in that tags its answers the +// way GitHub does and counts what it was asked; a memory written the +// plain way here (a list, oldest first) that the real one is compared +// with on generated runs; and for when to ask again, the bounds said +// here and held against generated headers. import { describe, expect, test } from "bun:test"; import { readConfig } from "../src/config.ts"; import { + askAgainAt, directClasses, directConfig, directRead, edgeRun, + githubMemory, + type KeptAnswer, type Outward, + QUIET_MOST_MS, queueWrites, READ_FROM, } from "../edge/src/direct.ts"; import type { Fetch } from "../src/ops.ts"; import type { EdgeConfig } from "../src/edge-proto.ts"; -import { asThePlatformFetch } from "./support.ts"; +import { asThePlatformFetch, letters, pick, rng } from "./support.ts"; const cfg = readConfig({ HOME: "/h", PM_CONSOLE_OWNER_EMAILS: "owner@example.com" }); const edgeConfig: EdgeConfig = { @@ -336,3 +345,276 @@ describe("what this side notes of each call it makes", () => { }); }); }); + +/** GitHub as it answers a list asked for by its tag. The tag is the + * number of times the list has changed; a read that carries the list's + * own tag is "not modified", with no body. A test can have it turn + * every call away, saying what it likes of when to ask again. */ +function tagging(options: { memory?: boolean; start?: number } = {}) { + const lists: Record = {}; + const calls: { method: string; url: string; tag: string | null }[] = []; + const seen: Outward[] = []; + const state: { limited: Record | null; tags: boolean; status: number | null } = { + limited: null, + tags: true, + status: null, + }; + const clock = { t: options.start ?? Date.UTC(2026, 10, 23, 17, 0, 0) }; + const fetchImpl = (async (url: string, init: { method: string; headers: Record }) => { + calls.push({ method: init.method, url, tag: init.headers["if-none-match"] ?? null }); + if (state.limited) { + return { + ok: false, + status: 403, + headers: new Headers(state.limited), + json: async () => ({ message: "API rate limit exceeded for user ID 1." }), + }; + } + if (state.status !== null) + return { ok: false, status: state.status, headers: new Headers(), json: async () => JSON.parse("") }; + if (init.method !== "GET") + return { ok: true, status: 200, headers: new Headers(), json: async () => ({ done: true }) }; + lists[url] ??= { rev: 1, body: [{ number: 1 }] }; + const list = lists[url]; + const etag = `W/"${list.rev}"`; + if (state.tags && init.headers["if-none-match"] === etag) { + return { ok: false, status: 304, headers: new Headers({ etag }), json: async () => JSON.parse("") }; + } + return { ok: true, status: 200, headers: new Headers(state.tags ? { etag } : {}), json: async () => list.body }; + }) as unknown as Fetch; + const memory = options.memory === false ? undefined : githubMemory(); + const run = edgeRun( + directConfig(edgeConfig), + { githubToken: "gh-test", seen: (call) => seen.push(call), github: memory, now: () => clock.t }, + asThePlatformFetch(fetchImpl) as typeof fetchImpl, + ); + const api = (...argv: string[]) => run(["fleet", "gh", "api", ...argv]); + const change = (url: string, body: unknown) => { + lists[url] = { rev: (lists[url]?.rev ?? 0) + 1, body }; + }; + return { api, calls, seen, state, clock, memory, change }; +} + +describe("what the edge remembers of GitHub", () => { + const PULLS = "repos/developing-today/code/pulls?state=open&per_page=60"; + const ISSUES = "repos/developing-today/code/issues?state=open"; + const at = (path: string) => `https://api.github.com/${path}`; + + test("a list asked for again is asked for by its tag, and one that has not changed is answered from what was kept", async () => { + const g = tagging(); + const first = await g.api(PULLS); + expect(first).toEqual({ code: 0, stdout: '[{"number":1}]', stderr: "" }); + expect(g.calls).toEqual([{ method: "GET", url: at(PULLS), tag: null }]); + // Again: by its tag, and GitHub's "not modified" is the same answer to whoever asked. + expect(await g.api(PULLS)).toEqual(first); + expect(g.calls[1]).toEqual({ method: "GET", url: at(PULLS), tag: 'W/"1"' }); + expect(g.seen).toEqual([ + { to: "github", write: false, status: 200 }, + { to: "github", write: false, status: 304 }, + ]); + // The list changes: the old tag gets a full answer, which replaces what was kept. + g.change(at(PULLS), [{ number: 1 }, { number: 2 }]); + expect((await g.api(PULLS)).stdout).toBe('[{"number":1},{"number":2}]'); + expect(g.calls[2].tag).toBe('W/"1"'); + expect((await g.api(PULLS)).stdout).toBe('[{"number":1},{"number":2}]'); + expect(g.calls[3].tag).toBe('W/"2"'); + expect(g.seen.map((call) => call.status)).toEqual([200, 304, 200, 304]); + }); + + test("each address has its own answer, and a write is never asked for by a tag", async () => { + const g = tagging(); + await g.api(PULLS); + g.change(at(ISSUES), [{ number: 9 }]); + expect((await g.api(ISSUES)).stdout).toBe('[{"number":9}]'); + expect((await g.api(PULLS)).stdout).toBe('[{"number":1}]'); + expect((await g.api(ISSUES)).stdout).toBe('[{"number":9}]'); + expect(g.calls.map((call) => call.tag)).toEqual([null, null, 'W/"1"', 'W/"2"']); + // The same address with other things asked of it is another address. + await g.api(PULLS, "-f", "page=2"); + expect(g.calls[4]).toEqual({ method: "GET", url: `${at(PULLS)}&page=2`, tag: null }); + // Writes: no tag sent, nothing kept from them, and what is kept is not disturbed. + await g.api("-X", "PUT", "repos/developing-today/code/pulls/55/merge", "-f", "merge_method=merge"); + await g.api("-X", "POST", PULLS, "-f", "title=x"); + expect(g.calls.slice(5).map((call) => [call.method, call.tag])).toEqual([ + ["PUT", null], + ["POST", null], + ]); + await g.api(PULLS); + expect(g.calls[7].tag).toBe('W/"1"'); + expect(g.memory?.size()).toBe(3); + }); + + test("an answer with no tag is not kept, one that is gone is let go, and with no memory every call is a full one", async () => { + const g = tagging(); + await g.api(PULLS); + // GitHub stops tagging: the full answer is used, and the old one is not kept under it. + g.state.tags = false; + await g.api(PULLS); + await g.api(PULLS); + expect(g.calls.map((call) => call.tag)).toEqual([null, 'W/"1"', null]); + expect(g.memory?.size()).toBe(0); + // Gone from GitHub: what was kept under the address goes too. + g.state.tags = true; + await g.api(PULLS); + expect(g.memory?.size()).toBe(1); + g.state.status = 404; + expect((await g.api(PULLS)).code).toBe(1); + expect(g.memory?.size()).toBe(0); + // A failure that says nothing of the list leaves what was kept alone. + g.state.status = null; + await g.api(PULLS); + g.state.status = 502; + expect(await g.api(PULLS)).toEqual({ code: 1, stdout: "", stderr: "GitHub answered http 502" }); + expect(g.memory?.size()).toBe(1); + // "Not modified" for something never kept is not an answer. + g.state.status = 304; + expect(await g.api(ISSUES)).toEqual({ code: 1, stdout: "", stderr: "GitHub answered http 304" }); + // No memory given: nothing is asked by a tag, ever. + const plain = tagging({ memory: false }); + await plain.api(PULLS); + await plain.api(PULLS); + expect(plain.calls.map((call) => call.tag)).toEqual([null, null]); + expect(plain.seen.map((call) => call.status)).toEqual([200, 200]); + }); + + test("turned away for calling too often with a time to ask again: the time is told, said at the front of why, and nothing is asked until it has come", async () => { + const g = tagging(); + await g.api(PULLS); + const back = g.clock.t + 40 * 60_000; + g.state.limited = { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(back / 1000) }; + const turned = await g.api(PULLS); + expect(turned).toEqual({ + code: 1, + stdout: "", + stderr: `GitHub says to ask again at ${new Date(back).toISOString()}: {"message":"API rate limit exceeded for user ID 1."}`, + }); + expect(g.seen[1]).toEqual({ to: "github", write: false, status: 403, limited: true, until: back }); + // Until then nothing goes out: not a read, not a write, though GitHub would answer now. + g.state.limited = null; + g.clock.t += 39 * 60_000; + const asked = g.calls.length; + const read = await g.api(ISSUES); + const write = await g.api("-X", "PUT", "repos/developing-today/code/pulls/55/merge"); + expect(g.calls.length).toBe(asked); + for (const held of [read, write]) { + expect(held.code).toBe(1); + expect(held.stderr).toStartWith(`GitHub says to ask again at ${new Date(back).toISOString()}: not asked`); + expect(held.stderr).toMatch(/rate limit/i); + } + // Each is recorded as the answer it would have had: not sent, so nothing written. + expect(g.seen.slice(2)).toEqual([ + { to: "github", write: false, status: 429, limited: true, until: back }, + { to: "github", write: true, status: 429, limited: true, until: back }, + ]); + // The time comes: it is asked again, and what was kept is still asked for by its tag. + g.clock.t = back; + expect((await g.api(PULLS)).code).toBe(0); + expect(g.calls[asked]).toEqual({ method: "GET", url: at(PULLS), tag: 'W/"1"' }); + }); + + test("when to ask again: the seconds GitHub gives, or the turn of the hour when nothing is left of it; never the past, never much over an hour", () => { + const now = Date.UTC(2026, 10, 23, 17, 0, 0); + const said = (headers: Record) => askAgainAt(new Headers(headers), now); + expect(said({ "retry-after": "60" })).toBe(now + 60_000); + expect(said({ "retry-after": "0" })).toBe(now); + expect(said({ "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(now / 1000 + 1500) })).toBe( + now + 1_500_000, + ); + // Both: the seconds are for this caller, now. + expect( + said({ "retry-after": "30", "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(now / 1000 + 1500) }), + ).toBe(now + 30_000); + // Something left of the hour's allowance: the turn of the hour is not when to ask again. + expect(said({ "x-ratelimit-remaining": "12", "x-ratelimit-reset": String(now / 1000 + 1500) })).toBeUndefined(); + expect(said({ "x-ratelimit-reset": String(now / 1000 + 1500) })).toBeUndefined(); + expect(said({})).toBeUndefined(); + expect(askAgainAt(undefined, now)).toBeUndefined(); + // A time that cannot be right is cut to a little over the hour; one already past is now. + expect(said({ "retry-after": "86400" })).toBe(now + QUIET_MOST_MS); + expect(said({ "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(now / 1000 + 7 * 3600) })).toBe( + now + QUIET_MOST_MS, + ); + expect(said({ "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(now / 1000 - 30) })).toBe(now); + // A date, as the header may also be written, is not read: no time is better than a wrong one. + expect(said({ "retry-after": "Mon, 23 Nov 2026 18:00:00 GMT" })).toBeUndefined(); + }); + + test("property: whatever GitHub's headers say, the time to ask again is none, or between now and a little over an hour on", () => { + const next = rng(13489); + let none = 0; + let some = 0; + for (let i = 0; i < 6000; i++) { + const now = Math.floor(next() * 2e12); + const value = () => + pick(next, [ + "0", + "1", + "60", + "3600", + String(Math.floor(now / 1000) + Math.floor((next() - 0.3) * 10_000)), + String(Math.floor(next() * 1e13)), + "-5", + "1.5", + "1e9", + "", + " 30 ", + "soon", + "Infinity", + "NaN", + letters(next, "0123456789 -.eE+x", 0, 14), + ]); + const headers: Record = {}; + for (const name of ["retry-after", "x-ratelimit-remaining", "x-ratelimit-reset"]) + if (next() < 0.7) headers[name] = value(); + const at = askAgainAt(new Headers(headers), now); + if (at === undefined) none++; + else { + some++; + expect([headers, now, Number.isInteger(at) && at >= now && at <= now + QUIET_MOST_MS]).toEqual([ + headers, + now, + true, + ]); + } + } + expect([none > 500, some > 500]).toEqual([true, true]); + }); + + test("property: what is kept is what a plain list kept the same way would hold, within its room and its count", () => { + const next = rng(304); + for (let round = 0; round < 60; round++) { + const room = 40 + Math.floor(next() * 400); + const most = 1 + Math.floor(next() * 6); + const real = githubMemory(room, most); + // The model: [address, answer] pairs, the one asked for longest ago first. + let model: [string, KeptAnswer][] = []; + const cost = (url: string, answer: KeptAnswer) => url.length + answer.etag.length + answer.text.length; + const urls = Array.from({ length: 2 + Math.floor(next() * 8) }, (_, n) => `https://api.github.com/list/${n}`); + for (let step = 0; step < 300; step++) { + const url = pick(next, urls); + const roll = next(); + if (roll < 0.45) { + const answer = { etag: `W/"${step}"`, text: letters(next, "abc", 0, pick(next, [5, 30, 120, 500])) }; + real.set(url, answer); + model = model.filter(([kept]) => kept !== url); + if (cost(url, answer) <= room) { + model.push([url, answer]); + while (model.length > most || model.reduce((sum, [u, a]) => sum + cost(u, a), 0) > room) model.shift(); + } + } else if (roll < 0.9) { + const want = model.find(([kept]) => kept === url); + expect([round, step, real.get(url)]).toEqual([round, step, want?.[1]]); + if (want) model = [...model.filter(([kept]) => kept !== url), want]; + } else { + real.delete(url); + model = model.filter(([kept]) => kept !== url); + } + const held = model.reduce((sum, [u, a]) => sum + cost(u, a), 0); + expect([round, step, real.size(), real.held()]).toEqual([round, step, model.length, held]); + expect([real.size() <= most, real.held() <= room]).toEqual([true, true]); + } + // What is left is exactly the model's, each under its own address. + for (const url of urls) expect(real.get(url)).toEqual(model.find(([kept]) => kept === url)?.[1]); + } + }); +}); diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index a8becb4d70..cc4ea54925 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -110,7 +110,7 @@ async function setup(options: { direct?: boolean } = {}) { // direct reads and writes go through these, and only these. The data // here is newer than the host's last report, as it would be after the // laptop has been away for a while. - const githubCalls: { method: string; url: string; body?: string }[] = []; + const githubCalls: { method: string; url: string; body?: string; unchanged?: true }[] = []; const queueCalls: { sql: string; args: (string | number)[] }[] = []; const ghIssues: Record< number, @@ -193,6 +193,13 @@ async function setup(options: { direct?: boolean } = {}) { /** Calls GitHub turns away for being one too many just now: the same * 403, with other words. */ const ghLimits: ((method: string, url: string) => boolean)[] = []; + /** What GitHub says with such an answer of when to ask again, if a + * test has it say anything. */ + const ghLimitSays: { headers: Record } = { headers: {} }; + /** GitHub tags what it answers a read with, and answers "not + * modified" to one asked for by the tag of what it would say. On + * for every test, as it is at GitHub; `unchanged` counts those. */ + const ghTags = { on: true, unchanged: 0 }; /** The queue store taking this side's token for reading only. */ const queueReadOnly = { on: false }; /** Calls GitHub gives no answer to at all, and calls it is slow to @@ -549,7 +556,8 @@ async function setup(options: { direct?: boolean } = {}) { const u = String(url); const method = init?.method ?? "GET"; if (u.startsWith("https://api.github.com/")) { - githubCalls.push({ method, url: u, body: init?.body }); + const call: (typeof githubCalls)[number] = { method, url: u, body: init?.body }; + githubCalls.push(call); for (const held of ghHolds) if (held.match(method, u)) await held.wait; if (ghDrops.some((drops) => drops(method, u))) throw new Error("socket hang up"); // A token that may not do this, as GitHub says it. @@ -564,6 +572,7 @@ async function setup(options: { direct?: boolean } = {}) { return { ok: false, status: 403, + headers: new Headers(ghLimitSays.headers), json: async () => ({ message: "API rate limit exceeded for user ID 1.", status: "403" }), }; } @@ -572,7 +581,21 @@ async function setup(options: { direct?: boolean } = {}) { } const says = ghSays.find((say) => say.match(method, u)); if (says) return { ok: false, status: says.status, json: async () => ({ message: says.message }) }; - return githubAnswer(method, u, init?.body); + const answer = githubAnswer(method, u, init?.body); + if (method !== "GET" || !answer.ok || !ghTags.on) return answer; + const etag = `W/"${Bun.hash(JSON.stringify(await answer.json())).toString(16)}"`; + if (init?.headers?.["if-none-match"] === etag) { + ghTags.unchanged++; + call.unchanged = true; + return { + ok: false, + status: 304, + headers: new Headers({ etag }), + // As a real answer with no body does. + json: async () => JSON.parse(""), + }; + } + return { ...answer, headers: new Headers({ etag }) }; } if (u === `${cfg.queueDbUrl}/v2/pipeline`) { // A token the queue store no longer takes. @@ -1009,6 +1032,8 @@ async function setup(options: { direct?: boolean } = {}) { ghStarted, ghOdd, ghRefuses, + ghLimitSays, + ghTags, ghLimits, ghDrops, ghSays, @@ -1056,6 +1081,7 @@ describe("before the host's first report", () => { directReady: false, refused: [], selfCheck: null, + github: { answers: 0, unchanged: 0, kept: 0, quietUntil: null }, hostSeen: null, hostVersion: null, androidBuild: null, @@ -4295,6 +4321,177 @@ describe("the edge does the core itself", () => { expect((await w.core()).doc.board.counts).toEqual(QUEUE_NOW); }); + /** The document pull requests and ranked issues are in. */ + const opsDoc = async (w: World) => + (await (await w.browse("/console/api/doc/ops")).json()) as { + prs: unknown; + priorities: unknown; + health: Record; + }; + const githubSaid = async (w: World) => + ( + (await (await w.browse("/console/health", { token: null })).json()) as { + github: { answers: number; unchanged: number; kept: number; quietUntil: number | null }; + } + ).github; + + test('a list that has not changed is asked for by its tag: GitHub is asked as often, says "not modified", and what is shown is the same', async () => { + const w = await primary(); + const list = () => w.githubCalls.filter((c) => /\/pulls\?/.test(c.url)); + const pulls = () => list().length; + const unchanged = () => list().filter((c) => c.unchanged).length; + const first = await opsDoc(w); + await settle(w); + expect(JSON.stringify(first.prs)).toContain("Fresh PR"); + expect([pulls(), unchanged()]).toEqual([1, 0]); + // Past the time the list of pull requests is read again. + w.now.t += 91_000; + await opsDoc(w); + await settle(w); + const second = await opsDoc(w); + await settle(w); + // It was asked for once more, by its tag, and that cost nothing of the hour's allowance. + expect([pulls(), unchanged()]).toEqual([2, 1]); + expect(second.prs).toEqual(first.prs); + // The list changes at GitHub: the tag no longer fits, the answer is a full one, and it is what is shown. + w.ghPrs.push({ + ...w.ghPrs[0], + number: 56, + title: "Another PR", + html_url: "https://github.com/developing-today/code/pull/56", + head: { ref: "queue/56", sha: "5656565656565656565656565656565656565656" }, + }); + w.now.t += 91_000; + await opsDoc(w); + await settle(w); + const third = await opsDoc(w); + await settle(w); + expect([pulls(), unchanged()]).toEqual([3, 1]); + expect(JSON.stringify(third.prs)).toContain("Another PR"); + // Health says it from outside: every answer of GitHub's, and how many were "not modified". + const said = await githubSaid(w); + await settle(w); + expect([said.unchanged, said.answers]).toEqual([w.ghTags.unchanged, w.githubCalls.length]); + expect([said.kept > 0, said.quietUntil]).toEqual([true, null]); + // A GitHub that gave no tags is the same to look at: every answer a full one. + const plain = await primary(); + plain.ghTags.on = false; + const a = await opsDoc(plain); + await settle(plain); + plain.now.t += 91_000; + await opsDoc(plain); + await settle(plain); + expect((await opsDoc(plain)).prs).toEqual(a.prs); + expect(plain.ghTags.unchanged).toBe(0); + }); + + test("the hour's allowance used up: GitHub's own time is kept to, nothing is asked of it until then, and the last good copy says why and when", async () => { + const w = await primary(); + const first = { core: (await w.core()).doc, ops: await opsDoc(w) }; + await settle(w); + // No machine either: what this side kept is all there is to show. + w.net.hostUp = false; + w.net.edgeUp = false; + // GitHub: the account's allowance is used up, and comes back in forty minutes. + w.now.t += 181_000; + const back = Math.floor((w.now.t + 40 * 60_000) / 1000) * 1000; + w.ghLimits.push(() => true); + w.ghLimitSays.headers = { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(back / 1000) }; + const asked = () => w.githubCalls.length; + const before = asked(); + const look = async () => { + await w.core(); + await opsDoc(w); + await settle(w); + const seen = { core: (await w.core()).doc, ops: await opsDoc(w) }; + await settle(w); + return seen; + }; + const limited = await look(); + // It was told once, by the first thing it asked. Nothing else was asked: not the + // other lists of that round, and not the second look. + expect(asked()).toBe(before + 1); + expect([limited.ops.prs, limited.ops.priorities, limited.core.asks]).toEqual([ + first.ops.prs, + first.ops.priorities, + first.core.asks, + ]); + const why = [limited.ops.health.prs, limited.ops.health.priorities, limited.core.health.asks]; + for (const section of why) { + expect(section.ok).toBe(false); + expect(section.error).toContain(`GitHub says to ask again at ${new Date(back).toISOString()}`); + expect(section.error).toMatch(/rate limit/i); + } + // For the forty minutes: screens looked at, minutes passing, the check that health makes. + // None of it reaches GitHub. + for (let minute = 3; minute < 40; minute += 3) { + w.now.t += 3 * 60_000; + await look(); + expect([minute, (await githubSaid(w)).quietUntil]).toEqual([minute, back]); + await settle(w); + } + // Nor does something the owner does: it is kept, not sent and not lost. + const tried = await w.act("issue.rank", { issue: 301, rank: "next" }); + expect(await tried.json()).toMatchObject({ ok: true, held: true }); + expect(asked()).toBe(before + 1); + // The time comes, and GitHub answers again: it is asked, and what it says is shown with nothing wrong. + w.ghLimits.length = 0; + w.now.t = back + 181_000; + const after = await look(); + expect(asked()).toBeGreaterThan(before + 1); + expect((await githubSaid(w)).quietUntil).toBeNull(); + expect([after.ops.health.prs.ok, after.ops.health.priorities.ok, after.core.health.asks.ok]).toEqual([ + true, + true, + true, + ]); + }); + + test("turned away with no time given, this side asks again in five minutes as before; a time that cannot be right is kept to for a little over an hour, no longer", async () => { + const w = await primary(); + await opsDoc(w); + await settle(w); + w.net.hostUp = false; + w.net.edgeUp = false; + const pulls = () => w.githubCalls.filter((c) => /\/pulls\?/.test(c.url)).length; + const look = async () => { + await opsDoc(w); + await settle(w); + }; + // No time given: nothing else is held back, and the list is left alone for five minutes + // and read again at its next turn after them. + w.now.t += 91_000; + w.ghLimits.push((method, url) => method === "GET" && /\/pulls\?/.test(url)); + await look(); + expect(pulls()).toBe(2); + // (Health makes its own check of each read the first time it is asked: one more.) + expect((await githubSaid(w)).quietUntil).toBeNull(); + await settle(w); + const before = pulls(); + expect(before).toBe(3); + w.now.t += 4 * 60_000; + await look(); + expect(pulls()).toBe(before); + w.now.t += 2 * 60_000; + await look(); + expect(pulls()).toBe(before + 1); + // A time a day off: kept to for a little over an hour, no longer. + w.ghLimitSays.headers = { "retry-after": String(24 * 60 * 60) }; + w.now.t += 5 * 60_000 + 1_000; + const told = w.now.t; + await look(); + expect(pulls()).toBe(before + 2); + expect((await githubSaid(w)).quietUntil).toBe(told + 65 * 60_000); + // And the owner saying "try again now" is taken at their word: the list is asked for at + // its next turn, not an hour on. + await w.act("edge.retry", {}); + w.ghLimits.length = 0; + w.now.t += 91_000; + await look(); + expect(pulls()).toBe(before + 3); + expect((await githubSaid(w)).quietUntil).toBeNull(); + }); + test("turned away for calling too often is not refused for the hour: the laptop does it meanwhile, and this side tries again in five minutes", async () => { const w = await primary(); const health = async () => From 2182dd9e5d1864a13508a95f36d0787ca65a3bcf Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 12:05:49 -0600 Subject: [PATCH 2/3] feat(pm-console): keep GitHub's two allowances apart, and say on each screen why its list is old Follows the commit before it on this branch (#13489). - GitHub counts searches by the minute and everything else by the hour. The time it gives for asking again is now kept to for what draws on the allowance that ran out, not for everything: ranked issues (a search) are still read while the hour's allowance is spent, and a minute's searches running out does not stop the lists. Going too fast (retry-after) is said of the caller and hushes both. - A call held back is marked as not sent, and why it failed carries GitHub's own words, so the app can say which of the two it was. - The app: "GitHub says it answers again at 12:40 PM, and it is not asked before then", and how old the copy shown is. - The screens drawn from the operations document (pull requests, ranked issues, agents, units) said nothing when their list could not be read: they showed the old copy as if it were current. Each now names its own list and is told of that one. - The real-runtime smoke run has GitHub's stand-in tag its answers and turn calls away with a time, and checks both in the Worker runtime. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01YLT5K1QVuzZjfWGFhXSSNF --- ...rchitecture_pm_platform_cloudflare_core.md | 63 ++++++++ pm-stack/console/edge/README.md | 46 +++++- pm-stack/console/edge/src/direct.ts | 76 +++++++--- pm-stack/console/edge/src/edge.ts | 18 ++- pm-stack/console/public/app.js | 63 ++++++-- pm-stack/console/scripts/edge-smoke.ts | 127 +++++++++++++--- pm-stack/console/test/app.test.ts | 88 ++++++++++- pm-stack/console/test/direct.test.ts | 141 +++++++++++++++--- pm-stack/console/test/edge.test.ts | 68 ++++++--- 9 files changed, 585 insertions(+), 105 deletions(-) diff --git a/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md b/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md index 61b321bd87..443f6079e0 100644 --- a/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md +++ b/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md @@ -658,3 +658,66 @@ Checked: 357 tests under bun, 4 beside the list. In a real Chrome against both demos, light and dark: the Platform screen's counts, groups, each kind of row and its links. axe-core over 22 screens: no violations. + +## 2026-11-23T18:10Z Update: after step 6 (review answered, and the shared allowance) + +**A review finding that arrived as #13487 merged.** The Worker-list +parser had example tests only, and the testing doctrine +(`doc/agents/testing-doctrine.md`) asks for property tests where code +has invariants. It was right, and so it was for the two other parsers +of this work. #13517 adds properties on the seeded generator the +console's tests already use: rows and accounts built to keep every +rule are read back as written, single faults refuse them, the list is +held to a model written out in the test, and the device's and the +platform's account of what an action is about are compared on +generated actions. One fault was found by them: a machine's name cut +at 63 characters just after a blank kept the blank. Fixed there. + +**The shared allowance (#13489), the half that needs no new +identity.** The edge reads GitHub with the fleet's token, so it draws +on the account's hourly allowance with the agents, who used the hour +up twice on 2026-11-23. + +- _Asked by tag._ Each answer to a read is kept under its address + with GitHub's tag and asked for again by it. "Not modified" does not + count against the allowance, so a list that has not changed costs + nothing. GitHub is still asked every time and decides whether the + kept answer stands: this is not a cache with an age, and nothing + shown is older than it was before. +- _GitHub's time is kept to._ Turned away for calling too often, + GitHub says when to ask again. Until then the edge asks it nothing + that draws on what ran out, where before it asked again every five + minutes for as long as the hour had left. Sixty-five minutes at + most, and the owner's "Try again now" lifts it. +- _Two allowances, kept apart._ GitHub counts searches by the minute + and everything else by the hour. Ranked issues are a search, so they + are still read while the hour's allowance is spent, and a minute's + searches running out (the commoner case) no longer has anything to + do with the lists. Going too fast (`retry-after`) is said of the + caller and hushes both. +- _Said in the app._ Why a read failed now carries that time and + GitHub's own words, and the notice says which it was ("the allowance + for the hour is used up" or "turned away for asking too often just + now"), "GitHub says it answers again at 12:00", and how old the copy + shown is. + +Considered and not done: serving the kept answers for a time without +asking (a cache with an age). It would save the calls that change +too, at the price of showing things late, and the edge is not what +uses the hour up. And persisting the answers in the object's storage: +a restart costs one full answer of each, which is less than the +writes would. + +What this does not do: give the edge an allowance of its own. When +the agents use the hour up the edge is still turned away until it +turns. That takes an identity of its own on the account (a GitHub +App's installation token), which is the owner's to make; #13489 stays +open for it. + +**Not folded in, and next.** With the allowance used up and no +machine, something the owner does is kept for a machine, as it was for +the five minutes before. Now that the wait can be most of an hour, the +edge should do what it holds itself once GitHub answers again, and not +wait for a machine that may not come. That touches the rule against +doing anything twice (a machine may already have been handed it), so +it is its own change. diff --git a/pm-stack/console/edge/README.md b/pm-stack/console/edge/README.md index b4b7ff2a95..8d2f5ba025 100644 --- a/pm-stack/console/edge/README.md +++ b/pm-stack/console/edge/README.md @@ -203,9 +203,49 @@ it (the laptop's, the sign-in issuer's). queue is not a write; changing it is. - **Calling too often is not a refusal.** GitHub turns a caller away for that with the same 403 (and says so in its answer), or a 429. - It is handed on in the same way, but for five minutes, not an hour: - it passes by itself. The token is the fleet's too, and search is - what runs out first. + It is handed on in the same way, but not for the hour: it passes by + itself. GitHub says when, and that time is kept to: until it comes + the edge asks GitHub nothing that draws on what ran out, not a read, + not a write and not its own check, because asking on while turned + away is what GitHub warns callers off and every such call would get + the same answer. It says it one of two ways. `retry-after`, in + seconds, means the caller is going too fast whatever it asks, and + everything waits. `x-ratelimit-reset`, with nothing left + (`x-ratelimit-remaining: 0`), means one allowance is used up, and + GitHub counts two apart: searches, a few dozen to the minute, and + everything else, by the hour. Only what draws on the one that ran + out waits, so ranked issues (a search) are still read while the + hour's allowance is spent, and a minute's searches running out does + not stop the lists. Where GitHub gives no time it is five minutes + for what was being done, and nothing else waits. No time is kept to + for more than sixty-five minutes, since the longer allowance is + counted by the hour and a time further off is a header that cannot + be right. Why a read failed starts with the time ("GitHub says to ask + again at ...") and carries GitHub's own words, which is how the app + says when it answers again and which of the two it was. Health has + the times as `github.quiet.core` and `github.quiet.search`. "Try + again now" lifts both. +- **A list that has not changed costs nothing.** The token is the + fleet's too: the agents draw on the same hourly allowance, which is + the account's, and twice on 2026-11-23 they used the hour up. So the + edge keeps each answer to a read under its address with the + tag GitHub gave it (`etag`) and asks again by that tag + (`if-none-match`). GitHub answers "not modified" for one that has not + changed, and a call answered so + [does not count against the allowance](https://docs.github.com/en/rest/using-the-rest-api/best-practices-for-using-the-rest-api#use-conditional-requests-if-appropriate). + A screen left open asks for the same lists every minute or two, so + most of what the edge asks is now free. Nothing is served from the + kept answers without asking: GitHub decides each time whether the + answer still stands, so what is shown is never older than it was + before. The answers live in the object's memory (twelve million + characters and two hundred answers at most, the one asked for longest + ago dropped first); a restart costs one full answer of each. A tag + belongs to the token it was given to, so after a new token the old + tags only get full answers. Health counts GitHub's answers and how + many were "not modified" (`github.answers`, `github.unchanged`). + This does not give the edge an allowance of its own: when the agents + use the hour up, the edge is turned away with them until it turns + (#13489 has what would change that). - **The same for what it reads.** A section the edge is refused for is the laptop's to read for the hour, exactly as it was before the edge read anything: the edge stops naming it under `owns`, the laptop's diff --git a/pm-stack/console/edge/src/direct.ts b/pm-stack/console/edge/src/direct.ts index b325d6682c..31a1dfce5d 100644 --- a/pm-stack/console/edge/src/direct.ts +++ b/pm-stack/console/edge/src/direct.ts @@ -46,16 +46,17 @@ export const DIRECT_ACTIONS = [ * the answer this side kept still stands. `write` is anything that may * have changed something. `limited` is a call turned away for being * one too many just now, not for what the token may do; `until` is - * when GitHub says it may be asked again, where it says. A call this - * side did not make, because GitHub had said not to ask before then, - * is recorded as the 429 it would have been: it was not sent, so it - * wrote nothing. */ + * when GitHub says it may be asked again, where it says. `unsent` is a + * call this side did not make, because GitHub had said not to ask + * before then: it is recorded as the 429 it would have been, and as + * it was not sent it wrote nothing and GitHub answered nothing. */ export interface Outward { to: "github" | "queue"; write: boolean; status: number; limited?: boolean; until?: number; + unsent?: boolean; } /** Which of the two each section this side reads is read from. */ @@ -103,13 +104,24 @@ export interface KeptAnswer { * old tags only get full answers again. * * And when it said to ask again, after turning a call away for being - * one too many: until then nothing is asked of it at all. */ + * one too many, with the words it said it in: until then nothing that + * draws on the same allowance is asked of it at all. */ export interface GitHubMemory { get(url: string): KeptAnswer | undefined; set(url: string, answer: KeptAnswer): void; delete(url: string): void; - /** Not to be asked before this time, in milliseconds; 0 when free to. */ - quietUntil: number; + quiet: Partial>; +} + +/** What a call draws on. GitHub counts searches apart, a few dozen to + * the minute, from everything else this side asks, which is counted by + * the hour: one running out says nothing of the other. */ +export type Allowance = "core" | "search"; +export const ALLOWANCES: readonly Allowance[] = ["core", "search"]; +/** Not to be asked before `until` (milliseconds), GitHub having said `why`. */ +export interface Quiet { + until: number; + why: string; } /** The longest this side stays quiet on GitHub's word: a little over @@ -132,7 +144,7 @@ export function githubMemory(room = 12_000_000, most = 200): GitHubMemory & { he kept.delete(url); }; return { - quietUntil: 0, + quiet: {}, get(url) { const had = kept.get(url); if (!had) return undefined; @@ -159,21 +171,30 @@ export function githubMemory(room = 12_000_000, most = 200): GitHubMemory & { he /** When GitHub says a caller it turned away for calling too often may * ask again, in milliseconds; undefined where it does not say. It says - * it one of two ways: `retry-after`, a number of seconds from now, or, - * when `x-ratelimit-remaining` is 0, `x-ratelimit-reset`, the second - * the allowance for the hour comes back. Never further off than - * QUIET_MOST_MS, and never in the past. */ -export function askAgainAt(headers: { get(name: string): string | null } | undefined, now: number): number | undefined { + * it one of two ways. `retry-after`, a number of seconds from now: the + * caller is going too fast, whatever it asks for (`whole`). Or, when + * `x-ratelimit-remaining` is 0, `x-ratelimit-reset`: the second the + * allowance the call drew on comes back, and only that one is spent. + * Never further off than QUIET_MOST_MS, and never in the past. */ +export function askAgainAt( + headers: { get(name: string): string | null } | undefined, + now: number, +): { until: number; whole: boolean } | undefined { const within = (at: number) => Math.min(Math.max(at, now), now + QUIET_MOST_MS); const after = headers?.get("retry-after") ?? null; - if (after !== null && /^\d{1,9}$/.test(after.trim())) return within(now + Number(after.trim()) * 1000); + if (after !== null && /^\d{1,9}$/.test(after.trim())) { + return { until: within(now + Number(after.trim()) * 1000), whole: true }; + } if (headers?.get("x-ratelimit-remaining")?.trim() === "0") { const reset = headers.get("x-ratelimit-reset") ?? ""; - if (/^\d{1,12}$/.test(reset.trim())) return within(Number(reset.trim()) * 1000); + if (/^\d{1,12}$/.test(reset.trim())) return { until: within(Number(reset.trim()) * 1000), whole: false }; } return undefined; } +/** Which allowance a call draws on, by what follows GitHub's address. */ +export const drawsOn = (path: string): Allowance => (/^\/?search\//.test(path) ? "search" : "core"); + /** Said at the front of why a call failed, when GitHub said when to * ask again: the app reads the time back out of it (whySaid). */ export const askAgainSaid = (until: number) => `GitHub says to ask again at ${new Date(until).toISOString()}: `; @@ -230,12 +251,14 @@ async function ghApi( // GitHub said not to ask before a time that has not come: it is not // asked. Asking on while turned away is what it warns callers off, // and each such call would be one more of the same answer. - if (memory && memory.quietUntil > now()) { - seen?.({ to: "github", write, status: 429, limited: true, until: memory.quietUntil }); + const draws = drawsOn(path); + const hush = memory?.quiet[draws]; + if (hush && hush.until > now()) { + seen?.({ to: "github", write, status: 429, limited: true, until: hush.until, unsent: true }); return { code: 1, stdout: "", - stderr: `${askAgainSaid(memory.quietUntil)}not asked, GitHub having turned this account away for calling too often (rate limit)`, + stderr: `${askAgainSaid(hush.until)}not asked again since GitHub answered: ${hush.why}`, }; } // A list asked for before is asked for by its tag. @@ -283,8 +306,21 @@ async function ghApi( // it uses for a token that may not do the thing, and says which in // the body; a 429 is always the former. const limited = res.status === 429 || (res.status === 403 && /rate limit/i.test(text)); - const until = limited ? askAgainAt(res.headers, now()) : undefined; - if (until !== undefined && memory) memory.quietUntil = Math.max(memory.quietUntil, until); + const again = limited ? askAgainAt(res.headers, now()) : undefined; + const until = again?.until; + if (again && memory) { + // Going too fast is said of the caller, whatever it asks for; an + // allowance used up is said of the one the call drew on, which + // GitHub names (and which is this call's own, where it does not). + const named = res.headers?.get("x-ratelimit-resource")?.trim(); + const spent: readonly Allowance[] = again.whole + ? ALLOWANCES + : [ALLOWANCES.find((allowance) => allowance === named) ?? draws]; + const why = (text === "" ? `GitHub answered http ${res.status}` : text).slice(0, 300); + for (const allowance of spent) { + if ((memory.quiet[allowance]?.until ?? 0) < again.until) memory.quiet[allowance] = { until: again.until, why }; + } + } seen?.({ to: "github", write, diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index 042188460c..916f274040 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -29,6 +29,7 @@ import { DIRECT_READ_SECTIONS, type DirectClasses, directClasses, + ALLOWANCES, directRead, githubMemory, type Outward, @@ -405,7 +406,7 @@ export class Edge { this.unread.clear(); // The owner's word outweighs GitHub's "not before": if it is // still turned away, the first call says so again. - this.github.quietUntil = 0; + this.github.quiet = {}; await this.saveAway(); return { tried }; }, @@ -877,9 +878,8 @@ export class Edge { now: this.now, github: this.github, seen: (call) => { - // Counted: what GitHub answered (not what was held back here, - // which is recorded as the 429 it would have been, with its time). - if (call.to === "github" && call.status !== 0 && !(call.status === 429 && call.until !== undefined)) { + // Counted: what GitHub answered, not what was held back here. + if (call.to === "github" && call.status !== 0 && !call.unsent) { this.githubAnswers.all++; if (call.status === 304) this.githubAnswers.unchanged++; } @@ -1492,12 +1492,18 @@ export class Edge { // What GitHub answered this side since it started, how many of // those were "not modified" (which cost nothing of the hour's // allowance), how many answers are kept to ask by, and until - // when GitHub said not to ask, if it has. + // when GitHub said not to ask, if it has: for searches, which + // it counts apart by the minute, and for everything else. github: { answers: this.githubAnswers.all, unchanged: this.githubAnswers.unchanged, kept: this.github.size(), - quietUntil: this.github.quietUntil > this.now() ? this.github.quietUntil : null, + quiet: Object.fromEntries( + ALLOWANCES.map((allowance) => { + const until = this.github.quiet[allowance]?.until ?? 0; + return [allowance, until > this.now() ? until : null]; + }), + ), }, hostSeen: this.hostSeen || null, // The commit the host's console is running, as it last said. diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js index 28e84e1827..8ae6e5e84a 100644 --- a/pm-stack/console/public/app.js +++ b/pm-stack/console/public/app.js @@ -509,7 +509,11 @@ export function awayNotice(primary, lastReport) { }; } -function notices(doc) { +/** What is said above a screen about what it shows: that a machine is + * away, that something is waiting for one, and each list that could + * not be read just now, with why. A screen that shows only some of a + * document's lists names them (`only`), and is told of those alone. */ +function notices(doc, only = null) { const out = []; // Served from the edge with the laptop out of reach: say what is // current and what is as old as its last report. @@ -523,12 +527,22 @@ function notices(doc) { h("div", { class: "card flag" }, h("p", { class: "meta" }, `${n} ${n === 1 ? "thing" : "things"} you did ${n === 1 ? "is" : "are"} waiting for the laptop. See “What you did” below.`)), ); } + for (const said of unreadSaid(doc, only)) out.push(h("div", { class: "card flag" }, h("p", { class: "meta" }, said))); + return out; +} + +/** What is said of each list a screen shows that could not be read + * just now: why, and how old the copy shown in its place is. `only` + * names the lists a screen shows, where it does not show all of the + * document's: it is told of those alone. */ +export function unreadSaid(doc, only = null, now = Date.now()) { + const out = []; for (const [name, s] of Object.entries(doc?.health || {})) { - if (!s.ok && s.error) { - out.push( - h("div", { class: "card flag" }, h("p", { class: "meta" }, `Could not read ${SECTION_SAID[name] || name} just now: ${whySaid(s.error)}. Showing the last good copy.`)), - ); - } + if (only && !only.includes(name)) continue; + if (s.ok || !s.error) continue; + const what = name === "services" ? "the machine's units" : SECTION_SAID[name] || name; + const read = doc.read?.[name] ? `, read ${ago(doc.read[name], now)}` : ""; + out.push(`Could not read ${what} just now: ${whySaid(s.error, now)}. Showing the last good copy${read}.`); } return out; } @@ -538,12 +552,28 @@ function notices(doc) { * as a line of JSON with a request number in it; what it means is that * the account's allowance for the hour is used up, and the agents * share that allowance with this app. */ -export function whySaid(error) { +export function whySaid(error, now = Date.now()) { const text = String(error || "").trim(); - if (/rate limit/i.test(text)) { - return "GitHub's allowance for the hour is used up on this account, which the agents share; it is asked again every few minutes and answers when the hour turns"; - } - return text || "no reason given"; + // Where Cloudflare was the one turned away, it puts the time GitHub + // gave for asking again at the front of why (askAgainSaid in + // edge/src/direct.ts), and asks nothing of GitHub until then. + const until = Date.parse((/GitHub says to ask again at (\d{4}-\d{2}-\d{2}T[\d:.]+Z)/.exec(text) || [])[1] || ""); + const timed = Number.isFinite(until); + if (!timed && !/rate limit/i.test(text)) return text || "no reason given"; + // The hour's allowance, or only going too fast for a moment? GitHub + // says the first in these words; but it says them of searches too, + // which it counts by the minute, so a wait of a minute or two is the + // second whatever the words. + const soon = timed && until > now && until - now <= 2 * 60_000; + const hourly = /API rate limit exceeded/i.test(text) && !soon; + const when = !timed + ? `it is asked again every few minutes${hourly ? " and answers when the hour turns" : ""}` + : until > now + ? `GitHub says it answers again at ${new Date(until).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" })}, and it is not asked before then` + : "the time GitHub gave for asking again has come, and it is being asked"; + return hourly + ? `GitHub's allowance for the hour is used up on this account, which the agents share; ${when}` + : `GitHub turned this account away for asking too often just now; ${when}`; } function viewNow() { @@ -2784,6 +2814,7 @@ function viewPrs() { const ready = prs.filter((p) => !p.draft); const drafts = prs.filter((p) => p.draft); return [ + ...notices(docs.ops, ["prs"]), h("h2", {}, `Ready (${ready.length})`), ...(ready.length ? ready.map(row) : [empty("No pull request is ready.")]), drafts.length ? h("h2", {}, `Drafts (${drafts.length})`) : null, @@ -2795,6 +2826,7 @@ function viewIssues() { const list = docs.ops?.priorities; if (!list) return [empty("Loading…")]; return [ + ...notices(docs.ops, ["priorities"]), list.truncated ? empty("There are more ranked issues than this list reads. The most urgent may not all be here.") : null, ...(list.issues.length ? list.issues.map(issueCard) : [empty("No ranked issues.")]), ]; @@ -2835,6 +2867,7 @@ async function viewAgents() { unread = error.message; } return [ + ...notices(docs.ops, ["agents"]), compose, h("h2", {}, `Agents (${agents.length})`), ...agents.map((a) => @@ -2897,7 +2930,13 @@ function viewServices() { }; const failed = units.filter((u) => u.active === "failed"); const rest = units.filter((u) => u.active !== "failed"); - return [failed.length ? h("h2", {}, `Failed (${failed.length})`) : null, ...failed.map(row), h("h2", {}, `All units (${units.length})`), ...rest.map(row)]; + return [ + ...notices(docs.ops, ["services"]), + failed.length ? h("h2", {}, `Failed (${failed.length})`) : null, + ...failed.map(row), + h("h2", {}, `All units (${units.length})`), + ...rest.map(row), + ]; } // ---- shell ------------------------------------------------------------- diff --git a/pm-stack/console/scripts/edge-smoke.ts b/pm-stack/console/scripts/edge-smoke.ts index 64628bf37e..6257dedbcf 100644 --- a/pm-stack/console/scripts/edge-smoke.ts +++ b/pm-stack/console/scripts/edge-smoke.ts @@ -133,7 +133,30 @@ deps.link = link; const seen: string[] = []; /** What reached the stand-ins for GitHub and the queue store, and with * what: the Worker's own reads, made in its runtime. */ -const outside: { to: "github" | "queue"; path: string; auth: string | null; agent: string | null }[] = []; +const outside: { + to: "github" | "queue"; + path: string; + auth: string | null; + agent: string | null; + /** The tag a read of GitHub was asked by, and what it was answered. */ + tag?: string | null; + status?: number; +}[] = []; +/** GitHub turning every call away as one too many, until this second + * (as it says it: nothing left of the allowance, and when it is back). */ +const spent = { until: 0 }; +/** GitHub's answer to a read: tagged, and "not modified" (with no body) + * to a read that carries the tag of what it would say. */ +const tagged = (req: Request, entry: { tag?: string | null; status?: number }, body: unknown, status = 200) => { + const etag = `W/"${Bun.hash(JSON.stringify(body)).toString(16)}"`; + entry.tag = req.headers.get("if-none-match"); + if (status === 200 && req.method === "GET" && entry.tag === etag) { + entry.status = 304; + return new Response(null, { status: 304, headers: { etag } }); + } + entry.status = status; + return Response.json(body, { status, headers: status === 200 ? { etag } : {} }); +}; const server = Bun.serve({ hostname: "127.0.0.1", port: 4898, @@ -142,23 +165,31 @@ const server = Bun.serve({ if (url.pathname === "/jwks") return Response.json({ keys: [jwk] }); if (url.pathname.startsWith("/github/")) { const path = url.pathname.slice("/github/".length); - outside.push({ + const entry: (typeof outside)[number] = { to: "github", path, auth: req.headers.get("authorization"), agent: req.headers.get("user-agent"), - }); + }; + outside.push(entry); + if (spent.until > 0) { + entry.status = 403; + return Response.json( + { message: "API rate limit exceeded for user ID 1.", status: "403" }, + { status: 403, headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(spent.until) } }, + ); + } if (path.endsWith("/contents/pm-stack/platform/workers.json")) { // The platform read's list, served as GitHub serves a file. - return Response.json({ + return tagged(req, entry, { content: Buffer.from(readFileSync(join(import.meta.dir, "..", "..", "platform", "workers.json"))).toString( "base64", ), }); } - if (path.includes("/actions/workflows/")) return Response.json({ workflow_runs: [] }); + if (path.includes("/actions/workflows/")) return tagged(req, entry, { workflow_runs: [] }); if (path.endsWith("/pulls")) { - return Response.json([ + return tagged(req, entry, [ { number: 7, title: "Smoke pull request", @@ -170,9 +201,9 @@ const server = Bun.serve({ }, ]); } - if (path === "search/issues") return Response.json({ total_count: 0, items: [] }); - if (path.endsWith("/issues")) return Response.json([]); - return Response.json({ message: "Not Found" }, { status: 404 }); + if (path === "search/issues") return tagged(req, entry, { total_count: 0, items: [] }); + if (path.endsWith("/issues")) return tagged(req, entry, []); + return tagged(req, entry, { message: "Not Found" }, 404); } if (url.pathname === "/queue/v2/pipeline") { outside.push({ to: "queue", path: url.pathname, auth: req.headers.get("authorization"), agent: null }); @@ -342,10 +373,67 @@ try { (platform.workers ?? []).some((w) => w.name === "pm-console-edge"), `${(platform.workers ?? []).length} workers, checked ${platform.checked}; host saw ${seen.join(", ")}`, ); + check("and no machine was asked for it", !seen.some((path) => path.includes("/api/platform")), seen.join(", ")); + // Read again, the list is asked for by the tag GitHub gave it, GitHub + // says "not modified" with no body, and this runtime's fetch hands + // that back as it is: the answer is the one kept, whole. + const githubSaid = async () => + ( + (await (await get("/console/health")).json()) as { + github?: { + answers: number; + unchanged: number; + kept: number; + quiet: { core: number | null; search: number | null }; + }; + } + ).github; + const list = () => outside.filter((call) => call.path.endsWith("/contents/pm-stack/platform/workers.json")); + const unchangedBefore = (await githubSaid())?.unchanged ?? -1; + const again = (await (await asOwner("/console/api/platform")).json()) as typeof platform; + const lastAsk = list().at(-1); + const said = await githubSaid(); check( - "and no machine was asked for it", - !seen.some((path) => path.includes("/api/platform")), - seen.join(", "), + 'a list read again is asked for by its tag, and GitHub\'s "not modified" is the kept answer', + lastAsk?.status === 304 && + typeof lastAsk.tag === "string" && + lastAsk.tag.startsWith('W/"') && + JSON.stringify(again.workers) === JSON.stringify(platform.workers) && + (again.workers ?? []).length > 0 && + (said?.unchanged ?? 0) > unchangedBefore && + (said?.kept ?? 0) > 0, + `asked by ${lastAsk?.tag}, answered ${lastAsk?.status}; health ${JSON.stringify(said)}, before ${unchangedBefore}`, + ); + // GitHub turns the account away: nothing left of the hour, back in a + // few seconds. The time is kept to in this runtime: until it comes + // the Worker asks GitHub for nothing counted by the hour, and then + // it asks again. + spent.until = Math.ceil(Date.now() / 1000) + 4; + const quietTo = spent.until * 1000; + const turned = await asOwner("/console/api/platform"); + await turned.text(); + spent.until = 0; + const until = (await githubSaid())?.quiet.core ?? null; + const askedBy = outside.filter((call) => call.to === "github").length; + // GitHub would answer now, and is not asked: not for this read, and + // not by anything else the Worker does meanwhile. + const held = await asOwner("/console/api/platform"); + await held.text(); + check( + "turned away with the hour used up, the Worker keeps to the time GitHub gave and asks it nothing more", + until === quietTo && outside.filter((call) => call.to === "github").length === askedBy, + `quiet until ${until}, GitHub said ${quietTo}; the read answered ${turned.status}, then ${held.status}; ${ + outside.filter((call) => call.to === "github").length - askedBy + } calls while quiet`, + ); + await new Promise((resolve) => setTimeout(resolve, Math.max(0, (until ?? 0) - Date.now()) + 400)); + const back = (await (await asOwner("/console/api/platform")).json()) as typeof platform; + check( + "and when the time has come it asks again, and reads the list", + (back.workers ?? []).some((w) => w.name === "pm-console-edge") && + outside.filter((call) => call.to === "github").length > askedBy && + (await githubSaid())?.quiet.core === null, + `${(back.workers ?? []).length} workers; ${outside.filter((call) => call.to === "github").length - askedBy} more calls`, ); // Someone to tell: a device takes notifications (its service is a // known one and its key a real point; nothing is sent to it in @@ -354,16 +442,19 @@ try { "sign", "verify", ])) as CryptoKeyPair; - const devicePoint = Buffer.from((await crypto.subtle.exportKey("raw", devicePair.publicKey)) as ArrayBuffer).toString( - "base64url", - ); + const devicePoint = Buffer.from( + (await crypto.subtle.exportKey("raw", devicePair.publicKey)) as ArrayBuffer, + ).toString("base64url"); const subscribed = (await ( await actAsOwner( "push.on", { subscription: { endpoint: "https://fcm.googleapis.com/fcm/send/smoke-run", - keys: { p256dh: devicePoint, auth: Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString("base64url") }, + keys: { + p256dh: devicePoint, + auth: Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString("base64url"), + }, }, label: "smoke", }, @@ -450,7 +541,9 @@ try { // With the host gone, what may be done late is held here instead of // lost: signed in, it can be seen waiting and taken back. const heldId = "33333333-3333-4333-8333-333333333333"; - const heldAnswer = (await (await actAsOwner("message.send", { to: "smoke", text: "held by the smoke run" }, heldId)).json()) as { + const heldAnswer = (await ( + await actAsOwner("message.send", { to: "smoke", text: "held by the smoke run" }, heldId) + ).json()) as { ok?: boolean; held?: boolean; }; diff --git a/pm-stack/console/test/app.test.ts b/pm-stack/console/test/app.test.ts index 116bbb3a41..fcb32fd03d 100644 --- a/pm-stack/console/test/app.test.ts +++ b/pm-stack/console/test/app.test.ts @@ -36,6 +36,7 @@ import { servingSaid, subscriptionState, testSaid, + unreadSaid, whySaid, workerSaid, } from "../public/app.js"; @@ -960,9 +961,94 @@ test("why something could not be read is said in the owner's words where the rea ); // None of the raw answer is shown: no JSON, no request number, no user number. expect(/[{}"]|request ID|11225574/.test(said)).toBe(false); - expect(whySaid("You have exceeded a secondary rate limit")).toBe(said); + // Turned away for going too fast is not the hour's allowance, and is not said to be. + const fast = "GitHub turned this account away for asking too often just now"; + expect(whySaid("You have exceeded a secondary rate limit")).toBe(`${fast}; it is asked again every few minutes`); + // Where Cloudflare was the one turned away, why starts with the time GitHub gave, and that + // time is said as the clock on this device shows it. + const now = Date.UTC(2026, 10, 23, 17, 20, 0); + const back = Date.UTC(2026, 10, 23, 18, 0, 0); + const clock = (at: number) => new Date(at).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" }); + const then = (at: number) => `GitHub says it answers again at ${clock(at)}, and it is not asked before then`; + const asked = (at: number, why: string) => `GitHub says to ask again at ${new Date(at).toISOString()}: ${why}`; + const hour = "GitHub's allowance for the hour is used up on this account, which the agents share"; + const timed = `fleet gh failed (exit 1): ${asked(back, limited)}`; + expect(whySaid(timed, now)).toBe(`${hour}; ${then(back)}`); + expect(/[{}"]|request ID|11225574|2026-11-23T/.test(whySaid(timed, now))).toBe(false); + // What Cloudflare says of a call it did not make, GitHub having said not to ask yet: the same. + expect(whySaid(asked(back, `not asked again since GitHub answered: ${limited}`), now)).toBe(whySaid(timed, now)); + // Read after the time has come (the notice is older than the wait): no time already past is promised. + expect(whySaid(timed, back + 1)).toBe( + `${hour}; the time GitHub gave for asking again has come, and it is being asked`, + ); + expect(whySaid(timed, back)).toBe(whySaid(timed, back + 1)); + // Going too fast, with a time. + expect(whySaid(asked(back, "You have exceeded a secondary rate limit"), now)).toBe(`${fast}; ${then(back)}`); + // GitHub says "rate limit exceeded" of searches too, which it counts by the minute: a wait + // of a minute or two is not the hour's allowance, whatever the words. + expect(whySaid(asked(now + 40_000, limited), now)).toBe(`${fast}; ${then(now + 40_000)}`); + expect(whySaid(asked(now + 120_000, limited), now)).toBe(`${fast}; ${then(now + 120_000)}`); + expect(whySaid(asked(now + 120_001, limited), now)).toBe(`${hour}; ${then(now + 120_001)}`); + // Turned away with a time and no words at all. + expect(whySaid(asked(back, "GitHub answered http 429"), now)).toBe(`${fast}; ${then(back)}`); + // A time that is not one is not read as one. + expect(whySaid("GitHub says to ask again at teatime: API rate limit exceeded", now)).toBe(said); // Anything else is said as it came, and nothing is said as "no reason given". expect(whySaid("connection refused")).toBe("connection refused"); expect(whySaid(" timed out \n")).toBe("timed out"); for (const none of ["", null, undefined, " "]) expect([none, whySaid(none)]).toEqual([none, "no reason given"]); }); + +test("each list that could not be read is said on the screens that show it, with why and how old the copy is", () => { + const now = Date.UTC(2026, 10, 23, 17, 20, 0); + const limited = + 'fleet gh failed (exit 1): {"message":"API rate limit exceeded for user ID 11225574.","status":"403"}'; + const doc = { + health: { + prs: { ok: false, error: limited }, + priorities: { ok: true, error: null }, + agents: { ok: false, error: "bridge: connection refused" }, + services: { ok: false, error: "systemctl: timed out" }, + // Not read, and no reason given: nothing is made up for it. + more: { ok: false, error: null }, + }, + read: { + prs: new Date(now - 12 * 60_000).toISOString(), + agents: null, + services: new Date(now - 2 * 3600_000).toISOString(), + }, + }; + const hour = + "GitHub's allowance for the hour is used up on this account, which the agents share; it is asked again every few minutes and answers when the hour turns"; + // A screen that shows all of a document's lists is told of each, in the document's order. + expect(unreadSaid(doc, null, now)).toEqual([ + `Could not read pull requests just now: ${hour}. Showing the last good copy, read 12 min ago.`, + "Could not read agents just now: bridge: connection refused. Showing the last good copy.", + "Could not read the machine's units just now: systemctl: timed out. Showing the last good copy, read 2 h ago.", + ]); + // A screen that shows one list is told of that one, and of no other's trouble. + expect(unreadSaid(doc, ["prs"], now)).toEqual([ + `Could not read pull requests just now: ${hour}. Showing the last good copy, read 12 min ago.`, + ]); + expect(unreadSaid(doc, ["priorities"], now)).toEqual([]); + expect(unreadSaid(doc, ["agents", "services"], now)).toHaveLength(2); + // A document with nothing wrong, or none yet, says nothing. + expect(unreadSaid({ health: { prs: { ok: true, error: null } } }, null, now)).toEqual([]); + for (const none of [null, undefined, {}]) expect(unreadSaid(none, ["prs"], now)).toEqual([]); + // Every screen drawn from the operations document names its own list, so that none shows + // an old copy with nothing said (the Pull requests screen did, until this was written). + const source = readFileSync(new URL("../public/app.js", import.meta.url), "utf8"); + for (const [view, list] of [ + ["viewPrs", "prs"], + ["viewIssues", "priorities"], + ["viewAgents", "agents"], + ["viewServices", "services"], + ]) { + const at = source.indexOf(`function ${view}(`); + const body = source.slice( + at, + source.indexOf("\nfunction ", at + 10) > 0 ? source.indexOf("\nfunction ", at + 10) : undefined, + ); + expect([view, at > 0 && body.includes(`...notices(docs.ops, ["${list}"])`)]).toEqual([view, true]); + } +}); diff --git a/pm-stack/console/test/direct.test.ts b/pm-stack/console/test/direct.test.ts index c2201789ce..4863b2a2cf 100644 --- a/pm-stack/console/test/direct.test.ts +++ b/pm-stack/console/test/direct.test.ts @@ -16,6 +16,7 @@ import { directClasses, directConfig, directRead, + drawsOn, edgeRun, githubMemory, type KeptAnswer, @@ -424,6 +425,8 @@ describe("what the edge remembers of GitHub", () => { test("each address has its own answer, and a write is never asked for by a tag", async () => { const g = tagging(); await g.api(PULLS); + // (Changed twice before it is first read, so its tag is not the other list's.) + g.change(at(ISSUES), []); g.change(at(ISSUES), [{ number: 9 }]); expect((await g.api(ISSUES)).stdout).toBe('[{"number":9}]'); expect((await g.api(PULLS)).stdout).toBe('[{"number":1}]'); @@ -483,10 +486,11 @@ describe("what the edge remembers of GitHub", () => { const back = g.clock.t + 40 * 60_000; g.state.limited = { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(back / 1000) }; const turned = await g.api(PULLS); + const said = '{"message":"API rate limit exceeded for user ID 1."}'; expect(turned).toEqual({ code: 1, stdout: "", - stderr: `GitHub says to ask again at ${new Date(back).toISOString()}: {"message":"API rate limit exceeded for user ID 1."}`, + stderr: `GitHub says to ask again at ${new Date(back).toISOString()}: ${said}`, }); expect(g.seen[1]).toEqual({ to: "github", write: false, status: 403, limited: true, until: back }); // Until then nothing goes out: not a read, not a write, though GitHub would answer now. @@ -496,47 +500,140 @@ describe("what the edge remembers of GitHub", () => { const read = await g.api(ISSUES); const write = await g.api("-X", "PUT", "repos/developing-today/code/pulls/55/merge"); expect(g.calls.length).toBe(asked); + // Why is the time and GitHub's own words, so whoever reads it can tell which allowance it was. for (const held of [read, write]) { - expect(held.code).toBe(1); - expect(held.stderr).toStartWith(`GitHub says to ask again at ${new Date(back).toISOString()}: not asked`); - expect(held.stderr).toMatch(/rate limit/i); + expect(held).toEqual({ + code: 1, + stdout: "", + stderr: `GitHub says to ask again at ${new Date(back).toISOString()}: not asked again since GitHub answered: ${said}`, + }); } - // Each is recorded as the answer it would have had: not sent, so nothing written. + // Each is recorded as the answer it would have had, and as not sent: nothing was written. expect(g.seen.slice(2)).toEqual([ - { to: "github", write: false, status: 429, limited: true, until: back }, - { to: "github", write: true, status: 429, limited: true, until: back }, + { to: "github", write: false, status: 429, limited: true, until: back, unsent: true }, + { to: "github", write: true, status: 429, limited: true, until: back, unsent: true }, ]); // The time comes: it is asked again, and what was kept is still asked for by its tag. + g.clock.t = back - 1; + await g.api(PULLS); + expect(g.calls.length).toBe(asked); g.clock.t = back; expect((await g.api(PULLS)).code).toBe(0); expect(g.calls[asked]).toEqual({ method: "GET", url: at(PULLS), tag: 'W/"1"' }); }); + test("searches are counted apart: their allowance running out does not hush the rest, nor the rest theirs; going too fast hushes both", async () => { + const SEARCH = "search/issues?q=repo%3Adeveloping-today%2Fcode+label%3Anow"; + const g = tagging(); + const start = g.clock.t; + // The minute's searches are used up, back in forty seconds. + g.state.limited = { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String((start + 40_000) / 1000) }; + expect((await g.api(SEARCH)).code).toBe(1); + g.state.limited = null; + expect(g.memory?.quiet).toEqual({ + search: { until: start + 40_000, why: '{"message":"API rate limit exceeded for user ID 1."}' }, + }); + // The lists are asked for as before; another search is not. + expect((await g.api(PULLS)).code).toBe(0); + expect((await g.api(SEARCH)).stderr).toContain("not asked again"); + expect(g.calls.map((call) => call.url)).toEqual([at(SEARCH), at(PULLS)]); + g.clock.t = start + 40_000; + expect((await g.api(SEARCH)).code).toBe(0); + // The hour's allowance used up, as a list is read: searches are still asked. + const back = g.clock.t + 30 * 60_000; + g.state.limited = { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(back / 1000) }; + expect((await g.api(PULLS)).code).toBe(1); + g.state.limited = null; + const asked = g.calls.length; + expect((await g.api(SEARCH)).code).toBe(0); + expect((await g.api(ISSUES)).stderr).toContain("not asked again"); + expect(g.calls.length).toBe(asked + 1); + // GitHub names the allowance it means, and is believed over the address asked at. + const named = tagging(); + named.state.limited = { + "x-ratelimit-remaining": "0", + "x-ratelimit-reset": String((named.clock.t + 600_000) / 1000), + "x-ratelimit-resource": "core", + }; + await named.api(SEARCH); + expect(Object.keys(named.memory?.quiet ?? {})).toEqual(["core"]); + // One it names that this side does not know is taken as the call's own. + const other = tagging(); + other.state.limited = { + "x-ratelimit-remaining": "0", + "x-ratelimit-reset": String((other.clock.t + 600_000) / 1000), + "x-ratelimit-resource": "code_search", + }; + await other.api(SEARCH); + expect(Object.keys(other.memory?.quiet ?? {})).toEqual(["search"]); + // Going too fast is said in seconds, of the caller: both are hushed, and a nearer time + // never shortens a further one. + const fast = tagging(); + fast.state.limited = { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String((fast.clock.t + 900_000) / 1000) }; + await fast.api(PULLS); + fast.state.limited = { "retry-after": "60" }; + await fast.api(SEARCH); + expect([fast.memory?.quiet.core?.until, fast.memory?.quiet.search?.until]).toEqual([ + fast.clock.t + 900_000, + fast.clock.t + 60_000, + ]); + }); + + test("an answer is an answer: one that says nothing is left of the hour hushes nothing, and neither does being turned away with no time", async () => { + const g = tagging(); + // The last call the hour allows is answered in full, and its headers say nothing is left. + const run = edgeRun( + directConfig(edgeConfig), + { githubToken: "gh-test", github: g.memory, now: () => g.clock.t }, + (async () => ({ + ok: true, + status: 200, + headers: new Headers({ + etag: '"a"', + "x-ratelimit-remaining": "0", + "x-ratelimit-reset": String((g.clock.t + 1_800_000) / 1000), + }), + json: async () => [], + })) as unknown as Fetch, + ); + expect((await run(["fleet", "gh", "api", PULLS])).code).toBe(0); + expect(g.memory?.quiet).toEqual({}); + // Turned away with no time given: told as limited, and the next call is asked all the same. + g.state.limited = {}; + expect((await g.api(ISSUES)).stderr).toBe('{"message":"API rate limit exceeded for user ID 1."}'); + expect(g.seen.at(-1)).toEqual({ to: "github", write: false, status: 403, limited: true }); + g.state.limited = null; + expect((await g.api(ISSUES)).code).toBe(0); + expect(g.memory?.quiet).toEqual({}); + }); + test("when to ask again: the seconds GitHub gives, or the turn of the hour when nothing is left of it; never the past, never much over an hour", () => { const now = Date.UTC(2026, 10, 23, 17, 0, 0); const said = (headers: Record) => askAgainAt(new Headers(headers), now); - expect(said({ "retry-after": "60" })).toBe(now + 60_000); - expect(said({ "retry-after": "0" })).toBe(now); - expect(said({ "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(now / 1000 + 1500) })).toBe( - now + 1_500_000, - ); + const reset = (seconds: number) => ({ + "x-ratelimit-remaining": "0", + "x-ratelimit-reset": String(now / 1000 + seconds), + }); + expect(said({ "retry-after": "60" })).toEqual({ until: now + 60_000, whole: true }); + expect(said({ "retry-after": "0" })).toEqual({ until: now, whole: true }); + expect(said(reset(1500))).toEqual({ until: now + 1_500_000, whole: false }); // Both: the seconds are for this caller, now. - expect( - said({ "retry-after": "30", "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(now / 1000 + 1500) }), - ).toBe(now + 30_000); - // Something left of the hour's allowance: the turn of the hour is not when to ask again. + expect(said({ "retry-after": "30", ...reset(1500) })).toEqual({ until: now + 30_000, whole: true }); + // Something left of the allowance: the turn of the hour is not when to ask again. expect(said({ "x-ratelimit-remaining": "12", "x-ratelimit-reset": String(now / 1000 + 1500) })).toBeUndefined(); expect(said({ "x-ratelimit-reset": String(now / 1000 + 1500) })).toBeUndefined(); expect(said({})).toBeUndefined(); expect(askAgainAt(undefined, now)).toBeUndefined(); // A time that cannot be right is cut to a little over the hour; one already past is now. - expect(said({ "retry-after": "86400" })).toBe(now + QUIET_MOST_MS); - expect(said({ "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(now / 1000 + 7 * 3600) })).toBe( - now + QUIET_MOST_MS, - ); - expect(said({ "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(now / 1000 - 30) })).toBe(now); + expect(said({ "retry-after": "86400" })?.until).toBe(now + QUIET_MOST_MS); + expect(said(reset(7 * 3600))?.until).toBe(now + QUIET_MOST_MS); + expect(said(reset(-30))?.until).toBe(now); // A date, as the header may also be written, is not read: no time is better than a wrong one. expect(said({ "retry-after": "Mon, 23 Nov 2026 18:00:00 GMT" })).toBeUndefined(); + // Which allowance a call draws on is by what is asked for. + expect( + ["search/issues?q=x", "/search/code", "repos/o/r/pulls", "repos/o/search/x", "searches"].map(drawsOn), + ).toEqual(["search", "search", "core", "core", "core"]); }); test("property: whatever GitHub's headers say, the time to ask again is none, or between now and a little over an hour on", () => { @@ -566,7 +663,7 @@ describe("what the edge remembers of GitHub", () => { const headers: Record = {}; for (const name of ["retry-after", "x-ratelimit-remaining", "x-ratelimit-reset"]) if (next() < 0.7) headers[name] = value(); - const at = askAgainAt(new Headers(headers), now); + const at = askAgainAt(new Headers(headers), now)?.until; if (at === undefined) none++; else { some++; diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index cc4ea54925..41b0236219 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -1081,7 +1081,7 @@ describe("before the host's first report", () => { directReady: false, refused: [], selfCheck: null, - github: { answers: 0, unchanged: 0, kept: 0, quietUntil: null }, + github: { answers: 0, unchanged: 0, kept: 0, quiet: { core: null, search: null } }, hostSeen: null, hostVersion: null, androidBuild: null, @@ -4331,7 +4331,12 @@ describe("the edge does the core itself", () => { const githubSaid = async (w: World) => ( (await (await w.browse("/console/health", { token: null })).json()) as { - github: { answers: number; unchanged: number; kept: number; quietUntil: number | null }; + github: { + answers: number; + unchanged: number; + kept: number; + quiet: { core: number | null; search: number | null }; + }; } ).github; @@ -4372,7 +4377,7 @@ describe("the edge does the core itself", () => { const said = await githubSaid(w); await settle(w); expect([said.unchanged, said.answers]).toEqual([w.ghTags.unchanged, w.githubCalls.length]); - expect([said.kept > 0, said.quietUntil]).toEqual([true, null]); + expect([said.kept > 0, said.quiet]).toEqual([true, { core: null, search: null }]); // A GitHub that gave no tags is the same to look at: every answer a full one. const plain = await primary(); plain.ghTags.on = false; @@ -4385,20 +4390,22 @@ describe("the edge does the core itself", () => { expect(plain.ghTags.unchanged).toBe(0); }); - test("the hour's allowance used up: GitHub's own time is kept to, nothing is asked of it until then, and the last good copy says why and when", async () => { + test("the hour's allowance used up: GitHub's own time is kept to, nothing that draws on it is asked until then, and the last good copy says why and when", async () => { const w = await primary(); const first = { core: (await w.core()).doc, ops: await opsDoc(w) }; await settle(w); // No machine either: what this side kept is all there is to show. w.net.hostUp = false; w.net.edgeUp = false; - // GitHub: the account's allowance is used up, and comes back in forty minutes. + // GitHub: the account's allowance for the hour is used up, and comes back in forty minutes. + // Searches it counts apart, and those it still answers. w.now.t += 181_000; const back = Math.floor((w.now.t + 40 * 60_000) / 1000) * 1000; - w.ghLimits.push(() => true); + w.ghLimits.push((_method, url) => !url.includes("/search/")); w.ghLimitSays.headers = { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(back / 1000) }; - const asked = () => w.githubCalls.length; - const before = asked(); + const hourly = () => w.githubCalls.filter((c) => !c.url.includes("/search/")).length; + const searches = () => w.githubCalls.length - hourly(); + const before = { hourly: hourly(), searches: searches() }; const look = async () => { await w.core(); await opsDoc(w); @@ -4408,38 +4415,50 @@ describe("the edge does the core itself", () => { return seen; }; const limited = await look(); - // It was told once, by the first thing it asked. Nothing else was asked: not the - // other lists of that round, and not the second look. - expect(asked()).toBe(before + 1); + // It was told once, by the first thing it asked. Nothing else that draws on the hour was + // asked: not the other list of that round, and not the second look. + expect(hourly()).toBe(before.hourly + 1); expect([limited.ops.prs, limited.ops.priorities, limited.core.asks]).toEqual([ first.ops.prs, first.ops.priorities, first.core.asks, ]); - const why = [limited.ops.health.prs, limited.ops.health.priorities, limited.core.health.asks]; - for (const section of why) { + for (const section of [limited.ops.health.prs, limited.core.health.asks]) { expect(section.ok).toBe(false); expect(section.error).toContain(`GitHub says to ask again at ${new Date(back).toISOString()}`); - expect(section.error).toMatch(/rate limit/i); + expect(section.error).toMatch(/API rate limit exceeded/); } - // For the forty minutes: screens looked at, minutes passing, the check that health makes. - // None of it reaches GitHub. - for (let minute = 3; minute < 40; minute += 3) { + // Ranked issues are a search: read as ever. + expect(limited.ops.health.priorities.ok).toBe(true); + expect(searches()).toBeGreaterThan(before.searches); + // Twenty minutes with nobody looking: the two lists are still not this side's to read, and + // it has not claimed them back in between only to be turned away again. + const refused = async () => + ((await (await w.browse("/console/health", { token: null })).json()) as { refused: string[] }).refused; + w.now.t += 20 * 60_000; + expect(await refused()).toEqual(["read.asks", "read.prs"]); + await settle(w); + // For the rest of the forty: screens looked at, minutes passing, the check that health + // makes. None of it asks GitHub for anything counted by the hour, and what is held back + // here is not counted as an answer of GitHub's. + for (let minute = 23; minute < 40; minute += 3) { w.now.t += 3 * 60_000; await look(); - expect([minute, (await githubSaid(w)).quietUntil]).toEqual([minute, back]); + const said = await githubSaid(w); await settle(w); + expect([minute, said.quiet, said.answers]).toEqual([minute, { core: back, search: null }, w.githubCalls.length]); + expect([minute, hourly()]).toEqual([minute, before.hourly + 1]); } // Nor does something the owner does: it is kept, not sent and not lost. const tried = await w.act("issue.rank", { issue: 301, rank: "next" }); expect(await tried.json()).toMatchObject({ ok: true, held: true }); - expect(asked()).toBe(before + 1); + expect(hourly()).toBe(before.hourly + 1); // The time comes, and GitHub answers again: it is asked, and what it says is shown with nothing wrong. w.ghLimits.length = 0; w.now.t = back + 181_000; const after = await look(); - expect(asked()).toBeGreaterThan(before + 1); - expect((await githubSaid(w)).quietUntil).toBeNull(); + expect(hourly()).toBeGreaterThan(before.hourly + 1); + expect((await githubSaid(w)).quiet).toEqual({ core: null, search: null }); expect([after.ops.health.prs.ok, after.ops.health.priorities.ok, after.core.health.asks.ok]).toEqual([ true, true, @@ -4465,7 +4484,7 @@ describe("the edge does the core itself", () => { await look(); expect(pulls()).toBe(2); // (Health makes its own check of each read the first time it is asked: one more.) - expect((await githubSaid(w)).quietUntil).toBeNull(); + expect((await githubSaid(w)).quiet).toEqual({ core: null, search: null }); await settle(w); const before = pulls(); expect(before).toBe(3); @@ -4481,7 +4500,8 @@ describe("the edge does the core itself", () => { const told = w.now.t; await look(); expect(pulls()).toBe(before + 2); - expect((await githubSaid(w)).quietUntil).toBe(told + 65 * 60_000); + // (Said in seconds, it is said of the caller: searches are hushed with the rest.) + expect((await githubSaid(w)).quiet).toEqual({ core: told + 65 * 60_000, search: told + 65 * 60_000 }); // And the owner saying "try again now" is taken at their word: the list is asked for at // its next turn, not an hour on. await w.act("edge.retry", {}); @@ -4489,7 +4509,7 @@ describe("the edge does the core itself", () => { w.now.t += 91_000; await look(); expect(pulls()).toBe(before + 3); - expect((await githubSaid(w)).quietUntil).toBeNull(); + expect((await githubSaid(w)).quiet).toEqual({ core: null, search: null }); }); test("turned away for calling too often is not refused for the hour: the laptop does it meanwhile, and this side tries again in five minutes", async () => { From 06914ce89db78b6378479fe4c7c9793b2dbcbb26 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 12:06:37 -0600 Subject: [PATCH 3/3] docs(planning): the edge's GitHub allowance is under way (#13489) Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01YLT5K1QVuzZjfWGFhXSSNF --- planning/roadmaps/pm-stack.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/planning/roadmaps/pm-stack.md b/planning/roadmaps/pm-stack.md index dd098e0d9c..9281a05879 100644 --- a/planning/roadmaps/pm-stack.md +++ b/planning/roadmaps/pm-stack.md @@ -17,7 +17,7 @@ The roadmap of record is this file and its siblings in `planning/roadmaps/`. The | The app works with no connection | shipped | It shows what the device last saw and sends what was done once, in order, when the connection is back. | #13287 | | Machines | shipped | The laptop is one machine among several: what each can do, what waits for one, and taking it back. | #13471 | | Platform: every Worker in one list | shipped | Eighteen Workers, where each lives, whether it is in service and how it gets there, held true to the repository by a test. | #13487 | -| The edge's own GitHub allowance | shaped | The core must not stop being readable when agents have used the account's hourly allowance. | #13489 | +| The edge's own GitHub allowance | in-progress | The core must not stop being readable when agents have used the account's hourly allowance. | #13489 | | Queue tasks filed, cancelled and unblocked from Cloudflare | shaped | A prompt sent with the laptop away is picked up, not only filed. | #13490 | | Questions, what needs you and sessions with no machine | shaped | The last sections that are only as fresh as a machine's last report. | #13491 |