diff options
Diffstat (limited to 'tools')
| -rw-r--r-- | tools/test-surface-reasons.json | 63 | ||||
| -rw-r--r-- | tools/test-surface.md | 149 | ||||
| -rw-r--r-- | tools/test-surface.py | 293 |
3 files changed, 505 insertions, 0 deletions
diff --git a/tools/test-surface-reasons.json b/tools/test-surface-reasons.json new file mode 100644 index 0000000..3ac9585 --- /dev/null +++ b/tools/test-surface-reasons.json @@ -0,0 +1,63 @@ +{ + "config.TestHooks": "the `hooks` field is already gated; the type and its impl are not, so they compile into a release build that can never read them.", + "config.shared_workspace": "`Config::validate` calls it at config.rs:226; tests/kata.rs and tests/remote_agent.rs call it too and both need a fixture.", + "config.store_dir": "the content-addressed store layout is used at config.rs:313 and :355; tests/invariants.rs pins it and needs a fixture.", + "db.MIGRATIONS": "`db::migrate` iterates it at db/mod.rs:135; tests/db.rs asserts the list is ordered and complete.", + "db.ReleaseState": "a row type named by twenty sites inside db; tests/pipeline.rs names it while driving a real pipeline.", + "db.cas_accepted_release": "the compare-and-set on the accepted-release pointer; nothing in production performs that CAS today, but it is the primitive `accepted_release_for` is paired with.", + "db.claim": "production leases with `claim_batch`; `claim` is called only by tests, so the release build need not compile it.", + "db.set_setting": "a settings writer with no production caller; `setting`/`setting_i64` readers are used, the setter is not.", + "db.shutdown": "`Writer::shutdown` is never called by the server; tests use it to quiesce the writer thread.", + "db.snapshot_by_commit": "a snapshot lookup nothing in production performs.", + "db.touch": "census false positive: `touch` appears in tests/shims.rs only inside a string literal. Narrow on its merits, not for the test tier.", + "db.tx_for_tests": "already gated behind test-support \u2014 the pattern the rest of this table asks for.", + "db.unapproved_index_entries": "an invariant query nothing runs; it needs `pub(crate)` diff internals to be useful, so it is gated rather than relocated.", + "db.world_members": "a world-snapshot reader nothing calls; `put_world_snapshot` is the half production uses.", + "http.Attention": "census false positive: named in crash.rs only inside a string.", + "http.LogTail": "the SSE tail type; the live test that names it drives a real server.", + "http.Page": "the render model, named by twenty sites in http; tests/mod.rs asserts on it directly.", + "http.Panel": "a diff panel in the render model; tests/versions.rs asserts on its body.", + "http.cookie": "the auth cookie helper; the tests that use it build no fixture, so they move into the module and it narrows.", + "http.html": "census false positive: named in http.rs only inside a string.", + "http.login": "the login route handler; same \u2014 its tests are harness-free and move with it.", + "http.logout": "census false positive: named in http.rs only inside a string.", + "http.redirect": "census false positive: named in http.rs only inside a string.", + "http.route": "census false positive: named in http.rs only inside a string.", + "ops.STAGING_GRACE_SECS": "the grace period the staging sweep applies at ops.rs:286; tests/ops.rs pins the value it must be.", + "ops.build_success_rate": "computed inside the maintenance report at ops.rs:87; tests/ops.rs checks the arithmetic.", + "ops.sweep_staging": "called by the maintenance pass at ops.rs:286; tests/ops.rs exercises it directly.", + "pipeline.admissible": "the dispatch filter, called at dispatch.rs:86; tests/dispatch.rs pins which builds it admits.", + "pipeline.dispatch_once": "one tick of the dispatcher, called by the scheduler loop at dispatch.rs:60; tests/dispatch.rs drives single ticks.", + "pipeline.free_disk_mb": "the disk probe the dispatcher consults at dispatch.rs:106.", + "pipeline.index_world": "the world-index step, used by the pipeline at mod.rs:255 and steps.rs:92; tests/kata.rs checks what landed in the index.", + "pipeline.run_with": "the run entry point with an injected sandbox; production uses `run`, tests inject a fake.", + "review.BulkRefusal": "the bulk-refusal payload, built and matched across approve.rs; tests/approve.rs asserts on it.", + "review.LOW": "the risk floor, compared at risk.rs:94,189,195; tests/notices.rs pins where the floor bites.", + "review.render_and_store": "intake renders through `review::intake::record`; this wrapper has zero callers in src and 17 in tests. Gated, not relocated: it needs the module-private diff renderer.", + "sandbox.Exit": "the sandbox exit record, named across the backends; tests/failure_modes.rs asserts on it.", + "sandbox.K8sSandboxProvisioner": "the kata provisioner impl; tests/kata.rs drives it directly.", + "sandbox.KataBackend": "the kata backend; tests/kata.rs constructs it rather than going through `for_config`'s caller.", + "sandbox.LocalAgentProvisioner": "the local agent provisioner impl; tests/kata.rs drives it.", + "sandbox.LoopbackBackend": "the default backend; tests/failure_modes.rs constructs it to inject a fault.", + "sandbox.ProvisionRequest": "kata provisioning internals; the test that names them needs no fixture.", + "sandbox.Provisioner": "kata provisioning internals; same test.", + "sandbox.RemoteBackend": "the remote backend; tests/remote_agent.rs constructs it against a real agent.", + "sandbox.SandboxInfo": "the sandbox descriptor returned by the trait; tests/failure_modes.rs reads its fields.", + "sandbox.for_config": "kata backend constructor; same test.", + "sandbox.local_addr": "the agent's local address, read by the backend selection at mod.rs:120; tests/remote_agent.rs asserts on it.", + "sandbox.provision_request": "kata request builder; same test.", + "sandbox.reclaim": "kata reclaim path; the TTL test that names it needs no fixture.", + "sandbox.sandbox_cr": "kata container-record shape; same test.", + "sandbox.shared_for": "kata workspace helper; same test.", + "shims.called_with": "reads the shim's invocation log, which only tests inspect.", + "shims.invocations": "reads the shim invocation log; the shim writes it in production (mod.rs:112) but nothing in src reads it back.", + "shims.manifest": "the shim manifest, read by `run` at mod.rs:161; seven test files read it to assert what a build did.", + "shims.valid_db_arg": "the shim's `--db` argument validator; production calls it at mod.rs:510, tests check its verdicts.", + "time.unpin": "the clock escape hatch; `pin`/`unpin` exist so a test can freeze time. Its only in-module mention is a unit test.", + "time.virtual_sleep": "already gated behind test-support.", + "time.virtualize": "already gated behind test-support.", + "watch.StageBSlot": "the stage-B cache slot shape; tests/vcs.rs asserts on it while driving a real mirror.", + "watch.needs_stage_b": "the stage-B predicate, consulted by detect.rs:101.", + "watch.probe": "the upstream probe, called by detect.rs:95; tests/ops.rs and tests/vcs.rs both need a fixture.", + "watch.sync_mirror": "the mirror sync, called by detect.rs:40; tests/detect.rs drives a real sync." +}
\ No newline at end of file diff --git a/tools/test-surface.md b/tools/test-surface.md new file mode 100644 index 0000000..f632e80 --- /dev/null +++ b/tools/test-surface.md @@ -0,0 +1,149 @@ +# The test surface: every `pub` item that exists because a test names it + +Regenerate with `python3 tools/test-surface.py --write`. The reasons in the +`why` column live in `tools/test-surface-reasons.json` and are reviewed by +hand; everything else is derived from the source. + +## What counts + +The census (`tools/arch-census.py`) calls a `pub` item **dead** when no file +*outside its own top-level module* names it, and **test-only** when a file +under `tests/` does. That definition is coarse in two ways that matter here: + +- *Module is the top-level directory.* An item in `src/db/candidates.rs` used + only from `src/db/builds/mod.rs` counts as dead, because both are in `db`. + Many rows below are therefore not "used only by tests" — they are used only + inside their own module, and a test happens to be the only outside reader. + +- *Mentions are matched over raw source, including string literals.* Some + items are named by a test only inside a string. Nothing in the test tier + depends on them; they are census false positives. + +## The four dispositions + +| disposition | meaning | applies when | +|---|---|---| +| `gate` | add `#[cfg(feature = "test-support")]` | production never calls it; a test does | +| `move-test` | move the test into the module, then make the item private | the test that names it builds no fixture, so it is a unit test in the wrong file | +| `narrow` | `pub(crate)` or private | no test calls it at all (string-only mention) | +| `residue` | stays `pub`, documented, counted | production needs it *inside* its module **and** a fixture-bound integration test needs it from outside | + +### Why `residue` exists at all + +Rust has no test-conditional visibility. No attribute makes an item `pub` +under one feature and `pub(crate)` under another, and `pub use` cannot +re-export a `pub(crate)` item. An item that production needs inside its own +module *and* an integration test needs from outside cannot be narrowed +without breaking one or the other. + +The way to shrink that column is not a visibility change. It is to make the +integration tests stop reaching in — by moving them into the module, or by +exercising the behaviour through the module's real entry point. That is a +test-design change with a real cost per row, recorded here rather than +attempted blind. + +The `residue` count is ratcheted by `tests/architecture.rs`, so it can only +shrink. + + +## Gate behind `test-support` — 9 items + +| module | item | declared at | test files | why | +|---|---|---|---|---| +| `db` | `claim` | `src/db/builds/mod.rs:130` | `common/mod.rs`, `state_machine.rs`, `time.rs` | production leases with `claim_batch`; `claim` is called only by tests, so the release build need not compile it. | +| `db` | `set_setting` | `src/db/settings.rs:38` | `db.rs` | a settings writer with no production caller; `setting`/`setting_i64` readers are used, the setter is not. | +| `db` | `shutdown` | `src/db/mod.rs:244` | `common/mod.rs`, `crash.rs`, `dispatch.rs` | `Writer::shutdown` is never called by the server; tests use it to quiesce the writer thread. | +| `db` | `snapshot_by_commit` | `src/db/snapshots.rs:50` | `detect.rs` | a snapshot lookup nothing in production performs. | +| `db` | `unapproved_index_entries` | `src/db/invariants.rs:7` | `db.rs`, `detect.rs`, `notices.rs`, `shims.rs` | an invariant query nothing runs; it needs `pub(crate)` diff internals to be useful, so it is gated rather than relocated. | +| `db` | `world_members` | `src/db/world.rs:27` | `db.rs` | a world-snapshot reader nothing calls; `put_world_snapshot` is the half production uses. | +| `review` | `render_and_store` | `src/review/diff.rs:269` | `approve.rs`, `common/mod.rs`, `crash.rs`, `dispatch.rs` … | intake renders through `review::intake::record`; this wrapper has zero callers in src and 17 in tests. Gated, not relocated: it needs the module-private diff renderer. | +| `shims` | `called_with` | `src/shims/mod.rs:144` | `crash.rs`, `dispatch.rs`, `invariants.rs`, `kata.rs` … | reads the shim's invocation log, which only tests inspect. | +| `time` | `unpin` | `src/time.rs:47` | `time.rs` | the clock escape hatch; `pin`/`unpin` exist so a test can freeze time. Its only in-module mention is a unit test. | + +## Move the test into the module, then narrow — 9 items + +| module | item | declared at | test files | why | +|---|---|---|---|---| +| `http` | `cookie` | `src/http/mod.rs:36` | `common/mod.rs`, `http.rs` | the auth cookie helper; the tests that use it build no fixture, so they move into the module and it narrows. | +| `http` | `login` | `src/http/routes/mod.rs:45` | `common/mod.rs`, `http.rs` | the login route handler; same — its tests are harness-free and move with it. | +| `sandbox` | `ProvisionRequest` | `src/sandbox/kata.rs:19` | `kata.rs` | kata provisioning internals; the test that names them needs no fixture. | +| `sandbox` | `Provisioner` | `src/sandbox/kata.rs:28` | `kata.rs` | kata provisioning internals; same test. | +| `sandbox` | `for_config` | `src/sandbox/kata.rs:74` | `kata.rs` | kata backend constructor; same test. | +| `sandbox` | `provision_request` | `src/sandbox/kata.rs:202` | `kata.rs` | kata request builder; same test. | +| `sandbox` | `reclaim` | `src/sandbox/kata.rs:241` | `kata.rs` | kata reclaim path; the TTL test that names it needs no fixture. | +| `sandbox` | `sandbox_cr` | `src/sandbox/kata.rs:39` | `kata.rs` | kata container-record shape; same test. | +| `sandbox` | `shared_for` | `src/sandbox/kata.rs:177` | `kata.rs` | kata workspace helper; same test. | + +## Narrow — no test actually calls it — 6 items + +| module | item | declared at | test files | why | +|---|---|---|---|---| +| `db` | `touch` | `src/db/builds/steps.rs:153` | `shims.rs` | census false positive: `touch` appears in tests/shims.rs only inside a string literal. Narrow on its merits, not for the test tier. | +| `http` | `Attention` | `src/http/render.rs:182` | `crash.rs` | census false positive: named in crash.rs only inside a string. | +| `http` | `html` | `src/http/mod.rs:51` | `http.rs` | census false positive: named in http.rs only inside a string. | +| `http` | `logout` | `src/http/routes/mod.rs:36` | `http.rs` | census false positive: named in http.rs only inside a string. | +| `http` | `redirect` | `src/http/mod.rs:67` | `http.rs` | census false positive: named in http.rs only inside a string. | +| `http` | `route` | `src/http/routes/mod.rs:65` | `http.rs` | census false positive: named in http.rs only inside a string. | + +## Residue — `pub` because Rust has no test-conditional visibility — 34 items + +| module | item | declared at | test files | why | +|---|---|---|---|---| +| `config` | `TestHooks` | `src/config.rs:138` | `common/mod.rs`, `production_surface.rs` | the `hooks` field is already gated; the type and its impl are not, so they compile into a release build that can never read them. | +| `config` | `shared_workspace` | `src/config.rs:93` | `config.rs`, `kata.rs`, `remote_agent.rs` | `Config::validate` calls it at config.rs:226; tests/kata.rs and tests/remote_agent.rs call it too and both need a fixture. | +| `config` | `store_dir` | `src/config.rs:351` | `invariants.rs` | the content-addressed store layout is used at config.rs:313 and :355; tests/invariants.rs pins it and needs a fixture. | +| `db` | `MIGRATIONS` | `src/db/migrations.rs:326` | `db.rs` | `db::migrate` iterates it at db/mod.rs:135; tests/db.rs asserts the list is ordered and complete. | +| `db` | `ReleaseState` | `src/db/model/state.rs:78` | `pipeline.rs` | a row type named by twenty sites inside db; tests/pipeline.rs names it while driving a real pipeline. | +| `db` | `cas_accepted_release` | `src/db/pkgbases.rs:84` | `db.rs` | the compare-and-set on the accepted-release pointer; nothing in production performs that CAS today, but it is the primitive `accepted_release_for` is paired with. | +| `http` | `LogTail` | `src/http/sse.rs:11` | `live.rs` | the SSE tail type; the live test that names it drives a real server. | +| `http` | `Page` | `src/http/render.rs:4` | `common/mod.rs` | the render model, named by twenty sites in http; tests/mod.rs asserts on it directly. | +| `http` | `Panel` | `src/http/render.rs:142` | `versions.rs` | a diff panel in the render model; tests/versions.rs asserts on its body. | +| `ops` | `STAGING_GRACE_SECS` | `src/ops.rs:310` | `ops.rs` | the grace period the staging sweep applies at ops.rs:286; tests/ops.rs pins the value it must be. | +| `ops` | `build_success_rate` | `src/ops.rs:46` | `ops.rs` | computed inside the maintenance report at ops.rs:87; tests/ops.rs checks the arithmetic. | +| `ops` | `sweep_staging` | `src/ops.rs:332` | `ops.rs` | called by the maintenance pass at ops.rs:286; tests/ops.rs exercises it directly. | +| `pipeline` | `admissible` | `src/pipeline/dispatch.rs:100` | `dispatch.rs` | the dispatch filter, called at dispatch.rs:86; tests/dispatch.rs pins which builds it admits. | +| `pipeline` | `dispatch_once` | `src/pipeline/dispatch.rs:71` | `dispatch.rs` | one tick of the dispatcher, called by the scheduler loop at dispatch.rs:60; tests/dispatch.rs drives single ticks. | +| `pipeline` | `free_disk_mb` | `src/pipeline/dispatch.rs:113` | `dispatch.rs` | the disk probe the dispatcher consults at dispatch.rs:106. | +| `pipeline` | `index_world` | `src/pipeline/publish.rs:21` | `kata.rs` | the world-index step, used by the pipeline at mod.rs:255 and steps.rs:92; tests/kata.rs checks what landed in the index. | +| `pipeline` | `run_with` | `src/pipeline/mod.rs:189` | `failure_modes.rs`, `kata.rs`, `remote_agent.rs` | the run entry point with an injected sandbox; production uses `run`, tests inject a fake. | +| `review` | `BulkRefusal` | `src/review/approve.rs:155` | `approve.rs` | the bulk-refusal payload, built and matched across approve.rs; tests/approve.rs asserts on it. | +| `review` | `LOW` | `src/review/risk.rs:6` | `notices.rs` | the risk floor, compared at risk.rs:94,189,195; tests/notices.rs pins where the floor bites. | +| `sandbox` | `Exit` | `src/sandbox/mod.rs:43` | `failure_modes.rs` | the sandbox exit record, named across the backends; tests/failure_modes.rs asserts on it. | +| `sandbox` | `K8sSandboxProvisioner` | `src/sandbox/kata.rs:86` | `kata.rs` | the kata provisioner impl; tests/kata.rs drives it directly. | +| `sandbox` | `KataBackend` | `src/sandbox/kata.rs:167` | `kata.rs` | the kata backend; tests/kata.rs constructs it rather than going through `for_config`'s caller. | +| `sandbox` | `LocalAgentProvisioner` | `src/sandbox/kata.rs:124` | `kata.rs` | the local agent provisioner impl; tests/kata.rs drives it. | +| `sandbox` | `LoopbackBackend` | `src/sandbox/loopback.rs:10` | `failure_modes.rs` | the default backend; tests/failure_modes.rs constructs it to inject a fault. | +| `sandbox` | `RemoteBackend` | `src/sandbox/remote.rs:12` | `remote_agent.rs` | the remote backend; tests/remote_agent.rs constructs it against a real agent. | +| `sandbox` | `SandboxInfo` | `src/sandbox/mod.rs:70` | `failure_modes.rs` | the sandbox descriptor returned by the trait; tests/failure_modes.rs reads its fields. | +| `sandbox` | `local_addr` | `src/sandbox/kata.rs:245` | `remote_agent.rs` | the agent's local address, read by the backend selection at mod.rs:120; tests/remote_agent.rs asserts on it. | +| `shims` | `invocations` | `src/shims/mod.rs:133` | `shims.rs` | reads the shim invocation log; the shim writes it in production (mod.rs:112) but nothing in src reads it back. | +| `shims` | `manifest` | `src/shims/mod.rs:88` | `common/mod.rs`, `invariants.rs`, `pipeline.rs`, `production_surface.rs` … | the shim manifest, read by `run` at mod.rs:161; seven test files read it to assert what a build did. | +| `shims` | `valid_db_arg` | `src/shims/mod.rs:479` | `shims.rs` | the shim's `--db` argument validator; production calls it at mod.rs:510, tests check its verdicts. | +| `watch` | `StageBSlot` | `src/watch/upstream.rs:118` | `vcs.rs` | the stage-B cache slot shape; tests/vcs.rs asserts on it while driving a real mirror. | +| `watch` | `needs_stage_b` | `src/watch/upstream.rs:20` | `vcs.rs` | the stage-B predicate, consulted by detect.rs:101. | +| `watch` | `probe` | `src/watch/upstream.rs:25` | `ops.rs`, `vcs.rs` | the upstream probe, called by detect.rs:95; tests/ops.rs and tests/vcs.rs both need a fixture. | +| `watch` | `sync_mirror` | `src/watch/mirror.rs:17` | `detect.rs` | the mirror sync, called by detect.rs:40; tests/detect.rs drives a real sync. | + +## Already gated — 3 items + +| module | item | declared at | test files | why | +|---|---|---|---|---| +| `db` | `tx_for_tests` | `src/db/mod.rs:251` | `approve.rs`, `common/mod.rs`, `db.rs`, `invariants.rs` … | already gated behind test-support — the pattern the rest of this table asks for. | +| `time` | `virtual_sleep` | `src/time.rs:168` | `production_surface.rs` | already gated behind test-support. | +| `time` | `virtualize` | `src/time.rs:119` | `crash.rs`, `dispatch.rs`, `production_surface.rs` | already gated behind test-support. | + +## Totals + +| disposition | count | +|---|---| +| `gate` | 9 | +| `move-test` | 9 | +| `narrow` | 6 | +| `residue` | 34 | +| `already-gated` | 3 | +| **total** | **61** | + +Of these, 58 are ungated today. Gating the `gate` rows and narrowing the +`narrow` rows removes 15 items from the release build's public surface; the +`move-test` rows remove 9 more and take their tests home with them. + diff --git a/tools/test-surface.py b/tools/test-surface.py new file mode 100644 index 0000000..40385ad --- /dev/null +++ b/tools/test-surface.py @@ -0,0 +1,293 @@ +#!/usr/bin/env python3 +"""The test surface: every `pub` item that exists because a test names it. + +Reads the crate the way `tools/arch-census.py` does — a `pub` item is *dead* when +no file outside its own top-level module names it, and *test-only* when a file +under `tests/` does — and then asks two further questions of every test-only +item, because the census's answer is not the whole answer: + + 1. Does a test *call* it, or merely mention it inside a string literal? + The census matches over raw source, so a string counts. Those items are + census false positives: nothing in the test tier depends on them. + 2. Does production code inside the declaring module call it? If it does, the + item is not "test-only" in substance; it is module-internal, and a test + happens to be the only outside reader. + +Those two questions yield the four dispositions written to +`tools/test-surface.md`. Run with `--json` for the machine-readable form, whose +`residue` count `tests/architecture.rs` ratchets. + +Rust has no test-conditional visibility: no attribute makes an item `pub` under +one feature and `pub(crate)` under another, and `pub use` cannot re-export a +`pub(crate)` item. An item that production needs inside its own module *and* a +fixture-bound integration test needs from outside therefore cannot be narrowed +without breaking one or the other. Those rows are `residue`, and the only way to +shrink them is to change the tests, not the visibility. +""" +import argparse, collections, json, os, re, sys + +ROOT = os.path.dirname(os.path.abspath(__file__)) + "/.." +SRC = os.path.join(ROOT, "src") +TESTS = os.path.join(ROOT, "tests") +DOC = os.path.join(ROOT, "tools", "test-surface.md") + +PUB_RE = re.compile(r"^\s*pub\s+(?:fn|struct|enum|trait|const|static|type)\s+([A-Za-z0-9_]+)") +COMMENT = re.compile(r"^\s*(?://|//!|///)") +GATE = "test-support" +HARNESS = ("Env::new", "env_with_fixture", "Fixture", "tempdir", "Command::new", + "fs::", "shim_dir", "corpus_root") + +# Reasons that take argument to state; everything else is derived from the +# evidence the analysis already has. +REASONS = json.load(open(os.path.join(ROOT, "tools", "test-surface-reasons.json"))) + + +def rust_files(d): + out = [] + for base, _, files in os.walk(d): + for f in files: + if f.endswith(".rs"): + out.append(os.path.join(base, f)) + return sorted(out) + + +def module_of(path): + rel = os.path.relpath(path, SRC) + parts = rel.split(os.sep) + if parts[0] == "bin": + return os.path.join("bin", *parts[1:]).removesuffix(".rs") + if len(parts) > 1: + return parts[0] + return parts[0].removesuffix(".rs") + + +def strip_test_modules(path): + """Lines of `path` with `#[cfg(test)] mod ... {}` blocks removed.""" + lines = open(path).read().split("\n") + out, i = [], 0 + while i < len(lines): + if lines[i].strip() == "#[cfg(test)]": + j = i + 1 + while j < len(lines) and lines[j].strip().startswith("//"): + j += 1 + if j < len(lines) and re.match(r"\s*(?:pub(?:\(crate\))?\s+)?mod\s+\w+", lines[j]): + depth, started, k = 0, False, j + while k < len(lines): + depth += lines[k].count("{") - lines[k].count("}") + if "{" in lines[k]: + started = True + if started and depth <= 0: + break + k += 1 + i = k + 1 + continue + out.append(lines[i]) + i += 1 + return out + + +def gated_declarations(path): + """{name: (line, gated)} honouring cfg-gated enclosing blocks.""" + lines = open(path).read().split("\n") + depth, gated_open, pending = 0, [], False + out = {} + for i, line in enumerate(lines): + s = line.strip() + if s.startswith("#[") and GATE in s: + pending = True + if COMMENT.match(line): + continue + m = PUB_RE.match(line) + if m: + out.setdefault(m.group(1), []).append((i + 1, pending or bool(gated_open))) + opens, closes = line.count("{"), line.count("}") + if re.match(r"^\s*(?:pub(?:\(crate\))?\s+)?(?:mod|impl|trait|enum)\b", line) and pending: + gated_open.append(None if not opens else depth) + depth += opens - closes + while gated_open and gated_open[-1] is not None and depth <= gated_open[-1]: + gated_open.pop() + if not s.startswith("#"): + pending = False + return out + + +def integration_tests(path): + lines = open(path).read().split("\n") + starts = [i for i, l in enumerate(lines) if l.lstrip().startswith("#[test]")] + starts.append(len(lines)) + out = [] + for a, b in zip(starts, starts[1:]): + body = "\n".join(lines[a:b]) + m = re.search(r"fn (\w+)", body) + if m: + out.append((m.group(1), body)) + return out + + +def analyse(): + src = {p: open(p).read() for p in rust_files(SRC)} + tests = {p: open(p).read() for p in rust_files(TESTS)} + names = collections.defaultdict(list) + for path, text in src.items(): + for line in text.splitlines(): + if COMMENT.match(line): + continue + m = PUB_RE.match(line) + if m: + names[m.group(1)].append(path) + + rows = [] + for name, paths in sorted(names.items()): + declaring = {module_of(p) for p in paths} + if any(module_of(p) not in declaring and re.search(r"\b%s\b" % re.escape(name), t) + for p, t in src.items()): + continue + users = sorted(os.path.relpath(f, TESTS) for f, t in tests.items() + if re.search(r"\b%s\b" % re.escape(name), t)) + if not users: + continue + + occ = [(os.path.relpath(p, ROOT), ln, g) + for p in paths for (ln, g) in gated_declarations(p).get(name, [])] + gated = any(g for _, _, g in occ) + + # A mention inside a string literal is not a call. + string_only = all( + not re.search(r"\b%s\b" % re.escape(name), + re.sub(r'"(?:[^"\\]|\\.)*"', '""', t)) + for t in tests.values()) + + sites = [] + if not string_only: + for f in users: + for (tname, body) in integration_tests(os.path.join(TESTS, f)): + if re.search(r"\b%s\b" % re.escape(name), body): + sites.append((f, tname, any(k in body for k in HARNESS))) + + internal = [] + mod = module_of(paths[0]) + base = os.path.join(SRC, mod) + files = rust_files(base) if os.path.isdir(base) else [os.path.join(SRC, mod + ".rs")] + for p in files: + for i, line in enumerate(strip_test_modules(p), 1): + if not re.search(r"\b%s\b" % re.escape(name), line): + continue + s = line.strip() + if s.startswith("//") or s.startswith("///"): + continue + if re.match(r"^\s*pub\s+(?:fn|struct|enum|trait|const|static|type)\s+%s\b" + % re.escape(name), line): + continue + if re.match(r"^\s*(?:pub(?:\(crate\))?\s+)?use\s+", line): + continue + internal.append("%s:%d" % (os.path.relpath(p, ROOT), i)) + + if gated: + disp = "already-gated" + elif string_only: + disp = "narrow" + elif sites and all(not h for _, _, h in sites): + disp = "move-test" + elif not internal: + disp = "gate" + else: + disp = "residue" + + rows.append(dict( + module=mod, name=name, + where=("%s:%d" % (occ[0][0], occ[0][1])) if occ else "?", + gated=gated, string_only=string_only, tests=users, + internal=internal, sites=[list(s) for s in sites], + disp=disp, + reason=(REASONS.get("%s.%s" % (mod, name)) + or ("production uses it at %s; the test that names it needs a fixture." + % internal[0] if internal + else "nothing in src calls it; a test does.")), + hand_written=("%s.%s" % (mod, name)) in REASONS, + )) + return rows + + +def render(rows): + order = ["gate", "move-test", "narrow", "residue", "already-gated"] + title = {"gate": "Gate behind `test-support`", + "move-test": "Move the test into the module, then narrow", + "narrow": "Narrow — no test actually calls it", + "residue": "Residue — `pub` because Rust has no test-conditional visibility", + "already-gated": "Already gated"} + out = [open(DOC).read().split("## gate-marker")[0]] if False else [] + L = [] + A = L.append + A("# The test surface: every `pub` item that exists because a test names it\n") + A("Regenerate with `python3 tools/test-surface.py --write`. The reasons in the\n" + "`why` column live in `tools/test-surface-reasons.json` and are reviewed by\n" + "hand; everything else is derived from the source.\n") + A("## What counts\n") + A("The census (`tools/arch-census.py`) calls a `pub` item **dead** when no file\n" + "*outside its own top-level module* names it, and **test-only** when a file\n" + "under `tests/` does. That definition is coarse in two ways that matter here:\n") + A("- *Module is the top-level directory.* An item in `src/db/candidates.rs` used\n" + " only from `src/db/builds/mod.rs` counts as dead, because both are in `db`.\n" + " Many rows below are therefore not \"used only by tests\" — they are used only\n" + " inside their own module, and a test happens to be the only outside reader.\n") + A("- *Mentions are matched over raw source, including string literals.* Some\n" + " items are named by a test only inside a string. Nothing in the test tier\n" + " depends on them; they are census false positives.\n") + A("## The four dispositions\n") + A("| disposition | meaning | applies when |\n|---|---|---|") + A("| `gate` | add `#[cfg(feature = \"test-support\")]` | production never calls it; a test does |") + A("| `move-test` | move the test into the module, then make the item private | the test that names it builds no fixture, so it is a unit test in the wrong file |") + A("| `narrow` | `pub(crate)` or private | no test calls it at all (string-only mention) |") + A("| `residue` | stays `pub`, documented, counted | production needs it *inside* its module **and** a fixture-bound integration test needs it from outside |\n") + A("### Why `residue` exists at all\n") + A("Rust has no test-conditional visibility. No attribute makes an item `pub`\n" + "under one feature and `pub(crate)` under another, and `pub use` cannot\n" + "re-export a `pub(crate)` item. An item that production needs inside its own\n" + "module *and* an integration test needs from outside cannot be narrowed\n" + "without breaking one or the other.\n") + A("The way to shrink that column is not a visibility change. It is to make the\n" + "integration tests stop reaching in — by moving them into the module, or by\n" + "exercising the behaviour through the module's real entry point. That is a\n" + "test-design change with a real cost per row, recorded here rather than\n" + "attempted blind.\n") + A("The `residue` count is ratcheted by `tests/architecture.rs`, so it can only\nshrink.\n") + tot = collections.Counter(r["disp"] for r in rows) + for d in order: + sel = sorted([r for r in rows if r["disp"] == d], key=lambda r: (r["module"], r["name"])) + if not sel: + continue + A("\n## %s — %d items\n" % (title[d], len(sel))) + A("| module | item | declared at | test files | why |\n|---|---|---|---|---|") + for r in sel: + A("| `%s` | `%s` | `%s` | %s | %s |" % ( + r["module"], r["name"], r["where"], + ", ".join("`%s`" % t for t in r["tests"][:4]) + (" …" if len(r["tests"]) > 4 else ""), + r["reason"].replace("|", "\\|"))) + A("\n## Totals\n\n| disposition | count |\n|---|---|") + for d in order: + if tot[d]: + A("| `%s` | %d |" % (d, tot[d])) + A("| **total** | **%d** |\n" % len(rows)) + A("Of these, %d are ungated today. Gating the `gate` rows and narrowing the\n" + "`narrow` rows removes %d items from the release build's public surface; the\n" + "`move-test` rows remove %d more and take their tests home with them.\n" + % (sum(1 for r in rows if not r["gated"]), tot["gate"] + tot["narrow"], tot["move-test"])) + return "\n".join(L) + "\n" + + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--json", action="store_true") + ap.add_argument("--write", action="store_true") + a = ap.parse_args() + rows = analyse() + if a.json: + counts = collections.Counter(r["disp"] for r in rows) + counts["gate_pending"] = sum(1 for r in rows if r["disp"] == "gate" and not r["gated"]) + print(json.dumps({"rows": rows, "counts": counts}, indent=1)) + elif a.write: + open(DOC, "w").write(render(rows)) + print("wrote", os.path.relpath(DOC, ROOT)) + else: + sys.stderr.write("nothing to do; use --write or --json\n") + sys.exit(2) |
