mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-03 02:08:18 +00:00
feat(scan): an unwritable tree keeps a scan's learnings under the runs directory (item 5b)
The decision of the maintainer on the ninth session's menu, answer 9 (.kiro/handover.md,
untracked, 1340-1343 as it stood on 2026-11-27; the option as offered, 1451-1452):
> 9. The ledger in the image. Answer: "Decide the key now": a digest of the tree's files
> (the `fingerprint` of the `provenance` stage is no digest), one ledger per digest under
> the runs directory; a design note is shown to the maintainer before any code.
The design note (/tmp/opencode/s10_c10_design_note.md, 299 lines) was reviewed in five
rounds before it was shown, and shown to the maintainer whole on 2026-11-27 with its three
questions. The maintainer's answers came on 2026-11-28, through the question tool, each the
recommended option as offered: "Stand as written (Recommended)" on the note's rule of reading
and writing (its section 3.3), "With the runs, by last use (Recommended)" on how long a ledger
stays (section 3.5), and "Build it now (Recommended)". The dated note on task 3.1 of
.kiro/specs/contributor-scan/tasks.md (lines 459-502) carries the rule as approved.
The fault: the image mounts the target read-only, so the ledger a scan writes into the tree
(<target>/.openultrasast/calibration/false_positive_learnings.json) cannot be written there,
the scan records ledger_not_written, and the next scan in the image starts without the
learnings of the one before.
What changed
- src/openultrasast/tree_digest.py: tree_digest(target, runs_directory) (line 48), a sha256
over one entry per file in path order (the length of the path, a colon, the path, a tab,
the sha256 of the bytes), after a version line. Left out: links, the directories a scan
ignores (IGNORED_DIRS, so that the tree's ledger does not change its own key) and the runs
directory, whichever way it is reached (by device and inode). A file that cannot be read
and a directory that cannot be listed are named "unreadable"; a directory that can be
listed but not searched raises, as the scan's own reading of the tree does.
- src/openultrasast/digest_ledger.py: the ledger of a digest, calibration/<digest>.json under
the runs directory, in the JSON of the tree's ledger. read_digest_ledger (line 47) reads it
and marks it as used; settle_digest_ledger (line 65) applies the rule.
The tree took the write: the ledger is removed. The tree refused: the ledger is written
with its own entries and this scan's new ones, never one whose finding id the tree's
ledger has, only when that differs from its content, and removed when that would leave it
empty. No write: a ledger whose every entry the tree's ledger also has is removed. One that
could not be read (a file that is not a ledger, whatever its top level or its depth) is
taken for empty and goes, unless the tree refused and this scan wrote it. It is written
through a temporary file of the writer's own and a rename (line 112).
- src/openultrasast/cli.py: the stage tree_digest, before any stage reads the tree
(cli.py:603-605); _read_ledgers (cli.py:1085-1099), the tree's ledger and then the
digest's, the tree's entry winning by finding id; _persist_calibration_feedback
(cli.py:1101-1136), which writes the tree's ledger when its content would differ from what
it held, also when only the digest's entries are new to it; the manifest's ledger block
(cli.py:731-735); a notice when the digest's ledger could not be written or removed
(cli.py:755).
- src/openultrasast/run.py: prune_expired_ledgers (run.py:112), called by prune_scan_runs
(run.py:71-99). Under calibration/ of the same two locations as the runs, a ledger, or the
temporary file it was written through, last used OPENULTRASAST_RUNS_RETENTION_DAYS days
ago is removed; 0 keeps all. Files called something else, links and directories stay. A
removal that fails is said once and costs the scan nothing.
- src/openultrasast/reports.py: write_manifest takes ledger (reports.py:212, 254-255). The
ledger_not_written sentence names the digest's ledger when it holds the learnings
(reports.py:461-467, chosen at 479-483).
- README.md, docs/examples.md, docs/architecture.md and
.agents/skills/openultrasast-scan/SKILL.md say where the learnings of a read-only tree go,
and what removes them.
Two departures from recorded decisions, both put to the maintainer in the note and accepted
with it:
- The tree's ledger is written when a scan learns nothing new, because the digest's entries
are new to it. The decision of 2026-11-24 says it "is written only when a scan learns
something" (spec.json:68).
- A ledger of a digest is removed when it expires, and its time is changed when a scan reads
it. The decision of 2026-11-24 says "the scan's own run and anything not named like a run
are never touched" (spec.json:73), and dates a run by its id, where a ledger is dated by
its use.
Measured
- The built function gives the note's prototype's digest for the four-file subject
(915506a8...) and for libpng's copy (1dcd664f...): s10_c10_port.out.
- In the image, on the final code. A probe image of openultrasast:dev (3f959b31f2f2) with
the tree's package copied over it, built at 09:06:36Z and holding the tree's 297 .py files
(s10_c10_image_probe/03_probe_sources.out, s10_c10_sources_still_equal4.out). Standard
mode, no key, network none. The four C files of contrib/examples of libpng and their
README, copied fresh and mounted read-only at /target; a scratch runs directory mounted at
/reports with the wrapper's OPENULTRASAST_RUNS_DIR=/reports (s10_c10_image_probe.sh,
stamps 09:06:36Z to 09:09:14Z, 2026-11-28).
- The first scan learns four entries and keeps them in /reports/calibration/<digest>.json:
calibrations_applied=0, project_score 26, the manifest's ledger {digest_ledger: written,
learnings_read: {digest: 0, tree: 0}} (10_, 11_). The report names the file.
- The second scan of the same bytes reads them: calibrations_applied=2 on two files,
project_score 59, penalty_total 32.0, learnings_read 4 from the digest's ledger,
digest_ledger "left as it was" (20_, 21_). The file's time is that of the second scan's
read, 09:07:19Z (22_).
- The digest the scan took in the image equals the one taken on the host for the same
files (s10_c10_image_digest_host4.out). The target is unchanged
(s10_c10_image_target_same4.out).
- Three earlier runs of this probe and of the native run below, each on the code as it
stood before a later correction of the same rule (the value for a ledger that could not
be read; a ledger whose top level is not an object; one nested too deep), gave the same
numbers. Their stamps: 08:12:50Z to 08:17:31Z, 08:23:38Z to 08:27:42Z and 08:50:15Z to
08:54:17Z. They are kept as s10_c10_image_probe_run1, _run2, s10_c10_native_run1,
_run2 and _run3; of the third image run s10_c10_image_probe_run3.out and the host,
target and sources checks numbered 3 remain, since s10_c10_image_probe_run3 is empty.
Its files were read by the reviewer in round two.
- The shipped image, the control, on the same files: calibrations_applied=0 and
project_score 26 on both scans, no ledger block and no ledger (30_ to 42_).
- Natively, on a fresh copy of the same five files, the network off (s10_c10_native.sh,
09:09:14Z to 09:10:38Z): the first scan writes the tree's ledger (calibrations_applied=0,
project_score 26, digest_ledger none), the second reads it (calibrations_applied=2,
project_score 59, learnings_read 4 from the tree's ledger), and no ledger of a digest is
made (s10_c10_native/10_ to 22_).
- The probe left no container (2 before, 2 after: 00_, 91_) and its image is removed (90_,
92_).
Tests
- tests/test_tree_digest.py (7) and tests/test_digest_ledger.py (11, one over nine contents
a file may hold); seven tests in tests/test_scan_output_location.py, six through the scan
(three over two cases) and one on _read_ledgers; six in tests/test_run_pruning.py; one
sentence in tests/test_reports.py. The scan test of a refused write selects its run by
name now, since the runs directory holds calibration/ as well.
- RED on an archive of e231b78 with the final test files: the two unit files do not import
(s10_c10_red14.out); the scan, pruning and report files give 15 failed, 101 passed
(s10_c10_red13.out; the tree's tree_digest.py and digest_ledger.py were copied into that
archive, since the test file imports both, and cli.py, run.py and reports.py were HEAD's).
On the tree before each fix: the test of a ledger that is not a JSON object failed
(s10_c10_red8.out), and so did the content nested too deep and its scan test
(s10_c10_red12.out).
- GREEN on the final tree: 134 passed over the five files (s10_c10_green9.out); 873 passed
over the 60 files of the scan path (s10_c10_wide4_full.out; the list is
s10_c10_testfiles.txt); the docs and skills tests, with the strict site build, 11 passed
(s10_c10_docs_tests4.out; no page changed after it).
- Gates on the final tree: ten zeros (s10_c10e_exits.txt), the three gate outputs equal to
the baseline.
- Review: three rounds against e231b78, by one reviewer subagent, read-only; no
docker and no wrapper run, the probes read from their files. Round one blocked
on one finding and measured it end to end on a scratch tree: a ledger of a
digest whose top level is not a JSON object raised AttributeError in the tree's
loader and stopped the scan (exit 1), against the note's "a cache must not stop
a scan". Round two approved with remarks, which the code and the tests took:
RecursionError joined the tuple (digest_ledger.py:57), with a ninth content in
the unit test and a scan test of a ledger that is not a ledger, red before the
fix (s10_c10_red12.out). Round three approved the code, the tests and the dated
note, and blocked on one sentence of this message, which named
s10_c10_image_probe_run3 as kept: that directory is empty. On the final tree the
reviewer measured the scan past a digest's ledger nested 5000 deep (exit 0,
"unreadable", the file removed) and passed 30000 contents through
read_digest_ledger, with none let through; it re-ran the five files (134
passed), the docs and skills files with two scan files outside the sixty (20
passed), ruff, mypy (297 files) and the comparison of the three gate outputs
with the baseline, the gates themselves not run; it recomputed the three
digests, matched the tree's 297 .py files to the fourth probe image's list, and
read the fourth image and native runs. The third image run's files were read in
round two, before they were lost. The sentence was reworded as the reviewer
wrote it.
By reading, not measured
- A pre-push run does not go through _run_scan, and src/openultrasast/push names no ledger:
nothing changes there.
- ousast benchmark and the MCP server call _run_scan and get the rule as a scan does.
- mark_all of the hunt tooling lists the children of a runs root it is given; it has no
caller under src.
Found and not fixed, for the maintainer
- The note says the digest stage's seconds are in the manifest. No stage's are: a stage's
time is in trace/events.jsonl (stage_start and stage_end), and so is this one's. The pages
and the dated note do not repeat the sentence.
- The report's sentence (reports.py:461-467) says this scan's learnings are kept in the
ledger of the digest whenever that file holds some of them (cli.py:1131-1133). A new
learning whose finding id the tree's ledger already holds is left out by the rule; the
tree's version stands, and the new evidence text is in the run directory alone. The
sentence is the note's as approved.
- The tree's own ledger stops the scan when its top level is not a JSON object, or when it
is nested too deep (calibration.py:157-159, read at cli.py:610 outside any stage). That
is older than this commit; the ledger of a digest does not.
- read_digest_ledger raises when calibration/ cannot be searched, as the tree's ledger does
when .openultrasast/calibration cannot (digest_ledger.py:53).
- By reading: a tree whose runs directory is the target itself gets another digest at every
scan, since its run directory is made inside the target before the stage. Such a tree can
be written, so its own ledger takes the learnings and no ledger of a digest is made.
- docs/architecture.md draws no provenance stage, which cli.py runs between
entry_point_mapping and rank.
- The wrapper builds its image only when the image is missing: until a rebuild, a scan
through it runs the shipped code, which has none of this.
- The notice of a removed ledger names the runs directory as the scan sees it (/reports in
the image), not the host's path.
Not checked
- the whole test suite; Windows; ops/shell/ousast.ps1 (not read for this commit); two scans
of one tree at once; the wrapper and the compose route (the probe used docker run with the
wrapper's mount and override); a removal that fails on a real cache; Docker Desktop, where
a directory mounted twice may not keep one inode.
This commit is contained in:
@@ -81,7 +81,10 @@ Each entry in `manifest.json` `degradations` is `{"stage": ..., "reason": ...}`.
|
||||
- `ledger_not_written` (stage `record_calibration`): the scan rejected or held a finding and could not write the
|
||||
false-positive ledger into the analysed tree, as on a read-only mount. Recorded whenever such a scan has a
|
||||
learning the tree's ledger does not already hold; the learnings are in this run's
|
||||
`calibration/false_positive_learnings.json`, and the next scan starts without them.
|
||||
`calibration/false_positive_learnings.json`. They are also kept in the ledger of the tree's digest,
|
||||
`<runs_dir>/calibration/<digest>.json`, which the next scan of the very same bytes reads: the report's sentence
|
||||
names that file when it holds them (`digest_ledger` is `written` or `left as it was` in the manifest's `ledger`
|
||||
block), and says the next scan starts without them when it could not be written either.
|
||||
- coverage facts from the graph, rendered in `report.md` under "What could not be analysed":
|
||||
`cpg_empty`, `cpg_build_failed`, `cpg_sharded`, `files_unparsed`, `query_failed`,
|
||||
`query_budget_reserved`, `query_too_expensive`, `budget_exhausted`, `regions_truncated`,
|
||||
@@ -115,7 +118,8 @@ above, and that is what `--fail-on verified` counts. There is no configurable re
|
||||
|
||||
Under `~/.cache/openultrasast/runs/<scan-id>/`:
|
||||
|
||||
- `report.md`, `report.sarif` (SARIF 2.1.0 for code hosts and IDEs), `manifest.json` (stages, degradations, model payload)
|
||||
- `report.md`, `report.sarif` (SARIF 2.1.0 for code hosts and IDEs), `manifest.json` (stages, degradations, model
|
||||
payload, the `ledger` block: the tree's digest and what became of the digest's ledger)
|
||||
- `findings.json`, `verification.json`, `score.json`, `shadow_findings.json` (rules shipped as `shadow`)
|
||||
- `harness.json`: the resolved harness configuration the run used
|
||||
- standard: `fusion.json`, `complexity_map.json`, `overlay.json`; deep: `verdicts.json`
|
||||
@@ -124,7 +128,9 @@ Under `~/.cache/openultrasast/runs/<scan-id>/`:
|
||||
The only write a scan makes into the scanned tree is the ledger
|
||||
`<target>/.openultrasast/calibration/false_positive_learnings.json`: a scan that rejects or holds a finding
|
||||
writes it only when that file's content would change; on a read-only tree the scan records `ledger_not_written`
|
||||
instead and keeps the learnings in this run directory's `calibration/false_positive_learnings.json`.
|
||||
instead and keeps the learnings in this run directory's `calibration/false_positive_learnings.json` and in the
|
||||
ledger of the tree's digest, `<runs_dir>/calibration/<digest>.json`, which the next scan of the very same bytes
|
||||
reads; the first scan that can write the tree carries its entries into the tree's ledger and removes it.
|
||||
|
||||
## Changed code only
|
||||
|
||||
|
||||
@@ -456,6 +456,50 @@
|
||||
`s8_d_standard_nokey.out`, `s8_d_native_standard.out`, the run directories
|
||||
`s8_build/reports/runs/20261126T125414Z-facce3bb` and `s8_native_runs/20261126T125839Z-ec9e1a0e`; the
|
||||
ninth session's readings `s9_c7_*.out`.
|
||||
- _The ledger of a tree that cannot be written, 2026-11-28 (tenth session), by the maintainer's decision of
|
||||
2026-11-27 on the ninth session's menu (item 5b, answer 9, "Decide the key now": "a digest of the tree's files
|
||||
(the `fingerprint` of the `provenance` stage is no digest), one ledger per digest under the runs directory; a
|
||||
design note is shown to the maintainer before any code") and by the maintainer's three answers of 2026-11-28 to
|
||||
that note, given through the question tool: "Stand as written (Recommended)" on its rule of reading and writing
|
||||
(the note's section 3.3), "With the runs, by last use (Recommended)" on how long a ledger stays (section 3.5),
|
||||
and "Build it now (Recommended)". The rule as it stands: a scan reads the tree's ledger and then the ledger of
|
||||
the tree's digest, `<runs_dir>/calibration/<digest>.json`, the tree's entry winning by finding id; the first
|
||||
scan that can write the tree's ledger carries the digest's entries into it and removes the digest's ledger,
|
||||
whether or not that scan learns something new, which departs from the decision of 2026-11-24 that the tree's
|
||||
ledger "is written only when a scan learns something" (`spec.json:68`); an expired ledger of a digest is
|
||||
removed by the step that removes old runs, in the same two locations, dated by its last use, which changes
|
||||
the decision of 2026-11-24 in three points (`spec.json:73`: anything under the runs directory not named like a
|
||||
run is never touched; a run is dated by its id)._
|
||||
Evidence of the tenth session. The digest (`src/openultrasast/tree_digest.py`) is a sha256 over one entry per
|
||||
file in path order (the length of the path, a colon, the path, a tab, the sha256 of the bytes), over every
|
||||
regular file under the target but links, the directories a scan ignores and the runs directory; a file that
|
||||
cannot be read and a directory that cannot be listed are named `unreadable`. The built function gives the
|
||||
digest of the design note's prototype for the four-file subject and for libpng (`s10_c10_port.out`), and the
|
||||
digest the scan took in the image equals the one taken on the host for the same files
|
||||
(`s10_c10_image_digest_host4.out`). The rule is `src/openultrasast/digest_ledger.py`, read in `_read_ledgers`
|
||||
and settled in `_persist_calibration_feedback` (`cli.py`); the removal is `prune_expired_ledgers`
|
||||
(`run.py`), called by `prune_scan_runs`. The manifest gains a `ledger` block: `tree_digest`,
|
||||
`learnings_read` from the tree's ledger and from the digest's, and `digest_ledger`, what became of the
|
||||
digest's ledger in the scan (none, unreadable, written, left as it was, removed, failed). The report's
|
||||
`ledger_not_written` sentence names the digest's ledger when it holds the learnings; a `notice:` line when
|
||||
an expired ledger is removed or cannot be. Tests first: `tests/test_tree_digest.py` (7),
|
||||
`tests/test_digest_ledger.py` (11, one over nine contents a file may hold), seven tests in
|
||||
`tests/test_scan_output_location.py` (six through the scan, three of them over two cases; one on
|
||||
`_read_ledgers`), six in `tests/test_run_pruning.py`, one sentence in `tests/test_reports.py`; RED 15 failed
|
||||
on an archive of e231b78, GREEN 134 passed over the five files and 873 over the 60 files of the scan path.
|
||||
Measured in the image on the build (a probe image of `openultrasast:dev` with the tree's package), standard
|
||||
mode, no key, the four C files of `contrib/examples` of libpng mounted read-only: the first scan learns four
|
||||
entries and keeps them in `/reports/calibration/<digest>.json` (`calibrations_applied=0`, `project_score` 26);
|
||||
the second scan of the same bytes reads them (`learnings_read` 4 from the digest's ledger,
|
||||
`calibrations_applied=2` on two files, `project_score` 59, `penalty_total` 32.0). The shipped image
|
||||
`3f959b31f2f2`, the control, gives 0 and 26 on both scans, with no `ledger` block and no ledger. Natively, on
|
||||
a fresh copy of the same five files, the network off: the first scan writes the tree's ledger
|
||||
(`calibrations_applied=0`, `project_score` 26, `digest_ledger` none), the second reads it (`learnings_read` 4
|
||||
from the tree's ledger, `calibrations_applied=2`, `project_score` 59), and no ledger of a digest is made: the
|
||||
native path is as before. Evidence, the tenth session's scratch under `/tmp/opencode`, not kept:
|
||||
`s10_c10_design_note.md`, `s10_c10_digest.py`, `s10_c10_probe.sh`, `s10_c10_digest_probe/`,
|
||||
`s10_c10_image_probe/`, `s10_c10_native/`, and the test and gate outputs `s10_c10_red12.out`,
|
||||
`s10_c10_red13.out`, `s10_c10_green9.out`, `s10_c10_wide4_full.out`, `s10_c10e_exits.txt`.
|
||||
|
||||
- [x] 3.2 Build and verify the image
|
||||
- `docker compose build`, then run a real scan through it and through the shell wrapper. The Dockerfile and
|
||||
|
||||
@@ -195,7 +195,8 @@ there older than 30 days are removed, and `ousast` prints one `notice:` line whe
|
||||
`OPENULTRASAST_RUNS_RETENTION_DAYS` sets the number of days (`0` keeps every run), and nothing is
|
||||
ever removed from a location chosen with `OPENULTRASAST_RUNS_DIR`, except through the shell wrapper:
|
||||
it mounts `~/.cache/openultrasast/runs` at `/reports` in the image, and a scan through it removes the
|
||||
expired runs there as well. A scan does not read the files
|
||||
expired runs there as well; the ledgers of tree digests (`calibration/` under the same directories)
|
||||
go by the same number of days, dated by their last use. A scan does not read the files
|
||||
under its runs directory when that directory lies inside the scanned path; when this leaves source
|
||||
files out of the scan, `ousast` prints one `notice:` line naming the directory and how many.
|
||||
|
||||
@@ -206,8 +207,13 @@ files out of the scan, `ousast` prints one `notice:` line naming the directory a
|
||||
|
||||
A scan that rejects or holds a finding writes one file into the scanned tree,
|
||||
`<target>/.openultrasast/calibration/false_positive_learnings.json`, and only when that file's
|
||||
content would change; on a read-only tree the scan records `ledger_not_written` instead and keeps
|
||||
the learnings in the run directory.
|
||||
content would change. On a read-only tree the scan records `ledger_not_written` instead and keeps
|
||||
the learnings in the ledger of the tree's digest, `<runs_dir>/calibration/<digest>.json`, where the
|
||||
digest is a sha256 of every file's name and bytes under the target. Only a scan of the very same
|
||||
bytes reads it; the first scan that can write the tree carries its entries into the tree's ledger
|
||||
and removes it. The `ledger` block of `manifest.json` names the digest, how many learnings came
|
||||
from each ledger, and what became of the digest's ledger. A digest's ledger is removed like a run
|
||||
once its last use is `OPENULTRASAST_RUNS_RETENTION_DAYS` days past.
|
||||
|
||||
`ousast pre-push` (experimental) analyses the commits a push would publish against their base.
|
||||
First, the quick rules run on the changed lines. Then the engine compares head with base, and only
|
||||
|
||||
@@ -35,6 +35,10 @@ policy_load ─▶ ruleset_load ─▶ policy_check (fail loud on an
|
||||
─▶ report.md, report.sarif, manifest.json
|
||||
```
|
||||
|
||||
Before `policy_load`, the `tree_digest` stage takes a sha256 of the tree's files: the key of a
|
||||
ledger under the runs directory, for a tree the scan cannot write into ("Scoped calibration",
|
||||
point 3).
|
||||
|
||||
**The model layer** (`model/`, `cpg/`) is the core of `standard`. It builds one code property
|
||||
graph (CPG: a graph of the program's syntax, control flow and data flow) per scan with Joern.
|
||||
It runs `joern-parse`, then batched `joern --script` queries from `cpg/queries/*.sc`. Each
|
||||
@@ -146,6 +150,12 @@ next scan ─▶ rank ─▶ calibrate (demote rejected scopes) ─▶ findings
|
||||
the ledger, de-duplicated by finding ID.
|
||||
2. `calibrate` runs after `rank`. It demotes the priority of every scope that produced a
|
||||
rejection and writes `applied_calibrations.json`.
|
||||
3. `tree_digest` runs on every scan, before `preprocess`: a sha256 of every file's name and bytes
|
||||
under the target. It is the key of a second ledger under the runs directory,
|
||||
`<runs_dir>/calibration/<digest>.json`, in which `record_calibration` keeps what it learned when
|
||||
the tree refused the write, as the image's read-only mount does. Only a scan of the very same
|
||||
bytes reads it; the first scan that can write the tree carries its entries into the tree's ledger
|
||||
and removes it (`src/openultrasast/digest_ledger.py`, `tests/test_digest_ledger.py`).
|
||||
|
||||
Demotion is scoped and reversible (`tests/test_pipeline_calibration.py`).
|
||||
|
||||
|
||||
+6
-3
@@ -10,7 +10,8 @@ are removed, and `ousast` prints one `notice:` line when it removes any;
|
||||
`OPENULTRASAST_RUNS_RETENTION_DAYS` sets the number of days (`0` keeps every run), and nothing is
|
||||
ever removed from a location chosen with `OPENULTRASAST_RUNS_DIR`, except through the shell wrapper:
|
||||
it mounts `~/.cache/openultrasast/runs` at `/reports` in the image, and a scan through it removes the
|
||||
expired runs there as well. A scan does not read the files
|
||||
expired runs there as well; the ledgers of tree digests (`calibration/` under the same directories)
|
||||
go by the same number of days, dated by their last use. A scan does not read the files
|
||||
under its runs directory when that directory lies inside the scanned path; when this leaves source
|
||||
files out of the scan, `ousast` prints one `notice:` line naming the directory and how many.
|
||||
`ousast benchmark` writes its run to the same directory, as `<runs_dir>/<benchmark-run-id>/` beside
|
||||
@@ -20,8 +21,10 @@ scan run.
|
||||
A scan that rejects or holds a finding writes one file into the scanned tree, and only when that
|
||||
file's content would change:
|
||||
`<target>/.openultrasast/calibration/false_positive_learnings.json` (`.openultrasast/` is
|
||||
gitignored in this repository, not in one of your own); on a read-only tree the scan records
|
||||
`ledger_not_written` instead and keeps the learnings in the run directory.
|
||||
gitignored in this repository, not in one of your own). On a read-only tree the scan records
|
||||
`ledger_not_written` instead and keeps the learnings in the ledger of the tree's digest,
|
||||
`<runs_dir>/calibration/<digest>.json`, read by the next scan of the very same bytes (the README says
|
||||
the same under "Scan modes").
|
||||
|
||||
## 1. Quick scan a local repo (deterministic, no keys)
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ from .calibration import (
|
||||
)
|
||||
from .complexity import map as complexity_map
|
||||
from .config import ModelLayerConfig, ObligationsConfig, ResolvedConfig, RetiredConfigError, load_config, load_dotenv
|
||||
from .digest_ledger import HOLDS_LEARNINGS, DigestLedger, digest_ledger_path, read_digest_ledger, settle_digest_ledger
|
||||
from .findings import StaticFinding, quick_scan_findings, uncovered_languages, write_findings
|
||||
from .fusion import FusionDecision, fuse_findings
|
||||
from .harness import HarnessRuntime, HarnessTraceWriter, write_harness_config
|
||||
@@ -82,6 +83,7 @@ from .semantic import (
|
||||
)
|
||||
from .semantic.facts import FactLoadError, SemanticFacts
|
||||
from .stages import Stage, plan_for_mode, record_completed, record_skip, skip_as_degradation, stages_payload
|
||||
from .tree_digest import tree_digest
|
||||
from .verification import VerificationResult, verify_findings, write_verification_results
|
||||
|
||||
CALIBRATION_DIR = ".openultrasast/calibration"
|
||||
@@ -598,11 +600,14 @@ def _run_scan(path: Path, config_path: Path, mode: str, fail_on: str) -> ScanOut
|
||||
)
|
||||
write_harness_config(config=config, path=run.root / "harness.json")
|
||||
runtime.start(mode=mode, target=run.target)
|
||||
# The key of the ledger kept under the runs directory for a tree that could not be written into. Taken before
|
||||
# any stage reads the tree.
|
||||
digest = runtime.run_stage("tree_digest", lambda: tree_digest(run.target, Path(config.runs_dir)))
|
||||
policy, ruleset, targets, entry_points, left_out = _map_scan_targets(runtime, run, config, mode)
|
||||
ledger_path = run.target / CALIBRATION_DIR / "false_positive_learnings.json"
|
||||
provenance = runtime.run_stage("provenance", lambda: fingerprint(run.target))
|
||||
rankings = runtime.run_stage("rank", lambda: rank_targets(targets))
|
||||
prior_learnings = load_false_positive_learnings(ledger_path)
|
||||
tree_learnings, ledger_of_digest, prior_learnings = _read_ledgers(ledger_path, Path(config.runs_dir), digest)
|
||||
rankings, calibrations = runtime.run_stage("calibrate", lambda: calibrate_rankings(rankings, prior_learnings))
|
||||
applied_calibrations = [calibration for calibration in calibrations if calibration.applied_learning_ids]
|
||||
write_rankings(rankings, run.root / "rank" / "ranking.json")
|
||||
@@ -617,7 +622,16 @@ def _run_scan(path: Path, config_path: Path, mode: str, fail_on: str) -> ScanOut
|
||||
write_hunter_trajectories(trajectories, files.trajectories)
|
||||
|
||||
verifications, fusion_decisions = _verify_and_fuse(
|
||||
runtime, run, config, mode, findings=findings, prior_learnings=prior_learnings, ledger_path=ledger_path, files=files
|
||||
runtime,
|
||||
run,
|
||||
config,
|
||||
mode,
|
||||
findings=findings,
|
||||
tree_learnings=tree_learnings,
|
||||
ledger_of_digest=ledger_of_digest,
|
||||
prior_learnings=prior_learnings,
|
||||
ledger_path=ledger_path,
|
||||
files=files,
|
||||
)
|
||||
cwe_by_rule = {rule.rule_id: rule.cwe for rule in ruleset}
|
||||
rule_cwe_by_id = {finding.finding_id: cwe_by_rule.get(finding.finding_id.split(":", 1)[0], "") for finding in findings}
|
||||
@@ -714,10 +728,16 @@ def _run_scan(path: Path, config_path: Path, mode: str, fail_on: str) -> ScanOut
|
||||
provenance=provenance.to_dict(),
|
||||
obligations=map_stage.obligations_summary,
|
||||
model=map_stage.model,
|
||||
ledger={
|
||||
"tree_digest": digest,
|
||||
"learnings_read": {"tree": len(tree_learnings), "digest": len(ledger_of_digest.learnings)},
|
||||
"digest_ledger": runtime.state["digest_ledger"][0],
|
||||
},
|
||||
),
|
||||
)
|
||||
runtime.finish(status="succeeded")
|
||||
prune_notices = prune_scan_runs(config, keep=run.root)
|
||||
ledger_error = runtime.state["digest_ledger"][1]
|
||||
return ScanOutcome(
|
||||
scan_id=run.scan_id,
|
||||
run_dir=run.root,
|
||||
@@ -732,6 +752,7 @@ def _run_scan(path: Path, config_path: Path, mode: str, fail_on: str) -> ScanOut
|
||||
if item.get("reason") == "language_not_covered"
|
||||
)
|
||||
+ prune_notices
|
||||
+ ((f"the ledger of this tree's digest could not be written or removed: {ledger_error}",) if ledger_error else ())
|
||||
+ _skipped_files_notices(Path(config.runs_dir), left_out),
|
||||
)
|
||||
|
||||
@@ -845,6 +866,8 @@ def _verify_and_fuse(
|
||||
mode: str,
|
||||
*,
|
||||
findings: list[StaticFinding],
|
||||
tree_learnings: list[FalsePositiveLearning],
|
||||
ledger_of_digest: DigestLedger,
|
||||
prior_learnings: list[FalsePositiveLearning],
|
||||
ledger_path: Path,
|
||||
files: _RunFiles,
|
||||
@@ -854,7 +877,9 @@ def _verify_and_fuse(
|
||||
write_verification_results(verifications, files.verification)
|
||||
runtime.run_stage(
|
||||
"record_calibration",
|
||||
lambda: _persist_calibration_feedback(run, ledger_path, prior_learnings, findings, verifications, runtime),
|
||||
lambda: _persist_calibration_feedback(
|
||||
run, ledger_path, tree_learnings, ledger_of_digest, prior_learnings, findings, verifications, runtime
|
||||
),
|
||||
)
|
||||
# Fusion: deterministic two-panel adjudication for triggered findings (standard mode).
|
||||
fusion_decisions: list[FusionDecision] = []
|
||||
@@ -1057,9 +1082,27 @@ def _attach_tool_hunter(
|
||||
return built_map, findings, verifications
|
||||
|
||||
|
||||
def _read_ledgers(
|
||||
ledger_path: Path, runs_directory: Path, digest: str
|
||||
) -> tuple[list[FalsePositiveLearning], DigestLedger, list[FalsePositiveLearning]]:
|
||||
"""What the tree's ledger holds, the ledger of the tree's digest (what scans learned while the tree could not be
|
||||
written into), and the learnings the scan is to apply.
|
||||
|
||||
An entry whose finding id is in both is taken from the tree's ledger: that is the file a user can read, edit
|
||||
and commit.
|
||||
"""
|
||||
tree_learnings = load_false_positive_learnings(ledger_path)
|
||||
ledger_of_digest = read_digest_ledger(digest_ledger_path(runs_directory, digest))
|
||||
tree_ids = {learning.finding_id for learning in tree_learnings}
|
||||
prior_learnings = tree_learnings + [learning for learning in ledger_of_digest.learnings if learning.finding_id not in tree_ids]
|
||||
return tree_learnings, ledger_of_digest, prior_learnings
|
||||
|
||||
|
||||
def _persist_calibration_feedback(
|
||||
run: ScanRun,
|
||||
ledger_path: Path,
|
||||
tree_learnings: list[FalsePositiveLearning],
|
||||
ledger_of_digest: DigestLedger,
|
||||
prior_learnings: list[FalsePositiveLearning],
|
||||
findings: list[StaticFinding],
|
||||
verifications: list[VerificationResult],
|
||||
@@ -1068,14 +1111,27 @@ def _persist_calibration_feedback(
|
||||
# Store rejected or held findings as scoped learnings for the next scan.
|
||||
new_learnings = learnings_from_verifications(findings, verifications)
|
||||
merged = merge_false_positive_learnings(prior_learnings, new_learnings)
|
||||
if merged != prior_learnings:
|
||||
# The ledger is the one thing a scan still writes into the analysed tree, so it is written only when its
|
||||
# content would change: a false positive already in the store is not a new learning. A tree that refuses
|
||||
# the write (mounted read-only) is recorded, not fatal.
|
||||
refused: OSError | None = None
|
||||
tree_takes_it = False
|
||||
if merged != tree_learnings:
|
||||
# The ledger is the one thing a scan still writes into the analysed tree. It is written when its content
|
||||
# would change, also when only the entries of the digest's ledger are new to it: the first scan that can
|
||||
# write the tree carries them into it. A tree that refuses the write (mounted read-only) is recorded, not
|
||||
# fatal: what was learned is kept in the ledger of the tree's digest under the runs directory instead.
|
||||
try:
|
||||
write_false_positive_learnings(merged, ledger_path)
|
||||
tree_takes_it = True
|
||||
except OSError as exc:
|
||||
runtime.state["degradations"].append({"stage": "record_calibration", "reason": "ledger_not_written", "detail": str(exc)})
|
||||
refused = exc
|
||||
outcome, error = settle_digest_ledger(
|
||||
ledger_of_digest, tree=tree_learnings, merged=merged, new=new_learnings, tree_takes_it=tree_takes_it
|
||||
)
|
||||
runtime.state["digest_ledger"] = (outcome, error)
|
||||
if refused is not None:
|
||||
degradation: dict[str, object] = {"stage": "record_calibration", "reason": "ledger_not_written", "detail": str(refused)}
|
||||
if outcome in HOLDS_LEARNINGS:
|
||||
degradation["kept_in"] = str(ledger_of_digest.path)
|
||||
runtime.state["degradations"].append(degradation)
|
||||
write_false_positive_learnings(new_learnings, run.root / "calibration" / "false_positive_learnings.json")
|
||||
return merged
|
||||
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
"""The ledger of a tree's digest: what scans learned while the tree could not be written into, kept under the runs
|
||||
directory and read by the next scan of the very same bytes (the decision of 2026-11-28)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from .calibration import (
|
||||
FalsePositiveLearning,
|
||||
load_false_positive_learnings,
|
||||
merge_false_positive_learnings,
|
||||
write_false_positive_learnings,
|
||||
)
|
||||
|
||||
LEDGERS_DIRNAME = "calibration"
|
||||
FOUND_NONE = "none"
|
||||
FOUND_READ = "read"
|
||||
FOUND_UNREADABLE = "unreadable"
|
||||
WRITTEN = "written"
|
||||
LEFT_AS_IT_WAS = "left as it was"
|
||||
REMOVED = "removed"
|
||||
FAILED = "failed"
|
||||
# What became of a ledger after which it holds what a refusing tree could not take.
|
||||
HOLDS_LEARNINGS = (WRITTEN, LEFT_AS_IT_WAS)
|
||||
# A ledger, and the temporary file it is written through before its rename.
|
||||
LEDGER_NAME = re.compile(r"[0-9a-f]{64}\.json(?:\.[0-9a-f]{32}\.tmp)?")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DigestLedger:
|
||||
"""The ledger of one tree digest: where it is, whether a scan could read it, and what it held."""
|
||||
|
||||
path: Path
|
||||
found: str
|
||||
learnings: list[FalsePositiveLearning] = field(default_factory=list)
|
||||
|
||||
|
||||
def digest_ledger_path(runs_directory: Path, digest: str) -> Path:
|
||||
return Path(runs_directory) / LEDGERS_DIRNAME / f"{digest}.json"
|
||||
|
||||
|
||||
def read_digest_ledger(path: Path) -> DigestLedger:
|
||||
"""The ledger at `path` and what it held: `FOUND_NONE` when there is no file, `FOUND_UNREADABLE` when there is one
|
||||
that is not a ledger (a cache must not stop a scan), `FOUND_READ` otherwise.
|
||||
|
||||
Reading one marks it as used, so that a ledger read every day stays while one left alone goes.
|
||||
"""
|
||||
if not path.is_file():
|
||||
return DigestLedger(path, FOUND_NONE)
|
||||
try:
|
||||
learnings = load_false_positive_learnings(path)
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError, RecursionError):
|
||||
# Whatever a hand or another tool left there: the reader of the tree's ledger stops on it, a cache must not.
|
||||
return DigestLedger(path, FOUND_UNREADABLE)
|
||||
with contextlib.suppress(OSError): # a mark that fails costs the scan nothing
|
||||
os.utime(path)
|
||||
return DigestLedger(path, FOUND_READ, learnings)
|
||||
|
||||
|
||||
def settle_digest_ledger(
|
||||
ledger: DigestLedger,
|
||||
*,
|
||||
tree: list[FalsePositiveLearning],
|
||||
merged: list[FalsePositiveLearning],
|
||||
new: list[FalsePositiveLearning],
|
||||
tree_takes_it: bool,
|
||||
) -> tuple[str, str]:
|
||||
"""Bring the ledger of the digest in line with what this scan did to the tree's ledger.
|
||||
|
||||
Returns what became of it and, when something failed, why. `tree` is what the tree's ledger held before this
|
||||
scan, `merged` what it is to hold now, `new` what this scan learned, and `tree_takes_it` whether the tree took
|
||||
that write, when there was one.
|
||||
|
||||
- The tree took the write: everything the ledger held is in the tree's ledger now, so the ledger is removed.
|
||||
- The tree refused the write: the ledger is written instead, with its own entries and this scan's new ones,
|
||||
never one whose finding id the tree's ledger has, and only when that differs from its content; when that
|
||||
would leave it empty, it is removed.
|
||||
- There was no write: a ledger whose every entry the tree's ledger also has is removed. It has nothing left
|
||||
to give. This is also what removes a ledger again when an earlier removal failed, and one that could not
|
||||
be read, which is taken for empty.
|
||||
|
||||
A ledger that could not be read is "unreadable" unless this scan wrote it or failed to: it is taken for
|
||||
empty and goes, since it has nothing left to give. A removal that finds the file already gone is nothing,
|
||||
and nothing here raises.
|
||||
"""
|
||||
outcome = FOUND_NONE if ledger.found == FOUND_NONE else LEFT_AS_IT_WAS
|
||||
error = ""
|
||||
tree_ids = {learning.finding_id for learning in tree}
|
||||
if merged != tree:
|
||||
if tree_takes_it:
|
||||
if ledger.found != FOUND_NONE:
|
||||
outcome, error = _remove(ledger.path)
|
||||
else:
|
||||
kept = [learning for learning in merge_false_positive_learnings(ledger.learnings, new) if learning.finding_id not in tree_ids]
|
||||
if not kept:
|
||||
if ledger.found != FOUND_NONE:
|
||||
outcome, error = _remove(ledger.path)
|
||||
elif kept != ledger.learnings:
|
||||
outcome, error = _write(ledger.path, kept)
|
||||
elif ledger.found != FOUND_NONE and all(learning.finding_id in tree_ids for learning in ledger.learnings):
|
||||
outcome, error = _remove(ledger.path)
|
||||
if ledger.found == FOUND_UNREADABLE and outcome not in (WRITTEN, FAILED):
|
||||
outcome = FOUND_UNREADABLE
|
||||
return outcome, error
|
||||
|
||||
|
||||
def _write(path: Path, learnings: list[FalsePositiveLearning]) -> tuple[str, str]:
|
||||
"""Through a temporary file of this writer's own and a rename: a scan stopped midway leaves the old ledger or the
|
||||
new one, and two scans of one tree never share a name."""
|
||||
temporary = path.with_name(f"{path.name}.{uuid.uuid4().hex}.tmp")
|
||||
try:
|
||||
write_false_positive_learnings(learnings, temporary)
|
||||
os.replace(temporary, path)
|
||||
except OSError as exc:
|
||||
with contextlib.suppress(OSError):
|
||||
temporary.unlink(missing_ok=True)
|
||||
return FAILED, str(exc)
|
||||
return WRITTEN, ""
|
||||
|
||||
|
||||
def _remove(path: Path) -> tuple[str, str]:
|
||||
try:
|
||||
path.unlink()
|
||||
except FileNotFoundError:
|
||||
pass # already gone: nothing to remove
|
||||
except OSError as exc:
|
||||
return FAILED, str(exc)
|
||||
return REMOVED, ""
|
||||
@@ -209,6 +209,7 @@ def write_manifest(
|
||||
variants: dict[str, object] | None = None,
|
||||
obligations: dict[str, object] | None = None,
|
||||
model: dict[str, object] | None = None,
|
||||
ledger: dict[str, object] | None = None,
|
||||
) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
verification_by_id = _verification_by_id(verifications)
|
||||
@@ -250,6 +251,8 @@ def write_manifest(
|
||||
payload["obligations"] = obligations
|
||||
if model is not None:
|
||||
payload["model"] = model
|
||||
if ledger is not None:
|
||||
payload["ledger"] = ledger
|
||||
path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n")
|
||||
|
||||
|
||||
@@ -455,6 +458,13 @@ _COVERAGE_DEGRADATIONS: dict[str, str] = {
|
||||
"The false-positive ledger in the analysed tree could not be written, so this scan's learnings are kept "
|
||||
"only in this run directory and the next scan starts without them. {detail}"
|
||||
),
|
||||
# The same degradation when the ledger of the tree's digest holds the learnings (`kept_in`, written in this scan
|
||||
# or before): the next scan of the same bytes reads them there.
|
||||
"ledger_kept_by_digest": (
|
||||
"The false-positive ledger in the analysed tree could not be written, so this scan's learnings are kept in "
|
||||
"the ledger of this tree's digest under the runs directory, at `{kept_in}`, and the next scan of the same "
|
||||
"bytes reads them. {detail}"
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@@ -467,7 +477,10 @@ def _append_not_analysed(lines: list[str], degradations: Sequence[Mapping[str, o
|
||||
"""
|
||||
rendered: list[str] = []
|
||||
for item in degradations:
|
||||
template = _COVERAGE_DEGRADATIONS.get(str(item.get("reason") or ""))
|
||||
reason = str(item.get("reason") or "")
|
||||
if reason == "ledger_not_written" and item.get("kept_in"):
|
||||
reason = "ledger_kept_by_digest"
|
||||
template = _COVERAGE_DEGRADATIONS.get(reason)
|
||||
if template is None:
|
||||
# Never hide a recorded degradation because nobody wrote a sentence for it yet.
|
||||
rendered.append(f"`{item.get('reason')}` (stage `{item.get('stage', 'unknown')}`)")
|
||||
|
||||
@@ -8,6 +8,7 @@ from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
from .config import ResolvedConfig, runs_dir_is_overridden, runs_dir_is_the_wrappers, write_resolved_config
|
||||
from .digest_ledger import LEDGER_NAME, LEDGERS_DIRNAME
|
||||
|
||||
_RUN_ID = re.compile(r"(\d{8}T\d{6}Z)-[0-9a-f]{8}")
|
||||
|
||||
@@ -68,12 +69,15 @@ def prune_old_runs(runs_root: Path, *, keep: Path | None = None, retention_days:
|
||||
|
||||
|
||||
def prune_scan_runs(config: ResolvedConfig, *, keep: Path) -> tuple[str, ...]:
|
||||
"""Remove the expired runs once a scan has written its own; returns what the scan is to say about it.
|
||||
"""Remove the expired runs and ledgers once a scan has written its own; returns what the scan is to say about it.
|
||||
|
||||
Two locations are pruned: the default one, and the shell wrapper's runs directory, which is the user's runs
|
||||
directory mounted in the image (`runs_dir_is_the_wrappers`). While `OPENULTRASAST_RUNS_DIR` points anywhere
|
||||
else, wherever it points, every run stays. Nothing is said when nothing was removed, and a removal that
|
||||
fails is said once and costs the scan nothing.
|
||||
|
||||
The ledgers of tree digests (`prune_expired_ledgers`) lie under the same two locations and go by the same
|
||||
number of days, dated by their last use.
|
||||
"""
|
||||
if runs_dir_is_overridden() and not runs_dir_is_the_wrappers():
|
||||
return ()
|
||||
@@ -82,7 +86,59 @@ def prune_scan_runs(config: ResolvedConfig, *, keep: Path) -> tuple[str, ...]:
|
||||
removed = prune_old_runs(root, keep=keep, retention_days=config.runs_retention_days)
|
||||
except (OSError, RecursionError) as exc:
|
||||
return (f"old runs could not be removed from {root}: {exc}",)
|
||||
if not removed:
|
||||
return ()
|
||||
runs = "run" if len(removed) == 1 else "runs"
|
||||
return (f"removed {len(removed)} {runs} older than {config.runs_retention_days} days from {root}",)
|
||||
notices = []
|
||||
if removed:
|
||||
runs = "run" if len(removed) == 1 else "runs"
|
||||
notices.append(f"removed {len(removed)} {runs} older than {config.runs_retention_days} days from {root}")
|
||||
ledgers = root / LEDGERS_DIRNAME
|
||||
gone, failed = prune_expired_ledgers(ledgers, retention_days=config.runs_retention_days)
|
||||
if gone:
|
||||
name = "ledger" if len(gone) == 1 else "ledgers"
|
||||
notices.append(f"removed {len(gone)} {name} of a tree digest unused for {config.runs_retention_days} days from {ledgers}")
|
||||
notices.extend(f"a ledger of a tree digest could not be removed from {ledgers}: {exc}" for _, exc in failed)
|
||||
return tuple(notices)
|
||||
|
||||
|
||||
def _is_expired_ledger(entry: Path, cutoff: datetime) -> bool:
|
||||
"""A ledger of a tree digest, or the temporary file it was written through, last used before `cutoff`."""
|
||||
if LEDGER_NAME.fullmatch(entry.name) is None or entry.is_symlink() or not entry.is_file():
|
||||
return False
|
||||
try:
|
||||
return datetime.fromtimestamp(entry.stat().st_mtime, UTC) < cutoff
|
||||
except (OSError, OverflowError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def prune_expired_ledgers(
|
||||
directory: Path, *, retention_days: int, now: datetime | None = None
|
||||
) -> tuple[list[Path], list[tuple[Path, OSError]]]:
|
||||
"""Remove the ledgers of tree digests under `directory` that were last used before `retention_days`; return them
|
||||
and the removals that failed.
|
||||
|
||||
A ledger is dated by its use, since a scan marks it when it reads it, where a run is dated by its id. Files
|
||||
called something else, links and directories stay. Nothing raises.
|
||||
"""
|
||||
if retention_days <= 0 or not directory.is_dir():
|
||||
return [], []
|
||||
try:
|
||||
cutoff = (now or datetime.now(UTC)) - timedelta(days=retention_days)
|
||||
except OverflowError:
|
||||
return [], [] # a retention longer than the calendar: no ledger is that old
|
||||
removed: list[Path] = []
|
||||
failed: list[tuple[Path, OSError]] = []
|
||||
try:
|
||||
entries = sorted(directory.iterdir())
|
||||
except OSError as exc:
|
||||
return [], [(directory, exc)]
|
||||
for entry in entries:
|
||||
if not _is_expired_ledger(entry, cutoff):
|
||||
continue
|
||||
try:
|
||||
entry.unlink()
|
||||
except FileNotFoundError:
|
||||
pass # already gone
|
||||
except OSError as exc:
|
||||
failed.append((entry, exc))
|
||||
else:
|
||||
removed.append(entry)
|
||||
return removed, failed
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
"""The key of the ledger a scan keeps for a tree it could not write into: a digest of the tree's files."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
from .preprocess import IGNORED_DIRS
|
||||
|
||||
# The hashed text starts with this, so that a later change of the definition cannot pass for the same key.
|
||||
_VERSION = b"openultrasast-tree-v1\n"
|
||||
|
||||
|
||||
def _identity(path: Path) -> tuple[int, int] | None:
|
||||
"""The device and the inode of `path`: the same under every path it is reached by."""
|
||||
try:
|
||||
status = os.stat(path)
|
||||
except OSError:
|
||||
return None
|
||||
return status.st_dev, status.st_ino
|
||||
|
||||
|
||||
def _files(root: Path, skipped: tuple[int, int] | None) -> Iterator[tuple[str, Path | None]]:
|
||||
"""Every file to hash and every directory that could not be listed: its path under `root`, and the file
|
||||
(None for a directory that could not be listed), in path order."""
|
||||
entries: list[tuple[str, Path | None]] = []
|
||||
|
||||
def unlisted(error: OSError) -> None:
|
||||
if error.filename is not None:
|
||||
entries.append((Path(os.path.relpath(error.filename, root)).as_posix(), None))
|
||||
|
||||
def kept(name: str, path: Path) -> bool:
|
||||
return name not in IGNORED_DIRS and (skipped is None or _identity(path) != skipped)
|
||||
|
||||
for parent, directories, names in os.walk(root, followlinks=False, onerror=unlisted):
|
||||
base = Path(parent)
|
||||
directories[:] = sorted(name for name in directories if kept(name, base / name))
|
||||
for name in names:
|
||||
path = base / name
|
||||
if path.is_symlink() or not path.is_file():
|
||||
continue
|
||||
entries.append((path.relative_to(root).as_posix(), path))
|
||||
yield from sorted(entries, key=lambda entry: entry[0])
|
||||
|
||||
|
||||
def tree_digest(target: Path, runs_directory: Path | None = None) -> str:
|
||||
"""A sha256 of the name and the bytes of every file under `target`, in path order.
|
||||
|
||||
Left out: links; the directories a scan ignores (`IGNORED_DIRS`), so that the ledger in the tree does not
|
||||
change its own key; and `runs_directory`, whichever way it is reached. A file that cannot be read and a
|
||||
directory that cannot be listed are named `unreadable` instead of a hash, so that neither is skipped in
|
||||
silence. Each entry is the length of the path, a colon, the path, a tab and the hash: one path is one entry.
|
||||
A directory that can be listed but not searched raises, as the scan's own reading of the tree does.
|
||||
"""
|
||||
digest = hashlib.sha256()
|
||||
digest.update(_VERSION)
|
||||
skipped = _identity(runs_directory) if runs_directory is not None else None
|
||||
for relative, path in _files(target, skipped):
|
||||
name = relative.encode("utf-8", "surrogatepass")
|
||||
digest.update(f"{len(name)}:".encode("ascii") + name + b"\t")
|
||||
digest.update(_hash(path) if path is not None else b"unreadable")
|
||||
digest.update(b"\n")
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _hash(path: Path) -> bytes:
|
||||
"""The sha256 of the file's bytes, read in chunks, or the word `unreadable`."""
|
||||
try:
|
||||
with path.open("rb") as handle:
|
||||
return hashlib.file_digest(handle, "sha256").hexdigest().encode("ascii")
|
||||
except OSError:
|
||||
return b"unreadable"
|
||||
@@ -0,0 +1,174 @@
|
||||
"""The ledger of a tree's digest (contributor-scan, the design note of 2026-11-27, approved on 2026-11-28): what
|
||||
scans learned while the tree could not be written, kept under the runs directory and read by the next scan of the
|
||||
very same bytes."""
|
||||
|
||||
import errno
|
||||
import os
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from openultrasast import digest_ledger
|
||||
from openultrasast.calibration import FalsePositiveLearning, FalsePositiveReason, write_false_positive_learnings
|
||||
from openultrasast.digest_ledger import digest_ledger_path, read_digest_ledger, settle_digest_ledger
|
||||
|
||||
DIGEST = "a" * 64
|
||||
|
||||
|
||||
def _learning(finding_id: str, evidence: str = "no route reaches it") -> FalsePositiveLearning:
|
||||
return FalsePositiveLearning(finding_id, f"pkg/{finding_id}.py", "xss", FalsePositiveReason.UNREACHABLE_PATH, evidence, "pkg")
|
||||
|
||||
|
||||
def _ids(learnings: list[FalsePositiveLearning]) -> list[str]:
|
||||
return [learning.finding_id for learning in learnings]
|
||||
|
||||
|
||||
def _ledger(runs: Path, learnings: list[FalsePositiveLearning] | None) -> digest_ledger.DigestLedger:
|
||||
"""The ledger of one digest under `runs`, holding `learnings` (no file when None), as a scan reads it."""
|
||||
path = digest_ledger_path(runs, DIGEST)
|
||||
if learnings is not None:
|
||||
write_false_positive_learnings(learnings, path)
|
||||
return read_digest_ledger(path)
|
||||
|
||||
|
||||
def _settle(
|
||||
ledger: digest_ledger.DigestLedger,
|
||||
*,
|
||||
tree: list[FalsePositiveLearning],
|
||||
merged: list[FalsePositiveLearning],
|
||||
new: list[FalsePositiveLearning],
|
||||
tree_takes_it: bool = False,
|
||||
) -> str:
|
||||
return settle_digest_ledger(ledger, tree=tree, merged=merged, new=new, tree_takes_it=tree_takes_it)[0]
|
||||
|
||||
|
||||
def test_the_ledger_of_a_digest_sits_under_the_runs_directory_named_by_the_digest(tmp_path: Path) -> None:
|
||||
assert digest_ledger_path(tmp_path, DIGEST) == tmp_path / "calibration" / f"{DIGEST}.json"
|
||||
|
||||
|
||||
def test_reading_a_ledger_marks_it_as_used(tmp_path: Path) -> None:
|
||||
"""A ledger read every day stays while one left alone goes: an expired ledger is dated by its use."""
|
||||
path = digest_ledger_path(tmp_path, DIGEST)
|
||||
write_false_positive_learnings([_learning("a")], path)
|
||||
old = datetime.now(UTC) - timedelta(days=40)
|
||||
os.utime(path, (old.timestamp(), old.timestamp()))
|
||||
|
||||
ledger = read_digest_ledger(path)
|
||||
|
||||
assert (ledger.found, _ids(ledger.learnings)) == ("read", ["a"])
|
||||
assert path.stat().st_mtime > (datetime.now(UTC) - timedelta(days=1)).timestamp()
|
||||
|
||||
|
||||
def test_a_missing_ledger_is_none_and_one_that_is_not_a_ledger_is_unreadable(tmp_path: Path) -> None:
|
||||
"""Whatever a hand or another tool left there: a file that is not a ledger must not stop a scan. (An object whose
|
||||
`learnings` is a string or an object reads as an empty ledger, as the tree's own loader reads it.)"""
|
||||
path = digest_ledger_path(tmp_path, DIGEST)
|
||||
assert read_digest_ledger(path).found == "none"
|
||||
|
||||
path.parent.mkdir(parents=True)
|
||||
for content in ("not a ledger\n", "", "{", "[]\n", "null\n", "5\n", '"text"\n', "true\n", "[" * 5000 + "]" * 5000):
|
||||
path.write_text(content)
|
||||
|
||||
assert read_digest_ledger(path).found == "unreadable", content
|
||||
|
||||
|
||||
def test_when_the_tree_refuses_the_ledger_takes_what_the_tree_does_not_already_hold(tmp_path: Path) -> None:
|
||||
"""The tree's ledger holds `a`; this scan learned `a` once more and `b`: only `b` is new to the tree."""
|
||||
ledger = _ledger(tmp_path, None)
|
||||
|
||||
outcome = _settle(ledger, tree=[_learning("a")], merged=[_learning("a"), _learning("b")], new=[_learning("a"), _learning("b")])
|
||||
|
||||
assert outcome == "written"
|
||||
assert _ids(read_digest_ledger(ledger.path).learnings) == ["b"]
|
||||
|
||||
|
||||
def test_a_ledger_whose_content_would_not_change_is_left_as_it_was(tmp_path: Path) -> None:
|
||||
"""The common case in the image: the same bytes scanned again re-learn what the ledger already holds."""
|
||||
ledger = _ledger(tmp_path, [_learning("b")])
|
||||
before = ledger.path.read_bytes()
|
||||
|
||||
outcome = _settle(ledger, tree=[], merged=[_learning("b")], new=[_learning("b")])
|
||||
|
||||
assert outcome == "left as it was"
|
||||
assert ledger.path.read_bytes() == before
|
||||
|
||||
|
||||
def test_when_the_tree_takes_the_write_the_ledger_is_removed(tmp_path: Path) -> None:
|
||||
ledger = _ledger(tmp_path, [_learning("b")])
|
||||
|
||||
assert _settle(ledger, tree=[], merged=[_learning("b")], new=[], tree_takes_it=True) == "removed"
|
||||
assert not ledger.path.exists()
|
||||
|
||||
|
||||
def test_a_ledger_is_removed_once_the_tree_holds_every_entry_it_had(tmp_path: Path) -> None:
|
||||
"""Nothing was written into the tree this scan: the entries were put there by hand, as a commit could."""
|
||||
ledger = _ledger(tmp_path, [_learning("b")])
|
||||
|
||||
assert _settle(ledger, tree=[_learning("b")], merged=[_learning("b")], new=[_learning("b")]) == "removed"
|
||||
assert not ledger.path.exists()
|
||||
|
||||
|
||||
def test_an_emptied_ledger_is_removed_rather_than_written_empty(tmp_path: Path) -> None:
|
||||
"""The tree holds `b` with other evidence; the scan re-learned `b`, the tree refused, and nothing is left to keep."""
|
||||
ledger = _ledger(tmp_path, [_learning("b", "the first evidence")])
|
||||
|
||||
outcome = _settle(ledger, tree=[_learning("b", "the first evidence")], merged=[_learning("b")], new=[_learning("b")])
|
||||
|
||||
assert outcome == "removed"
|
||||
assert not ledger.path.exists()
|
||||
|
||||
|
||||
def test_a_ledger_that_cannot_be_read_is_taken_for_empty_and_said_unreadable_unless_it_is_written(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
path = digest_ledger_path(tmp_path, DIGEST)
|
||||
path.parent.mkdir(parents=True)
|
||||
path.write_text("not a ledger\n")
|
||||
|
||||
assert _settle(read_digest_ledger(path), tree=[], merged=[_learning("b")], new=[_learning("b")]) == "written"
|
||||
assert _ids(read_digest_ledger(path).learnings) == ["b"]
|
||||
|
||||
path.write_text("not a ledger\n")
|
||||
assert _settle(read_digest_ledger(path), tree=[_learning("b")], merged=[_learning("b")], new=[]) == "unreadable"
|
||||
assert not path.exists()
|
||||
|
||||
|
||||
def test_a_write_that_fails_leaves_the_old_ledger_and_no_temporary_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Written through a temporary file of its own and a rename: a scan stopped midway leaves the old ledger or the
|
||||
new one, never the two together."""
|
||||
ledger = _ledger(tmp_path, [_learning("b")])
|
||||
before = ledger.path.read_bytes()
|
||||
names: list[str] = []
|
||||
|
||||
def interrupted(source, target): # type: ignore[no-untyped-def]
|
||||
names.append(Path(source).name)
|
||||
raise InterruptedError(errno.EINTR, "interrupted", str(source))
|
||||
|
||||
monkeypatch.setattr(digest_ledger.os, "replace", interrupted)
|
||||
|
||||
outcome = settle_digest_ledger(ledger, tree=[], merged=[_learning("b"), _learning("c")], new=[_learning("c")], tree_takes_it=False)
|
||||
|
||||
assert outcome[0] == "failed"
|
||||
assert "interrupted" in outcome[1]
|
||||
assert ledger.path.read_bytes() == before
|
||||
assert names and names[0].startswith(ledger.path.name) and names[0] != ledger.path.name
|
||||
assert [entry.name for entry in ledger.path.parent.iterdir()] == [ledger.path.name]
|
||||
|
||||
|
||||
def test_a_removal_that_fails_is_failed_and_raises_nothing(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
ledger = _ledger(tmp_path, [_learning("b")])
|
||||
unlink = Path.unlink
|
||||
|
||||
def refusing(path, *args, **kwargs): # type: ignore[no-untyped-def]
|
||||
if path == ledger.path:
|
||||
raise PermissionError(errno.EACCES, "Permission denied", str(path))
|
||||
return unlink(path, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(Path, "unlink", refusing)
|
||||
|
||||
assert settle_digest_ledger(ledger, tree=[], merged=[_learning("b")], new=[], tree_takes_it=True) == (
|
||||
"failed",
|
||||
f"[Errno 13] Permission denied: '{ledger.path}'",
|
||||
)
|
||||
assert ledger.path.is_file()
|
||||
@@ -616,6 +616,33 @@ def test_an_unwritable_ledger_is_stated_in_the_report(tmp_path) -> None: # type
|
||||
assert "`ledger_not_written`" not in section
|
||||
|
||||
|
||||
def test_an_unwritable_ledger_kept_by_digest_names_the_file_the_next_scan_reads(tmp_path) -> None: # type: ignore[no-untyped-def]
|
||||
"""When the learnings are kept in the ledger of the tree's digest, the sentence says where: a reader told only a
|
||||
code cannot find them."""
|
||||
path = tmp_path / "report.md"
|
||||
kept = "/reports/calibration/" + "a" * 64 + ".json"
|
||||
write_markdown_report(
|
||||
[],
|
||||
path,
|
||||
[],
|
||||
degradations=[
|
||||
{
|
||||
"stage": "record_calibration",
|
||||
"reason": "ledger_not_written",
|
||||
"detail": "[Errno 30] Read-only file system: '/target/.openultrasast'",
|
||||
"kept_in": kept,
|
||||
}
|
||||
],
|
||||
)
|
||||
section = path.read_text().split("### What could not be analysed", 1)[1]
|
||||
assert (
|
||||
"The false-positive ledger in the analysed tree could not be written, so this scan's learnings are kept in "
|
||||
f"the ledger of this tree's digest under the runs directory, at `{kept}`, and the next scan of the same "
|
||||
"bytes reads them. [Errno 30] Read-only file system: '/target/.openultrasast'"
|
||||
) in section
|
||||
assert "only in this run directory" not in section
|
||||
|
||||
|
||||
def test_quick_scan_names_a_language_nothing_covers(tmp_path, monkeypatch, capsys) -> None: # type: ignore[no-untyped-def]
|
||||
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", str(tmp_path / "runs"))
|
||||
"""pre-push 17.2 / Req 9.2: a Go-only tree is not a silent zero."""
|
||||
|
||||
@@ -369,3 +369,107 @@ def test_a_scan_with_a_retention_longer_than_the_calendar_succeeds_and_says_noth
|
||||
|
||||
assert (expired / "manifest.json").is_file()
|
||||
assert _notices(capsys.readouterr().out) == []
|
||||
|
||||
|
||||
def _ledger_file(runs: Path, age_days: int, name: str) -> Path:
|
||||
"""A file under the directory of the ledgers of tree digests, last used `age_days` ago by the real clock."""
|
||||
path = runs / "calibration" / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text('{"learnings": []}\n')
|
||||
last_used = (datetime.now(UTC) - timedelta(days=age_days)).timestamp()
|
||||
os.utime(path, (last_used, last_used))
|
||||
return path
|
||||
|
||||
|
||||
def _digest(suffix: str = ".json") -> str:
|
||||
return f"{uuid.uuid4().hex}{uuid.uuid4().hex[:32]}{suffix}"
|
||||
|
||||
|
||||
def test_a_ledger_of_a_tree_digest_unused_for_longer_than_the_retention_is_removed_with_the_runs(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""By the decision of 2026-11-28: a ledger is dated by its last use, a run by its id."""
|
||||
monkeypatch.delenv("OPENULTRASAST_RUNS_DIR", raising=False)
|
||||
monkeypatch.delenv(RETENTION, raising=False)
|
||||
runs = tmp_path / "runs"
|
||||
_ledger_file(runs, 40, _digest())
|
||||
last_week = _ledger_file(runs, 5, _digest())
|
||||
current = _run(runs, _run_id(datetime.now(UTC), "badc0de0"))
|
||||
|
||||
notices = prune_scan_runs(ResolvedConfig(runs_dir=str(runs)), keep=current)
|
||||
|
||||
assert notices == (f"removed 1 ledger of a tree digest unused for 30 days from {runs / 'calibration'}",)
|
||||
assert list((runs / "calibration").iterdir()) == [last_week]
|
||||
assert sorted(runs.iterdir()) == sorted([runs / "calibration", current])
|
||||
|
||||
|
||||
def test_a_scan_removes_the_expired_ledgers_and_says_so(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
runs = _default_cache(tmp_path, monkeypatch)
|
||||
_ledger_file(runs, 40, _digest(".json." + uuid.uuid4().hex + ".tmp"))
|
||||
_ledger_file(runs, 40, _digest())
|
||||
last_week = _ledger_file(runs, 5, _digest())
|
||||
repo = _target(tmp_path)
|
||||
|
||||
assert _scan(repo) == 0
|
||||
|
||||
assert list((runs / "calibration").iterdir()) == [last_week]
|
||||
assert _notices(capsys.readouterr().out) == [f"removed 2 ledgers of a tree digest unused for 30 days from {runs / 'calibration'}"]
|
||||
|
||||
|
||||
def test_nothing_under_the_ledgers_directory_that_is_not_a_ledger_is_touched(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.delenv("OPENULTRASAST_RUNS_DIR", raising=False)
|
||||
runs = tmp_path / "runs"
|
||||
notes = _ledger_file(runs, 40, "notes.txt")
|
||||
elsewhere = _ledger_file(tmp_path, 40, _digest())
|
||||
link = runs / "calibration" / _digest()
|
||||
link.symlink_to(elsewhere)
|
||||
directory = runs / "calibration" / _digest()
|
||||
directory.mkdir()
|
||||
|
||||
assert prune_scan_runs(ResolvedConfig(runs_dir=str(runs)), keep=runs / _run_id(datetime.now(UTC), "badc0de0")) == ()
|
||||
assert sorted(path.name for path in (runs / "calibration").iterdir()) == sorted([notes.name, link.name, directory.name])
|
||||
assert elsewhere.is_file()
|
||||
|
||||
|
||||
def test_a_retention_of_zero_keeps_every_ledger(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.delenv("OPENULTRASAST_RUNS_DIR", raising=False)
|
||||
monkeypatch.setenv(RETENTION, "0")
|
||||
runs = tmp_path / "runs"
|
||||
expired = _ledger_file(runs, 40, _digest())
|
||||
|
||||
assert prune_scan_runs(ResolvedConfig(runs_dir=str(runs), runs_retention_days=0), keep=None) == ()
|
||||
assert expired.is_file()
|
||||
|
||||
|
||||
def test_a_ledger_is_kept_through_compose_without_the_wrapper(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setenv("OPENULTRASAST_RUNS_DIR", "/reports/runs")
|
||||
monkeypatch.delenv(RETENTION, raising=False)
|
||||
runs = tmp_path / "reports" / "runs"
|
||||
expired = _ledger_file(runs, 40, _digest())
|
||||
|
||||
assert prune_scan_runs(ResolvedConfig(runs_dir=str(runs)), keep=None) == ()
|
||||
assert expired.is_file()
|
||||
|
||||
|
||||
def test_a_ledger_that_cannot_be_removed_is_said_once_and_costs_the_scan_nothing(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
runs = _default_cache(tmp_path, monkeypatch)
|
||||
expired = _ledger_file(runs, 40, _digest())
|
||||
refusal = PermissionError(errno.EACCES, "Permission denied", str(expired))
|
||||
unlink = Path.unlink
|
||||
|
||||
def refuse(path, *args, **kwargs):
|
||||
if path == expired:
|
||||
raise refusal
|
||||
unlink(path, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(Path, "unlink", refuse)
|
||||
repo = _target(tmp_path)
|
||||
|
||||
assert _scan(repo) == 0
|
||||
|
||||
assert expired.is_file()
|
||||
assert _notices(capsys.readouterr().out) == [f"a ledger of a tree digest could not be removed from {runs / 'calibration'}: {refusal}"]
|
||||
|
||||
@@ -4,21 +4,26 @@ tree is left as it was unless the scan has a false positive to remember."""
|
||||
import errno
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from openultrasast import cli
|
||||
from openultrasast import cli, digest_ledger
|
||||
from openultrasast.calibration import FalsePositiveLearning, FalsePositiveReason, write_false_positive_learnings
|
||||
from openultrasast.cli import main
|
||||
from openultrasast.config import ResolvedConfig, load_config
|
||||
from openultrasast.preprocess import enumerate_source_files
|
||||
from openultrasast.tree_digest import tree_digest
|
||||
|
||||
LEDGER = ".openultrasast/calibration/false_positive_learnings.json"
|
||||
LEDGER_DIRECTORIES = {".openultrasast", ".openultrasast/calibration"}
|
||||
LEDGER_UNWRITTEN = {"stage": "record_calibration", "reason": "ledger_not_written"}
|
||||
DIGEST_LEDGERS = "calibration"
|
||||
|
||||
|
||||
def _user_cache(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
@@ -94,6 +99,7 @@ def test_a_scan_that_learns_writes_the_ledger_into_the_tree_and_nothing_else(
|
||||
assert [learning["path"] for learning in learnings] == ["pkg/lib.py"]
|
||||
kept = json.loads((run / "calibration" / "false_positive_learnings.json").read_text())["learnings"]
|
||||
assert kept == learnings
|
||||
assert _ledger_of(run)["digest_ledger"] == "none"
|
||||
files_after, directories_after = _tree(repo)
|
||||
assert {name: files_after[name] for name in files_before} == files_before
|
||||
assert set(files_after) - set(files_before) == {LEDGER}
|
||||
@@ -113,7 +119,8 @@ def test_a_scan_that_cannot_write_the_ledger_records_it_and_goes_on(
|
||||
|
||||
assert _scan(repo, mode) == 0
|
||||
|
||||
(run,) = runs.iterdir()
|
||||
# This scan learned something the tree could not take: its learnings are kept in the ledger of the tree's digest.
|
||||
(run,) = [path for path in runs.iterdir() if path.name != DIGEST_LEDGERS]
|
||||
degradations = json.loads((run / "manifest.json").read_text())["degradations"]
|
||||
recorded = [{key: item.get(key) for key in LEDGER_UNWRITTEN} for item in degradations]
|
||||
assert LEDGER_UNWRITTEN in recorded
|
||||
@@ -182,6 +189,233 @@ def test_a_rescan_on_a_read_only_tree_records_nothing_because_nothing_needed_wri
|
||||
assert _tree(repo) == tree_before
|
||||
|
||||
|
||||
def _refusing(monkeypatch: pytest.MonkeyPatch, ledger: Path) -> None:
|
||||
"""The tree refuses its ledger from here on, as a read-only mount does, while its bytes stay as they are."""
|
||||
write = cli.write_false_positive_learnings
|
||||
|
||||
def refuse_the_store(learnings, path):
|
||||
if path == ledger:
|
||||
raise PermissionError(errno.EACCES, "Permission denied", str(path))
|
||||
write(learnings, path)
|
||||
|
||||
monkeypatch.setattr(cli, "write_false_positive_learnings", refuse_the_store)
|
||||
|
||||
|
||||
def _digest_ledger(runs: Path, repo: Path) -> Path:
|
||||
"""Where a scan keeps what it learned while `repo` could not be written."""
|
||||
return runs / DIGEST_LEDGERS / f"{tree_digest(repo, runs)}.json"
|
||||
|
||||
|
||||
def _ledger_of(run: Path) -> dict[str, object]:
|
||||
return json.loads((run / "manifest.json").read_text())["ledger"]
|
||||
|
||||
|
||||
def _reasons(run: Path) -> list[str]:
|
||||
return [item["reason"] for item in json.loads((run / "manifest.json").read_text()).get("degradations") or []]
|
||||
|
||||
|
||||
def test_a_scan_whose_tree_refuses_the_ledger_keeps_it_under_the_runs_directory(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
"""What a scan in the image learns is not lost: it goes to the ledger of the tree's digest, which only a scan of
|
||||
the very same bytes reads."""
|
||||
runs = _user_cache(tmp_path, monkeypatch)
|
||||
repo = _target(tmp_path, learns=True)
|
||||
tree_before = _tree(repo)
|
||||
|
||||
with pytest.MonkeyPatch.context() as refusing:
|
||||
_refusing(refusing, (repo / LEDGER).resolve())
|
||||
|
||||
assert _scan(repo) == 0
|
||||
|
||||
(run,) = [path for path in runs.iterdir() if path.name != DIGEST_LEDGERS]
|
||||
kept = _digest_ledger(runs, repo)
|
||||
learnings = json.loads(kept.read_text())["learnings"]
|
||||
assert [learning["path"] for learning in learnings] == ["pkg/lib.py"]
|
||||
assert json.loads((run / "calibration" / "false_positive_learnings.json").read_text())["learnings"] == learnings
|
||||
assert _ledger_of(run) == {
|
||||
"tree_digest": tree_digest(repo, runs),
|
||||
"learnings_read": {"tree": 0, "digest": 0},
|
||||
"digest_ledger": "written",
|
||||
}
|
||||
assert (
|
||||
"The false-positive ledger in the analysed tree could not be written, so this scan's learnings are kept in "
|
||||
f"the ledger of this tree's digest under the runs directory, at `{kept}`, and the next scan of the same "
|
||||
"bytes reads them."
|
||||
) in (run / "report.md").read_text()
|
||||
assert _tree(repo) == tree_before
|
||||
|
||||
|
||||
def test_the_next_scan_of_the_same_bytes_reads_the_ledger_of_its_digest(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
runs = _user_cache(tmp_path, monkeypatch)
|
||||
repo = _target(tmp_path, learns=True)
|
||||
|
||||
with pytest.MonkeyPatch.context() as refusing:
|
||||
_refusing(refusing, (repo / LEDGER).resolve())
|
||||
|
||||
assert _scan(repo) == 0
|
||||
assert "calibrations_applied=0\n" in capsys.readouterr().out
|
||||
kept = _digest_ledger(runs, repo)
|
||||
assert kept.is_file()
|
||||
earlier = set(runs.iterdir())
|
||||
|
||||
assert _scan(repo) == 0
|
||||
|
||||
assert "calibrations_applied=1\n" in capsys.readouterr().out
|
||||
(run,) = set(runs.iterdir()) - earlier
|
||||
assert _ledger_of(run)["learnings_read"] == {"tree": 0, "digest": 1}
|
||||
assert _ledger_of(run)["digest_ledger"] == "left as it was"
|
||||
assert [path.name for path in (runs / DIGEST_LEDGERS).iterdir()] == [kept.name]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("learns_again", [True, False])
|
||||
def test_the_first_scan_that_can_write_the_tree_carries_the_entries_into_it_and_removes_the_file(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], learns_again: bool
|
||||
) -> None:
|
||||
"""By the decision of 2026-11-28, also when that scan learns nothing new: the entries are new to the tree."""
|
||||
runs = _user_cache(tmp_path, monkeypatch)
|
||||
repo = _target(tmp_path, learns=True)
|
||||
ledger = (repo / LEDGER).resolve()
|
||||
|
||||
with pytest.MonkeyPatch.context() as refusing:
|
||||
_refusing(refusing, ledger)
|
||||
assert _scan(repo) == 0
|
||||
|
||||
kept = _digest_ledger(runs, repo)
|
||||
assert kept.is_file()
|
||||
if not learns_again:
|
||||
monkeypatch.setattr(cli, "learnings_from_verifications", lambda findings, verifications: [])
|
||||
earlier = set(runs.iterdir())
|
||||
|
||||
assert _scan(repo) == 0
|
||||
|
||||
(run,) = set(runs.iterdir()) - earlier
|
||||
assert [learning["path"] for learning in json.loads(ledger.read_text())["learnings"]] == ["pkg/lib.py"]
|
||||
assert not kept.exists()
|
||||
assert _ledger_of(run)["digest_ledger"] == "removed"
|
||||
assert "ledger_not_written" not in _reasons(run)
|
||||
|
||||
|
||||
def test_a_ledger_of_a_digest_is_removed_once_the_tree_holds_its_entries(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
runs = _user_cache(tmp_path, monkeypatch)
|
||||
repo = _target(tmp_path, learns=True)
|
||||
ledger = (repo / LEDGER).resolve()
|
||||
|
||||
with pytest.MonkeyPatch.context() as refusing:
|
||||
_refusing(refusing, ledger)
|
||||
assert _scan(repo) == 0
|
||||
|
||||
kept = _digest_ledger(runs, repo)
|
||||
# The entries reach the tree's ledger by hand, as a commit could bring them. `.openultrasast` is no part of the
|
||||
# digest, so this is still the same tree to a scan.
|
||||
ledger.parent.mkdir(parents=True)
|
||||
shutil.copyfile(kept, ledger)
|
||||
stamp = ledger.stat().st_mtime_ns
|
||||
earlier = set(runs.iterdir())
|
||||
|
||||
assert _scan(repo) == 0
|
||||
|
||||
(run,) = set(runs.iterdir()) - earlier
|
||||
assert not kept.exists()
|
||||
assert ledger.is_file()
|
||||
assert ledger.stat().st_mtime_ns == stamp
|
||||
assert _ledger_of(run)["digest_ledger"] == "removed"
|
||||
|
||||
|
||||
def test_an_entry_that_is_in_both_ledgers_is_taken_from_the_trees(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""The tree's ledger is the file a user can read, edit and commit: where the two disagree, its version is applied."""
|
||||
runs = _user_cache(tmp_path, monkeypatch)
|
||||
repo = _target(tmp_path)
|
||||
tree_entry = FalsePositiveLearning(
|
||||
"py-eval:pkg/lib.py:2", "pkg/lib.py", "xss", FalsePositiveReason.UNREACHABLE_PATH, "the tree's evidence", "pkg"
|
||||
)
|
||||
tree_ledger = repo / LEDGER
|
||||
write_false_positive_learnings([tree_entry], tree_ledger)
|
||||
write_false_positive_learnings([replace(tree_entry, evidence="the digest's evidence")], _digest_ledger(runs, repo))
|
||||
|
||||
tree_learnings, ledger, prior_learnings = cli._read_ledgers(tree_ledger.resolve(), runs, tree_digest(repo, runs))
|
||||
|
||||
assert (ledger.found, [learning.evidence for learning in tree_learnings]) == ("read", ["the tree's evidence"])
|
||||
assert [learning.evidence for learning in prior_learnings] == ["the tree's evidence"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("content", ["not a ledger\n", "[" * 5000 + "]" * 5000], ids=["not a ledger", "nested too deep"])
|
||||
def test_a_ledger_of_a_digest_that_is_not_a_ledger_does_not_stop_the_scan(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], content: str
|
||||
) -> None:
|
||||
"""Whatever a hand or another tool left there: taken for empty, said unreadable, and gone."""
|
||||
runs = _user_cache(tmp_path, monkeypatch)
|
||||
repo = _target(tmp_path, learns=True)
|
||||
ledger = (repo / LEDGER).resolve()
|
||||
with pytest.MonkeyPatch.context() as refusing:
|
||||
_refusing(refusing, ledger)
|
||||
assert _scan(repo) == 0
|
||||
kept = _digest_ledger(runs, repo)
|
||||
kept.write_text(content)
|
||||
earlier = set(runs.iterdir())
|
||||
|
||||
assert _scan(repo) == 0
|
||||
|
||||
(run,) = set(runs.iterdir()) - earlier
|
||||
assert _ledger_of(run)["digest_ledger"] == "unreadable"
|
||||
assert not kept.exists()
|
||||
assert [learning["path"] for learning in json.loads(ledger.read_text())["learnings"]] == ["pkg/lib.py"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure", ["write", "removal"])
|
||||
def test_a_ledger_of_a_digest_that_cannot_be_written_or_removed_is_said_once_and_costs_the_scan_nothing(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], failure: str
|
||||
) -> None:
|
||||
runs = _user_cache(tmp_path, monkeypatch)
|
||||
repo = _target(tmp_path, learns=True)
|
||||
ledger = (repo / LEDGER).resolve()
|
||||
rename = os.replace
|
||||
unlink = Path.unlink
|
||||
|
||||
def refusing_rename(source, target): # type: ignore[no-untyped-def]
|
||||
if Path(target) == kept:
|
||||
raise PermissionError(errno.EACCES, "Permission denied", str(target))
|
||||
return rename(source, target)
|
||||
|
||||
def refusing_unlink(path, *args, **kwargs): # type: ignore[no-untyped-def]
|
||||
if path == kept:
|
||||
raise PermissionError(errno.EACCES, "Permission denied", str(path))
|
||||
return unlink(path, *args, **kwargs)
|
||||
|
||||
kept = _digest_ledger(runs, repo)
|
||||
with pytest.MonkeyPatch.context() as refusing:
|
||||
_refusing(refusing, ledger)
|
||||
if failure == "write":
|
||||
refusing.setattr(digest_ledger.os, "replace", refusing_rename)
|
||||
assert _scan(repo) == 0
|
||||
if failure == "write":
|
||||
(run,) = [path for path in runs.iterdir() if path.name != DIGEST_LEDGERS]
|
||||
assert not kept.exists()
|
||||
assert "kept only in this run directory" in (run / "report.md").read_text()
|
||||
else:
|
||||
assert kept.is_file()
|
||||
earlier = set(runs.iterdir())
|
||||
monkeypatch.setattr(Path, "unlink", refusing_unlink)
|
||||
|
||||
assert _scan(repo) == 0
|
||||
|
||||
(run,) = set(runs.iterdir()) - earlier
|
||||
assert kept.is_file()
|
||||
assert ledger.is_file()
|
||||
|
||||
assert _ledger_of(run)["digest_ledger"] == "failed"
|
||||
assert (
|
||||
capsys.readouterr().out.count(
|
||||
f"notice: the ledger of this tree's digest could not be written or removed: [Errno 13] Permission denied: '{kept}'"
|
||||
)
|
||||
== 1
|
||||
)
|
||||
|
||||
|
||||
def test_the_scan_prints_the_run_directory_once(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
"""The key of the ledger a scan keeps for a tree it could not write into: a digest of the tree's files
|
||||
(contributor-scan, the design note of 2026-11-27 approved on 2026-11-28)."""
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from openultrasast.tree_digest import tree_digest
|
||||
|
||||
|
||||
def _write(root: Path, relative: str, content: bytes) -> Path:
|
||||
path = root / relative
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(content)
|
||||
return path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tree(tmp_path: Path) -> Path:
|
||||
"""Two source files, a file under an ignored directory and a link to a source file."""
|
||||
root = tmp_path / "tree"
|
||||
_write(root, "app.py", b"print('hello')\n")
|
||||
_write(root, "pkg/lib.py", b"def helper(x):\n return eval(x)\n")
|
||||
_write(root, ".git/config", b"[core]\n")
|
||||
_write(root, "node_modules/x/index.js", b"module.exports = 1;\n")
|
||||
(root / "link.py").symlink_to("app.py")
|
||||
return root
|
||||
|
||||
|
||||
def test_the_same_bytes_give_the_same_digest_and_one_changed_byte_another(tmp_path: Path, tree: Path) -> None:
|
||||
twin = tmp_path / "twin"
|
||||
shutil.copytree(tree, twin, symlinks=True)
|
||||
digest = tree_digest(tree)
|
||||
|
||||
assert tree_digest(twin) == digest
|
||||
assert len(digest) == 64
|
||||
int(digest, 16)
|
||||
|
||||
_write(twin, "pkg/lib.py", b"def helper(x):\n return eval(x) \n")
|
||||
|
||||
assert tree_digest(twin) != digest
|
||||
|
||||
|
||||
def test_links_and_the_ignored_directories_are_left_out(tmp_path: Path, tree: Path) -> None:
|
||||
"""The ledger lives under `.openultrasast`: a ledger must not change its own key."""
|
||||
before = tree_digest(tree)
|
||||
|
||||
(tree / "link.py").unlink()
|
||||
_write(tree, "node_modules/y/index.js", b"module.exports = 2;\n")
|
||||
_write(tree, "__pycache__/app.cpython-311.pyc", b"\x00")
|
||||
_write(tree, ".openultrasast/calibration/false_positive_learnings.json", b'{"learnings": []}\n')
|
||||
|
||||
assert tree_digest(tree) == before
|
||||
|
||||
|
||||
def test_the_runs_directory_is_left_out_whichever_way_it_is_reached(tmp_path: Path, tree: Path) -> None:
|
||||
runs = _write(tree / "cache" / "runs" / "20260101T000000Z-00000000", "manifest.json", b"{}").parents[1]
|
||||
(tree / "alias").symlink_to(runs, target_is_directory=True)
|
||||
before = tree_digest(tree, runs)
|
||||
|
||||
_write(runs / "20260102T000000Z-00000000", "manifest.json", b"{}")
|
||||
|
||||
assert tree_digest(tree, runs) == before
|
||||
assert tree_digest(tree) != before
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.geteuid() == 0, reason="root lists every directory and reads every file")
|
||||
def test_a_file_that_cannot_be_read_and_a_directory_that_cannot_be_listed_are_named_not_skipped(tmp_path: Path, tree: Path) -> None:
|
||||
before = tree_digest(tree)
|
||||
secret = _write(tree, "pkg/secret.py", b"x = 1\n")
|
||||
with_secret = tree_digest(tree)
|
||||
secret.chmod(0)
|
||||
unreadable = tree_digest(tree)
|
||||
hidden = _write(tree / "hidden", "a.py", b"a = 1\n").parent
|
||||
hidden.chmod(0)
|
||||
|
||||
assert (with_secret, unreadable) != (before, before)
|
||||
assert tree_digest(tree) not in (before, with_secret, unreadable)
|
||||
|
||||
|
||||
def test_a_change_of_mode_leaves_the_digest_and_a_change_of_line_endings_gives_another(tmp_path: Path, tree: Path) -> None:
|
||||
before = tree_digest(tree)
|
||||
|
||||
(tree / "app.py").chmod(0o600)
|
||||
|
||||
assert tree_digest(tree) == before
|
||||
|
||||
_write(tree, "app.py", b"print('hello')\r\n")
|
||||
|
||||
assert tree_digest(tree) != before
|
||||
|
||||
|
||||
def test_a_name_cannot_spell_two_entries(tmp_path: Path) -> None:
|
||||
"""One file whose name holds what would be the first entry of a two-file tree, and the next path."""
|
||||
two = tmp_path / "two"
|
||||
_write(two, "a", b"one")
|
||||
_write(two, "b", b"two")
|
||||
one = tmp_path / "one"
|
||||
_write(one, f"a\t{hashlib.sha256(b'one').hexdigest()}\nb", b"two")
|
||||
|
||||
assert tree_digest(one) != tree_digest(two)
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.geteuid() == 0, reason="root searches every directory")
|
||||
def test_a_directory_that_can_be_listed_but_not_searched_stops_the_digest(tmp_path: Path, tree: Path) -> None:
|
||||
"""As the scan's own reading of the tree stops: a digest that skipped it would key a ledger to a tree
|
||||
nobody scanned."""
|
||||
locked = _write(tree / "locked", "a.py", b"a = 1\n").parent
|
||||
locked.chmod(0o444)
|
||||
|
||||
with pytest.raises(PermissionError):
|
||||
tree_digest(tree)
|
||||
Reference in New Issue
Block a user