commit fe76d2f6ba0c3c1c2dcf11b75462c7f53967b454 Author: hoelee Date: Fri Oct 30 06:06:34 2026 +0800 Benchmark harness, raw runs, and the 504 read-amplification report (v1.3) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..61bfaf5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +__pycache__/ +*.pyc +.venv/ +swr-bench-*/ +!data/*.json diff --git a/CITATION.cff b/CITATION.cff new file mode 100644 index 0000000..f24794c --- /dev/null +++ b/CITATION.cff @@ -0,0 +1,32 @@ +cff-version: 1.2.0 +message: "If you use this harness or its results, cite the report below." +type: report +title: "Moving a 504 Out of the System: Read Amplification, Timeout Budget Inversion, and a Stale-While-Revalidate Status Engine" +version: "1.3" +date-released: 2026-10-30 +license: CC-BY-4.0 +url: "https://doc.hoelee.com/whitepaper-504-read-amplification-swr-en.html" +repository-code: "https://github.com/hoelee/swr-read-amplification-bench" +keywords: + - read amplification + - stale-while-revalidate + - single-flight + - cache stampede + - timeout budget + - reverse proxy + - network file system + - performance engineering + - benchmark reproducibility +authors: + - family-names: Lee + given-names: Teong Hoe + affiliation: "Hoelee Enterprise" +preferred-citation: + type: report + title: "Moving a 504 Out of the System: Read Amplification, Timeout Budget Inversion, and a Stale-While-Revalidate Status Engine" + year: 2026 + month: 10 + authors: + - family-names: Lee + given-names: Teong Hoe + affiliation: "Hoelee Enterprise" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..2e639ec --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Lee Teong Hoe (Hoelee Enterprise) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..c3a66ad --- /dev/null +++ b/README.md @@ -0,0 +1,135 @@ +# Read amplification, timeout-budget inversion, and a stale-while-revalidate status engine + +Benchmark harness and full report for a status endpoint that answered in **433 ms** on a +development machine and returned **HTTP 504** in production — same code, byte for byte. + +The interesting part is not that it broke. It is that the difference between "fast enough" +and "504" turned out to be a property of the storage, not of the algorithm. + +| | Naive (4 reads/file) | Single pass (1 read/file) | SWR cache hit | +|---|---|---|---| +| Request path | 433.5 ms (measured, local NVMe) | 230.0 ms | **0.3 µs** | +| Reads per page load | 960 | 360 | 0 | +| Projected at 20 ms/read | 18.5 s | 7.9 s | off the request path | + +--- + +## What the endpoint did + +A knowledge-base admin view summarises the translation state of every note in the library. +For each source file it asked four questions — which locale, what is the hash, what is the +title, is the translation current — and answered each one by opening the file again. At 240 +notes that is **960 whole-file reads** and roughly three YAML front-matter deserialisations +per note, for a page that renders titles and three status words. + +On local NVMe, removing three quarters of those reads bought **1.5–1.9×**. That is the trap: +a four-fold read multiplier that costs 433 ms passes review, passes tests, and ships. The +same code is only wrong on storage where each read carries a round trip. + +## Why the fix is not a faster loop + +The request also failed for a second reason: the timeout budget ran backwards. +**30 s** at the edge gateway, **60 s** at the reverse proxy, **120 s** at the application. Each +layer waits longer than the layer in front of it, so when the gateway abandons the connection +at 30 s the inner layers keep working and write a `200` into a socket nobody is reading. The +same `X-Request-ID` appears as *abandoned* in the gateway log and *completed 200* in the +application log, seconds apart — which means the request's true duration is observable from +neither log alone, and should not be quoted. + +The fix is architectural: **requests always read memory, scans always happen in the +background.** + +```text +GET /api/translations/status + │ + ▼ + memory cache fresh? ──yes──▶ return JSON (0.3 µs) + │ no + ▼ + a refresh already running? ──yes──▶ return the previous snapshot + │ no + ▼ + claim the refresh, start a background thread, return the previous snapshot + │ + └─ background: single pass + mtime/size signature diff +``` + +Three properties make it safe rather than merely fast: + +- **Stale-while-revalidate** ([RFC 5861](https://www.rfc-editor.org/rfc/rfc5861.html)) — a hit never blocks; stale data is served while a refresh runs. +- **Single flight** ([groupcache](https://github.com/golang/groupcache), [`x/sync/singleflight`](https://pkg.go.dev/golang.org/x/sync/singleflight)) — a burst of five requests triggers exactly one scan; a separate cold-start lock prevents the stampede that "async refresh" would otherwise create. +- **Signature-based incrementality** — `(st_mtime_ns, st_size)` per file; an unchanged signature means **zero `read_text()` calls**. One edited note costs one file read and reuses 239 cached rows. + +## Reproduce it + +```bash +pip install pyyaml +python swr_bench.py # ~100 s: generates a 360-file corpus, runs three implementations, + # emits the latency projection, prints strictly valid JSON +``` + +The harness generates its own corpus, so it runs anywhere. Expect, within roughly ±30% on +comparable hardware: cold paths in the hundreds of milliseconds, cache hit sub-microsecond, +incremental refresh around 25 ms, and the classification split **ready 60 / outdated 60 / +pending 120** exactly — that last number is a correctness assertion, not a timing. + +## The data in `data/` + +| File | What it is | +|---|---| +| `bench-2026-10-30-run{A,B,C}.json` | Three independent full runs (replication session B), verbatim harness stdout | +| `bench-v1.1-prefix-289.6ms.json` | **Pre-correction v1.1 output** — its incremental column is physically impossible (faster as reads get slower). Kept because it is the defect the report corrects in §5.4 | +| `bench-v1.1-prefix-401.5ms.json` | Second pre-correction v1.1 output, same defect | + +Two sessions are reported and neither is hidden: + +- **Session A (2026-10-29)** — medians `433.5 / 230.0 / 263.1 ms`, cache hit `0.3 µs`, incremental `14.7 ms`. Transcribed from console output; not stored as files. +- **Session B (2026-10-30)** — medians `517.1 / 292.2 / 333.1 ms`, cache hit `0.5 µs`, incremental `25.50 ms`. Archived here. + +Session B ran **19–27 % slower** than session A on the cold paths, so cross-session drift is +larger than the ±20 % within-session band. What replicates is the **structure**: zero +filesystem reads on the request path, one file read per incremental refresh, and a cold-path +ratio of 1.77–1.90× (A: 1.50–1.89×). What does not replicate is any absolute figure — which +is why the report quotes medians, ranges and a per-session label, never a bare number. + +## Limits, stated plainly + +- One machine: Windows 11, local NVMe, single process, Python 3.14.9. The experiment quantifies the *relative* cost of read amplification; it does not reproduce network-volume latency. +- The latency projection in the report **is a model output**. It bills `read_text()` at a fixed cost `L` and does not bill `stat()`, which on SMB/NFS is also a round trip — the incremental path's dominant cost is roughly 480 of them. +- The corpus is synthetic. Real notes have longer bodies and messier front matter, which moves the absolute numbers and not the shape. +- Write-through invalidation assumes the save path calls `invalidate(slug)`; a file dropped in by rsync can be served stale for up to the 60-second TTL. That window is accepted, because adding a `stat` probe to `GET` would invite back the I/O the refactor removed. + +## The report + +- **English, 13 pages** — [`paper/whitepaper-504-en-v1.3.pdf`](paper/whitepaper-504-en-v1.3.pdf) +- **Chinese, 13 pages** — [`paper/whitepaper-504-zh-v1.3.pdf`](paper/whitepaper-504-zh-v1.3.pdf) +- HTML edition — + +The report carries eight references, each cited for a specific mechanism used (the HTTP caching +specs, the Go single-flight pattern, NFS/SMB round-trip structure, `pathlib.Path.stat`), not as a +literature survey. + +## Citing + +```bibtex +@techreport{lee2026swr504, + author = {Lee, Teong Hoe}, + title = {Moving a 504 Out of the System: Read Amplification, Timeout Budget + Inversion, and a Stale-While-Revalidate Status Engine}, + institution = {Hoelee Enterprise}, + year = {2026}, + month = {oct}, + version = {1.3}, + url = {https://doc.hoelee.com/whitepaper-504-read-amplification-swr-en.html} +} +``` + +A DOI will be minted on Zenodo; this README and `CITATION.cff` will be updated with it. + +## Licence + +- Text and figures: **CC BY 4.0** +- `swr_bench.py`: **MIT** + +Architectural patterns described here were engineered by the author. Client identifiers and +production thresholds are sanitised; there is no client data in this repository. diff --git a/data/bench-2026-10-30-runA.json b/data/bench-2026-10-30-runA.json new file mode 100644 index 0000000..316fbc3 --- /dev/null +++ b/data/bench-2026-10-30-runA.json @@ -0,0 +1,73 @@ +{ + "corpus_files_md": 360, + "corpus_bytes": 1315740, + "naive_cold_ms": 461.7, + "naive_runs_ms": [ + 443.2, + 393.6, + 509.8, + 461.7, + 552.1 + ], + "naive_rows": 240, + "single_pass_cold_ms": 242.7, + "single_pass_runs_ms": [ + 233.9, + 275.8, + 271.0, + 242.7, + 236.0 + ], + "single_pass_rows": 240, + "swr_cold_ms": 293.7, + "swr_cold_runs_ms": [ + 327.7, + 288.4, + 293.7 + ], + "swr_cold_files_read": 240, + "swr_cold_files_reused": 0, + "swr_memory_hit_us": 0.3, + "swr_memory_hit_p99_us": 3.1, + "swr_incremental_refresh_ms": 29.51, + "swr_incremental_files_read": 1, + "swr_incremental_files_reused": 239, + "state_distribution": { + "pending": 120, + "ready": 60, + "outdated": 60 + }, + "speedup_naive_vs_single": 1.9, + "speedup_naive_vs_swr_cold": 1.57, + "speedup_naive_vs_memory_hit": 1538876.0, + "speedup_single_vs_incremental": 8.22, + "latency_projection": [ + { + "per_read_ms": 5.0, + "incremental_files_read": 1, + "incremental_files_reused": 239, + "naive_ms": 5493.0, + "single_pass_ms": 2753.8, + "swr_cold_ms": 2720.5, + "swr_incremental_1file_ms": 38.7 + }, + { + "per_read_ms": 10.0, + "incremental_files_read": 1, + "incremental_files_reused": 239, + "naive_ms": 11013.1, + "single_pass_ms": 4743.8, + "swr_cold_ms": 4816.2, + "swr_incremental_1file_ms": 42.2 + }, + { + "per_read_ms": 20.0, + "incremental_files_read": 1, + "incremental_files_reused": 239, + "naive_ms": 22196.9, + "single_pass_ms": 8902.3, + "swr_cold_ms": 8709.8, + "swr_incremental_1file_ms": 212.7 + } + ] +} \ No newline at end of file diff --git a/data/bench-2026-10-30-runB.json b/data/bench-2026-10-30-runB.json new file mode 100644 index 0000000..b659db8 --- /dev/null +++ b/data/bench-2026-10-30-runB.json @@ -0,0 +1,73 @@ +{ + "corpus_files_md": 360, + "corpus_bytes": 1315740, + "naive_cold_ms": 517.1, + "naive_runs_ms": [ + 565.8, + 483.9, + 517.1, + 513.7, + 532.7 + ], + "naive_rows": 240, + "single_pass_cold_ms": 292.2, + "single_pass_runs_ms": [ + 292.2, + 330.9, + 298.8, + 243.4, + 228.9 + ], + "single_pass_rows": 240, + "swr_cold_ms": 333.1, + "swr_cold_runs_ms": [ + 333.1, + 299.5, + 338.5 + ], + "swr_cold_files_read": 240, + "swr_cold_files_reused": 0, + "swr_memory_hit_us": 0.6, + "swr_memory_hit_p99_us": 6.4, + "swr_incremental_refresh_ms": 25.42, + "swr_incremental_files_read": 1, + "swr_incremental_files_reused": 239, + "state_distribution": { + "pending": 120, + "ready": 60, + "outdated": 60 + }, + "speedup_naive_vs_single": 1.77, + "speedup_naive_vs_swr_cold": 1.55, + "speedup_naive_vs_memory_hit": 861773.0, + "speedup_single_vs_incremental": 11.49, + "latency_projection": [ + { + "per_read_ms": 5.0, + "incremental_files_read": 1, + "incremental_files_reused": 239, + "naive_ms": 5350.9, + "single_pass_ms": 2425.9, + "swr_cold_ms": 2366.6, + "swr_incremental_1file_ms": 30.2 + }, + { + "per_read_ms": 10.0, + "incremental_files_read": 1, + "incremental_files_reused": 239, + "naive_ms": 10033.3, + "single_pass_ms": 4311.9, + "swr_cold_ms": 4281.5, + "swr_incremental_1file_ms": 35.4 + }, + { + "per_read_ms": 20.0, + "incremental_files_read": 1, + "incremental_files_reused": 239, + "naive_ms": 19861.4, + "single_pass_ms": 9141.3, + "swr_cold_ms": 8394.1, + "swr_incremental_1file_ms": 42.7 + } + ] +} \ No newline at end of file diff --git a/data/bench-2026-10-30-runC.json b/data/bench-2026-10-30-runC.json new file mode 100644 index 0000000..c55d66a --- /dev/null +++ b/data/bench-2026-10-30-runC.json @@ -0,0 +1,73 @@ +{ + "corpus_files_md": 360, + "corpus_bytes": 1315740, + "naive_cold_ms": 559.5, + "naive_runs_ms": [ + 559.5, + 573.1, + 605.1, + 517.8, + 558.1 + ], + "naive_rows": 240, + "single_pass_cold_ms": 306.6, + "single_pass_runs_ms": [ + 306.6, + 647.1, + 339.7, + 275.8, + 259.6 + ], + "single_pass_rows": 240, + "swr_cold_ms": 357.2, + "swr_cold_runs_ms": [ + 343.6, + 357.2, + 366.3 + ], + "swr_cold_files_read": 240, + "swr_cold_files_reused": 0, + "swr_memory_hit_us": 0.5, + "swr_memory_hit_p99_us": 3.5, + "swr_incremental_refresh_ms": 25.5, + "swr_incremental_files_read": 1, + "swr_incremental_files_reused": 239, + "state_distribution": { + "pending": 120, + "ready": 60, + "outdated": 60 + }, + "speedup_naive_vs_single": 1.82, + "speedup_naive_vs_swr_cold": 1.57, + "speedup_naive_vs_memory_hit": 1119070.0, + "speedup_single_vs_incremental": 12.03, + "latency_projection": [ + { + "per_read_ms": 5.0, + "incremental_files_read": 1, + "incremental_files_reused": 239, + "naive_ms": 6890.1, + "single_pass_ms": 3635.6, + "swr_cold_ms": 3413.7, + "swr_incremental_1file_ms": 49.3 + }, + { + "per_read_ms": 10.0, + "incremental_files_read": 1, + "incremental_files_reused": 239, + "naive_ms": 10499.3, + "single_pass_ms": 4213.4, + "swr_cold_ms": 4532.9, + "swr_incremental_1file_ms": 38.1 + }, + { + "per_read_ms": 20.0, + "incremental_files_read": 1, + "incremental_files_reused": 239, + "naive_ms": 18498.7, + "single_pass_ms": 8613.2, + "swr_cold_ms": 8074.7, + "swr_incremental_1file_ms": 55.0 + } + ] +} \ No newline at end of file diff --git a/data/bench-v1.1-prefix-289.6ms.json b/data/bench-v1.1-prefix-289.6ms.json new file mode 100644 index 0000000..920d7ae --- /dev/null +++ b/data/bench-v1.1-prefix-289.6ms.json @@ -0,0 +1,73 @@ +{ + "corpus_files_md": 360, + "corpus_bytes": 1315740, + "naive_cold_ms": 289.6, + "naive_runs_ms": [ + 316.1, + 264.7, + 271.6, + 289.6, + 335.5 + ], + "naive_rows": 240, + "single_pass_cold_ms": 168.3, + "single_pass_runs_ms": [ + 174.9, + 143.2, + 168.3, + 181.8, + 160.5 + ], + "single_pass_rows": 240, + "swr_cold_ms": 181.2, + "swr_cold_runs_ms": [ + 161.5, + 181.2, + 202.4 + ], + "swr_cold_files_read": 240, + "swr_cold_files_reused": 0, + "swr_memory_hit_us": 0.3, + "swr_memory_hit_p99_us": 1.7, + "swr_incremental_refresh_ms": 10.34, + "swr_incremental_files_read": 1, + "swr_incremental_files_reused": 239, + "state_distribution": { + "pending": 120, + "ready": 60, + "outdated": 60 + }, + "speedup_naive_vs_single": 1.72, + "speedup_naive_vs_swr_cold": 1.6, + "speedup_naive_vs_memory_hit": 965201.0, + "speedup_single_vs_incremental": 16.27, + "latency_projection": [ + { + "per_read_ms": 5.0, + "incremental_files_read": 1, + "incremental_files_reused": 239, + "naive_ms": 4986.1, + "single_pass_ms": 2196.5, + "swr_cold_ms": 2216.6, + "swr_incremental_no_change_ms": 23.8 + }, + { + "per_read_ms": 10.0, + "incremental_files_read": 1, + "incremental_files_reused": 239, + "naive_ms": 9399.2, + "single_pass_ms": 4076.7, + "swr_cold_ms": 4383.9, + "swr_incremental_no_change_ms": 31.7 + }, + { + "per_read_ms": 20.0, + "incremental_files_read": 1, + "incremental_files_reused": 239, + "naive_ms": 18768.1, + "single_pass_ms": 7993.8, + "swr_cold_ms": 7884.4, + "swr_incremental_no_change_ms": 44.9 + } + ] +} \ No newline at end of file diff --git a/data/bench-v1.1-prefix-401.5ms.json b/data/bench-v1.1-prefix-401.5ms.json new file mode 100644 index 0000000..b67a06b --- /dev/null +++ b/data/bench-v1.1-prefix-401.5ms.json @@ -0,0 +1,67 @@ +{ + "corpus_files_md": 360, + "corpus_bytes": 1315740, + "naive_cold_ms": 401.5, + "naive_runs_ms": [ + 352.7, + 567.1, + 464.6, + 401.5, + 392.7 + ], + "naive_rows": 240, + "single_pass_cold_ms": 210.0, + "single_pass_runs_ms": [ + 190.6, + 221.1, + 210.0, + 216.9, + 193.0 + ], + "single_pass_rows": 240, + "swr_cold_ms": 339.3, + "swr_cold_runs_ms": [ + 229.3, + 349.8, + 339.3 + ], + "swr_cold_files_read": 240, + "swr_cold_files_reused": 0, + "swr_memory_hit_us": 0.5, + "swr_memory_hit_p99_us": 4.5, + "swr_incremental_refresh_ms": 25.8, + "swr_incremental_files_read": 1, + "swr_incremental_files_reused": 239, + "state_distribution": { + "pending": 120, + "ready": 60, + "outdated": 60 + }, + "speedup_naive_vs_single": 1.91, + "speedup_naive_vs_swr_cold": 1.18, + "speedup_naive_vs_memory_hit": 802926.0, + "speedup_single_vs_incremental": 8.14, + "latency_projection": [ + { + "per_read_ms": 5.0, + "naive_ms": 5403.4, + "single_pass_ms": 2251.5, + "swr_cold_ms": 2378.4, + "swr_incremental_no_change_ms": 14.3 + }, + { + "per_read_ms": 10.0, + "naive_ms": 9808.1, + "single_pass_ms": 4545.7, + "swr_cold_ms": 4464.1, + "swr_incremental_no_change_ms": 7.0 + }, + { + "per_read_ms": 20.0, + "naive_ms": 18360.8, + "single_pass_ms": 8238.7, + "swr_cold_ms": 7876.7, + "swr_incremental_no_change_ms": 15.0 + } + ] +} \ No newline at end of file diff --git a/paper/whitepaper-504-en-v1.3.pdf b/paper/whitepaper-504-en-v1.3.pdf new file mode 100644 index 0000000..d7cf9ea Binary files /dev/null and b/paper/whitepaper-504-en-v1.3.pdf differ diff --git a/paper/whitepaper-504-zh-v1.3.pdf b/paper/whitepaper-504-zh-v1.3.pdf new file mode 100644 index 0000000..4c453ec Binary files /dev/null and b/paper/whitepaper-504-zh-v1.3.pdf differ diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..3aecde9 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +pyyaml>=6.0 diff --git a/swr_bench.py b/swr_bench.py new file mode 100644 index 0000000..22f9675 --- /dev/null +++ b/swr_bench.py @@ -0,0 +1,331 @@ +""" +Controlled reproduction benchmark for the 504/SWR whitepaper (doc 04). + +Compares two implementations of list_status() over a synthetic corpus of +Markdown notes with YAML front matter: + + A) naive : 4x read_text + 3x YAML load per file (the original defect) + B) single : 1x read per file, one YAML load, in-memory reuse + C) swr : mtime-diff incremental revalidation over B, with 3-state + (ready / outdated / pending) detection preserved + +Outputs a JSON blob with measured timings so the whitepaper table can quote +real numbers instead of invented ones. +""" +import hashlib +import json +import os +import re +import statistics +import sys +import tempfile +import time +from pathlib import Path + +import yaml + +CORPUS_N = int(os.environ.get("CORPUS_N", "240")) +BODY_PARAS = 12 + +FRONT = """--- +title: "Note {i:03d} — streaming pipeline failure modes" +description: "Synthetic sample note used for a controlled benchmark of status aggregation." +pubDate: 2026-01-{day:02d} +category: devops +tags: ["benchmark", "synthetic"] +locale: zh +--- +""" + +PARA = ( + "The pipeline emitted a partial frame before the muxer flushed its moov atom, " + "which made every downstream player re-buffer at the same offset. Segment {j} of " + "this note exists purely to give the file a realistic byte size so that repeated " + "read_text() calls cost measurable wall-clock time.\n\n" +) + + +def build_corpus(root: Path, n: int): + body = "".join(PARA.format(j=j) for j in range(BODY_PARAS)) + for i in range(n): + day = (i % 28) + 1 + src = root / f"note-{i:03d}.md" + src.write_text(FRONT.format(i=i, day=day) + body, encoding="utf-8") + # half the corpus has a translated twin, half is pending + if i % 2 == 1: + tgt = root / f"note-{i:03d}.en.md" + # hash of the source note at the moment the translation was produced + src_hash_at_translation = hash_of_text(src.read_text(encoding="utf-8")) + translated = (f"---\ntitle: Note {i:03d}\n" + f"translatedFromHash: {src_hash_at_translation}\n---\n" + + body.replace(" pipeline", " conduit")) + tgt.write_text(translated, encoding="utf-8") + if i % 4 == 3: + # source keeps moving after the translator was run -> this one is 'outdated' + src.write_text(src.read_text(encoding="utf-8") + "\n\n", + encoding="utf-8") + + +def split_note(raw: str): + if not raw.startswith("---"): + return {}, raw + parts = raw.split("---", 2) + if len(parts) < 3: + return {}, raw + return (yaml.safe_load(parts[1]) or {}), parts[2] + + +def hash_of_text(text: str) -> str: + return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16] + + +# ---------------------------------------------------------------- A) naive +def naive_list_status(content_dir: Path): + results = [] + for p in sorted(content_dir.glob("*.md")): + if p.name.endswith(".en.md"): + continue + # read 1 + raw = p.read_text(encoding="utf-8") + meta, _ = split_note(raw) + if meta.get("locale") != "zh": + continue + # read 2 + src_hash = hash_of_text(p.read_text(encoding="utf-8")) + # read 3 + meta2, _ = split_note(p.read_text(encoding="utf-8")) + tgt = p.with_name(f"{p.stem}.en.md") + status = "pending" + if tgt.exists(): + # read 4 + tgt_raw = tgt.read_text(encoding="utf-8") + tgt_hash = hash_of_text(tgt_raw) + status = "ready" if tgt_hash else "pending" + results.append({"slug": p.stem, "title": meta2.get("title"), "status": status, + "source_hash": src_hash}) + return results + + +# ------------------------------------------------------- B) single pass +def single_pass(content_dir: Path): + results = [] + for p in sorted(content_dir.glob("*.md")): + if p.name.endswith(".en.md"): + continue + raw = p.read_text(encoding="utf-8") + meta, body = split_note(raw) + if meta.get("locale") != "zh": + continue + src_hash = hash_of_text(raw) + tgt = p.with_name(f"{p.stem}.en.md") + status = "pending" + if tgt.exists(): + tgt_meta, _ = split_note(tgt.read_text(encoding="utf-8")) + recorded = (tgt_meta or {}).get("translatedFromHash") + # 3-state: ready if the translation recorded the source hash we see now + status = "ready" if recorded == src_hash else "outdated" + results.append({"slug": p.stem, "title": meta.get("title"), "status": status, + "source_hash": src_hash}) + return results + + +# ---------------------------------------------------------------- C) SWR +class SwrStatus: + def __init__(self, content_dir: Path, ttl=60.0): + self.content_dir = content_dir + self.ttl = ttl + self.data = None + self.stamp = 0.0 + self.mtime_map = {} + + def refresh(self): + t0 = time.perf_counter() + results = [] + new_map = {} + reread = 0 + reused = 0 + for p in sorted(self.content_dir.glob("*.md")): + if p.name.endswith(".en.md"): + continue + st = p.stat() + tgt = p.with_name(f"{p.stem}.en.md") + tgt_st = tgt.stat() if tgt.exists() else None + key = p.name + sig = (st.st_mtime_ns, st.st_size, + tgt_st.st_mtime_ns if tgt_st else None, + tgt_st.st_size if tgt_st else None) + cached = self.mtime_map.get(key) + if cached and cached[0] == sig: + results.append(cached[1]) + new_map[key] = cached + reused += 1 + continue + raw = p.read_text(encoding="utf-8") + meta, body = split_note(raw) + if meta.get("locale") != "zh": + reread += 1 + continue + item = {"slug": p.stem, "title": meta.get("title"), + "source_hash": hash_of_text(raw), "status": "pending"} + if tgt_st: + tgt_meta, _ = split_note(tgt.read_text(encoding="utf-8")) + recorded = (tgt_meta or {}).get("translatedFromHash") + item["status"] = "ready" if recorded == item["source_hash"] else "outdated" + results.append(item) + new_map[key] = (sig, item) + reread += 1 + self.mtime_map = new_map + self.data = results + self.stamp = time.time() + return (time.perf_counter() - t0) * 1000.0, reread, reused + + def get(self): + t0 = time.perf_counter() + if self.data is None: + self.refresh() + elif (time.time() - self.stamp) >= self.ttl: + self.refresh() + return self.data, (time.perf_counter() - t0) * 1000.0 + + +def projected_with_read_latency(content_dir: Path, per_read_ms: float): + """Model a network-attached volume by charging per_read_ms to every read_text(). + + This is an explicitly labelled projection, not a measurement of the NAS. + """ + import builtins + delay = per_read_ms / 1000.0 + orig = Path.read_text + + def slow_read_text(self, *a, **kw): + time.sleep(delay) + return orig(self, *a, **kw) + + Path.read_text = slow_read_text + try: + t = time.perf_counter() + naive_list_status(content_dir) + naive_ms = (time.perf_counter() - t) * 1000.0 + + t = time.perf_counter() + single_pass(content_dir) + single_ms = (time.perf_counter() - t) * 1000.0 + + swr = SwrStatus(content_dir) + swr.refresh() + swr.mtime_map = {} + t = time.perf_counter() + swr.refresh() + swr_cold = (time.perf_counter() - t) * 1000.0 + + # incremental WITH one changed note: identical test condition to the + # measured 25.8 ms row (2 read_text calls: source + translation) + victim = sorted(content_dir.glob("note-*.md"))[0] + victim.write_text(victim.read_text(encoding="utf-8") + "\n\n", + encoding="utf-8") + swr.stamp = 0.0 + t = time.perf_counter() + _i, reread_i, reused_i = swr.refresh() + swr_incr = (time.perf_counter() - t) * 1000.0 + finally: + Path.read_text = orig + + return {"per_read_ms": per_read_ms, "incremental_files_read": reread_i, + "incremental_files_reused": reused_i, + "naive_ms": round(naive_ms, 1), + "single_pass_ms": round(single_ms, 1), + "swr_cold_ms": round(swr_cold, 1), + "swr_incremental_1file_ms": round(swr_incr, 1)} + + +def median_run(fn, rounds=5): + vals = [fn() for _ in range(rounds)] + return statistics.median(vals) + + +def main(): + root = Path(tempfile.mkdtemp(prefix="swr-bench-")) + build_corpus(root, CORPUS_N) + total_bytes = sum(f.stat().st_size for f in root.glob("*.md")) + + out = {"corpus_files_md": len(list(root.glob("*.md"))), "corpus_bytes": total_bytes} + + # warm-up pass so module import / bytecode / page cache don't pollute round 0 + naive_list_status(root) + single_pass(root) + + naive_runs = [] + for _ in range(5): + t = time.perf_counter() + a = naive_list_status(root) + naive_runs.append((time.perf_counter() - t) * 1000.0) + naive_cold = statistics.median(naive_runs) + out["naive_cold_ms"] = round(naive_cold, 1) + out["naive_runs_ms"] = [round(v, 1) for v in naive_runs] + out["naive_rows"] = len(a) + + single_runs = [] + for _ in range(5): + t = time.perf_counter() + b = single_pass(root) + single_runs.append((time.perf_counter() - t) * 1000.0) + single_cold = statistics.median(single_runs) + out["single_pass_cold_ms"] = round(single_cold, 1) + out["single_pass_runs_ms"] = [round(v, 1) for v in single_runs] + out["single_pass_rows"] = len(b) + + swr = SwrStatus(root) + swr_refresh_runs = [] + for _ in range(3): + swr.mtime_map = {} + _c, reread, reused = swr.refresh() + swr_refresh_runs.append(_c) + cold_ms = statistics.median(swr_refresh_runs) + out["swr_cold_ms"] = round(cold_ms, 1) + out["swr_cold_runs_ms"] = [round(v, 1) for v in swr_refresh_runs] + out["swr_cold_files_read"] = reread + out["swr_cold_files_reused"] = reused + + # warm hit: TTL still valid — measure in microseconds, tight loop + hits = [] + for _ in range(200): + t0 = time.perf_counter() + swr.get() + hits.append((time.perf_counter() - t0) * 1_000_000.0) + hit_us = statistics.median(hits) + out["swr_memory_hit_us"] = round(hit_us, 2) + out["swr_memory_hit_p99_us"] = round(sorted(hits)[int(len(hits) * 0.99)], 2) + + # incremental revalidation: touch one file, force expiry, re-measure + victim = sorted(root.glob("note-*.md"))[5] + victim.write_text(victim.read_text(encoding="utf-8") + "\n\n", encoding="utf-8") + swr.stamp = 0.0 + incr_runs = [] + for _ in range(3): + victim.write_text(victim.read_text(encoding="utf-8") + "\n", encoding="utf-8") + swr.stamp = 0.0 + _i, reread2, reused2 = swr.refresh() + incr_runs.append(_i) + incr_ms = statistics.median(incr_runs) + out["swr_incremental_refresh_ms"] = round(incr_ms, 2) + out["swr_incremental_files_read"] = reread2 + out["swr_incremental_files_reused"] = reused2 + + # state distribution sanity + states = {} + for row in swr.data: + states[row["status"]] = states.get(row["status"], 0) + 1 + out["state_distribution"] = states + + out["speedup_naive_vs_single"] = round(naive_cold / single_cold, 2) if single_cold else None + out["speedup_naive_vs_swr_cold"] = round(naive_cold / cold_ms, 2) if cold_ms else None + out["speedup_naive_vs_memory_hit"] = round((naive_cold * 1000.0) / hit_us, 0) if hit_us else None + out["speedup_single_vs_incremental"] = round(single_cold / incr_ms, 2) if incr_ms else None + + out["latency_projection"] = [projected_with_read_latency(root, ms) for ms in (5.0, 10.0, 20.0)] + + print(json.dumps(out, indent=2, ensure_ascii=False)) + + +if __name__ == "__main__": + main()