Skip to content

Preflight every run-directory descendant against the exact allowed set - #1189

Merged
brettheap merged 4 commits into
mainfrom
fix/1186-run-dir-descendant-preflight
Sep 27, 2026
Merged

brettheap merged 4 commits into
mainfrom
fix/1186-run-dir-descendant-preflight

Conversation

@brettheap

@brettheap brettheap commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Lane: openxfactory-1

DRAFT, authorized by Brett Heap on 2026-09-27 ("go ahead with both follow-up drafts"); lands only on his word, and only the coordinator lands it.

OPEN QUESTION before landing (not fixed in this PR)

Copilot's last round (thread on catalog.py:925, resolved by decline, not by fix) found that _is_writer_temp's basename-plus-is_file() predicate is a shape match, not proof of ownership: a foreign regular file deliberately or coincidentally named exactly like a plausible writer temp (e.g. alpha.yaml.z9k2p7.tmp) still passes it and is silently tolerated forever. Closing that for real needs a structural fix -- moving _write_rendered's tempfile.mkstemp staging outside the tree _refuse_foreign_descendants/_refuse_links_inside scan -- which touches _write_rendered, shared by every write in this module (both of write_snapshot's call sites), not something scoped to write_run's preflight. That is outside this PR's declared ownership, so it was escalated rather than fixed here or silently declined. Decision needed: fix it in a follow-up (the same way this issue was itself raised as a follow-up to #1175), accept the residual gap as consistent with this module's stated non-adversarial threat model (accidental/crash artifacts, per _refuse_foreign_node's own docstring), or something else.

For #1186, a follow-up to #1175 (squash c5e2614). Copilot's review thread on that PR (catalog.py:1161) found that write_run's stranger preflight only ever saw paths _snapshot_files yields, which filters to *.yaml -- so a non-YAML file (notes.txt), a *.yaml.bak-style file, or a stranger subdirectory (empty, or holding only non-YAML content) inside an existing run directory was never checked against the run's recorded content, and the run-identity hash never saw it. That was declined on #1175 as out of scope for that landing and raised as this follow-up.

Change

_refuse_foreign_descendants walks every descendant of the run directory -- file or subdirectory, at any depth -- and refuses anything outside the exact allowed set (run.yaml plus the repository-snapshot paths the run records), before the first write or claim, reported the same way (CatalogError, "does not record") as the existing stranger-snapshot refusal. write_run's preflight now calls it in place of the *.yaml-filtered strangers check. _snapshot_files itself is unchanged and still serves its other callers (_load_run, _load_run_bytes) exactly as before.

This PR does not touch _iter_runs or its callers (#1187, in flight in parallel, makes that shared scan link-safe).

Review round 2 (Copilot + Codex, at head e3778f6a)

Both threads answered by fixing, not declining:

  • Copilot: os.walk silently swallows a directory it cannot enumerate when onerror is omitted, so a foreign descendant hidden inside an unreadable subdirectory of an otherwise legitimate, allowed ancestor would never be seen at all. _refuse_foreign_descendants now passes an onerror callback that raises CatalogError ("could not be fully enumerated"), failing closed instead of silently passing.
  • Codex (P1): _write_rendered's tempfile.mkstemp deliberately creates "<final-name>.<random>.tmp" inside the run directory, so an identical writer racing this one (caught between its own mkstemp and os.replace), or a hard crash that orphaned one before _write_rendered's own cleanup could run, was mistaken for a foreign descendant -- turning a normally harmless race, or a normally healable crash, into a permanent refusal on every retry. _is_writer_temp now excludes exactly that shape from the refusal; neither the run-identity hash nor _snapshot_files ever reads a .tmp file, so this does not weaken what the run records.

Two new tests for the temp-file fix (a concurrent writer's in-flight temp, and a crash-orphaned one -- both now tolerated) and one for the enumeration fix (an unreadable allowed-ancestor subdirectory -- now refused instead of silently passing). All three confirmed to fail against the commit review round 2 replaced and pass on the current head.

Review round 2, continued (Copilot, at head eda41227)

Copilot found the temp-tolerance fix itself too loose: _is_writer_temp's first cut accepted a same-directory "<final-name>.tmp" with NO random component (mkstemp never omits one, so that exact string can only be a stranger), and any non-symlink special node (a FIFO, for instance) sharing a temp-shaped name (mkstemp only ever creates a plain file). Both are now required: a non-empty random component between the prefix and .tmp, and node.is_file() (safe once _refuse_links_inside has already refused every symlink in the tree). One new test, two cases, both confirmed to fail against the commit this round replaced and pass on the current head.

Tests

Five new tests in tests/doc-health/test_catalog.py:

  • a non-YAML stranger (top-level and nested inside a slash-separated repository's subdirectory)
  • a *.yaml.bak-suffixed stranger
  • an empty stranger subdirectory
  • a stranger subdirectory holding a non-YAML file
  • a symlinked stranger -- already refused pre-existing by _refuse_links_inside (Address each catalog run by its content, so one run id can never name two snapshots (for opensoft/xFactory#519) #1175 rounds 6 and 9), so this one does NOT newly fail on main; it is kept as an interaction guard proving the new check does not loosen or reorder that existing guarantee
  • a clean run that still passes (fresh, and a repeat over an already-recorded nested-repository run)

Confirmed each of the first four scenarios (plus the symlinked one, for the pre-existing reason above) raises on current main and passes on this branch.

Verification

  • tests/doc-health/test_catalog.py (56 tests, including the 8 new ones) plus test_catalog_dispatch.py, test_cataloger.py, test_catalog_baseline.py, test_document_catalog.py, test_families.py, test_families_real_lines.py, test_family_enumeration.py, test_suite.py, test_lifecycle_scan_set.py: 379 passed.
  • Full tests/doc-health/ suite: 1987 passed, 1 skipped, 7 failed -- all 7 failures are pre-existing and unrelated (carved_reach.CarveReachUnavailable, a missing openDox/openXdox submodule checkout in this clone); confirmed identical on unmodified main.
  • python3 scripts/validate-document-catalog.py --strict: 0 errors, 0 warnings.
  • python3 scripts/validate-openspec-cli-pin.py --all: 110 passed, 1 failure (the accepted add-chain-attestation exception), PIN held, rc 0.
  • The aggregation's real recorded runs: a fresh read-only clone of opensoft/xFactory (its health/document-catalog/ data is committed directly in that repo, not inside a submodule, so no submodule init was needed) -- validate-document-catalog.py against it: 237 real document-cataloging artifacts checked, 0 errors, 0 warnings. Directly re-checked all 31 real recorded run directories against the new preflight (read-only, no writes), re-run after review round 2: all 31 pass with no foreign descendant and no symlink.

🤖 Generated with Claude Code

write_run's stranger preflight only ever saw paths _snapshot_files
yields, which filters to *.yaml -- so a non-YAML file (notes.txt), a
*.yaml.bak-style file, or a stranger subdirectory (empty, or holding
only non-YAML content) inside an existing run directory was never
checked against the run's recorded content, and the run-identity hash
never saw it.

_refuse_foreign_descendants walks every descendant of the run
directory -- file or subdirectory, at any depth -- and refuses
anything outside the exact allowed set (run.yaml plus the
repository-snapshot paths the run records) before the first write or
claim, reported the same way (CatalogError, "does not record") as the
existing stranger-snapshot refusal. write_run's preflight now calls it
in place of the *.yaml-filtered strangers check; _snapshot_files
itself is unchanged, and still serves its other callers (_load_run,
_load_run_bytes) exactly as before.

Five new tests: a non-YAML stranger (top-level and nested), a
*.yaml.bak-suffixed stranger, an empty stranger subdirectory, a
stranger subdirectory holding a non-YAML file, a symlinked stranger
(already refused pre-existing by _refuse_links_inside -- kept as an
interaction guard, not new coverage), and a clean run (fresh, and a
repeat over an already-recorded nested-repository run) that still
passes. Verified against the aggregation's real recorded runs (31
directories, 237 real document-cataloging artifacts): every one still
passes the new preflight and scripts/validate-document-catalog.py.

For #1186, a follow-up to #1175 (squash
c5e2614), raised by Copilot's review thread on catalog.py:1161 and
declined there as out of scope for that landing.

Lane: openxfactory-1
Co-Authored-By: Claude Sonnet 5 <[email protected]>
Copilot AI lite review requested due to automatic review settings September 27, 2026 18:09
@sourcery-ai

sourcery-ai Bot commented Sep 27, 2026

Copy link
Copy Markdown

Reviewer's Guide

The PR hardens write-run preflight by validating every descendant against the exact set of run metadata and recorded snapshot paths, preventing unrecorded files or directories from bypassing run-identity checks while preserving symlink handling and existing snapshot-file behavior.

Flow diagram for exact run-directory preflight

flowchart TD
    A[write_run] --> B[_refuse_unsafe_run_paths]
    B --> C{run_dir exists}
    C -- no --> D[_recorded]
    C -- yes --> E[_refuse_links_inside]
    E --> F[_refuse_foreign_descendants]
    F --> G{Every descendant is allowed}
    G -- no --> H[CatalogError: path does not record]
    G -- yes --> D
    D --> I[Write recorded snapshots]
Loading

Flow diagram for allowed run-directory descendants

flowchart TD
    A[run_dir] --> B[run.yaml]
    A --> C[Recorded snapshot paths]
    C --> D[Allowed ancestor directories]
    E[Foreign file or directory at any depth] --> F[CatalogError]
    G[Symlink anywhere] --> H[_refuse_links_inside]
    H --> F
Loading

File-Level Changes

Change Details Files
Replace the YAML-filtered stranger check with an exact descendant allowlist preflight.
  • Walk every file and directory below the run directory at arbitrary depth.
  • Allow only run.yaml, recorded snapshot files, and ancestor directories required by nested repository paths.
  • Reject unrecorded files, suffixed metadata files, empty directories, and non-YAML stranger subtrees before any write or sequence claim.
  • Preserve the existing symlink refusal as the preceding guard and leave _snapshot_files unchanged for its other callers.
scripts/doc_health/catalog.py
Add regression and compatibility coverage for complete run-directory validation.
  • Cover top-level and nested non-YAML strangers, yaml.bak files, empty and populated stranger directories.
  • Verify symlink rejection remains ordered through the existing guard.
  • Verify fresh runs and repeated writes with slash-separated repository paths still succeed without mutation.
tests/doc-health/test_catalog.py

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@brettheap

Copy link
Copy Markdown
Contributor Author

@codex review

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Two moderate issues remain unresolved in the descendant walk and interrupted-write recovery.

Review effort: Lite
Findings: 1 Medium severity

Open (1)
What changed in this PR

Hardens catalog run preflight by rejecting unrecorded files and directories within existing runs.

Changes:

  • Adds exact descendant allowlisting.
  • Integrates validation into write_run.
  • Adds regression tests for foreign descendants and clean reruns.

Review findings: Two moderate issues remain: directory-enumeration errors are not handled fail-closed, and interrupted temporary writes can block crash recovery.

File Description
tests/​doc-health/​test_catalog.py Adds coverage for foreign descendants and clean runs.
scripts/​doc_health/​catalog.py Implements descendant validation and integrates it into write_run.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread scripts/doc_health/catalog.py Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e3778f6a11

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread scripts/doc_health/catalog.py Resolved
Two findings from review on PR #1189 (for #1186):

Copilot: os.walk silently swallows a directory it cannot enumerate
when onerror is omitted, so a foreign descendant hidden inside an
unreadable subdirectory of an otherwise legitimate, allowed ancestor
would never be seen at all -- the preflight would complete over a
subtree it never actually verified. _refuse_foreign_descendants now
passes an onerror callback that raises CatalogError, failing closed
instead.

Codex (P1): _write_rendered's tempfile.mkstemp deliberately creates
"<final-name>.<random>.tmp" inside the run directory. An identical
writer racing this one -- caught between its own mkstemp and
os.replace when this preflight runs, the overlap
test_overlapping_identical_runs_both_complete already relies on -- or
a hard crash that orphaned one before write_rendered's own cleanup
could run, was mistaken for a foreign descendant, turning a normally
harmless race or a normally healable crash into a permanent refusal on
every retry. _is_writer_temp now excludes exactly that shape (a
same-directory sibling of an allowed file, named "<that file's
name>.<anything>.tmp") from the refusal; neither the run-identity hash
nor _snapshot_files ever reads a .tmp file, so this does not weaken
what the run records.

Four new tests, each proven to fail against the prior commit and pass
on this one: a concurrent writer's in-flight temp and a crash-orphaned
one (both tolerated), and an unreadable allowed-ancestor subdirectory
(now refused, "could not be fully enumerated", instead of silently
passing).

Lane: openxfactory-1
Co-Authored-By: Claude Sonnet 5 <[email protected]>
Copilot AI review requested due to automatic review settings September 27, 2026 19:11

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

The temporary-file exemption must require a non-empty random suffix and a regular-file check.

Review effort: Lite
Findings: 1 Medium severity

Open (1)
Resolved since last review (1)

Comment thread scripts/doc_health/catalog.py Resolved
Review round 2 continued (Copilot, PR #1189 for #1186, after the
first onerror/temp-tolerance round): _is_writer_temp's first cut
accepted "<final-name>.tmp" with no random component at all, and any
non-symlink special node (a FIFO, for instance) sharing a temp-shaped
name. mkstemp never omits its random component and never creates
anything but a plain file, so both shapes can only be a stranger
deliberately or accidentally named to resemble a temp -- outside the
exact allowed set, and still refused now: the random component between
the prefix and ".tmp" must be non-empty, and the node must satisfy
is_file() (safe once _refuse_links_inside has already refused every
symlink in the tree).

One new test, two cases, each proven to fail against the prior commit
and pass on this one: a same-directory "alpha.yaml.tmp" with no random
part, and a FIFO named "alpha.yaml.z9k2p7.tmp".

Lane: openxfactory-1
Co-Authored-By: Claude Sonnet 5 <[email protected]>
Copilot AI review requested due to automatic review settings September 27, 2026 19:33

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

The temporary-file exemption can accept arbitrary unrecorded regular files matching the temp naming pattern.

Review effort: Lite
Findings: 1 High severity

Open (1)
Resolved since last review (1)

Comment thread scripts/doc_health/catalog.py Resolved
Copilot AI review requested due to automatic review settings September 27, 2026 19:57

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🔵 Needs a closer look

Handle listed entries that disappear during concurrent validation without weakening fail-closed enumeration.

Review effort: Lite
Findings: None

Resolved since last review (1)

@sonarqubecloud

Copy link
Copy Markdown

@brettheap
brettheap marked this pull request as ready for review September 27, 2026 20:22

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry @brettheap, you've used your own review budget of 250,000 diff characters for the last 7 days.

You can request another review in 1 day and 1 hour by commenting @sourcery-ai review. Upgrade to get a review now.

brettheap added a commit that referenced this pull request Sep 29, 2026
…dmit no temp-shaped sibling (for #1196) (#1199)

* Stage the catalog's rendered temps outside the scanned run tree (for #1196)

_write_rendered staged every render with mkstemp beside its target, that
is inside the run directory write_run's preflight walks, so the preflight
admitted any regular file named "<final-name>.<random>.tmp" beside an
allowed file (_is_writer_temp), and a stranger merely named that way
passed too: the residual Copilot's last round on PR #1189 left open, as a
follow-up to #1186.

Every write is now staged in health/document-catalog/runs/.staging/
(catalog.STAGING_DIR): beside the day directories, so on the run tree's
own filesystem; dot-named like .sequence, so _iter_runs skips it by name;
and outside every run directory, so no preflight walk meets it.
_write_rendered(root, path, text) re-checks the staging directory when it
stages (never a symlink, never a non-directory), refuses before staging
anything when the staging directory is on another device than the
target's directory, and keeps the unique per-invocation mkstemp name, the
write-in-full-then-close-then-os.replace order and mkstemp's 0600 mode.
_refuse_unsafe_run_paths checks the staging directory before any claim.
The temp-shape admission is deleted: the preflight admits no .tmp sibling
at all.

A temp a crash leaves in the staging directory is ignored, never swept:
nothing tells it apart from a concurrent writer's temp in flight, whose
rename a sweep would break, and an age test would read the wall clock. It
is never read, so it is never admitted as a snapshot, and the
document-catalog family reports it as immutable-path.

Tests: the test that pinned the admission becomes its refusal (a
temp-shaped stranger beside a snapshot, a nested snapshot, run.yaml, and
a partial run). New tests pin the staged temp's place at every rename
under the publish-time interleave of Codex's P1 on PR #1189, stale staging
content ignored and never admitted, a foreign staging directory refused
before any write, _write_rendered's atomic-rename terms, and the family's
report of a stale staged temp.

Lane: openxfactory-1
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Refuse a cross-filesystem run in the preflight, before any claim (for #1196)

PR #1199 review (Copilot, catalog.py:691): _write_rendered's
same-filesystem check ran only when a write was staged, after
write_snapshot had claimed a sequence and made the run's directories, so
a staging directory on another filesystem than the run left an orphaned
claim and a partial run behind, although that refusal depends on the
layout alone.

_refuse_unsafe_run_paths now checks every directory the run publishes a
file into against the staging directory before anything is claimed or
made, counting a directory not made yet as its nearest existing
ancestor's (_nearest_existing), where it would be made. _write_rendered
keeps its own check before anything is staged, for a directory mounted
in between. Both refusals share _cross_filesystem_refusal, which names
tree-relative paths; _filesystem_id is the one st_dev read.

New test: a staging, day or crashed run directory on another filesystem
(a mount simulated through _filesystem_id) is refused by write_run and
write_snapshot with no claim and nothing made; a run tree mounted whole
still records. At the reviewed head 0ba9078 the same layout left claim
000001 and a run directory behind.

Lane: openxfactory-1
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Tell two mounts of one filesystem apart before any claim (for #1196)

PR #1199 review round 2 (Copilot, catalog.py:650): an st_dev match does
not prove os.replace can cross two directories. rename(2) fails with
EXDEV across mount points even when one filesystem is mounted at both,
so two bind mounts of one filesystem, which share an st_dev, passed the
preflight, a sequence was claimed, and only the later publish failed.

_rename_compatible (was _same_filesystem) now requires one st_dev
(_device_id) AND one mount: _mount_id reads Linux's mnt_id from
/proc/self/fdinfo through an O_PATH descriptor, the identity rename(2)
compares, and the check falls back to st_dev alone where the platform
gives no mount id. Both probes follow links, so a directory made below a
host-owned linked ancestor of the catalog root counts on its target's
mount; the writer has refused every link from the root down before this
runs. The refusal (_cross_mount_refusal) still names tree-relative paths
only.

Tests: the preflight test covers both seams, another filesystem and a
bind mount of the same one, at the staging, day and crashed run
directory, each refused by write_run and write_snapshot with no claim and
nothing made, and a tree mounted whole still records. The atomic-rename
test asserts the mount id is really read on Linux.

Lane: openxfactory-1
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Fsync each staged write before its rename publishes it (for #1196)

PR #1199 review (Copilot, round 3 overview): #1196 keeps the
fsync-then-rename order, but _write_rendered has never fsynced. Closing
the temp flushes Python's buffer and makes nothing durable, so a power
loss after the rename could leave a published catalog record whose
bytes never reached the disk.

The temp is now flushed and fsynced through its own descriptor, complete,
before its handle closes and os.replace publishes it. The directory is
not fsynced: a rename a power loss undoes leaves the record absent, the
crash window every retry already heals, never a torn record. Measured:
test_catalog plus test_document_catalog go from about 6.2 s to 8.0 s.

New test: the temp's own descriptor is fsynced once, holding the complete
bytes, strictly before the one os.replace; against the previous head it
fails with the replace as the only event.

Lane: openxfactory-1
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Make each publish, and the run's claim, durable before the next (for #1196)

PR #1199 review round 4 (Copilot, catalog.py:774): fsyncing the temp
made its bytes durable but not the rename, so a power loss could undo a
snapshot's rename while keeping the run.yaml published after it, leaving
a recorded run holding no snapshot, against write_snapshot's crash-safety
promise.

_write_rendered now fsyncs the directory each file lands in, and every
directory from it up to the runs directory, deepest first
(_fsync_publish), before it returns and so before the run's next file is
staged. That also makes a slash-separated repository's directory entry
inside the run durable, and a new day directory's entry in the runs
directory. Nothing above the runs directory is synced: losing one of
those entries loses the runs directory whole, and an absent run is what
a retry records. By the same reasoning _claim_sequence fsyncs its claim
and its entry before anything of the run is written, so no durable
run.yaml can name a claim a power loss took (_recorded would then refuse
the run for good). Directory fsync is POSIX-only; elsewhere
_fsync_directory does nothing.

The ordering test now runs a whole write_run with a nested repository
and pins every durable step in order: the claim, then for each of the
three files its complete temp, its rename, and its directory chain up to
the runs directory. Against the previous head it fails, missing the
claim and directory syncs. Measured: test_catalog plus
test_document_catalog take about 10.6 s (8.3 s with the file fsync only).

Lane: openxfactory-1
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Accept another writer's publish only once it is durable (for #1196)

PR #1199 review (Copilot, catalog.py:816 at caf0c02): os.replace makes
a file visible before its writer's directory sync runs, so an identical
writer in that window could accept the file as published without
syncing it, then publish a run.yaml over it or report success. Were the
first writer to die before its sync, a power loss could still take what
the second had reported recorded; sharpest for a slash-separated
repository, whose directory no run.yaml sync covers.

write_snapshot now syncs the chain through _fsync_publish on every path
that accepts a file it did not publish itself: the completed no-op
(target matches, run recorded), the complete-run no-op (the run
addresses itself and the target has landed), the mid-write re-check
(another writer published the target; synced before run.yaml names it),
and a run found recorded after this call claimed (another writer's
run.yaml; synced before this reports it recorded). A run already
recorded when the call started is covered by the target step's own chain
sync, which passes through the run directory after run.yaml was seen.

New test test_a_writer_accepts_another_writers_publish_only_once_durable
interleaves writers at the exact moment: case 1 pauses the first writer
right after its nested snapshot's rename and case 2 right after its
run.yaml's rename; in each the second runs to completion and the first
dies before its sync. Case 3 pauses the first after its snapshot's sync
while the second publishes run.yaml and dies right after that rename.
Case 4 lands the missing snapshot of a recorded partial run just as a
call finds the run complete. Against caf0c02 the test fails at case 1;
with each path's fix added in turn it fails at the next case, and
passes with all four.

Lane: openxfactory-1
Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
brettheap added a commit that referenced this pull request Sep 30, 2026
… read a subdirectory, and correct the 3.13 rationale (for #1197) (#1200)

* Fail the write_run preflight closed when the link-refusal walk cannot read a subdirectory, and correct the 3.13 rationale

_refuse_links_inside's own os.walk(run_dir) passed no onerror at all,
unlike its sibling _refuse_foreign_descendants (PR #1189/#1190), which
already fails closed the same way. An unreadable subdirectory was
silently skipped, so a symlink hiding inside one would never be caught.
Both walks now share a new _refuse_unreadable_walk(run_dir) onerror
factory that refuses by name, tree-relative to run_dir.

Also corrects the false "Python 3.13 pathlib swallows every OSError"
rationale left in catalog.py's _own_mode docstring and two
tests/doc-health/test_catalog.py comments: verification against the
actual CPython 3.12/3.13 sources found the _ignore_error errno
allow-list unchanged between versions, so the behaviour those comments
justify (explicit os.lstat + errno handling) is correct, but the
stated reason was wrong. See the PR body for the sources.

For #1197 (re-scoped after the verification pass
found the original Python 3.13 premise false).

Lane: openxfactory-1
Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Describe the documented pathlib contract instead of calling it private

Copilot review (PR #1200): the prior rewrite called the propagate-vs-
absent contract on Path.is_symlink/is_dir/is_file "private" and
"undocumented." Checked against the official docs.python.org/3.13
pathlib page: it explicitly says "False is also returned if the path
doesn't exist or is a broken symlink; other errors (such as permission
errors) are propagated" for all three. That is a documented, public
contract, not an internal detail.

Reworded catalog.py's _own_mode docstring and both corrected
test_catalog.py comments to say so, and reframed the explicit os.lstat
as insulation against a future version changing that contract, not a
correction of today's.

Lane: openxfactory-1
Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Qualify the pathlib contract as documented through 3.13, changed in 3.14

Codex review (PR #1200, P3): the previous wording framed Python 3.14
delegating is_symlink/is_dir/is_file to os.path.islink/isdir/isfile
(which swallow every OSError) as only a hypothetical future change.
Checked the CPython 3.14 branch directly: Lib/pathlib/__init__.py's
Path.is_symlink() already is `return os.path.islink(self)`, and
is_dir()/is_file() call os.path.isdir()/isfile() the same way when
follow_symlinks=True (the default), falling back to a bare
`except (OSError, ValueError): return False` otherwise. The change
has already landed there; it is not speculative.

Reworded catalog.py's _own_mode docstring and both test_catalog.py
comments to say the propagate-vs-absent contract holds through 3.13
and changes in 3.14, and reframed the link-free test's monkeypatch as
pinning to Python 3.14's actual is_symlink body, not a hypothetical
worst case.

Lane: openxfactory-1
Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Classify every listed node by its own lstat, not by Path.is_symlink

Copilot review (PR #1200, high severity): onerror only covers a failed
scandir(top), not a failed per-entry classification. os.walk's own
is_dir() catches an OSError from one listed entry and treats it as a
plain file rather than aborting (same on 3.12, 3.13, and 3.14), and
the entry is still yielded either way. A bare node.is_symlink() would
then misclassify it right along with os.walk: not a directory to
refuse enumerating, and on Python 3.14 not a symlink either, since
is_symlink there swallows the same error (Lib/pathlib/__init__.py:
`return os.path.islink(self)`).

_refuse_links_inside now classifies every listed name with _own_mode,
the same explicit os.lstat primitive _link_inside already uses for
the read-side scan, instead of calling Path.is_symlink directly. A
node _own_mode cannot check (any errno but ENOENT/ENOTDIR) refuses by
name, on every interpreter version alike.

New test test_refuse_links_inside_fails_closed_on_an_unprobeable_entry
injects the OSError from os.lstat itself (the per-node probe), not
from scandir, per the review's ask.

Lane: openxfactory-1
Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Drive both run-directory walks by each node's own lstat, not os.walk's split

Codex (P1) and Copilot, reviewing PR #1200 at 9f3e67b, found the same
fail-open: os.walk splits each listing with DirEntry.is_dir(), and when
that call raises it files the entry as a non-directory and never enters
it, though the entry's own lstat then says it is a directory. Classifying
every listed name by _own_mode did not help while os.walk still chose
what to enter, so a symlink below such a directory stayed hidden and
_refuse_links_inside passed the run.

Both writer walks now go through one explicit walk, _walk_run_tree: it
lists names only (os.scandir, never asked to classify an entry), splits
them by each node's own lstat (_own_mode), enters exactly the nodes that
lstat says are directories, and refuses a link, an unprobeable node or
an unlistable directory as it goes. It is the walk _link_inside already
makes for the read-side scan, raising where that one returns.
_refuse_foreign_descendants uses it too: under os.walk's split a
directory whose is_dir() failed was refused under its own name instead
of the stranger inside it, or, at a recorded file's own path, passed
without being entered. The onerror factory _refuse_unreadable_walk
becomes _unenumerable_refusal, the same tree-relative refusal.

Two regression tests inject the failure on DirEntry.is_dir() alone (a
scandir wrapper), assert the premise that os.walk then never enters the
directory, and assert both walks still refuse by name. Both failed
before this change: the link test did not raise, and the stranger test
named the directory, not the stranger. The os.walk is_dir() handling was
checked in CPython 3.12, 3.13 and 3.14's Lib/os.py.

Lane: openxfactory-1
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Name a node the writer's walk cannot probe by its path in the run

Copilot, reviewing PR #1200 at 89c1d63: the walk raised _own_mode's
refusal unchanged for a node whose lstat fails, and that refusal
interpolates the raw OSError, host-absolute path and all, while the
same walk names a directory it cannot list relative to run_dir.

_walk_run_tree now probes each node with _walked_mode: the explicit
lstat _own_mode makes, with the same errno handling, refusing a symlink
exactly as _own_mode does (_symlink_refusal) but naming a node it cannot
check by its path relative to run_dir, in _unenumerable_refusal's form,
with the OSError kept as the cause. _own_mode itself, which the
read-side scan uses, is unchanged; follow-up #1201 covers its message.

The unprobeable-entry test now nests the denied node, and both
fail-closed tests assert the relative name and the absence of the
absolute path; the extended test failed on the prior head.

Lane: openxfactory-1
Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
brettheap added a commit that referenced this pull request Oct 5, 2026
… with a Python 3.14 CI leg (for #1201) (#1211)

* Fail the write_run preflight closed when the link-refusal walk cannot read a subdirectory, and correct the 3.13 rationale

_refuse_links_inside's own os.walk(run_dir) passed no onerror at all,
unlike its sibling _refuse_foreign_descendants (PR #1189/#1190), which
already fails closed the same way. An unreadable subdirectory was
silently skipped, so a symlink hiding inside one would never be caught.
Both walks now share a new _refuse_unreadable_walk(run_dir) onerror
factory that refuses by name, tree-relative to run_dir.

Also corrects the false "Python 3.13 pathlib swallows every OSError"
rationale left in catalog.py's _own_mode docstring and two
tests/doc-health/test_catalog.py comments: verification against the
actual CPython 3.12/3.13 sources found the _ignore_error errno
allow-list unchanged between versions, so the behaviour those comments
justify (explicit os.lstat + errno handling) is correct, but the
stated reason was wrong. See the PR body for the sources.

For #1197 (re-scoped after the verification pass
found the original Python 3.13 premise false).

Lane: openxfactory-1
Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Describe the documented pathlib contract instead of calling it private

Copilot review (PR #1200): the prior rewrite called the propagate-vs-
absent contract on Path.is_symlink/is_dir/is_file "private" and
"undocumented." Checked against the official docs.python.org/3.13
pathlib page: it explicitly says "False is also returned if the path
doesn't exist or is a broken symlink; other errors (such as permission
errors) are propagated" for all three. That is a documented, public
contract, not an internal detail.

Reworded catalog.py's _own_mode docstring and both corrected
test_catalog.py comments to say so, and reframed the explicit os.lstat
as insulation against a future version changing that contract, not a
correction of today's.

Lane: openxfactory-1
Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Qualify the pathlib contract as documented through 3.13, changed in 3.14

Codex review (PR #1200, P3): the previous wording framed Python 3.14
delegating is_symlink/is_dir/is_file to os.path.islink/isdir/isfile
(which swallow every OSError) as only a hypothetical future change.
Checked the CPython 3.14 branch directly: Lib/pathlib/__init__.py's
Path.is_symlink() already is `return os.path.islink(self)`, and
is_dir()/is_file() call os.path.isdir()/isfile() the same way when
follow_symlinks=True (the default), falling back to a bare
`except (OSError, ValueError): return False` otherwise. The change
has already landed there; it is not speculative.

Reworded catalog.py's _own_mode docstring and both test_catalog.py
comments to say the propagate-vs-absent contract holds through 3.13
and changes in 3.14, and reframed the link-free test's monkeypatch as
pinning to Python 3.14's actual is_symlink body, not a hypothetical
worst case.

Lane: openxfactory-1
Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Classify every listed node by its own lstat, not by Path.is_symlink

Copilot review (PR #1200, high severity): onerror only covers a failed
scandir(top), not a failed per-entry classification. os.walk's own
is_dir() catches an OSError from one listed entry and treats it as a
plain file rather than aborting (same on 3.12, 3.13, and 3.14), and
the entry is still yielded either way. A bare node.is_symlink() would
then misclassify it right along with os.walk: not a directory to
refuse enumerating, and on Python 3.14 not a symlink either, since
is_symlink there swallows the same error (Lib/pathlib/__init__.py:
`return os.path.islink(self)`).

_refuse_links_inside now classifies every listed name with _own_mode,
the same explicit os.lstat primitive _link_inside already uses for
the read-side scan, instead of calling Path.is_symlink directly. A
node _own_mode cannot check (any errno but ENOENT/ENOTDIR) refuses by
name, on every interpreter version alike.

New test test_refuse_links_inside_fails_closed_on_an_unprobeable_entry
injects the OSError from os.lstat itself (the per-node probe), not
from scandir, per the review's ask.

Lane: openxfactory-1
Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Route the six doc-health gates through one strict probe, fs_probe (for #1201)

Python 3.14's Path.exists/is_dir/is_file/is_symlink answer False for a node
whose stat fails for any reason; through 3.13 they raise every OSError that
does not name the node's absence. The #1201 survey found six read-side sites
where that False switches a gate off: the complete-coverage baseline gate
(catalog_baseline.is_baseline_complete and load_baseline), the regression
gate (runner.main's --previous-report), the preflight validators
(preflight._entrypoints and run_preflight), the pin-record ladder
(families._pinned_arm), the aggregation-backlog detector
(ideation_routing._aggregation_backlog_findings) and the catalog-tag guard
(ideation_readiness.load_catalog_tags).

Brett Heap's ruling (1(b), raw OSError) routes them through one leaf module,
scripts/doc_health/fs_probe.py: one explicit os.stat or os.lstat with the
3.12/3.13 allow-list written out (ENOENT, ENOTDIR, EBADF and ELOOP read as
absent, every other errno propagates raw). On 3.12 and 3.13 each site
behaves exactly as before; on 3.14 it stops swallowing. Each site carries a
one-line comment saying why it must refuse.

tests/doc-health/conftest.py gains pathlib_314, which runs a test natively
and again under CPython 3.14's own query bodies (transcribed from
Lib/pathlib/__init__.py), and ProbeDenial, which denies os.stat/os.lstat of
named nodes (chmod denies nothing to root). test_fs_probe.py pins the errno
table and drives each gate with EACCES and EIO under both models; against
the old probes every 3.14-model gate case fails.

Lane: openxfactory-1
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Fail the catalog writer's probes closed, with a tree-relative refusal (for #1201)

The writer's five pathlib probes (_refuse_foreign_node, _occupied,
_read_claims, and the run-directory probes in write_snapshot and write_run)
now classify a node by the one explicit lstat the run scan already used
(_node_mode, beneath _own_mode). A node whose lstat fails for any reason but
FileNotFoundError or NotADirectoryError is a CatalogError, never absent. On
3.14 the no-follow guard used to pass an unstat-able node, a symlink
included, as absent, and an existing immutable record read as "nothing
there".

The refusal (_unchecked_refusal, which _own_mode's refusal now uses too)
names the node by its path under the catalog root and the failure by its
errno name, never str(exc): CI's secret sweeper redacts the host-absolute
path the OSError carries. To name nodes tree-relative, the catalog root is
threaded through _own_mode, _link_inside, _refuse_links_inside,
_refuse_foreign_node, _read_claims, _occupied, _read_record, _holds_exactly,
_load_run_bytes and _addresses_itself (document_catalog's one caller and
the tests' direct calls updated). The symlink and "occupied by a" messages
keep their text.

Tests: every node the preflight classifies, and every probe after it, with
EACCES and EIO, under both pathlib models: a controlled refusal, a redacted
message, and a tree unchanged node for node. Against the pre-change code all
56 of those cases fail. Absence still reads as absent, ELOOP refuses (the
catalog's flavour is stricter than fs_probe's), and no refusal carries the
OSError's own filename or strerror.

Lane: openxfactory-1
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add the doc-health-py314 CI leg, a job of its own beside pytest-suite (for #1201)

Ruling 3 on #1201: .github/workflows/doc-health-py314.yml runs
python -m pytest tests/doc-health on actions/setup-python 3.14, with the
same nested checkout, gitlinks and hash-pinned lock as pytest-suite. It is
a separate job, not a matrix on pytest-suite, because a matrix renames that
required job's check-runs and its pinned context would never report. No
ruleset requires it. test_py314_leg.py pins both halves.

Lane: openxfactory-1
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Refuse a symlink loop in resolve_in_root on every Python version (for #1201)

RULED by Brett Heap, "#1201 3.14: 1(a)". Python 3.12's non-strict
Path.resolve() stat-ed its own result and raised RuntimeError on ELOOP,
which resolve_in_root turned into its UNRESOLVABLE refusal. Python 3.13
dropped that check (its resolve() is a bare os.path.realpath), so on 3.13
and 3.14 a looping pin record came back resolved and the pinned-target arm
reported it as merely absent. The new doc-health-py314 leg measured this:
test_a_self_looping_symlink_record_cannot_be_resolved_and_reads_nothing
failed on 3.14.7, on this branch and on its unchanged base alike.

scripts/pin_containment.py now asks the filesystem itself: after resolving,
_is_symlink_loop stats the root and the target and refuses on ELOOP (or
Windows' ERROR_CANT_RESOLVE_FILENAME), the question 3.12 asked, with no
version test. Any other stat failure is left to the caller, as 3.12 left
it. The refusal's reason names no path.

Tests: the existing loop test is unchanged and passes on 3.12 and 3.14. New:
a self-loop and a two-link cycle under CPython 3.13's own resolve body
(monkeypatched onto Path on any interpreter), same finding byte for byte and
nothing read; and a loop in an intermediate directory, called directly,
under both resolves. Without the fix the three 3.13-model cases fail.

Lane: openxfactory-1
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Refuse a looping root in boundary_dir on every Python version too (for #1201)

The same ruling as the previous commit, "#1201 3.14: 1(a)", applied to the
other resolve in scripts/pin_containment.py. boundary_dir resolves the root
before it checks the contracts/ boundary. On 3.12 a root that loops (or one
reached through a looping ancestor) made that resolve raise RuntimeError,
and the root refused as UNRESOLVABLE. From 3.13 on the resolve returned, the
contracts/ probes below it failed on ELOOP and read as absent, and the root
refused as BOUNDARY_MISSING instead: a refusal that changed with the
interpreter.

boundary_dir now asks _is_symlink_loop of the resolved root (os.stat and
ELOOP, no version test) and returns UNRESOLVABLE, whose reason names no
path. Its second resolve needs no check: it runs only on a contracts/ that
already stat-ed as a real directory. The two refusals now share one reason
string. The one caller, families._pinned_arm, prints the reason text, which
is unchanged.

Tests: a root that is itself a loop, and a root under a looping ancestor,
each natively and under CPython 3.13's own resolve body patched onto Path.
Without the fix the two 3.13-model cases fail.

Lane: openxfactory-1
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Install the 3.14 leg's lock binary-only, and return the pathlib_314 model (for #1201)

SonarCloud flagged the new doc-health-py314 job's pip step (githubactions
S8541): without --only-binary :all:, a package could run a setup script.
Every package in requirements/hermes-runtime-contracts.lock ships a 3.14
wheel (17 of 17 on the job's first runs and on a local 3.14.7), so the step
now installs as former-id-arrival-gate.yml and openxdox-consumer-gate.yml
do: --require-hashes --only-binary :all:, in a literal block because ":all:
-r" is not a plain YAML scalar. pytest-suite.yml keeps its own form.

The pathlib_314 fixture returns its model instead of yielding it (SonarCloud
python S9100): it has no teardown of its own, monkeypatch undoes the swap.

Lane: openxfactory-1
Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants