console-budget-cold-warm: a two-tier performance budget, 150 ms warm and 500 ms cold, and S3 requests per background job
internal/perf classifies every request. A GET or HEAD that made no S3 or box request before its first byte is warm (WarmBudget, 150 ms); one that made at least one is cold (ColdBudget, 500 ms), both judged on the first byte. A write (POST, PUT, PATCH, DELETE) has WriteBudget, 500 ms, measured from the read that finished its request body (EOF, or Content-Length bytes, else the last read before the first byte) to the first byte, so an upload's transfer time is not the console's latency. The middleware wraps the body in a plain timing io.ReadCloser to see that read. Samples carry Class, BodyRead and Latency; groups count warm, cold and write requests each with its own over-budget count, and their p50/p95 are of the judged time. The Console speed section on /fleet/metrics is two tables: pages (Warm, Over 150 ms, Cold, Over 500 ms; on a phone Route, both over columns and p95) and Changes (Requests, Over 500 ms). New copy CPF-20 to CPF-29 in docs/superpowers/plans/2026-10-28-console-budget-copy.md, Luna's wording applied verbatim (4 changed, none flagged), registered in the console perf copy gate, which now reads both records; CPF-2 and CPF-11 are retired. Background S3: every s.jobs.Run carries a perf.Counter on its context, so TimeDoer charges a run's S3 and box requests to the job rather than to the unattributed background count. The jobs table on Boxes and the dashboard shows S3 requests since start and the average per finished run. The footer now counts only what no page request and no job made. The CI walk holds warm views to a 150 ms median, every view and every cold first view to 500 ms, and its one write (promote) to 500 ms after the body, judged on the console's own sample (Recorder.Last). Every over record was re-measured with CARLOS_PERF_REMEASURE=1: five deleted, fourteen become calls records (they pass but read S3 on every view), four stay over (Overview, Running, instance page, the Domains settings section) plus the promote write. The cold reset now also clears the metrics sweep. The walk times the screens it used to exempt, so its total cap is 15 s (was 10 s). Tests: perf unit tests for each class, the body read and the counter; a production-wired job run on newPerfFixture whose S3 requests the fake answered all land on the job and on its Boxes and dashboard row; an opt-in report (CARLOS_JOBS_S3_REPORT=1) that runs every worker once and checks jobs plus unattributed equal the fake's count. Census card clean; record- write census unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
22 files changed,
+1,365
−218
approved_console_perf_copy_test.go+42 −13docs/superpowers/plans/2026-10-25-console-perf-copy.md+4 −0docs/superpowers/plans/2026-10-28-console-budget-copy.md+47 −0docs/superpowers/plans/LUNA-COPY-BRIEF-CONSOLE-BUDGET.md+70 −0docs/superpowers/plans/LUNA-COPY-REVIEW-CONSOLE-BUDGET.md+14 −0docs/superpowers/specs/2026-10-25-console-ux-perf-design.md+11 −0internal/console/jobs.go+84 −15internal/console/jobs_s3_test.go+165 −0internal/console/jobs_test.go+1 −1internal/console/perflatency_test.go+8 −5internal/console/perfspeed.go+38 −12internal/console/perfspeed_test.go+64 −2internal/console/perfwalk_test.go+233 −33internal/console/server.go+6 −3internal/console/static/ops.css+1 −1internal/console/templates/metrics.html+26 −5internal/console/templates/opparts.html+5 −3internal/console/testdata/perf-budgets.txt+59 −42internal/perf/middleware.go+133 −22internal/perf/middleware_test.go+204 −28internal/perf/perf.go+110 −30internal/perf/perf_test.go+40 −3
CI passed — run details
diff --git a/approved_console_perf_copy_test.go b/approved_console_perf_copy_test.go| index 5ab430df5..65ef0e6b9 100644 |
| --- a/approved_console_perf_copy_test.go |
| +++ b/approved_console_perf_copy_test.go |
| @@ -14,7 +14,9 @@ import ( |
| // the moves gate's helpers (parseCopyTable, checkMovesInventory, |
| // checkMovesNoEmDash, checkRunBuilt, checkRunApplied), exactly as the edge |
| // asset cache gate does, so the parser, the em dash rule and the "text is in |
| -// the file" match are the record formats' already. |
| +// the file" match are the record formats' already. The two-tier budget's rows |
| +// (CPF-20 on) are a second record, 2026-10-28-console-budget-copy.md, read |
| +// beside the first as one inventory. |
| // |
| // - TestConsolePerfCopyInventory: the record names exactly |
| // consolePerfCopyIDs, and no row holds an em dash; |
| @@ -23,15 +25,21 @@ import ( |
| // names. No pending string reaches code or templates. |
| const consolePerfCopyRecordPath = "docs/superpowers/plans/2026-10-25-console-perf-copy.md" |
| +// consoleBudgetCopyRecordPath is the two-tier budget's record (CPF-20 on). |
| +const consoleBudgetCopyRecordPath = "docs/superpowers/plans/2026-10-28-console-budget-copy.md" |
| + |
| var consolePerfCopyIDPattern = regexp.MustCompile(`^CPF-[0-9]+$`) |
| -// consolePerfCopyIDs is the record's inventory, pinned: CPF-1 to CPF-11 (plan |
| -// 1). Plan 2 adds its rows from CPF-20 and extends this list. |
| +// consolePerfCopyIDs is the records' inventory, pinned: CPF-1 to CPF-11 |
| +// (plan 1) and CPF-20 to CPF-29 (the two-tier budget). |
| var consolePerfCopyIDs = func() []string { |
| - ids := make([]string, 0, 11) |
| + ids := make([]string, 0, 21) |
| for i := 1; i <= 11; i++ { |
| ids = append(ids, "CPF-"+strconv.Itoa(i)) |
| } |
| + for i := 20; i <= 29; i++ { |
| + ids = append(ids, "CPF-"+strconv.Itoa(i)) |
| + } |
| return ids |
| }() |
| @@ -40,9 +48,14 @@ var consolePerfCopyIDs = func() []string { |
| // once the row is approved. An entry is "CPF-n", checked in the row's first |
| // file, or "CPF-n@<path>", checked in that file. The record's file cell is |
| // metadata and is never edited for this. |
| +// |
| +// CPF-2 and CPF-11 are retired: the two-tier budget replaced them with CPF-20 |
| +// and CPF-27, and their rows stay in the first record as history. |
| var consolePerfCopyBuilt = []string{ |
| - "CPF-1", "CPF-2", "CPF-3", "CPF-4", "CPF-5", "CPF-6", |
| - "CPF-7", "CPF-8", "CPF-9", "CPF-10", "CPF-11", |
| + "CPF-1", "CPF-3", "CPF-4", "CPF-5", "CPF-6", |
| + "CPF-7", "CPF-8", "CPF-9", "CPF-10", |
| + "CPF-20", "CPF-21", "CPF-22", "CPF-23", "CPF-24", |
| + "CPF-25", "CPF-26", "CPF-27", "CPF-28", "CPF-29", |
| } |
| // consolePerfBuiltRows is entryBuiltRows (approved_asset_cache_copy_test.go) |
| @@ -60,15 +73,31 @@ func checkConsolePerfBuilt(rows []copyRow, entries []string, root string) []stri |
| return append(problems, checkRunApplied(built, root)...) |
| } |
| +// mustParseConsolePerfCopyRecord reads both records as one, refusing an id |
| +// that is in both. |
| func mustParseConsolePerfCopyRecord(t *testing.T) []copyRow { |
| t.Helper() |
| - raw, err := os.ReadFile(consolePerfCopyRecordPath) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - rows, err := parseCopyTable(string(raw), consolePerfCopyRecordPath, consolePerfCopyIDPattern, "a CPF-<n>") |
| - if err != nil { |
| - t.Fatal(err) |
| + var rows []copyRow |
| + seen := map[string]string{} |
| + for _, path := range []string{consolePerfCopyRecordPath, consoleBudgetCopyRecordPath} { |
| + raw, err := os.ReadFile(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + part, err := parseCopyTable(string(raw), path, consolePerfCopyIDPattern, "a CPF-<n>") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(part) == 0 { |
| + t.Fatalf("%s has no rows", path) |
| + } |
| + for _, r := range part { |
| + if prev, dup := seen[r.ID]; dup { |
| + t.Fatalf("copy id %s is in both %s and %s", r.ID, prev, path) |
| + } |
| + seen[r.ID] = path |
| + } |
| + rows = append(rows, part...) |
| } |
| return rows |
| } |
diff --git a/docs/superpowers/plans/2026-10-25-console-perf-copy.md b/docs/superpowers/plans/2026-10-25-console-perf-copy.md| index 00a2965cc..411333244 100644 |
| --- a/docs/superpowers/plans/2026-10-25-console-perf-copy.md |
| +++ b/docs/superpowers/plans/2026-10-25-console-perf-copy.md |
| @@ -36,6 +36,10 @@ flagged, 9 left alone). Every row below is approved by delegation to Luna, |
| Placeholders: `<n>` a whole number. In CPF-9 it is a time in whole |
| milliseconds. |
| +Retired 2026-10-28: the two-tier budget (`2026-10-28-console-budget-copy.md`) |
| +replaced CPF-2 with CPF-20 and CPF-11 with CPF-27. Their rows stay below as |
| +history; the gate no longer builds them. |
| + |
| ## Console speed table (plan 1) |
| | id | file | text | status | |
diff --git a/docs/superpowers/plans/2026-10-28-console-budget-copy.md b/docs/superpowers/plans/2026-10-28-console-budget-copy.md| new file mode 100644 |
| index 000000000..16f29a0ff |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-10-28-console-budget-copy.md |
| @@ -0,0 +1,47 @@ |
| +# Console budget: copy record |
| + |
| +Every user-facing string the two-tier console budget writes (branch |
| +`console-budget-cold-warm`, spec `2026-10-25-console-ux-perf-design.md`, |
| +Part 2): the Console speed tables on the operator-only metrics page, the |
| +line under them, and the S3 columns of the background jobs table on Boxes |
| +and the dashboard. The gate is `approved_console_perf_copy_test.go` at the |
| +repo root, which reads this record beside `2026-10-25-console-perf-copy.md`; |
| +the rules are that record's. Ids continue from CPF-20 and are never |
| +renumbered. |
| + |
| +The budget: a warm request (GET or HEAD that made no S3 or box request |
| +before its first byte) has 150 ms to its first byte; a cold one 500 ms; a |
| +change (POST, PUT, PATCH or DELETE) 500 ms from when its request body had |
| +been read. |
| + |
| +This record replaces two rows of the 2026-10-25 record, which stay there as |
| +history and are no longer built: CPF-2 (the table's explanation) by CPF-20, |
| +and CPF-11 (the line under the table) by CPF-27. CPF-1, CPF-3, CPF-4, CPF-5, |
| +CPF-6, CPF-7, CPF-8, CPF-9 and CPF-10 are unchanged and still built. |
| + |
| +Luna's review is `LUNA-COPY-REVIEW-CONSOLE-BUDGET.md` (brief |
| +`LUNA-COPY-BRIEF-CONSOLE-BUDGET.md`): 4 rows changed (CPF-20, CPF-25, |
| +CPF-27, CPF-29), none flagged, 6 left alone. Every row below is approved by |
| +delegation to Luna, 2026-10-28, with Luna's text applied verbatim. |
| + |
| +Placeholders: `<n>` a whole number. |
| + |
| +## Console speed tables |
| + |
| +| id | file | text | status | |
| +|---|---|---|---| |
| +| CPF-20 | internal/console/templates/metrics.html | This page shows the time to first byte for the last 2,048 page requests. Warm requests make no S3 or box requests before the first byte. They use memory and the console database and have a 150 ms budget. Cold requests make at least one S3 or box request before the first byte and have a 500 ms budget. | approved | |
| +| CPF-21 | internal/console/templates/metrics.html | Warm | approved | |
| +| CPF-22 | internal/console/templates/metrics.html | Cold | approved | |
| +| CPF-23 | internal/console/templates/metrics.html | Over 500 ms | approved | |
| +| CPF-24 | internal/console/templates/metrics.html | Changes | approved | |
| +| CPF-25 | internal/console/templates/metrics.html | Each change is timed from when the console has read the whole request to its first byte. Upload time does not count. The budget is 500 ms. | approved | |
| +| CPF-26 | internal/console/templates/metrics.html | No changes measured since the console started. | approved | |
| +| CPF-27 | internal/console/templates/metrics.html | The console has made <n> S3 requests since it started outside page requests and background jobs. | approved | |
| + |
| +## Background jobs table |
| + |
| +| id | file | text | status | |
| +|---|---|---|---| |
| +| CPF-28 | internal/console/templates/opparts.html | S3 requests | approved | |
| +| CPF-29 | internal/console/templates/opparts.html | Average S3 requests | approved | |
diff --git a/docs/superpowers/plans/LUNA-COPY-BRIEF-CONSOLE-BUDGET.md b/docs/superpowers/plans/LUNA-COPY-BRIEF-CONSOLE-BUDGET.md| new file mode 100644 |
| index 000000000..696fdae9b |
| --- /dev/null |
| +++ b/docs/superpowers/plans/LUNA-COPY-BRIEF-CONSOLE-BUDGET.md |
| @@ -0,0 +1,70 @@ |
| +# Copy review brief: the two-tier console budget (2026-10-28) |
| + |
| +Paul delegated copy review for this work to you. You are the copy editor; |
| +your edits will be applied as approved copy, verbatim. |
| + |
| +Read `docs/superpowers/plans/2026-10-28-console-budget-copy.md` (10 rows, ids |
| +CPF-20 to CPF-29). The draft text in each row is yours to change. The ids and |
| +files are fixed. For context, the strings already on the page are in |
| +`docs/superpowers/plans/2026-10-25-console-perf-copy.md` (CPF-1 to CPF-11: |
| +"Console speed", "Route", "Requests", "Over 150 ms", "p50", "p95", |
| +"S3 requests", "No requests measured since the console started."). |
| + |
| +## Where the strings appear |
| + |
| +Operator-only pages of the console. Only people who run the platform see |
| +them. They know what a first byte, a percentile and an S3 request are, but |
| +the words should still be plain. Many read these pages on a phone, where |
| +only the first few columns show. |
| + |
| +- The metrics page's Console speed section now has two tables. |
| + - The first is pages (GET and HEAD). CPF-20 is the sentence under the |
| + "Console speed" heading. It explains the two budgets: a request that |
| + made no S3 or box request before its first byte (served from memory and |
| + the console's own database) has 150 ms; one that made at least one has |
| + 500 ms. 2,048 is how many recent requests the console remembers. |
| + - Its columns, in order: Route, CPF-21 (how many warm requests), "Over |
| + 150 ms" (how many warm requests were over 150 ms), CPF-22 (how many cold |
| + requests), CPF-23 (how many cold requests were over 500 ms), p50, p95, |
| + S3 requests. On a phone only Route, "Over 150 ms", CPF-23 and p95 show, |
| + so those headings must make sense on their own. |
| + - The second table is changes: form posts and API writes (POST, PUT, |
| + PATCH, DELETE). CPF-24 is its heading. CPF-25 is the sentence under it: |
| + a change is timed from the moment the console has read the whole request |
| + to its first byte, so a slow upload does not count against the console, |
| + and the budget is 500 ms. Its columns: Route, Requests, CPF-23 (reused: |
| + how many changes were over 500 ms), p50, p95, S3 requests. CPF-26 shows |
| + instead of the table when nothing has been measured yet. |
| + - CPF-27 is the line under both tables: S3 requests the console made since |
| + it started that neither a page request nor a background job made (for |
| + example a cache filling itself). Background jobs now show their own S3 |
| + requests on the jobs table. `<n>` is a whole number. |
| +- The background jobs table on the Boxes page and the dashboard gains two |
| + columns, after Job, Status and Last ran, before Note. CPF-28 is the S3 |
| + requests the job has made since the console started. CPF-29 is the |
| + average S3 requests per finished run of the job. Both hold a whole number. |
| + On a phone these columns are hidden. |
| + |
| +## House rules (Paul's, all binding) |
| + |
| +- No em dashes, ever. Use a full stop and a new sentence instead. |
| +- Plain words. No jargon a reader would not know. Short. |
| +- Headings and labels in sentence case with a capital first letter. |
| +- Human text only. If a string is not human text (a log line, a route |
| + pattern, a header name, a JSON key), flag it rather than edit it. |
| +- Neutral names only (shop, example.com). Never a tenant's name. |
| +- Keep every placeholder exactly (`<n>`). |
| +- Do not change the facts a string states (2,048 requests, 150 ms, 500 ms, |
| + "since the console started", served from memory, S3 or a box, the whole |
| + request read). If a fact looks wrong or conflicts with another row, flag |
| + it, don't rewrite it. |
| +- A column heading must stay short enough to scan. |
| + |
| +## Output |
| + |
| +Markdown, in this shape: |
| + |
| +1. A table of changes only: `id | current | new | why` (a few words in why). |
| + Leave unchanged rows out. The `new` cell is the exact text to apply. |
| +2. A list of flagged rows: `id | problem`. |
| +3. One line of counts: how many rows you changed, flagged and left alone. |
diff --git a/docs/superpowers/plans/LUNA-COPY-REVIEW-CONSOLE-BUDGET.md b/docs/superpowers/plans/LUNA-COPY-REVIEW-CONSOLE-BUDGET.md| new file mode 100644 |
| index 000000000..2e094a77d |
| --- /dev/null |
| +++ b/docs/superpowers/plans/LUNA-COPY-REVIEW-CONSOLE-BUDGET.md |
| @@ -0,0 +1,14 @@ |
| +| id | current | new | why | |
| +|---|---|---|---| |
| +| CPF-20 | How long the console took to send the first byte of each page over its last 2,048 requests. A warm request was served from memory and should answer within 150 ms. A cold request had to fetch from S3 or a box and should answer within 500 ms. | This page shows the time to first byte for the last 2,048 page requests. Warm requests make no S3 or box requests before the first byte. They use memory and the console database and have a 150 ms budget. Cold requests make at least one S3 or box request before the first byte and have a 500 ms budget. | Defines both budgets clearly | |
| +| CPF-25 | How long each change took to answer, timed from when the console had read the whole request, so upload time does not count. Changes should answer within 500 ms. | Each change is timed from when the console has read the whole request to its first byte. Upload time does not count. The budget is 500 ms. | Uses the exact timing point | |
| +| CPF-27 | The console has made <n> S3 requests since it started that no page request or background job caused. | The console has made <n> S3 requests since it started outside page requests and background jobs. | Shorter and clearer | |
| +| CPF-29 | S3 per run | Average S3 requests | States that the value is an average | |
| + |
| +Flagged rows: |
| + |
| +| id | problem | |
| +|---|---| |
| +| None | No rows flagged. | |
| + |
| +Changed: 4. Flagged: 0. Left alone: 6. |
| \ No newline at end of file |
diff --git a/docs/superpowers/specs/2026-10-25-console-ux-perf-design.md b/docs/superpowers/specs/2026-10-25-console-ux-perf-design.md| index aaf8fdc6e..fce6bff45 100644 |
| --- a/docs/superpowers/specs/2026-10-25-console-ux-perf-design.md |
| +++ b/docs/superpowers/specs/2026-10-25-console-ux-perf-design.md |
| @@ -161,6 +161,17 @@ layout; dark-mode work beyond keeping new CSS on the existing variables. |
| ### 2.1 The rule |
| +**Superseded 2026-10-28 (branch `console-budget-cold-warm`) by a two-tier |
| +rule, the one Tito Go and Rastrillo use.** A GET or HEAD that made no S3 or |
| +box request before its first byte is *warm* and has **150 ms**; one that made |
| +at least one is *cold* and has **500 ms**, both to first byte. A write (POST, |
| +PUT, PATCH, DELETE) has **500 ms** from the moment its handler had read the |
| +request body, so an upload's transfer time is not the console's latency. The |
| +constants are `perf.WarmBudget`, `perf.ColdBudget` and `perf.WriteBudget`; the |
| +CI walk holds warm views to a 150 ms median, every view to 500 ms, and the |
| +walk's writes to 500 ms after the body. The text below is the first round's |
| +rule, kept as history. |
| + |
| Same rule as Rastrillo's `perf`: |
| - A **GET or HEAD to a console screen** must send its first byte within |
diff --git a/internal/console/jobs.go b/internal/console/jobs.go| index b0010071f..0635943e8 100644 |
| --- a/internal/console/jobs.go |
| +++ b/internal/console/jobs.go |
| @@ -4,11 +4,16 @@ import ( |
| "context" |
| "fmt" |
| "log" |
| + "maps" |
| + "math" |
| "runtime/debug" |
| "sort" |
| + "strconv" |
| "strings" |
| "sync" |
| "time" |
| + |
| + "github.com/carlosframework/platform/internal/perf" |
| ) |
| // The background job registry: every claim worker (claim_workers.go) wraps |
| @@ -18,6 +23,12 @@ import ( |
| // until its next run). A pass that logs a failure and steps over it calls |
| // jobFailed beside the log line, so a run that "succeeded" while it |
| // swallowed an error still shows as Failed. |
| +// |
| +// Each run also carries a perf.Counter on its context: the S3 and box |
| +// requests the pass makes through the console's timed clients are charged |
| +// to the job (perf.TimeDoer), counted since the console started and per |
| +// finished run, rather than to the recorder's unattributed background |
| +// count. |
| // JobState is a job's last outcome. |
| type JobState int |
| @@ -30,11 +41,20 @@ const ( |
| // JobStatus is one job as the registry last saw it. LastRan is when the |
| // last run finished; Err is that run's error, "" when it succeeded. |
| +// |
| +// Runs is how many runs have finished since the console started. Calls is |
| +// every outbound request the job's runs made since then, by span name |
| +// ("s3", "box"), the run in progress and work a run left behind |
| +// included; RunCalls is the finished runs' alone, so RunCalls/Runs is |
| +// the requests per run. |
| type JobStatus struct { |
| - Name string |
| - State JobState |
| - LastRan time.Time |
| - Err string |
| + Name string |
| + State JobState |
| + LastRan time.Time |
| + Err string |
| + Runs int64 |
| + Calls map[string]int64 |
| + RunCalls map[string]int64 |
| } |
| // jobEntry is one job's record. configured is false once the worker has |
| @@ -105,11 +125,40 @@ func (j *jobRegistry) exited(name string) { |
| } |
| // jobRun is the handle one run carries on its context, where jobFailed |
| -// finds it. A pass may fan out (the mail push sends per app in parallel), |
| -// hence the lock. |
| +// finds it, and the perf.Counter its outbound requests are charged to. A |
| +// pass may fan out (the mail push sends per app in parallel), hence the |
| +// lock. |
| type jobRun struct { |
| mu sync.Mutex |
| err error |
| + |
| + reg *jobRegistry |
| + name string |
| + // calls is this run's requests, until finished is set; a request |
| + // after that (work the run detached) counts in the job's total only. |
| + calls map[string]int64 |
| + finished bool |
| +} |
| + |
| +// CountCall charges one outbound request to the run's job: to the job's |
| +// total at once, so the operator pages see a long run's requests as it |
| +// makes them, and to the run's own count until the run has finished. |
| +func (r *jobRun) CountCall(name string) { |
| + r.reg.mu.Lock() |
| + e := r.reg.entry(r.name) |
| + if e.status.Calls == nil { |
| + e.status.Calls = map[string]int64{} |
| + } |
| + e.status.Calls[name]++ |
| + r.reg.mu.Unlock() |
| + r.mu.Lock() |
| + if !r.finished { |
| + if r.calls == nil { |
| + r.calls = map[string]int64{} |
| + } |
| + r.calls[name]++ |
| + } |
| + r.mu.Unlock() |
| } |
| type jobRunKey struct{} |
| @@ -138,19 +187,29 @@ func (j *jobRegistry) Run(ctx context.Context, name string, pass func(context.Co |
| e.started = j.now() |
| j.mu.Unlock() |
| - run := &jobRun{} |
| - err := runRecovered(context.WithValue(ctx, jobRunKey{}, run), name, pass) |
| + run := &jobRun{reg: j, name: name} |
| + runCtx := perf.WithCounter(context.WithValue(ctx, jobRunKey{}, run), run) |
| + err := runRecovered(runCtx, name, pass) |
| + run.mu.Lock() |
| recorded := err |
| if recorded == nil { |
| - run.mu.Lock() |
| recorded = run.err |
| - run.mu.Unlock() |
| } |
| + run.finished = true |
| + calls := run.calls |
| + run.mu.Unlock() |
| j.mu.Lock() |
| e = j.entry(name) |
| e.configured = true |
| e.running = false |
| + e.status.Runs++ |
| + for k, n := range calls { |
| + if e.status.RunCalls == nil { |
| + e.status.RunCalls = map[string]int64{} |
| + } |
| + e.status.RunCalls[k] += n |
| + } |
| e.status.LastRan = j.now() |
| if recorded != nil { |
| e.status.State = JobFailed |
| @@ -203,7 +262,9 @@ func (j *jobRegistry) Snapshot() []JobStatus { |
| out := make([]JobStatus, 0, len(j.jobs)) |
| for _, e := range j.jobs { |
| if e.configured { |
| - out = append(out, e.status) |
| + st := e.status |
| + st.Calls, st.RunCalls = maps.Clone(st.Calls), maps.Clone(st.RunCalls) |
| + out = append(out, st) |
| } |
| } |
| sort.Slice(out, func(a, b int) bool { return out[a].Name < out[b].Name }) |
| @@ -251,13 +312,18 @@ const ( |
| // one line in the table. |
| const jobNoteRunes = 160 |
| -// opJobRow is op_jobs's data: one job's label, status pill, last finish and |
| -// the first line of its last error. |
| +// opJobRow is op_jobs's data: one job's label, status pill, last finish, |
| +// its S3 requests since the console started and per finished run, and the |
| +// first line of its last error. |
| type opJobRow struct { |
| Label string |
| Status opPill |
| LastRan time.Time |
| - Note string |
| + S3 int64 |
| + // S3PerRun is the finished runs' S3 requests over their number, to a |
| + // whole number; "" before the first run finishes. |
| + S3PerRun string |
| + Note string |
| } |
| // opJobRows is snap as the jobs table's rows, sorted by label. A name with |
| @@ -270,7 +336,10 @@ func opJobRows(snap []JobStatus) []opJobRow { |
| if !ok { |
| label = st.Name |
| } |
| - row := opJobRow{Label: label, LastRan: st.LastRan} |
| + row := opJobRow{Label: label, LastRan: st.LastRan, S3: st.Calls["s3"]} |
| + if st.Runs > 0 { |
| + row.S3PerRun = strconv.FormatInt(int64(math.Round(float64(st.RunCalls["s3"])/float64(st.Runs))), 10) |
| + } |
| switch st.State { |
| case JobOK: |
| row.Status = opPill{Label: jobWordOK, Tone: "positive"} |
diff --git a/internal/console/jobs_s3_test.go b/internal/console/jobs_s3_test.go| new file mode 100644 |
| index 000000000..b10fdbbca |
| --- /dev/null |
| +++ b/internal/console/jobs_s3_test.go |
| @@ -0,0 +1,165 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "net/http" |
| + "os" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// One run of the plan limits pass through the job registry, on the perf |
| +// fixture's production S3 store: every S3 request the fake answers during |
| +// the run is the job's, in its total and in its finished runs', and none |
| +// is left in the console's unattributed background count. Boxes and the |
| +// dashboard then show the count in the job's row. |
| +func TestJobRunsChargeTheirS3RequestsToTheJob(t *testing.T) { |
| + perfCaptureLogs(t) |
| + fx, lat := newPerfFixture(t) |
| + rec := recordS3(lat, nil) |
| + b0 := fx.srv.PerfBackground()["s3"] |
| + if err := fx.srv.jobs.Run(context.Background(), "StartPlanLimitsPass", func(ctx context.Context) error { |
| + fx.srv.planLimitsPass(ctx, time.Now()) |
| + return nil |
| + }); err != nil { |
| + t.Fatalf("plan limits pass: %v", err) |
| + } |
| + n := int64(len(rec.all())) |
| + if n == 0 { |
| + t.Fatal("the plan limits pass made no S3 request on the fixture; pick a pass that reads the bucket") |
| + } |
| + st, _ := jobStatusOf(fx.srv, "StartPlanLimitsPass") |
| + if st.Runs != 1 || st.Calls["s3"] != n || st.RunCalls["s3"] != n { |
| + t.Errorf("job status = runs %d, s3 %d, finished runs' s3 %d; the fake answered %d in the run", st.Runs, st.Calls["s3"], st.RunCalls["s3"], n) |
| + } |
| + if bg := fx.srv.PerfBackground()["s3"] - b0; bg != 0 { |
| + t.Errorf("the run left %d S3 requests in the background count, want none", bg) |
| + } |
| + |
| + c := signInPaul(t, fx) |
| + for _, page := range []string{"/fleet/boxes", "/fleet"} { |
| + status, _, body := get(t, c, fx.ts.URL+page) |
| + if status != http.StatusOK { |
| + t.Fatalf("%s = %d:\n%s", page, status, body) |
| + } |
| + // The pass fails on the operator-scale accounts' sqids; the row is |
| + // there either way, and its status is not what this test is about. |
| + row := strings.Index(body, `<div rst-lrow><span>Plan limits</span>`) |
| + if row < 0 { |
| + t.Fatalf("%s has no Plan limits row:\n%s", page, body) |
| + } |
| + cells := fmt.Sprintf("<span>%d</span><span>%d</span>", n, n) |
| + if end := strings.Index(body[row:], "</div>"); end < 0 || !strings.Contains(body[row:row+end], cells) { |
| + t.Errorf("%s: the Plan limits row does not show %d S3 requests and %d per run (%s):\n%s", page, n, n, cells, body[row:]) |
| + } |
| + } |
| +} |
| + |
| +// The fixture's background jobs, each run once: every claim worker the |
| +// perf fixture configures is started, each is stopped once its first run |
| +// has finished, and the S3 requests each run made are printed, most first. |
| +// The printout is the measured half of the background S3 report (the |
| +// estimate per hour is the run counts times each job's interval). The |
| +// check is the accounting: every S3 request the fake answered while the |
| +// workers ran is either a job's or in the console's unattributed count, |
| +// never lost and never counted twice. It takes about ten seconds, so it |
| +// runs only for the report: CARLOS_JOBS_S3_REPORT=1. |
| +func TestBackgroundJobsS3OnTheFixture(t *testing.T) { |
| + if os.Getenv("CARLOS_JOBS_S3_REPORT") == "" { |
| + t.Skip("set CARLOS_JOBS_S3_REPORT=1 to run every job once on the perf fixture and print its S3 requests") |
| + } |
| + perfCaptureLogs(t) |
| + fx, lat := newPerfFixture(t) |
| + s0, _ := lat.Calls() |
| + b0 := fx.srv.PerfBackground()["s3"] |
| + |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + var wg sync.WaitGroup |
| + names := slices.Sorted(mapKeys(fx.srv.claimWorkers)) |
| + exited := make(map[string]bool) |
| + var mu sync.Mutex |
| + for _, name := range names { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + fx.srv.RunClaimWorker(ctx, name) |
| + mu.Lock() |
| + exited[name] = true |
| + mu.Unlock() |
| + }() |
| + } |
| + // A job is done when its first run finished or its worker returned |
| + // without one (nothing to do on this deployment). Some first runs wait |
| + // on a timer longer than the test; they are reported as not run. |
| + deadline := time.Now().Add(10 * time.Second) |
| + for time.Now().Before(deadline) { |
| + pending := 0 |
| + mu.Lock() |
| + for _, name := range names { |
| + if exited[name] { |
| + continue |
| + } |
| + if st, ok := jobStatusOf(fx.srv, name); !ok || st.Runs == 0 { |
| + pending++ |
| + } |
| + } |
| + mu.Unlock() |
| + if pending == 0 { |
| + break |
| + } |
| + time.Sleep(20 * time.Millisecond) |
| + } |
| + cancel() |
| + done := make(chan struct{}) |
| + go func() { wg.Wait(); close(done) }() |
| + select { |
| + case <-done: |
| + case <-time.After(30 * time.Second): |
| + t.Fatal("a claim worker did not return 30s after its context was cancelled") |
| + } |
| + if !perfIdle(perfSeedsOf(fx).inflight, 2*time.Second) { |
| + t.Fatal("a request was still running") |
| + } |
| + |
| + s1, _ := lat.Calls() |
| + bg := fx.srv.PerfBackground()["s3"] - b0 |
| + type line struct { |
| + label string |
| + runs, s3 int64 |
| + } |
| + var lines []line |
| + var jobs int64 |
| + for _, st := range fx.srv.jobs.Snapshot() { |
| + label := jobLabels[st.Name] |
| + lines = append(lines, line{label + " (" + st.Name + ")", st.Runs, st.Calls["s3"]}) |
| + jobs += st.Calls["s3"] |
| + } |
| + for _, name := range names { |
| + if _, ok := jobStatusOf(fx.srv, name); !ok { |
| + lines = append(lines, line{jobLabels[name] + " (" + name + "): not configured on the fixture", 0, 0}) |
| + } |
| + } |
| + slices.SortFunc(lines, func(a, b line) int { |
| + if a.s3 != b.s3 { |
| + return int(b.s3 - a.s3) |
| + } |
| + return strings.Compare(a.label, b.label) |
| + }) |
| + var b strings.Builder |
| + for _, l := range lines { |
| + b.WriteString(l.label + "\t" + strconv.FormatInt(l.runs, 10) + " runs\t" + strconv.FormatInt(l.s3, 10) + " S3\n") |
| + } |
| + t.Logf("background S3 requests by job, on the perf fixture, first run each:\n%s(unattributed: %d; the fake answered %d)", b.String(), bg, s1-s0) |
| + if jobs+bg != s1-s0 { |
| + t.Errorf("jobs %d + unattributed %d = %d S3 requests, the fake answered %d", jobs, bg, jobs+bg, s1-s0) |
| + } |
| + if jobs == 0 { |
| + t.Error("no job made an S3 request on the fixture") |
| + } |
| +} |
diff --git a/internal/console/jobs_test.go b/internal/console/jobs_test.go| index b64f8bac4..c9b17d3a8 100644 |
| --- a/internal/console/jobs_test.go |
| +++ b/internal/console/jobs_test.go |
| @@ -365,7 +365,7 @@ func TestJobNoteIsTheFirstLineCappedAndEscaped(t *testing.T) { |
| body := b.String() |
| for _, w := range []string{ |
| `<div rst-box-head id="jobs"><h2>Background jobs</h2></div>`, |
| - `<div rst-lrow="head"><span>Job</span><span>Status</span><span>Last ran</span><span>Note</span></div>`, |
| + `<div rst-lrow="head"><span>Job</span><span>Status</span><span>Last ran</span><span>S3 requests</span><span>Average S3 requests</span><span>Note</span></div>`, |
| "<b>disk</b> full", |
| `title="2026-10-26 09:30 UTC"`, |
| `<span rst-status rst-tone="negative">Failed</span>`, |
diff --git a/internal/console/perflatency_test.go b/internal/console/perflatency_test.go| index 97b26c116..49c183188 100644 |
| --- a/internal/console/perflatency_test.go |
| +++ b/internal/console/perflatency_test.go |
| @@ -166,12 +166,13 @@ func TestLatencyAppClientAnswersTheContract(t *testing.T) { |
| // cache answers an app page from memory in far less than the budget, so |
| // whether the over-budget warning fired would depend on how fast the |
| // page is; reading the frame afresh through the delayed fake makes the |
| -// view's S3 round trips the cost, whatever the cache saves. The frame's |
| -// reads run at once (console-perf-hot-routes), so the delay is 50 ms here, |
| -// not the walk's 25: the cold page's few rounds of them still cross the |
| -// budget. |
| +// view's S3 round trips the cost, whatever the cache saves. Such a view |
| +// is cold (it made S3 requests before its first byte), so its budget is |
| +// perf.ColdBudget, 500 ms. The frame's reads run at once |
| +// (console-perf-hot-routes), so the delay is 200 ms here, not the walk's |
| +// 25: the cold page's few rounds of them still cross that budget. |
| func TestFixtureOverTheS3FakeServesAppPage(t *testing.T) { |
| - lat := &perfLatency{S3Delay: 50 * time.Millisecond, HostDelay: 40 * time.Millisecond} |
| + lat := &perfLatency{S3Delay: 200 * time.Millisecond, HostDelay: 40 * time.Millisecond} |
| fx := newConsoleFixtureWith(t, consoleFixtureOptions{WithKey: true, S3: lat, AppClient: lat.AppClient()}) |
| c := signInPaul(t, fx) |
| const screen = "GET /a/{sqid}/apps/{app}" |
| @@ -259,6 +260,8 @@ func TestFixtureOverTheS3FakeServesAppPage(t *testing.T) { |
| t.Errorf("no over-budget warning for %s; log:\n%s", want, logs.String()) |
| } else if n := strings.Count(logs.String(), want+" "); n != 1 { |
| t.Errorf("over-budget warnings for %s = %d, want 1 (once a minute per route); log:\n%s", want, n, logs.String()) |
| + } else if !strings.Contains(logs.String(), want+" method=GET status=200 class=cold") { |
| + t.Errorf("the over-budget warning for %s does not say the view was cold; log:\n%s", want, logs.String()) |
| } |
| } |
| } |
diff --git a/internal/console/perfspeed.go b/internal/console/perfspeed.go| index 21c72bad8..6080edb51 100644 |
| --- a/internal/console/perfspeed.go |
| +++ b/internal/console/perfspeed.go |
| @@ -3,19 +3,26 @@ package console |
| import ( |
| "fmt" |
| "math" |
| + "net/http" |
| "strings" |
| "github.com/carlosframework/platform/internal/perf" |
| ) |
| -// consoleSpeedRow is one line of the Console speed table on /fleet/metrics: |
| -// one route's requests, how many were over the first-byte budget, and its |
| -// p50 and p95. S3 is the S3 requests the route's requests made. Route is |
| -// what the table's Route cell shows: the pattern with the method. |
| +// consoleSpeedRow is one line of the Console speed tables on |
| +// /fleet/metrics: one route's requests, how many were over their budget, |
| +// and the p50 and p95 of the judged time. A read's requests are counted |
| +// warm and cold, each with its own over-budget count (perf.WarmBudget, |
| +// perf.ColdBudget); a write's are Writes, over perf.WriteBudget. S3 is the |
| +// S3 requests the route's requests made. Route is what the table's Route |
| +// cell shows: the pattern with the method. |
| type consoleSpeedRow struct { |
| Screen, Method string |
| Route string |
| Requests, Over int |
| + Warm, WarmOver int |
| + Cold, ColdOver int |
| + WriteOver int |
| S3 int |
| P50, P95 string |
| } |
| @@ -27,19 +34,38 @@ func consoleSpeedRows(groups []perf.Group) []consoleSpeedRow { |
| rows := make([]consoleSpeedRow, 0, len(groups)) |
| for _, g := range groups { |
| rows = append(rows, consoleSpeedRow{ |
| - Screen: g.Screen, |
| - Method: g.Method, |
| - Route: consoleSpeedRoute(g.Screen, g.Method), |
| - Requests: g.Requests, |
| - Over: g.Over, |
| - S3: g.Calls["s3"], |
| - P50: consoleSpeedMillis(g.P50), |
| - P95: consoleSpeedMillis(g.P95), |
| + Screen: g.Screen, |
| + Method: g.Method, |
| + Route: consoleSpeedRoute(g.Screen, g.Method), |
| + Requests: g.Requests, |
| + Over: g.Over, |
| + Warm: g.Warm, |
| + WarmOver: g.WarmOver, |
| + Cold: g.Cold, |
| + ColdOver: g.ColdOver, |
| + WriteOver: g.WriteOver, |
| + S3: g.Calls["s3"], |
| + P50: consoleSpeedMillis(g.P50), |
| + P95: consoleSpeedMillis(g.P95), |
| }) |
| } |
| return rows |
| } |
| +// consoleSpeedTables splits the rows into the two tables: pages (GET and |
| +// HEAD, judged warm or cold on their first byte) and changes (every other |
| +// method, a write judged from its body read). Each keeps the rows' order. |
| +func consoleSpeedTables(groups []perf.Group) (pages, changes []consoleSpeedRow) { |
| + for _, row := range consoleSpeedRows(groups) { |
| + if row.Method == http.MethodGet || row.Method == http.MethodHead { |
| + pages = append(pages, row) |
| + } else { |
| + changes = append(changes, row) |
| + } |
| + } |
| + return pages, changes |
| +} |
| + |
| // consoleSpeedMillis is a time in milliseconds, rounded to a whole number. |
| func consoleSpeedMillis(ms float64) string { |
| return fmt.Sprintf("%d ms", int64(math.Round(ms))) |
diff --git a/internal/console/perfspeed_test.go b/internal/console/perfspeed_test.go| index 27020e10d..1174230fd 100644 |
| --- a/internal/console/perfspeed_test.go |
| +++ b/internal/console/perfspeed_test.go |
| @@ -3,6 +3,7 @@ package console |
| import ( |
| "net/http" |
| "net/url" |
| + "slices" |
| "strings" |
| "testing" |
| "time" |
| @@ -12,13 +13,13 @@ import ( |
| func TestConsoleSpeedRowsFormat(t *testing.T) { |
| rows := consoleSpeedRows([]perf.Group{ |
| - {Screen: "GET /a", Method: "GET", P50: 12.4, P95: 151.6, Requests: 3, Over: 1, Calls: map[string]int{"s3": 7}}, |
| + {Screen: "GET /a", Method: "GET", P50: 12.4, P95: 151.6, Requests: 3, Over: 1, Warm: 2, WarmOver: 1, Cold: 1, Calls: map[string]int{"s3": 7}}, |
| {Screen: "POST /b", Method: "POST", P50: 0.4, P95: 2, Requests: 1}, |
| }) |
| if len(rows) != 2 { |
| t.Fatalf("rows = %+v, want 2", rows) |
| } |
| - want := consoleSpeedRow{Screen: "GET /a", Method: "GET", Route: "GET /a", Requests: 3, Over: 1, S3: 7, P50: "12 ms", P95: "152 ms"} |
| + want := consoleSpeedRow{Screen: "GET /a", Method: "GET", Route: "GET /a", Requests: 3, Over: 1, Warm: 2, WarmOver: 1, Cold: 1, S3: 7, P50: "12 ms", P95: "152 ms"} |
| if rows[0] != want { |
| t.Errorf("row 0 = %+v, want %+v", rows[0], want) |
| } |
| @@ -146,3 +147,64 @@ func TestFleetMetricsConsoleSpeedEmptyState(t *testing.T) { |
| t.Errorf("second /fleet/metrics lacks its own route row:\n%s", again) |
| } |
| } |
| + |
| +// The pages table holds GET and HEAD, the changes table everything else, |
| +// each in the groups' order; a change row carries its over-budget count. |
| +func TestConsoleSpeedTablesSplitPagesAndChanges(t *testing.T) { |
| + pages, changes := consoleSpeedTables([]perf.Group{ |
| + {Screen: "POST /a", Method: "POST", P95: 900, Requests: 2, Writes: 2, WriteOver: 1, Over: 1}, |
| + {Screen: "GET /b", Method: "GET", P95: 600, Requests: 2, Cold: 2, ColdOver: 1, Over: 1}, |
| + {Screen: "/c", Method: "DELETE", P95: 10, Requests: 1, Writes: 1}, |
| + {Screen: "GET /b", Method: "HEAD", P95: 1, Requests: 1, Warm: 1}, |
| + }) |
| + var got []string |
| + for _, r := range pages { |
| + got = append(got, r.Route) |
| + } |
| + if want := []string{"GET /b", "GET /b (HEAD)"}; !slices.Equal(got, want) { |
| + t.Errorf("pages = %q, want %q", got, want) |
| + } |
| + got = nil |
| + for _, r := range changes { |
| + got = append(got, r.Route) |
| + } |
| + if want := []string{"POST /a", "DELETE /c"}; !slices.Equal(got, want) { |
| + t.Errorf("changes = %q, want %q", got, want) |
| + } |
| + if pages[0].Cold != 2 || pages[0].ColdOver != 1 || changes[0].WriteOver != 1 { |
| + t.Errorf("pages[0] = %+v, changes[0] = %+v, want the cold and write over counts kept", pages[0], changes[0]) |
| + } |
| +} |
| + |
| +// On the page: a write is a row of the Changes table, not of the pages |
| +// table, and a GET's row counts it warm. |
| +func TestFleetMetricsListsWritesUnderChanges(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + c := operatorBrowser(t, fx) |
| + for _, m := range []string{http.MethodGet, http.MethodPost} { |
| + req, _ := http.NewRequest(m, fx.ts.URL+"/fleet/architecture", nil) |
| + resp, err := c.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp.Body.Close() |
| + waitPerfRequests(t, fx.srv, "/fleet/architecture", m, 1) |
| + } |
| + status, _, body := get(t, c, fx.ts.URL+"/fleet/metrics") |
| + if status != 200 { |
| + t.Fatalf("/fleet/metrics = %d: %s", status, body) |
| + } |
| + pages, changes, ok := strings.Cut(body, `id="console-changes"`) |
| + if !ok { |
| + t.Fatalf("/fleet/metrics has no Changes section:\n%s", body) |
| + } |
| + if !strings.Contains(pages, "<td>GET /fleet/architecture</td>") || strings.Contains(pages, "<td>POST /fleet/architecture</td>") { |
| + t.Errorf("the pages table should list the GET and not the POST:\n%s", pages) |
| + } |
| + if !strings.Contains(changes, "<td>POST /fleet/architecture</td>") || strings.Contains(changes, "<td>GET /fleet/architecture</td>") { |
| + t.Errorf("the Changes table should list the POST and not the GET:\n%s", changes) |
| + } |
| + if !strings.Contains(pages, "<th co-m-hide>Warm</th><th>Over 150 ms</th><th co-m-hide>Cold</th><th>Over 500 ms</th>") { |
| + t.Errorf("the pages table lacks the warm and cold columns:\n%s", pages) |
| + } |
| +} |
diff --git a/internal/console/perfwalk_test.go b/internal/console/perfwalk_test.go| index dd639effc..b1a9336b5 100644 |
| --- a/internal/console/perfwalk_test.go |
| +++ b/internal/console/perfwalk_test.go |
| @@ -32,6 +32,7 @@ import ( |
| "github.com/carlosframework/platform/internal/mail" |
| "github.com/carlosframework/platform/internal/metrics" |
| "github.com/carlosframework/platform/internal/objstore" |
| + "github.com/carlosframework/platform/internal/perf" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/ratelimit" |
| "github.com/carlosframework/platform/internal/registry" |
| @@ -68,11 +69,18 @@ type perfScreenTarget struct { |
| var perfQuiesce = func(fx *consoleFixture) {} |
| // perfColdReset runs before a screen's cold request, so that it meets a |
| -// console that has cached nothing for it: no app-tab frames (appframe.go) |
| -// and no remembered account manifests. |
| +// console that has cached nothing for it: no app-tab frames (appframe.go), |
| +// no remembered account manifests and no metrics sweep (metricsview.go), |
| +// unless one is in flight. |
| var perfColdReset = func(fx *consoleFixture) { |
| fx.srv.frames.forgetAll() |
| fx.srv.manifestSeen.Clear() |
| + mc := &fx.srv.metricsCache |
| + mc.mu.Lock() |
| + if !mc.sweeping { |
| + mc.at, mc.boxes, mc.alerts = time.Time{}, nil, nil |
| + } |
| + mc.mu.Unlock() |
| } |
| // perfEnforce is whether timing fails the walk: only in CI, where the |
| @@ -80,12 +88,39 @@ var perfColdReset = func(fx *consoleFixture) { |
| // checks fail everywhere. |
| func perfEnforce() bool { return os.Getenv("CI") != "" || os.Getenv("AMADAN_CI") != "" } |
| +// The walk's budgets are the console's own (internal/perf): a warm view, |
| +// one that made no S3 or host call before its first byte, has 150 ms; a |
| +// cold view 500 ms; and no view of a screen may take longer than 500 ms. A |
| +// write has 500 ms from when its body was read. The console's sample for |
| +// each request says which a view was (perf.Recorder.Last). |
| const ( |
| - perfBudget = 150 * time.Millisecond |
| - perfWorstBudget = 450 * time.Millisecond |
| - perfTotalBudget = 10 * time.Second |
| + perfBudget = perf.WarmBudget |
| + perfColdBudget = perf.ColdBudget |
| + perfWorstBudget = perf.ColdBudget |
| + perfWriteBudget = perf.WriteBudget |
| + // perfTotalBudget was 10 s while the screens that read remotely on |
| + // every view were over records, requested twice with latency off. The |
| + // two-tier rule times them (a cold view and one repeat each, about 5 s |
| + // of injected latency in all), so the walk takes about 11 s. |
| + perfTotalBudget = 15 * time.Second |
| ) |
| +// perfBudgetOf is the first-byte budget of a read of class (perf.ClassWarm |
| +// or perf.ClassCold). |
| +func perfBudgetOf(class string) time.Duration { |
| + if class == perf.ClassCold { |
| + return perfColdBudget |
| + } |
| + return perfBudget |
| +} |
| + |
| +// perfRemeasure is whether the walk times the screens with an over record |
| +// as it times the rest, and prints whether each would pass, without |
| +// failing on them: CARLOS_PERF_REMEASURE=1, for the round that re-checks |
| +// the records. Off, an over screen is requested twice with latency off and |
| +// only its calls are printed, which keeps the walk inside perfTotalBudget. |
| +func perfRemeasure() bool { return os.Getenv("CARLOS_PERF_REMEASURE") != "" } |
| + |
| // perfSeeds is what newPerfFixture seeded that perfTargets needs to spell |
| // a path, and the walk's in-flight counter, keyed by fixture. |
| type perfSeeds struct { |
| @@ -600,10 +635,17 @@ func perfWalkTargets(fx *consoleFixture) []perfScreenTarget { |
| // perfStructural is the walk's fixture checks, made before anything is |
| // measured: a parameterised screen with no target, a target or record |
| -// naming no screen, a skip record on a screen that also has targets. |
| -func perfStructural(inventory []string, targets map[string][]perfTarget, recs map[string]perfRecord) []string { |
| +// naming no screen, a skip record on a screen that also has targets. A |
| +// record may also name one of writes, the writes the walk makes |
| +// (perfWriteScreens); only an over record means anything there. |
| +func perfStructural(inventory []string, targets map[string][]perfTarget, recs map[string]perfRecord, writes ...string) []string { |
| inInv := map[string]bool{} |
| var problems []string |
| + for _, s := range writes { |
| + if rec, ok := recs[s]; ok && rec.Kind != "over" { |
| + problems = append(problems, fmt.Sprintf("perf-budgets.txt line %d: %s is a write the walk makes; only an over record applies to it", rec.Line, s)) |
| + } |
| + } |
| for _, s := range inventory { |
| inInv[s] = true |
| _, has := targets[s] |
| @@ -621,7 +663,7 @@ func perfStructural(inventory []string, targets map[string][]perfTarget, recs ma |
| } |
| } |
| for _, s := range slices.Sorted(mapKeys(recs)) { |
| - if !inInv[s] { |
| + if !inInv[s] && !slices.Contains(writes, s) { |
| problems = append(problems, fmt.Sprintf("perf-budgets.txt line %d names %q, which is not in the inventory: stale, delete it", recs[s].Line, s)) |
| } |
| } |
| @@ -666,7 +708,9 @@ func (b perfBearer) RoundTrip(r *http.Request) (*http.Response, error) { |
| return http.DefaultTransport.RoundTrip(r) |
| } |
| -// perfResult is one walked request's measurement. |
| +// perfResult is one walked request's measurement. class and latency are |
| +// the console's own sample's: whether it was warm or cold (or a write), |
| +// and the time it judged (a write's, from its body read). |
| type perfResult struct { |
| ttfb time.Duration |
| status int |
| @@ -675,6 +719,18 @@ type perfResult struct { |
| notIdle bool |
| location string |
| bodyStart string |
| + class string |
| + latency time.Duration |
| +} |
| + |
| +// perfSampled fills r's class and latency from the console's newest |
| +// sample, which is r's: the walk makes one request at a time and waits for |
| +// its handler to return. |
| +func perfSampled(fx *consoleFixture, r *perfResult) { |
| + if s, ok := fx.srv.perf.Last(); ok { |
| + r.class = s.Class |
| + r.latency = time.Duration(s.Latency * float64(time.Millisecond)) |
| + } |
| } |
| // perfOnce makes one request and reads it to the end; TTFB is httptrace's |
| @@ -709,12 +765,25 @@ func perfOnce(fx *consoleFixture, lat *perfLatency, c *http.Client, tg perfTarge |
| } |
| r.bodyStart = string(body) |
| r.notIdle = !perfIdle(seeds.inflight, 2*time.Second) |
| + perfSampled(fx, &r) |
| perfQuiesce(fx) |
| s1, h1 := lat.Calls() |
| r.s3, r.host = s1-s0, h1-h0 |
| return r |
| } |
| +// perfMedian is the median of ds, which it sorts; zero for none. |
| +func perfMedian(ds []time.Duration) time.Duration { |
| + if len(ds) == 0 { |
| + return 0 |
| + } |
| + slices.Sort(ds) |
| + if n := len(ds); n%2 == 0 { |
| + return (ds[n/2-1] + ds[n/2]) / 2 |
| + } |
| + return ds[len(ds)/2] |
| +} |
| + |
| // perfIdle waits up to grace for every handler to return. |
| func perfIdle(inflight *atomic.Int32, grace time.Duration) bool { |
| deadline := time.Now().Add(grace) |
| @@ -773,7 +842,7 @@ func TestConsoleScreensMeetTheBudget(t *testing.T) { |
| fx, lat := newPerfFixture(t) |
| recs := loadPerfBudgets(t) |
| inventory := perfInventory(fx.srv.claimEntries.snapshot()) |
| - if problems := perfStructural(inventory, perfTargets(fx), recs); len(problems) > 0 { |
| + if problems := perfStructural(inventory, perfTargets(fx), recs, perfWriteScreens...); len(problems) > 0 { |
| for _, p := range problems { |
| t.Error(p) |
| } |
| @@ -805,6 +874,11 @@ func TestConsoleScreensMeetTheBudget(t *testing.T) { |
| return false |
| } |
| + remeasure := perfRemeasure() |
| + // verdicts is, per screen with an over record, what fails under the |
| + // rule when remeasuring ("" for a target that passes). |
| + verdicts := map[string][]string{} |
| + var verdictOrder []string |
| var table []string |
| for _, w := range perfWalkTargets(fx) { |
| tg := w.Target |
| @@ -817,7 +891,7 @@ func TestConsoleScreensMeetTheBudget(t *testing.T) { |
| if w.Record != nil { |
| kind = w.Record.Kind |
| } |
| - if kind == "over" { |
| + if kind == "over" && !remeasure { |
| lat.Enable(false) |
| var r perfResult |
| for i := 0; i < 2; i++ { |
| @@ -825,10 +899,15 @@ func TestConsoleScreensMeetTheBudget(t *testing.T) { |
| check(label, tg, r) |
| } |
| t.Logf("%s: over (%s): %d S3 and %d host calls warm", label, w.Record.Reason, r.s3, r.host) |
| - table = append(table, fmt.Sprintf("%s\t-\t-\t-\t%d+%d\tover", label, r.s3, r.host)) |
| + table = append(table, fmt.Sprintf("%s\t-\t-\t-\t-\t%d+%d\tover", label, r.s3, r.host)) |
| continue |
| } |
| + // fails is what this target breaks of the rule: errors in CI for |
| + // a screen with no over record, a verdict for one with. |
| + var fails []string |
| + fail := func(format string, a ...any) { fails = append(fails, fmt.Sprintf(format, a...)) } |
| + |
| cold, coldCalls := "-", "" |
| if kind != "deferred" { |
| perfColdReset(fx) |
| @@ -838,18 +917,25 @@ func TestConsoleScreensMeetTheBudget(t *testing.T) { |
| // started cost the test milliseconds. |
| r := perfOnce(fx, lat, c, tg, func() { lat.Enable(false) }) |
| if check(label+" (cold)", tg, r) { |
| - cold, coldCalls = ms(r.ttfb), fmt.Sprintf(" (%d+%d)", r.s3, r.host) |
| - if r.ttfb > perfBudget { |
| - timing("%s: cold first byte %sms, over %v", label, ms(r.ttfb), perfBudget) |
| + cold, coldCalls = ms(r.ttfb), fmt.Sprintf(" (%d+%d %s)", r.s3, r.host, r.class) |
| + if budget := perfBudgetOf(r.class); r.ttfb > budget { |
| + fail("first view after a cache reset (%s) first byte %sms, over %v", r.class, ms(r.ttfb), budget) |
| } |
| } |
| } |
| - lat.Enable(true) |
| - var ttfbs []time.Duration |
| + // Two views with latency off fill whatever the screen caches, and are |
| + // not counted. Then the counted views, with latency on: eight when |
| + // the first is warm, for the warm median; one when it is cold, since |
| + // a view that reads remotely every time has no warm median, and the |
| + // cold view above, which made the most remote calls, is its second |
| + // timed sample. That keeps the walk inside perfTotalBudget now that |
| + // the screens that read on every view are timed. |
| + var all, warm []time.Duration |
| var maxCalls, maxS3, maxHost int64 |
| good := true |
| - for i := 0; i < 10; i++ { |
| + for i, n := 0, 10; i < n; i++ { |
| + lat.Enable(i >= 2) |
| r := perfOnce(fx, lat, c, tg, nil) |
| if !check(label, tg, r) { |
| good = false |
| @@ -858,7 +944,13 @@ func TestConsoleScreensMeetTheBudget(t *testing.T) { |
| if i < 2 { |
| continue |
| } |
| - ttfbs = append(ttfbs, r.ttfb) |
| + if i == 2 && r.class == perf.ClassCold { |
| + n = 3 |
| + } |
| + all = append(all, r.ttfb) |
| + if r.class == perf.ClassWarm { |
| + warm = append(warm, r.ttfb) |
| + } |
| if r.s3+r.host > maxCalls { |
| maxCalls, maxS3, maxHost = r.s3+r.host, r.s3, r.host |
| } |
| @@ -867,14 +959,39 @@ func TestConsoleScreensMeetTheBudget(t *testing.T) { |
| if !good { |
| continue |
| } |
| - slices.Sort(ttfbs) |
| - median, worst := (ttfbs[3]+ttfbs[4])/2, ttfbs[len(ttfbs)-1] |
| - table = append(table, fmt.Sprintf("%s\t%s%s\t%s\t%s\t%d+%d\t%s", label, cold, coldCalls, ms(median), ms(worst), maxS3, maxHost, kind)) |
| - t.Logf("%s: cold %sms, median %sms, worst %sms, calls %d S3 + %d host", label, cold, ms(median), ms(worst), maxS3, maxHost) |
| - if kind == "deferred" { |
| - if worst > perfWorstBudget { |
| - timing("%s: worst first byte %sms, over %v", label, ms(worst), perfWorstBudget) |
| + worst := slices.Max(all) |
| + median := perfMedian(all) |
| + warmMedian := "-" |
| + if len(warm) > 0 { |
| + m := perfMedian(warm) |
| + warmMedian = ms(m) |
| + if kind != "deferred" && m > perfBudget { |
| + fail("warm median first byte %sms, over %v", ms(m), perfBudget) |
| } |
| + } |
| + if worst > perfWorstBudget { |
| + fail("worst first byte %sms, over %v", ms(worst), perfWorstBudget) |
| + } |
| + table = append(table, fmt.Sprintf("%s\t%s%s\t%d/%d\t%s\t%s\t%d+%d\t%s", label, cold, coldCalls, len(warm), len(all), warmMedian, ms(worst), maxS3, maxHost, kind)) |
| + t.Logf("%s: cold %sms%s, warm %d of %d (median %sms), median %sms, worst %sms, calls %d S3 + %d host", |
| + label, cold, coldCalls, len(warm), len(all), warmMedian, ms(median), ms(worst), maxS3, maxHost) |
| + if kind == "over" { |
| + if _, seen := verdicts[w.Screen]; !seen { |
| + verdictOrder = append(verdictOrder, w.Screen) |
| + verdicts[w.Screen] = []string{} |
| + } |
| + for _, f := range fails { |
| + verdicts[w.Screen] = append(verdicts[w.Screen], tg.Path+": "+f) |
| + } |
| + if maxCalls > 0 { |
| + verdicts[w.Screen+"\x00calls"] = append(verdicts[w.Screen+"\x00calls"], fmt.Sprintf("%s %d", tg.Path, maxCalls)) |
| + } |
| + continue |
| + } |
| + for _, f := range fails { |
| + timing("%s: %s", label, f) |
| + } |
| + if kind == "deferred" { |
| continue |
| } |
| allow := int64(0) |
| @@ -882,24 +999,107 @@ func TestConsoleScreensMeetTheBudget(t *testing.T) { |
| allow = int64(w.Record.Calls) |
| } |
| if maxCalls > allow { |
| - t.Errorf("%s: %d remote calls on a warm GET (%d S3, %d host), allowance %d: remove them, or record calls/over in testdata/perf-budgets.txt", |
| + t.Errorf("%s: %d remote calls on a repeat view (%d S3, %d host), allowance %d: remove them, or record calls/over in testdata/perf-budgets.txt", |
| label, maxCalls, maxS3, maxHost, allow) |
| } |
| - if median > perfBudget { |
| - timing("%s: median first byte %sms, over %v", label, ms(median), perfBudget) |
| + } |
| + for _, screen := range verdictOrder { |
| + calls := verdicts[screen+"\x00calls"] |
| + callNote := "no remote calls on a repeat view" |
| + if len(calls) > 0 { |
| + callNote = "remote calls on a repeat view: " + strings.Join(calls, ", ") |
| } |
| - if worst > perfWorstBudget { |
| - timing("%s: worst first byte %sms, over %v", label, ms(worst), perfWorstBudget) |
| + if fs := verdicts[screen]; len(fs) > 0 { |
| + t.Logf("REMEASURE %s: still over: %s (%s)", screen, strings.Join(fs, "; "), callNote) |
| + } else { |
| + t.Logf("REMEASURE %s: passes the rule (%s)", screen, callNote) |
| } |
| } |
| - t.Logf("screen\tcold ms\tmedian ms\tworst ms\tcalls (S3+host)\trecord\n%s", strings.Join(table, "\n")) |
| + |
| + table = append(table, perfWalkWrites(t, fx, lat, clients.paul, recs, timing)...) |
| + t.Logf("screen\tcold ms (calls, class)\twarm views\twarm median ms\tworst ms\tcalls (S3+host)\trecord\n%s", strings.Join(table, "\n")) |
| total := time.Since(began) |
| t.Logf("walk took %v", total.Round(time.Millisecond)) |
| - if enforce && total > perfTotalBudget { |
| + if enforce && !remeasure && total > perfTotalBudget { |
| t.Errorf("the walk took %v, over %v", total.Round(time.Millisecond), perfTotalBudget) |
| } |
| } |
| +// perfWriteScreens are the writes the walk makes, by registered pattern. |
| +var perfWriteScreens = []string{"POST /a/{sqid}/apps/{app}/promote"} |
| + |
| +// perfWalkWrites makes the walk's writes, once each with latency on, after |
| +// every screen's views (a write changes what they show), and judges each on |
| +// the console's own sample: from when its handler had read the request body |
| +// to its first byte, within perfWriteBudget, unless the write has an over |
| +// record, which is printed and never failed. It returns the walk table's |
| +// lines. |
| +func perfWalkWrites(t *testing.T, fx *consoleFixture, lat *perfLatency, c *http.Client, recs map[string]perfRecord, |
| + timing func(string, ...any)) []string { |
| + t.Helper() |
| + seeds := perfSeedsOf(fx) |
| + app := fx.path("/apps/kass") |
| + csrf := sessionToken(t, fx, c) |
| + writes := []struct { |
| + screen, what string |
| + do func() (int, string) |
| + }{ |
| + {"POST /a/{sqid}/apps/{app}/promote", "promote v2 to stable", func() (int, string) { |
| + status, _, body := postForm(t, c, fx.ts.URL+app+"/promote", |
| + url.Values{"csrf": {csrf}, "channel": {"stable"}, "version": {"v2"}, "confirmed": {"1"}}) |
| + return status, body |
| + }}, |
| + } |
| + if len(writes) != len(perfWriteScreens) { |
| + t.Fatalf("perfWalkWrites makes %d writes, perfWriteScreens names %d", len(writes), len(perfWriteScreens)) |
| + } |
| + var table []string |
| + for i, w := range writes { |
| + if w.screen != perfWriteScreens[i] { |
| + t.Fatalf("perfWalkWrites write %d is %s, perfWriteScreens names %s", i, w.screen, perfWriteScreens[i]) |
| + } |
| + s0, h0 := lat.Calls() |
| + lat.Enable(true) |
| + start := time.Now() |
| + status, body := w.do() |
| + took := time.Since(start) |
| + lat.Enable(false) |
| + if !perfIdle(seeds.inflight, 2*time.Second) { |
| + t.Errorf("%s: a handler was still running 2s after its response", w.screen) |
| + continue |
| + } |
| + var r perfResult |
| + perfSampled(fx, &r) |
| + s1, h1 := lat.Calls() |
| + label := w.screen + " (" + w.what + ")" |
| + if status != http.StatusSeeOther { |
| + t.Errorf("%s answered %d, want 303:\n%s", label, status, body) |
| + continue |
| + } |
| + if r.class != perf.ClassWrite { |
| + t.Errorf("%s: the console's sample is class %q, want %q", label, r.class, perf.ClassWrite) |
| + continue |
| + } |
| + rec, over := recs[w.screen] |
| + kind := "" |
| + if over { |
| + kind = rec.Kind |
| + } |
| + table = append(table, fmt.Sprintf("%s\t-\t-\t%s after the body (%s whole request)\t-\t%d+%d\twrite %s", label, ms(r.latency), ms(took), s1-s0, h1-h0, kind)) |
| + t.Logf("%s: %sms from the body read to the first byte (%sms for the whole request), %d S3 + %d host calls", label, ms(r.latency), ms(took), s1-s0, h1-h0) |
| + if r.latency > perfWriteBudget { |
| + if over { |
| + t.Logf("%s: over (%s): %sms after the body, over %v", label, rec.Reason, ms(r.latency), perfWriteBudget) |
| + } else { |
| + timing("%s: %sms from the body read to the first byte, over %v", label, ms(r.latency), perfWriteBudget) |
| + } |
| + } else if over { |
| + t.Logf("REMEASURE %s: passes the rule (%sms after the body)", w.screen, ms(r.latency)) |
| + } |
| + } |
| + return table |
| +} |
| + |
| // perfSessionCeiling reads testdata/perf-session-s3.txt: one line, |
| // "<n> <reason>". |
| func perfSessionCeiling(t *testing.T) (int64, string, bool) { |
diff --git a/internal/console/server.go b/internal/console/server.go| index 2d8d88c22..8526f61e2 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -2372,9 +2372,12 @@ type page struct { |
| Metrics []BoxMetricsView |
| MetricAlerts []AlertRow |
| - // The Console speed table on /fleet/metrics (perfspeed.go), and the S3 |
| - // requests made outside any page request since the console started. |
| + // The Console speed tables on /fleet/metrics (perfspeed.go): pages |
| + // (GET and HEAD) and changes (every other method). Then the S3 |
| + // requests made since the console started that neither a page request |
| + // nor a background job's run made (jobs.go charges those to the job). |
| ConsoleSpeed []consoleSpeedRow |
| + ConsoleChanges []consoleSpeedRow |
| ConsoleS3Background int64 |
| // /fleet/architecture (archgraph.go): the deployment's map. Arch is nil |
| @@ -3722,7 +3725,7 @@ func (s *Server) handleFleetMetrics(w http.ResponseWriter, r *http.Request) { |
| // it: a request is recorded once it has rendered. |
| p := s.opPage(addr, raw, "metrics") |
| p.Metrics, p.MetricAlerts = boxes, alerts |
| - p.ConsoleSpeed = consoleSpeedRows(s.PerfGroups()) |
| + p.ConsoleSpeed, p.ConsoleChanges = consoleSpeedTables(s.PerfGroups()) |
| p.ConsoleS3Background = s.PerfBackground()["s3"] |
| s.render(w, http.StatusOK, "metrics", p) |
| } |
diff --git a/internal/console/static/ops.css b/internal/console/static/ops.css| index e2380878b..69437275e 100644 |
| --- a/internal/console/static/ops.css |
| +++ b/internal/console/static/ops.css |
| @@ -25,7 +25,7 @@ |
| [co-cols="people"] { --rst-cols: minmax(12rem, 2fr) minmax(8rem, 1fr) 7rem 7rem; } |
| [co-cols="activity"] { --rst-cols: 6rem minmax(10rem, 1.2fr) minmax(12rem, 2fr) minmax(7rem, 1fr); } |
| [co-cols="boxes"] { --rst-cols: minmax(8rem, 1fr) 7rem 6rem minmax(9rem, 1.4fr) 8rem; } |
| -[co-cols="jobs"] { --rst-cols: minmax(10rem, 1.5fr) 9rem 8rem minmax(10rem, 2fr); } |
| +[co-cols="jobs"] { --rst-cols: minmax(10rem, 1.5fr) 9rem 8rem 7rem 6rem minmax(10rem, 2fr); } |
| [co-cols="persons"] { --rst-cols: minmax(12rem, 2fr) 7rem 7rem 6rem; } |
| [co-cols="accounts"] { --rst-cols: minmax(10rem, 2fr) 7rem minmax(6rem, 1fr) 5rem 6rem; } |
| [co-cols="feed"] { --rst-cols: 6rem minmax(10rem, 1.2fr) minmax(7rem, 1fr) minmax(12rem, 2fr) minmax(7rem, 1fr); } |
diff --git a/internal/console/templates/metrics.html b/internal/console/templates/metrics.html| index 3c977a3dc..844921bf8 100644 |
| --- a/internal/console/templates/metrics.html |
| +++ b/internal/console/templates/metrics.html |
| @@ -54,16 +54,18 @@ |
| {{end}} |
| <section co-section aria-labelledby="console-speed"> |
| <div rst-box-head><h2 id="console-speed">Console speed</h2></div> |
| -<p co-note>How long the console took to send the first byte of each page over its last 2,048 requests. Pages should answer within 150 ms.</p> |
| +<p co-note>This page shows the time to first byte for the last 2,048 page requests. Warm requests make no S3 or box requests before the first byte. They use memory and the console database and have a 150 ms budget. Cold requests make at least one S3 or box request before the first byte and have a 500 ms budget.</p> |
| {{if .ConsoleSpeed}} |
| <div rst-card class="co-table-wrap"> |
| <table co-table> |
| - <tr><th>Route</th><th co-m-hide>Requests</th><th>Over 150 ms</th><th co-m-hide>p50</th><th>p95</th><th co-m-hide>S3 requests</th></tr> |
| + <tr><th>Route</th><th co-m-hide>Warm</th><th>Over 150 ms</th><th co-m-hide>Cold</th><th>Over 500 ms</th><th co-m-hide>p50</th><th>p95</th><th co-m-hide>S3 requests</th></tr> |
| {{range .ConsoleSpeed}} |
| <tr> |
| <td>{{.Route}}</td> |
| - <td co-m-hide>{{.Requests}}</td> |
| - <td>{{.Over}}</td> |
| + <td co-m-hide>{{.Warm}}</td> |
| + <td>{{.WarmOver}}</td> |
| + <td co-m-hide>{{.Cold}}</td> |
| + <td>{{.ColdOver}}</td> |
| <td co-m-hide>{{.P50}}</td> |
| <td>{{.P95}}</td> |
| <td co-m-hide>{{.S3}}</td> |
| @@ -72,6 +74,25 @@ |
| </table> |
| </div> |
| {{else}}{{template "op_empty" (opEmpty "" "No requests measured since the console started.")}}{{end}} |
| -<p co-note>The console has made {{.ConsoleS3Background}} S3 requests that no page request caused since it started.</p> |
| +<div rst-box-head><h2 id="console-changes">Changes</h2></div> |
| +<p co-note>Each change is timed from when the console has read the whole request to its first byte. Upload time does not count. The budget is 500 ms.</p> |
| +{{if .ConsoleChanges}} |
| +<div rst-card class="co-table-wrap"> |
| +<table co-table> |
| + <tr><th>Route</th><th co-m-hide>Requests</th><th>Over 500 ms</th><th co-m-hide>p50</th><th>p95</th><th co-m-hide>S3 requests</th></tr> |
| + {{range .ConsoleChanges}} |
| + <tr> |
| + <td>{{.Route}}</td> |
| + <td co-m-hide>{{.Requests}}</td> |
| + <td>{{.WriteOver}}</td> |
| + <td co-m-hide>{{.P50}}</td> |
| + <td>{{.P95}}</td> |
| + <td co-m-hide>{{.S3}}</td> |
| + </tr> |
| + {{end}} |
| +</table> |
| +</div> |
| +{{else}}{{template "op_empty" (opEmpty "" "No changes measured since the console started.")}}{{end}} |
| +<p co-note>The console has made {{.ConsoleS3Background}} S3 requests since it started outside page requests and background jobs.</p> |
| </section> |
| {{template "op_bottom" .}}{{end}} |
diff --git a/internal/console/templates/opparts.html b/internal/console/templates/opparts.html| index ad4ec960a..6246faa9d 100644 |
| --- a/internal/console/templates/opparts.html |
| +++ b/internal/console/templates/opparts.html |
| @@ -89,12 +89,14 @@ |
| {{/* jobs: the background jobs table (data []opJobRow), one row per |
| configured job: its label, status pill, when its last run finished |
| - (the exact time as the title) and the first line of its last error. */}} |
| + (the exact time as the title), its S3 requests since the console |
| + started and per finished run (jobs.go), and the first line of its |
| + last error. */}} |
| {{define "op_jobs"}}<div rst-box-head id="jobs"><h2>Background jobs</h2></div> |
| <div rst-card co-cols="jobs"> |
| - <div rst-lrow="head"><span>Job</span><span>Status</span><span>Last ran</span><span>Note</span></div> |
| + <div rst-lrow="head"><span>Job</span><span>Status</span><span>Last ran</span><span>S3 requests</span><span>Average S3 requests</span><span>Note</span></div> |
| {{- range .}} |
| - <div rst-lrow><span>{{.Label}}</span><span>{{template "op_status" .Status}}</span>{{if .LastRan.IsZero}}<span>{{ago .LastRan}}</span>{{else}}<span title="{{fmtTime .LastRan}}">{{ago .LastRan}}</span>{{end}}<span>{{.Note}}</span></div> |
| + <div rst-lrow><span>{{.Label}}</span><span>{{template "op_status" .Status}}</span>{{if .LastRan.IsZero}}<span>{{ago .LastRan}}</span>{{else}}<span title="{{fmtTime .LastRan}}">{{ago .LastRan}}</span>{{end}}<span>{{.S3}}</span><span>{{.S3PerRun}}</span><span>{{.Note}}</span></div> |
| {{- end}} |
| </div>{{end}} |
diff --git a/internal/console/testdata/perf-budgets.txt b/internal/console/testdata/perf-budgets.txt| index 075ffb746..6443fbadd 100644 |
| --- a/internal/console/testdata/perf-budgets.txt |
| +++ b/internal/console/testdata/perf-budgets.txt |
| @@ -1,19 +1,31 @@ |
| # Console perf budgets. One record per line; blank lines and comments are |
| # ignored. Read by the perf walk (perfbudgets_test.go). |
| # |
| -# <screen> over: <reason> known slow today; measured and printed, never |
| -# failed; the next round deletes the record |
| +# The rule (internal/perf): a view that made no S3 or host call before its |
| +# first byte is warm, and the walk holds a screen's warm views to a median |
| +# of 150 ms; a view that made one is cold, held to 500 ms; no view of a |
| +# screen may take longer than 500 ms. A write the walk makes has 500 ms from |
| +# when its request body was read. By default a repeat view makes no remote |
| +# call at all. |
| +# |
| +# <screen> over: <reason> fails the rule today; measured and printed, |
| +# never failed; the next round deletes the |
| +# record (CARLOS_PERF_REMEASURE=1 times these |
| +# screens and prints whether each would pass) |
| # <screen> calls <n>: <reason> this screen may make n remote calls on a |
| -# warm-cache GET (n >= 1) |
| +# repeat view (n >= 1); each such view is |
| +# cold, so it is held to 500 ms |
| # <screen> deferred: <reason> a deferred-part endpoint: timed and printed, |
| -# exempt from 150 ms and the call count |
| +# held only to the 500 ms worst, exempt from |
| +# the warm median and the call count |
| # <screen> skip: <reason> not requested (a POST-only door that answers |
| # GET with the gate's 404, a JSON door) |
| # |
| # <screen> is the registered pattern verbatim: "GET /a/{sqid}/apps/{app}" (an |
| # upper-case method, a space, the path) or "/fleet/architecture" (a method-less |
| # registration). Every record needs a reason after the colon. A screen may |
| -# appear once. |
| +# appear once. A write the walk makes (perfWriteScreens) may have an over |
| +# record and nothing else. |
| # |
| # A # starts a comment that runs to the end of the line, so a reason cannot |
| # contain one: name a discussion as "discussion 404", not "#404". A comment |
| @@ -29,7 +41,7 @@ GET /static/{hash}/{file...} skip: static asset, not a screen; consolePerfSkip l |
| /fleet/economics/scenarios skip: POST-only door; a GET answers 404 on its first line by design (economicspass.go) |
| /fleet/economics/tier skip: POST-only door; a GET answers 404 on its first line by design (economicspass.go) |
| -# Deferred parts: timed and printed, exempt from 150 ms and the call count. |
| +# Deferred parts: timed and printed, held to the 500 ms worst only. |
| GET /a/{sqid}/apps/new calls 1: the account telemetry settings, which set the analytics checkbox the form starts from (1 S3 call warm, 10 ms or less) |
| # The CLI doors flagship's speed table put slowest (console-perf-hot-routes, |
| @@ -42,39 +54,44 @@ GET /api/cli/apps/{account}/{app}/instances calls 50: carlos instances list: the |
| GET /api/cli/system/status calls 14: carlos system status: the canary and stable pointers, bootstrap/carlos (a conditional read once its ETag is known, so an unchanged binary is not downloaded again), and the same box reports; median about 130 ms |
| GET /a/{sqid}/apps/{app}/logs/data deferred: deferred part (the Logs tab's data endpoint) |
| -# Known slow today (measured 2026-10-26 after console-perf-quick-wins, with |
| -# 25 ms per S3 request and 40 ms per app-host call; counts and times |
| -# re-measured 2026-10-27 after console-perf-hot-routes, whose fixture has |
| -# seven boxes and six edges files, and whose app-tab frame reads at once). |
| -# The next round deletes these. "the app-tab frame" is what every app tab reads before its own part: |
| -# the production flag, the pipeline, and a listing plus one read per channel |
| -# (6 S3 calls). It is cached per app for 30 s (appframe.go), so a warm view |
| -# reads none of it; the account manifest is read once per process and then |
| -# remembered. A cold view (perfColdReset) reads both: 7 S3 calls, about |
| -# 80 ms now the frame's reads run at once. |
| -# The walk prints only warm counts for these records; the cold counts below |
| -# were measured by walking with each record turned into a calls record. |
| -/fleet/architecture over: reads economics/active.json, infra/inventory.json and status/fleet.json, and lists and reads every box report (12 S3 calls warm and cold, median about 370 ms) |
| -GET /a/{sqid}/apps/{app} over: Overview is the release listing and every manifest (3 S3 calls warm, median about 80 ms); cold, also the app-tab frame, the account manifest and every box's metrics hours for two days (141 S3 calls, about 610 ms) |
| -GET /a/{sqid}/apps/{app}/account-review over: a warm view reads nothing (0 S3 calls; the app-tab frame is cached); a cold view reads the frame and the account manifest (7 S3 calls, about 80 ms) |
| -GET /a/{sqid}/apps/{app}/activity over: a warm view reads nothing (0 S3 calls; the app-tab frame is cached); a cold view reads the frame and the account manifest (7 S3 calls, about 80 ms) |
| -GET /a/{sqid}/apps/{app}/analytics over: both telemetry settings, the analytics day listing and one day read (4 S3 calls warm, median about 105 ms); cold, also the app-tab frame and the account manifest (11 S3 calls, about 180 ms) |
| -GET /a/{sqid}/apps/{app}/availability over: both telemetry settings and three listings and a read each for the log and error chunks (10 S3 calls warm, median about 260 ms); cold, also the app-tab frame and the account manifest (17 S3 calls, about 335 ms) |
| -GET /a/{sqid}/apps/{app}/errors over: both telemetry settings and three listings and a read each for the log and error chunks (10 S3 calls warm, median about 260 ms); cold, also the app-tab frame and the account manifest (17 S3 calls, about 335 ms) |
| -GET /a/{sqid}/apps/{app}/instances over: instances.json, and every edges file and box report listed and read once per view (17 S3 calls warm, median about 500 ms: the edges files are still read one after another); cold, also the app-tab frame and the account manifest (24 S3 calls and 1 host call, about 615 ms) |
| -GET /a/{sqid}/apps/{app}/instances/{host} over: the instance record, instances.json, the edges listing, and the box reports and the fleet box reports listed and read once per view (14 S3 calls warm, median about 210 ms); cold, also the app-tab frame and the account manifest (21 S3 calls, about 290 ms) |
| -GET /a/{sqid}/apps/{app}/logs over: three listings for the log chunks and a chunk read; the host picker uses the records the page already holds (4 S3 calls warm, median about 105 ms); cold, also the app-tab frame and the account manifest (11 S3 calls, about 180 ms) |
| -GET /a/{sqid}/apps/{app}/releases over: the release and tag listings, at most 20 manifests, retention and instances.json (6 S3 calls warm, median about 160 ms; 4 on the fixture's empty page 2); cold, also the app-tab frame and the account manifest (13 S3 calls, about 235 ms; 11 on page 2) |
| -GET /a/{sqid}/apps/{app}/settings over: the one-key app listing for the rename check (a second for the legacy prefix when the first is empty) and the swap policy (2 S3 calls warm, 3 at most, median about 55 ms); cold, also the app-tab frame and the account manifest (9 S3 calls, about 130 ms) |
| -GET /a/{sqid}/apps/{app}/settings/{section} over: Domains still reads the domain claims, cert-warm records, every box report and every instance record (16 S3 calls warm, median about 420 ms; 24 cold); the other sections read only their own data, warm (cold adds the app-tab frame and the account manifest, 7 more): General 2 (cold 9), Environments 5 (12), Storage 4 (11), Email 1 (8), Feature flags 1 (8), Errors and analytics 2 (9), the pipeline section, Placement and Delete none (7); the advanced redirect none, warm or cold |
| -GET /a/{sqid}/fleet over: reads status/fleet.json and lists and reads each customer fleet's box reports (3 S3 calls warm and cold, median about 80 ms) |
| -GET /a/{sqid}/fleets/{fleet} over: lists and reads the fleet's box reports (2 S3 calls warm and cold, median about 55 ms) |
| -GET /a/{sqid}/plan/keep over: the lapse inventory lists every app's instance records and reads each one, lists every app's sidecar records, and lists the domain claims (8 S3 calls warm for two apps and three instances, median 209 ms; it grows with the account) |
| -GET /a/{sqid}/settings calls 2: the account telemetry settings and the storage entitlement |
| -GET /a/{sqid}/trash over: reads each trashed app's deleted.json marker (1 S3 call warm and cold per app) |
| -GET /fleet over: the dashboard reads status/fleet.json, lists and reads every box report once each, and for a store operator lists and reads the storage entitlements, the same reads Boxes makes, all at once; operator pages are seldom viewed and carry no cache, and its SQLite reads add no remote call (12 S3 calls warm and cold, median about 133 ms, inside the budget; kept out of the timed walk, whose eleven views of it would cost 1.5 s of the walk's 10 s) |
| -GET /fleet/boxes over: lists and reads every box report, reads status/fleet.json, and lists and reads the storage entitlements, all at once; operator pages are seldom viewed and carry no cache (12 S3 calls warm and cold, median about 133 ms, inside the budget; kept out of the timed walk as Dashboard is) |
| -GET /fleet/economics over: a cold view reads the period's usage days ten at a time, each no further than 8 MiB, and keeps the settled ones, every day before yesterday, for up to 6 h (console-economics-speed); month to date on the 27th, five objects a day and six more: 141 S3 calls, about 400 ms, with nothing held (was 168 one after another, about 4.3 s); 16 S3 calls, about 110 ms, once a view or the hourly economics pass has read the settled days; warm views come from the 60 s cache (0 S3 calls) |
| -GET /fleet/economics/accounts over: shares /fleet/economics's sweep and its settled days, so its own cold view is that same sweep (141 S3 calls with nothing held, 16 with the settled days held, on the 27th); 0 S3 calls warm |
| -GET /fleet/metrics over: a cold view reads every box's metrics hours for two days (about 120 S3 calls, counted in Overview's cold view); warm views are cached (0 S3 calls), and the walk never sees it cold: the app pages before it fill that cache and perfColdReset leaves it |
| -GET /fleet/store over: lists the storage entitlements and the storage usage days and reads each pending application (3 S3 calls warm and cold, median about 80 ms) |
| +# Screens that read remotely on every view (re-measured 2026-10-28 against |
| +# the two-tier rule, 25 ms per S3 request and 40 ms per app-host call; each |
| +# was an over record under the 150 ms rule and now passes: cold first view |
| +# and every repeat view under 500 ms). "the app-tab frame" is what every app |
| +# tab reads before its own part: the production flag, the pipeline, and a |
| +# listing plus one read per channel (6 S3 calls), cached per app for 30 s |
| +# (appframe.go); the account manifest is read once per process. A cold view |
| +# (perfColdReset) reads both: 7 S3 calls, about 80 ms. |
| +/fleet/architecture calls 12: reads economics/active.json, infra/inventory.json and status/fleet.json, and lists and reads every box report (12 S3 calls warm and cold, about 390 ms) |
| +GET /a/{sqid}/apps/{app}/analytics calls 4: both telemetry settings, the analytics day listing and one day read (about 105 ms); cold, also the app-tab frame and the account manifest (11 S3 calls, about 190 ms) |
| +GET /a/{sqid}/apps/{app}/availability calls 10: both telemetry settings and three listings and a read each for the log and error chunks (about 265 ms); cold, also the app-tab frame and the account manifest (17 S3 calls, about 340 ms) |
| +GET /a/{sqid}/apps/{app}/errors calls 10: both telemetry settings and three listings and a read each for the log and error chunks (about 265 ms); cold, also the app-tab frame and the account manifest (17 S3 calls, about 340 ms) |
| +GET /a/{sqid}/apps/{app}/logs calls 4: three listings for the log chunks and a chunk read; the host picker uses the records the page already holds (about 105 ms); cold, also the app-tab frame and the account manifest (11 S3 calls, about 185 ms) |
| +GET /a/{sqid}/apps/{app}/releases calls 6: the release and tag listings, at most 20 manifests, retention and instances.json (about 165 ms; 4 on the fixture's empty page 2); cold, also the app-tab frame and the account manifest (13 S3 calls, about 240 ms; 11 on page 2) |
| +GET /a/{sqid}/apps/{app}/settings calls 3: the one-key app listing for the rename check (a second for the legacy prefix when the first is empty) and the swap policy (2 S3 calls on the fixture, about 55 ms); cold, also the app-tab frame and the account manifest (9 S3 calls, about 160 ms) |
| +GET /a/{sqid}/fleet calls 3: reads status/fleet.json and lists and reads each customer fleet's box reports (about 90 ms); cold, also the fleets' box report listings (36 S3 calls, about 245 ms) |
| +GET /a/{sqid}/fleets/{fleet} calls 2: lists and reads the fleet's box reports (2 S3 calls warm and cold, about 55 ms) |
| +GET /a/{sqid}/plan/keep calls 8: the lapse inventory lists every app's instance records and reads each one, lists every app's sidecar records, and lists the domain claims (8 S3 calls for two apps and three instances, about 210 ms; it grows with the account) |
| +GET /a/{sqid}/settings calls 2: the account telemetry settings and the storage entitlement (about 53 ms warm and cold) |
| +GET /a/{sqid}/trash calls 1: reads each trashed app's deleted.json marker (1 S3 call per trashed app, about 28 ms) |
| +GET /fleet calls 12: the dashboard reads status/fleet.json, lists and reads every box report once each, and for a store operator lists and reads the storage entitlements, the same reads Boxes makes, all at once; operator pages carry no cache (12 S3 calls warm and cold, about 140 ms) |
| +GET /fleet/boxes calls 12: lists and reads every box report, reads status/fleet.json, and lists and reads the storage entitlements, all at once; operator pages carry no cache (12 S3 calls warm and cold, about 140 ms) |
| +GET /fleet/store calls 3: lists the storage entitlements and the storage usage days and reads each pending application (3 S3 calls warm and cold, about 80 ms) |
| + |
| +# Known slow today: fails the two-tier rule (re-measured 2026-10-28 with |
| +# CARLOS_PERF_REMEASURE=1, 25 ms per S3 request and 40 ms per app-host call; |
| +# the cold view starts with no app-tab frame, no account manifest and no |
| +# metrics sweep, which a console that has seen no metrics view for two |
| +# minutes (metricsStaleServeCeiling) does not have either). The next round |
| +# deletes these. |
| +GET /a/{sqid}/apps/{app} over: cold, the app-tab frame, the account manifest and every box's metrics hours for two days (141 S3 calls, about 715 ms, over 500 ms); a repeat view is the release listing and every manifest (3 S3 calls, about 80 ms) |
| +GET /a/{sqid}/apps/{app}/instances over: cold, the app-tab frame, the account manifest, the metrics sweep, instances.json, and every edges file and box report (122 S3 calls and 1 host call, about 1,315 ms, over 500 ms); a repeat view still reads instances.json and every edges file and box report (17 S3 calls, 500 to 620 ms, at or over 500 ms: the edges files are read one after another) |
| +GET /a/{sqid}/apps/{app}/instances/{host} over: cold, the app-tab frame, the account manifest and the metrics sweep beside the instance record, instances.json, the edges listing and the box and fleet box reports (119 S3 calls, about 505 ms, over 500 ms); a repeat view reads the last five (14 S3 calls, 210 to 325 ms) |
| +GET /a/{sqid}/apps/{app}/settings/{section} over: Domains reads the domain claims, cert-warm records, every box report and every instance record (16 S3 calls on a repeat view, 430 to 470 ms; cold 24, about 555 ms, over 500 ms); every other section passes and reads only its own data on a repeat view: General 2 (cold 9), Environments 5 (12), Storage 4 (11), Email 1 (8), Feature flags 1 (8), Errors and analytics 2 (9), the pipeline section, Placement and Delete none (7); the advanced redirect none, warm or cold |
| +POST /a/{sqid}/apps/{app}/promote over: promoting v2 to stable reads and writes 18 S3 objects, about 520 ms from the body read to the first byte, over 500 ms (console-slow-writes is speeding it up) |
| + |
| +# Deleted 2026-10-28, passing the two-tier rule with no remote call on a |
| +# repeat view: account-review and activity (cold 7 S3 calls, about 80 ms), |
| +# /fleet/economics (cold 146 S3 calls, about 410 ms), /fleet/economics/accounts |
| +# and /fleet/metrics (cold 98 S3 calls, about 160 ms). |
| + |
diff --git a/internal/perf/middleware.go b/internal/perf/middleware.go| index 5faf600d5..5bf4eee26 100644 |
| --- a/internal/perf/middleware.go |
| +++ b/internal/perf/middleware.go |
| @@ -23,26 +23,25 @@ type Options struct { |
| // Skip leaves a request unmeasured. Nil skips /healthz only: a |
| // probe would crowd real pages out of the ring. |
| Skip func(*http.Request) bool |
| - // Budget is the first-byte budget for a GET or HEAD; zero means |
| - // DefaultBudget. Other methods have none and are never over. |
| - Budget time.Duration |
| // Logger receives the over-budget warnings and the lost-route |
| // warning. Nil is slog.Default(). |
| Logger *slog.Logger |
| } |
| // Middleware measures every request next serves that opts.Skip does |
| -// not skip, recording into c. Each measured response carries one |
| -// Server-Timing header: app (time to first byte), then each span that |
| -// ended before the first byte, by name. |
| +// not skip, recording into c, and judges it against WarmBudget, |
| +// ColdBudget or WriteBudget (see the package comment). Each measured |
| +// response carries one Server-Timing header: app (time to first byte), |
| +// then each span that ended before the first byte, by name. |
| +// |
| +// The request body is wrapped so its reads are timed: a write's budget |
| +// runs from the read that finished the body. The wrapper is a plain |
| +// io.ReadCloser, so nothing type-asserts the body underneath. |
| // |
| // Mount it directly around the mux: it reads the matched pattern back |
| // from the request it passed down, so middleware between the two that |
| // copies the request hides the route (and is warned about, once). |
| func Middleware(c *Recorder, opts Options) func(http.Handler) http.Handler { |
| - if opts.Budget <= 0 { |
| - opts.Budget = DefaultBudget |
| - } |
| if opts.Logger == nil { |
| opts.Logger = slog.Default() |
| } |
| @@ -72,6 +71,15 @@ func Middleware(c *Recorder, opts Options) func(http.Handler) http.Handler { |
| func defaultSkip(r *http.Request) bool { return r.URL.Path == "/healthz" } |
| +// isWrite is whether method has the write budget. |
| +func isWrite(method string) bool { |
| + switch method { |
| + case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete: |
| + return true |
| + } |
| + return false |
| +} |
| + |
| func defaultScreen(r *http.Request) string { |
| // A CONNECT is the one request ServeMux answers with a redirect |
| // whose Pattern is the concrete destination path rather than a |
| @@ -117,16 +125,28 @@ type writer struct { |
| // done is set once the sample is handed to the recorder. After it |
| // a span or a call changes nothing: the sample is the recorder's. |
| done bool |
| + // cold is set by an outbound call made before the first byte: the |
| + // read was not served from memory alone. |
| + cold bool |
| + |
| + // The request body's reads before the first byte: bodyLen is its |
| + // Content-Length (-1 unknown), bodyN the bytes read so far, bodyAt |
| + // the last read's time, and bodyEnded whether that read reached the |
| + // end, after which bodyAt stays. |
| + bodyLen int64 |
| + bodyN int64 |
| + bodyAt time.Time |
| + bodyEnded bool |
| } |
| func begin(c *Recorder, w http.ResponseWriter, r *http.Request, opts *Options) (*writer, *http.Request) { |
| start := c.now() |
| s := Sample{At: start.UTC(), Method: method(r.Method)} |
| - if r.Method == http.MethodGet || r.Method == http.MethodHead { |
| - s.Budget = ms(opts.Budget) |
| - } |
| - q := &writer{ResponseWriter: w, recorder: c, opts: opts, start: start, sample: s} |
| + q := &writer{ResponseWriter: w, recorder: c, opts: opts, start: start, sample: s, bodyLen: r.ContentLength} |
| r2 := r.WithContext(context.WithValue(r.Context(), contextKey{}, q)) |
| + if r.Body != nil && r.Body != http.NoBody { |
| + r2.Body = &bodyReader{ReadCloser: r.Body, q: q} |
| + } |
| // A mux outside this one may already have set Pattern. Cleared on |
| // this copy, so the pattern read back is the inner mux's or |
| // nothing: an inherited pattern would group every route under it |
| @@ -215,6 +235,9 @@ func (q *writer) call(name string) bool { |
| if q.done { |
| return false |
| } |
| + if !q.committed { |
| + q.cold = true |
| + } |
| if q.sample.Calls == nil { |
| q.sample.Calls = map[string]int{} |
| } |
| @@ -245,6 +268,7 @@ func (q *writer) commit(status int) bool { |
| q.committed = true |
| q.sample.Status = status |
| q.sample.TTFB = ms(q.since(q.start)) |
| + q.stampBody() |
| names := make([]string, 0, len(q.sample.Spans)) |
| for name := range q.sample.Spans { |
| names = append(names, name) |
| @@ -264,6 +288,48 @@ func (q *writer) Write(b []byte) (int, error) { |
| return q.ResponseWriter.Write(b) |
| } |
| +// stampBody puts the body's last read before the first byte into the |
| +// sample. q.mu is held, and the first byte has just been stamped. |
| +func (q *writer) stampBody() { |
| + if !q.bodyAt.IsZero() { |
| + q.sample.BodyRead = ms(q.bodyAt.Sub(q.start)) |
| + } |
| +} |
| + |
| +// bodyRead notes one read of the request body that returned n bytes and |
| +// err. Reads after the first byte, or after the body ended, change |
| +// nothing: the write's budget is judged up to its first byte. |
| +func (q *writer) bodyRead(n int, err error) { |
| + if n == 0 && err == nil { |
| + return |
| + } |
| + now := q.recorder.now() |
| + q.mu.Lock() |
| + defer q.mu.Unlock() |
| + if q.committed || q.bodyEnded { |
| + return |
| + } |
| + q.bodyN += int64(n) |
| + q.bodyAt = now |
| + if err != nil || (q.bodyLen >= 0 && q.bodyN >= q.bodyLen) { |
| + q.bodyEnded = true |
| + } |
| +} |
| + |
| +// bodyReader times the request body's reads for its writer. Read only: |
| +// io.Copy then reads it through Read, and a handler that type-asserts |
| +// the body finds nothing it would have found on the bare one either. |
| +type bodyReader struct { |
| + io.ReadCloser |
| + q *writer |
| +} |
| + |
| +func (b *bodyReader) Read(p []byte) (int, error) { |
| + n, err := b.ReadCloser.Read(p) |
| + b.q.bodyRead(n, err) |
| + return n, err |
| +} |
| + |
| // Unwrap lets http.ResponseController reach the writer underneath. |
| func (q *writer) Unwrap() http.ResponseWriter { return q.ResponseWriter } |
| @@ -287,6 +353,7 @@ func (q *writer) Hijack() (net.Conn, *bufio.ReadWriter, error) { |
| q.committed = true |
| q.sample.Status = http.StatusSwitchingProtocols |
| q.sample.TTFB = ms(q.since(q.start)) |
| + q.stampBody() |
| } |
| q.mu.Unlock() |
| } |
| @@ -309,6 +376,7 @@ func (q *writer) finish(r *http.Request, screenIsDefault bool, lostRoute *sync.O |
| if !committed { |
| q.committed = true |
| q.sample.TTFB = ms(q.since(q.start)) |
| + q.stampBody() |
| } |
| } |
| q.mu.Unlock() |
| @@ -327,7 +395,7 @@ func (q *writer) finish(r *http.Request, screenIsDefault bool, lostRoute *sync.O |
| lost := screenIsDefault && r.Pattern == "" && |
| q.sample.Status != http.StatusNotFound && q.sample.Status != http.StatusMethodNotAllowed |
| q.sample.Total = ms(q.since(q.start)) |
| - q.sample.Over = q.sample.Budget > 0 && q.sample.TTFB > q.sample.Budget |
| + q.judge() |
| // Handed over once. From here the sample is the recorder's (add |
| // keeps its own copy of the maps), and done turns every later span |
| // and call into a no-op. |
| @@ -347,6 +415,46 @@ func (q *writer) finish(r *http.Request, screenIsDefault bool, lostRoute *sync.O |
| } |
| } |
| +// judge classes the sample and sets its judged time, budget and verdict. |
| +// q.mu is held, and the first byte has been stamped. |
| +func (q *writer) judge() { |
| + s := &q.sample |
| + s.Latency = s.TTFB |
| + switch { |
| + case s.Method == http.MethodGet || s.Method == http.MethodHead: |
| + s.Class, s.Budget = ClassWarm, ms(WarmBudget) |
| + if q.cold { |
| + s.Class, s.Budget = ClassCold, ms(ColdBudget) |
| + } |
| + case isWrite(s.Method): |
| + s.Class, s.Budget = ClassWrite, ms(WriteBudget) |
| + s.Latency = max(0, s.TTFB-s.BodyRead) |
| + } |
| + s.Over = s.Budget > 0 && s.Latency > s.Budget |
| +} |
| + |
| +// Counter receives the outbound requests TimeDoer sees on a context that |
| +// carries it (WithCounter) when no measured request owns that context: a |
| +// background job's run, so its requests are charged to the job rather |
| +// than to the recorder's background counts. CountCall is called from the |
| +// goroutine making the request, so it must be safe for concurrent use. |
| +type Counter interface { |
| + CountCall(name string) |
| +} |
| + |
| +type counterKey struct{} |
| + |
| +// WithCounter returns ctx carrying k. A measured request on a context |
| +// derived from it still counts its own calls; k gets the rest. |
| +func WithCounter(ctx context.Context, k Counter) context.Context { |
| + return context.WithValue(ctx, counterKey{}, k) |
| +} |
| + |
| +func counterFrom(ctx context.Context) Counter { |
| + k, _ := ctx.Value(counterKey{}).(Counter) |
| + return k |
| +} |
| + |
| // Doer is the one method of *http.Client that outbound calls use. |
| type Doer interface { |
| Do(*http.Request) (*http.Response, error) |
| @@ -354,13 +462,14 @@ type Doer interface { |
| // TimeDoer wraps d so that each Do is one span named name and one count |
| // in Calls[name] on the measured request the outgoing request's context |
| -// belongs to. On a context no measured request owns it counts into c's |
| -// background counts instead (a nil c drops the count). So does a call |
| -// made on a measured request's context after that request finished, |
| -// by work it detached (context.WithoutCancel keeps the request's |
| -// values): the recorded sample never changes, and the call is still |
| -// counted somewhere. Counting is at the HTTP boundary, so every page of |
| -// a paginated listing is one count. |
| +// belongs to. On a context no measured request owns it counts into the |
| +// Counter the context carries (WithCounter), else into c's background |
| +// counts (a nil c drops the count). So does a call made on a measured |
| +// request's context after that request finished, by work it detached |
| +// (context.WithoutCancel keeps the request's values): the recorded |
| +// sample never changes, and the call is still counted somewhere. |
| +// Counting is at the HTTP boundary, so every page of a paginated listing |
| +// is one count. |
| // |
| // The span stays open until the response body reaches EOF or is closed, |
| // whichever comes first, so a prompt header followed by a slow body is |
| @@ -382,7 +491,9 @@ type timedDoer struct { |
| func (t *timedDoer) Do(req *http.Request) (*http.Response, error) { |
| q := fromContext(req.Context()) |
| if q == nil || !q.call(t.name) { |
| - if t.c != nil { |
| + if k := counterFrom(req.Context()); k != nil { |
| + k.CountCall(t.name) |
| + } else if t.c != nil { |
| t.c.countBackground(t.name) |
| } |
| return t.d.Do(req) |
diff --git a/internal/perf/middleware_test.go b/internal/perf/middleware_test.go| index 6e9d69bc1..469ef8161 100644 |
| --- a/internal/perf/middleware_test.go |
| +++ b/internal/perf/middleware_test.go |
| @@ -405,57 +405,233 @@ func (m *manualClock) advance(d time.Duration) { |
| // TestOverBudgetIsJudgedOnFirstByte: not acceptance. The clock is moved |
| // by hand inside the handlers, so the first-byte and total times are |
| -// exact and nothing waits on a real sleep. |
| +// exact and nothing waits on a real sleep. A warm read is judged at |
| +// WarmBudget on its first byte, however long its body then runs. |
| func TestOverBudgetIsJudgedOnFirstByte(t *testing.T) { |
| clk := newManualClock() |
| - opts := perf.Options{Budget: 20 * time.Millisecond} |
| mux := http.NewServeMux() |
| mux.HandleFunc("GET /stream", func(w http.ResponseWriter, r *http.Request) { |
| io.WriteString(w, "first") |
| w.(http.Flusher).Flush() |
| - clk.advance(50 * time.Millisecond) |
| + clk.advance(900 * time.Millisecond) |
| io.WriteString(w, "rest") |
| }) |
| mux.HandleFunc("GET /slow", func(w http.ResponseWriter, r *http.Request) { |
| - clk.advance(50 * time.Millisecond) |
| - io.WriteString(w, "late") |
| - }) |
| - mux.HandleFunc("POST /slow", func(w http.ResponseWriter, r *http.Request) { |
| - clk.advance(50 * time.Millisecond) |
| + clk.advance(151 * time.Millisecond) |
| io.WriteString(w, "late") |
| }) |
| var a perf.Recorder |
| perf.SetClock(&a, clk.now) |
| - _, ss := serve(t, &a, opts, mux, "GET", "/stream") |
| - if s := only(t, ss); s.Over || s.Budget != 20 || s.TTFB != 0 || s.Total != 50 { |
| - t.Fatalf("stream sample = %+v, want not over, budget 20, ttfb 0, total 50", s) |
| + _, ss := serve(t, &a, perf.Options{}, mux, "GET", "/stream") |
| + if s := only(t, ss); s.Over || s.Class != perf.ClassWarm || s.Budget != 150 || s.TTFB != 0 || s.Total != 900 { |
| + t.Fatalf("stream sample = %+v, want warm, not over, budget 150, ttfb 0, total 900", s) |
| } |
| var b perf.Recorder |
| perf.SetClock(&b, clk.now) |
| - _, ss = serve(t, &b, opts, mux, "GET", "/slow") |
| - if s := only(t, ss); !s.Over || s.TTFB != 50 { |
| - t.Fatalf("slow GET sample = %+v, want over with ttfb 50", s) |
| + _, ss = serve(t, &b, perf.Options{}, mux, "GET", "/slow") |
| + if s := only(t, ss); !s.Over || s.Class != perf.ClassWarm || s.TTFB != 151 || s.Latency != 151 { |
| + t.Fatalf("slow GET sample = %+v, want warm and over with ttfb 151", s) |
| + } |
| +} |
| + |
| +// TestColdReadsHaveTheColdBudget: not acceptance. A read that made an |
| +// outbound call before its first byte is cold and judged at ColdBudget; |
| +// one whose only call came after the first byte was served from memory |
| +// and stays warm. |
| +func TestColdReadsHaveTheColdBudget(t *testing.T) { |
| + clk := newManualClock() |
| + var c perf.Recorder |
| + perf.SetClock(&c, clk.now) |
| + call := func(r *http.Request) { |
| + req, _ := http.NewRequestWithContext(r.Context(), "GET", "http://store.example.com/k", nil) |
| + resp, err := perf.TimeDoer(answering{}, "s3", &c).Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + io.Copy(io.Discard, resp.Body) |
| + resp.Body.Close() |
| + } |
| + took := map[string]time.Duration{"/cold-in": 499 * time.Millisecond, "/cold-over": 501 * time.Millisecond, "/after": 200 * time.Millisecond} |
| + mux := http.NewServeMux() |
| + mux.HandleFunc("GET /cold-in", func(w http.ResponseWriter, r *http.Request) { |
| + call(r) |
| + clk.advance(took[r.URL.Path]) |
| + io.WriteString(w, "ok") |
| + }) |
| + mux.HandleFunc("GET /cold-over", func(w http.ResponseWriter, r *http.Request) { |
| + call(r) |
| + clk.advance(took[r.URL.Path]) |
| + io.WriteString(w, "ok") |
| + }) |
| + mux.HandleFunc("HEAD /after", func(w http.ResponseWriter, r *http.Request) { |
| + clk.advance(took[r.URL.Path]) |
| + w.WriteHeader(http.StatusOK) |
| + call(r) |
| + }) |
| + for _, tc := range []struct { |
| + method, path, class string |
| + budget float64 |
| + over bool |
| + }{ |
| + {"GET", "/cold-in", perf.ClassCold, 500, false}, |
| + {"GET", "/cold-over", perf.ClassCold, 500, true}, |
| + {"HEAD", "/after", perf.ClassWarm, 150, true}, |
| + } { |
| + c := perf.Recorder{} |
| + perf.SetClock(&c, clk.now) |
| + _, ss := serve(t, &c, perf.Options{}, mux, tc.method, tc.path) |
| + s := only(t, ss) |
| + if s.Class != tc.class || s.Budget != tc.budget || s.Over != tc.over || s.Calls["s3"] != 1 { |
| + t.Errorf("%s %s sample = %+v, want class %s, budget %v, over %v and one s3 call", tc.method, tc.path, s, tc.class, tc.budget, tc.over) |
| + } |
| } |
| - var p perf.Recorder |
| - perf.SetClock(&p, clk.now) |
| - _, ss = serve(t, &p, opts, mux, "POST", "/slow") |
| - if s := only(t, ss); s.Over || s.Budget != 0 || s.TTFB != 50 { |
| - t.Fatalf("POST sample = %+v, want ttfb 50, not over and budget 0", s) |
| +} |
| + |
| +// slowBody is a request body whose reads move the clock: an upload |
| +// arriving slowly. |
| +type slowBody struct { |
| + r io.Reader |
| + clk *manualClock |
| + each time.Duration |
| +} |
| + |
| +func (b *slowBody) Read(p []byte) (int, error) { |
| + b.clk.advance(b.each) |
| + if len(p) > 4 { |
| + p = p[:4] |
| } |
| + return b.r.Read(p) |
| } |
| -// TestDefaultBudgetAppliesToReads: not acceptance. A zero Budget is |
| -// DefaultBudget, for GET and HEAD alike. |
| -func TestDefaultBudgetAppliesToReads(t *testing.T) { |
| +// TestWritesAreJudgedFromTheBodyRead: not acceptance. A write's budget |
| +// runs from the read that finished its body to its first byte, so a slow |
| +// upload is not the console's latency. The body is finished by EOF, or |
| +// by reading as many bytes as Content-Length declared (a JSON decoder |
| +// stops there without asking for EOF), else by the last read before the |
| +// first byte. A write that read no body is judged from its start. |
| +func TestWritesAreJudgedFromTheBodyRead(t *testing.T) { |
| + clk := newManualClock() |
| + work := 0 * time.Millisecond |
| mux := http.NewServeMux() |
| - mux.HandleFunc("/x", func(w http.ResponseWriter, r *http.Request) {}) |
| - for _, m := range []string{"GET", "HEAD"} { |
| + mux.HandleFunc("POST /all", func(w http.ResponseWriter, r *http.Request) { |
| + io.ReadAll(r.Body) |
| + clk.advance(work) |
| + w.WriteHeader(http.StatusSeeOther) |
| + }) |
| + mux.HandleFunc("PUT /declared", func(w http.ResponseWriter, r *http.Request) { |
| + buf := make([]byte, 64) |
| + got := 0 |
| + for got < int(r.ContentLength) { |
| + n, _ := r.Body.Read(buf) |
| + got += n |
| + } |
| + clk.advance(work) |
| + w.WriteHeader(http.StatusNoContent) |
| + }) |
| + mux.HandleFunc("PATCH /part", func(w http.ResponseWriter, r *http.Request) { |
| + r.Body.Read(make([]byte, 4)) |
| + clk.advance(work) |
| + w.WriteHeader(http.StatusOK) |
| + io.ReadAll(r.Body) // after the first byte: changes nothing |
| + }) |
| + mux.HandleFunc("DELETE /none", func(w http.ResponseWriter, r *http.Request) { |
| + clk.advance(work) |
| + w.WriteHeader(http.StatusNoContent) |
| + }) |
| + run := func(method, path string, contentLength int64) perf.Sample { |
| + t.Helper() |
| var c perf.Recorder |
| - _, ss := serve(t, &c, perf.Options{}, mux, m, "/x") |
| - if s := only(t, ss); s.Budget != float64(perf.DefaultBudget/time.Millisecond) || s.Method != m { |
| - t.Fatalf("%s sample = %+v, want budget %v", m, s, perf.DefaultBudget) |
| + perf.SetClock(&c, clk.now) |
| + req := httptest.NewRequest(method, path, nil) |
| + req.Body = io.NopCloser(&slowBody{r: strings.NewReader("0123456789abcdef"), clk: clk, each: time.Second}) |
| + req.ContentLength = contentLength |
| + perf.Middleware(&c, perf.Options{Logger: quiet})(mux).ServeHTTP(httptest.NewRecorder(), req) |
| + return only(t, c.Snapshot()) |
| + } |
| + |
| + // Sixteen bytes in fours: four reads of data and, read to the end, a |
| + // fifth that answers EOF, each a second. |
| + work = 400 * time.Millisecond |
| + if s := run("POST", "/all", -1); s.Class != perf.ClassWrite || s.Budget != 500 || s.Over || s.BodyRead != 5000 || s.Latency != 400 || s.TTFB != 5400 { |
| + t.Errorf("POST read to EOF = %+v, want write, budget 500, body read at 5000, latency 400, not over", s) |
| + } |
| + work = 501 * time.Millisecond |
| + if s := run("POST", "/all", -1); !s.Over || s.Latency != 501 { |
| + t.Errorf("POST 501 ms after its body = %+v, want over with latency 501", s) |
| + } |
| + work = 100 * time.Millisecond |
| + if s := run("PUT", "/declared", 16); s.BodyRead != 4000 || s.Latency != 100 || s.Over { |
| + t.Errorf("PUT read to its Content-Length = %+v, want body read at 4000 and latency 100", s) |
| + } |
| + if s := run("PATCH", "/part", 16); s.BodyRead != 1000 || s.Latency != 100 { |
| + t.Errorf("PATCH that read part of its body = %+v, want body read at its last read (1000) and latency 100", s) |
| + } |
| + work = 600 * time.Millisecond |
| + if s := run("DELETE", "/none", 16); s.BodyRead != 0 || s.Latency != 600 || !s.Over { |
| + t.Errorf("DELETE that read no body = %+v, want judged from its start: latency 600, over", s) |
| + } |
| +} |
| + |
| +// TestOtherMethodsHaveNoBudget: not acceptance. |
| +func TestOtherMethodsHaveNoBudget(t *testing.T) { |
| + clk := newManualClock() |
| + mux := http.NewServeMux() |
| + mux.HandleFunc("/x", func(w http.ResponseWriter, r *http.Request) { clk.advance(time.Second) }) |
| + var c perf.Recorder |
| + perf.SetClock(&c, clk.now) |
| + _, ss := serve(t, &c, perf.Options{}, mux, "OPTIONS", "/x") |
| + if s := only(t, ss); s.Class != "" || s.Budget != 0 || s.Over { |
| + t.Fatalf("OPTIONS sample = %+v, want no class, no budget, not over", s) |
| + } |
| +} |
| + |
| +// countingCounter is a perf.Counter for the tests. |
| +type countingCounter struct { |
| + mu sync.Mutex |
| + n map[string]int |
| +} |
| + |
| +func (k *countingCounter) CountCall(name string) { |
| + k.mu.Lock() |
| + defer k.mu.Unlock() |
| + if k.n == nil { |
| + k.n = map[string]int{} |
| + } |
| + k.n[name]++ |
| +} |
| + |
| +// TestTimeDoerChargesTheContextsCounter: not acceptance. A call on a |
| +// context carrying a Counter, and no measured request, is the Counter's |
| +// and not background; a measured request under that context still counts |
| +// its own calls. |
| +func TestTimeDoerChargesTheContextsCounter(t *testing.T) { |
| + var c perf.Recorder |
| + k := &countingCounter{} |
| + ctx := perf.WithCounter(context.Background(), k) |
| + d := perf.TimeDoer(answering{}, "s3", &c) |
| + do := func(ctx context.Context) { |
| + req, _ := http.NewRequestWithContext(ctx, "GET", "http://store.example.com/k", nil) |
| + resp, err := d.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| } |
| + resp.Body.Close() |
| + } |
| + do(ctx) |
| + do(ctx) |
| + mux := http.NewServeMux() |
| + mux.HandleFunc("GET /x", func(w http.ResponseWriter, r *http.Request) { do(r.Context()) }) |
| + rec := httptest.NewRecorder() |
| + perf.Middleware(&c, perf.Options{Logger: quiet})(mux).ServeHTTP(rec, httptest.NewRequestWithContext(ctx, "GET", "/x", nil)) |
| + if k.n["s3"] != 2 { |
| + t.Errorf("counter = %v, want 2 s3 calls", k.n) |
| + } |
| + if bg := c.Background(); len(bg) != 0 { |
| + t.Errorf("background = %v, want none", bg) |
| + } |
| + if s := only(t, c.Snapshot()); s.Calls["s3"] != 1 { |
| + t.Errorf("request sample calls = %v, want its own one", s.Calls) |
| } |
| } |
| @@ -465,7 +641,7 @@ func TestUnknownMethodsFoldToOther(t *testing.T) { |
| mux.HandleFunc("/x", func(w http.ResponseWriter, r *http.Request) {}) |
| var c perf.Recorder |
| _, ss := serve(t, &c, perf.Options{}, mux, "BREW", "/x") |
| - if s := only(t, ss); s.Method != "OTHER" || s.Budget != 0 { |
| + if s := only(t, ss); s.Method != "OTHER" || s.Budget != 0 || s.Class != "" { |
| t.Fatalf("sample = %+v, want method OTHER and no budget", s) |
| } |
| } |
diff --git a/internal/perf/perf.go b/internal/perf/perf.go| index 100963cbe..3fd468d55 100644 |
| --- a/internal/perf/perf.go |
| +++ b/internal/perf/perf.go |
| @@ -2,11 +2,17 @@ |
| // keeps what it measured: a bounded ring of recent samples, summarised |
| // per route as p50 and p95. |
| // |
| -// The design follows Rastrillo's perf package, without its labels, cold |
| -// start or startup span: the console has no cold-start budget. The |
| -// budget is judged on time to first byte, so a download or a stream that |
| -// starts quickly is not a failure however long it runs, and only a read |
| -// (GET or HEAD) has one. |
| +// The design follows Rastrillo's perf package, without its labels or |
| +// startup span. The rule is two-tier, Tito Go's and Rastrillo's: a read |
| +// (GET or HEAD) is warm when it made no outbound call before its first |
| +// byte, so it was served from memory and the console's own database, and |
| +// cold when it made at least one (an S3 or box request). A warm read has |
| +// WarmBudget, a cold one ColdBudget, both judged on time to first byte, so |
| +// a download or a stream that starts quickly is not a failure however |
| +// long it runs. A write (POST, PUT, PATCH, DELETE) has WriteBudget, |
| +// judged from when the handler had read the request body to the first |
| +// byte, so an upload's transfer time is not charged to the console. Any |
| +// other method has no budget. |
| // |
| // A sample's Screen is a route pattern, never a path. A path can carry a |
| // token, and an over-budget warning is a log line that outlives the |
| @@ -24,10 +30,29 @@ import ( |
| // ring, so a busy process's memory is bounded by construction. |
| const Capacity = 2048 |
| -// DefaultBudget is the first-byte budget for a GET or HEAD. |
| -const DefaultBudget = 150 * time.Millisecond |
| +// The budgets. |
| +const ( |
| + // WarmBudget is the first-byte budget for a warm read: a GET or HEAD |
| + // that made no outbound call before its first byte. |
| + WarmBudget = 150 * time.Millisecond |
| + // ColdBudget is the first-byte budget for a cold read: a GET or HEAD |
| + // that made at least one outbound call (S3 or a box) before its first |
| + // byte. |
| + ColdBudget = 500 * time.Millisecond |
| + // WriteBudget is a write's budget (POST, PUT, PATCH, DELETE), from |
| + // the moment its handler had read the request body to its first byte. |
| + WriteBudget = 500 * time.Millisecond |
| +) |
| + |
| +// A sample's class: which budget it was judged against. |
| +const ( |
| + ClassWarm = "warm" |
| + ClassCold = "cold" |
| + ClassWrite = "write" |
| +) |
| -// Sample is one request. Times are in milliseconds. |
| +// Sample is one request. Times are in milliseconds from the request's |
| +// start. |
| type Sample struct { |
| At time.Time `json:"at"` |
| Screen string `json:"screen"` |
| @@ -38,20 +63,44 @@ type Sample struct { |
| Spans map[string]float64 `json:"spans_ms,omitempty"` |
| // Calls counts the outbound HTTP requests the request made, by span |
| // name. |
| - Calls map[string]int `json:"calls,omitempty"` |
| - Budget float64 `json:"budget_ms"` |
| - Over bool `json:"over_budget"` |
| + Calls map[string]int `json:"calls,omitempty"` |
| + // BodyRead is when the handler had read the request body: the read |
| + // that reached its end (EOF, or as many bytes as Content-Length |
| + // declared), else the last read before the first byte. Zero when it |
| + // read none before the first byte. |
| + BodyRead float64 `json:"body_read_ms,omitempty"` |
| + // Class is ClassWarm or ClassCold for a GET or HEAD, ClassWrite for a |
| + // POST, PUT, PATCH or DELETE, and "" for any other method, which has |
| + // no budget. |
| + Class string `json:"class,omitempty"` |
| + // Latency is the time judged against Budget: TTFB for a read, TTFB |
| + // less BodyRead for a write. |
| + Latency float64 `json:"latency_ms"` |
| + Budget float64 `json:"budget_ms"` |
| + Over bool `json:"over_budget"` |
| } |
| -// Group is one screen and method's requests. |
| +// Group is one screen and method's requests. A GET or HEAD group counts |
| +// its warm and cold requests apart, each against its own budget; a |
| +// write group's requests are all Writes. |
| type Group struct { |
| - Screen string `json:"screen"` |
| - Method string `json:"method"` |
| - Requests int `json:"requests"` |
| - Over int `json:"over_budget"` |
| - P50 float64 `json:"p50_ms"` |
| - P95 float64 `json:"p95_ms"` |
| - Total95 float64 `json:"total_p95_ms"` |
| + Screen string `json:"screen"` |
| + Method string `json:"method"` |
| + Requests int `json:"requests"` |
| + // Over is every request over its budget: WarmOver, ColdOver and |
| + // WriteOver together. |
| + Over int `json:"over_budget"` |
| + Warm int `json:"warm"` |
| + WarmOver int `json:"warm_over_budget"` |
| + Cold int `json:"cold"` |
| + ColdOver int `json:"cold_over_budget"` |
| + Writes int `json:"writes"` |
| + WriteOver int `json:"write_over_budget"` |
| + // P50 and P95 are of Latency, the judged time: first byte for a |
| + // read, from the body read to the first byte for a write. |
| + P50 float64 `json:"p50_ms"` |
| + P95 float64 `json:"p95_ms"` |
| + Total95 float64 `json:"total_p95_ms"` |
| // Calls is summed over the group's samples. |
| Calls map[string]int `json:"calls,omitempty"` |
| } |
| @@ -64,7 +113,7 @@ type Recorder struct { |
| next int |
| // background counts outbound requests made on a context no measured |
| - // request owns, since the process started. |
| + // request owns and no Counter claims, since the process started. |
| background map[string]int64 |
| // Over-budget logging is throttled twice, both on a rolling minute: |
| @@ -113,6 +162,18 @@ func (c *Recorder) Snapshot() []Sample { |
| return out |
| } |
| +// Last returns the most recent sample, and false when there is none. A |
| +// test that makes one request at a time reads that request's class and |
| +// judged time here. |
| +func (c *Recorder) Last() (Sample, bool) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + if len(c.samples) == 0 { |
| + return Sample{}, false |
| + } |
| + return cloneSample(c.samples[(c.next+len(c.samples)-1)%len(c.samples)]), true |
| +} |
| + |
| // cloneSample returns s with its own Spans and Calls maps. |
| func cloneSample(s Sample) Sample { |
| if s.Spans != nil { |
| @@ -136,8 +197,9 @@ func cloneSample(s Sample) Sample { |
| func (c *Recorder) Groups() []Group { return Groups(c.Snapshot()) } |
| // Background returns how many outbound requests, by span name, were made |
| -// on a context no measured request owns (background passes, view-cache |
| -// loads), counted since the process started. It is a copy. |
| +// on a context that neither a measured request owns nor a Counter claims |
| +// (view-cache loads, start-up reads, a pass outside the job registry), |
| +// counted since the process started. It is a copy. |
| func (c *Recorder) Background() map[string]int64 { |
| c.mu.Lock() |
| defer c.mu.Unlock() |
| @@ -157,8 +219,8 @@ func (c *Recorder) countBackground(name string) { |
| c.mu.Unlock() |
| } |
| -// Groups buckets samples by screen and method, with first-byte p50 and |
| -// p95 and total p95, slowest p95 first. Ties break by method, then |
| +// Groups buckets samples by screen and method, with the judged time's p50 |
| +// and p95 and total p95, slowest p95 first. Ties break by method, then |
| // screen. |
| func Groups(samples []Sample) []Group { |
| type key struct{ screen, method string } |
| @@ -170,13 +232,30 @@ func Groups(samples []Sample) []Group { |
| out := make([]Group, 0, len(buckets)) |
| for k, ss := range buckets { |
| g := Group{Screen: k.screen, Method: k.method, Requests: len(ss)} |
| - ttfb := make([]float64, 0, len(ss)) |
| + latency := make([]float64, 0, len(ss)) |
| total := make([]float64, 0, len(ss)) |
| for _, s := range ss { |
| if s.Over { |
| g.Over++ |
| } |
| - ttfb = append(ttfb, s.TTFB) |
| + switch s.Class { |
| + case ClassWarm: |
| + g.Warm++ |
| + if s.Over { |
| + g.WarmOver++ |
| + } |
| + case ClassCold: |
| + g.Cold++ |
| + if s.Over { |
| + g.ColdOver++ |
| + } |
| + case ClassWrite: |
| + g.Writes++ |
| + if s.Over { |
| + g.WriteOver++ |
| + } |
| + } |
| + latency = append(latency, s.Latency) |
| total = append(total, s.Total) |
| for name, n := range s.Calls { |
| if g.Calls == nil { |
| @@ -185,8 +264,8 @@ func Groups(samples []Sample) []Group { |
| g.Calls[name] += n |
| } |
| } |
| - g.P50 = percentile(ttfb, 50) |
| - g.P95 = percentile(ttfb, 95) |
| + g.P50 = percentile(latency, 50) |
| + g.P95 = percentile(latency, 95) |
| g.Total95 = percentile(total, 95) |
| out = append(out, g) |
| } |
| @@ -233,8 +312,9 @@ func (c *Recorder) add(s Sample, log *slog.Logger) { |
| c.mu.Unlock() |
| if emit && log != nil { |
| log.Warn("request over performance budget", |
| - "screen", s.Screen, "method", s.Method, "status", s.Status, |
| - "ttfb_ms", s.TTFB, "total_ms", s.Total, "budget_ms", s.Budget, "spans_ms", s.Spans) |
| + "screen", s.Screen, "method", s.Method, "status", s.Status, "class", s.Class, |
| + "latency_ms", s.Latency, "ttfb_ms", s.TTFB, "body_read_ms", s.BodyRead, |
| + "total_ms", s.Total, "budget_ms", s.Budget, "spans_ms", s.Spans, "calls", s.Calls) |
| } |
| } |
diff --git a/internal/perf/perf_test.go b/internal/perf/perf_test.go| index e371748b7..ace78985c 100644 |
| --- a/internal/perf/perf_test.go |
| +++ b/internal/perf/perf_test.go |
| @@ -29,7 +29,7 @@ func TestRingKeepsTheLast2048(t *testing.T) { |
| func TestGroupsPercentilesNearestRank(t *testing.T) { |
| var ss []Sample |
| for i := 1; i <= 100; i++ { |
| - ss = append(ss, Sample{Screen: "GET /x", Method: "GET", TTFB: float64(i), Total: float64(i), Over: i == 100}) |
| + ss = append(ss, Sample{Screen: "GET /x", Method: "GET", Latency: float64(i), Total: float64(i), Over: i == 100}) |
| } |
| gs := Groups(ss) |
| if len(gs) != 1 { |
| @@ -43,8 +43,8 @@ func TestGroupsPercentilesNearestRank(t *testing.T) { |
| func TestGroupsSlowestFirst(t *testing.T) { |
| gs := Groups([]Sample{ |
| - {Screen: "GET /a", Method: "GET", TTFB: 10}, |
| - {Screen: "GET /b", Method: "GET", TTFB: 90}, |
| + {Screen: "GET /a", Method: "GET", Latency: 10}, |
| + {Screen: "GET /b", Method: "GET", Latency: 90}, |
| }) |
| if len(gs) != 2 || gs[0].Screen != "GET /b" || gs[1].Screen != "GET /a" { |
| t.Fatalf("got %+v, want [B, A]", gs) |
| @@ -334,3 +334,40 @@ func TestBackgroundCountsAccumulate(t *testing.T) { |
| t.Fatalf("mutating the copy changed the recorder: %v", again) |
| } |
| } |
| + |
| +// A group counts its warm, cold and write requests apart, each with its |
| +// own over-budget count, and its percentiles are of the judged time. |
| +func TestGroupsCountEachClass(t *testing.T) { |
| + gs := Groups([]Sample{ |
| + {Screen: "GET /a", Method: "GET", Class: ClassWarm, Latency: 10}, |
| + {Screen: "GET /a", Method: "GET", Class: ClassWarm, Latency: 160, Over: true}, |
| + {Screen: "GET /a", Method: "GET", Class: ClassCold, Latency: 400}, |
| + {Screen: "GET /a", Method: "GET", Class: ClassCold, Latency: 600, Over: true}, |
| + {Screen: "GET /a", Method: "GET", Class: ClassCold, Latency: 700, Over: true}, |
| + {Screen: "POST /b", Method: "POST", Class: ClassWrite, TTFB: 9000, Latency: 300}, |
| + {Screen: "POST /b", Method: "POST", Class: ClassWrite, TTFB: 9000, Latency: 501, Over: true}, |
| + }) |
| + if len(gs) != 2 { |
| + t.Fatalf("groups = %+v, want 2", gs) |
| + } |
| + a, b := gs[0], gs[1] |
| + if a.Screen != "GET /a" || a.Warm != 2 || a.WarmOver != 1 || a.Cold != 3 || a.ColdOver != 2 || a.Writes != 0 || a.Over != 3 { |
| + t.Errorf("GET group = %+v, want 2 warm (1 over), 3 cold (2 over)", a) |
| + } |
| + if b.Screen != "POST /b" || b.Writes != 2 || b.WriteOver != 1 || b.Warm+b.Cold != 0 || b.P95 != 501 { |
| + t.Errorf("POST group = %+v, want 2 writes (1 over), p95 501 (the judged time, not the first byte)", b) |
| + } |
| +} |
| + |
| +func TestLastIsTheNewestSample(t *testing.T) { |
| + var r Recorder |
| + if _, ok := r.Last(); ok { |
| + t.Fatal("Last on an empty ring reported a sample") |
| + } |
| + for i := 0; i < Capacity+5; i++ { |
| + r.add(Sample{Screen: "GET /x", Method: "GET", TTFB: float64(i)}, nil) |
| + if s, ok := r.Last(); !ok || s.TTFB != float64(i) { |
| + t.Fatalf("after sample %d, Last = %+v, %v", i, s, ok) |
| + } |
| + } |
| +} |