Skip to content

Stage the catalog's rendered temps outside the scanned run tree and admit no temp-shaped sibling (for #1196) - #1199

Merged
brettheap merged 8 commits into
mainfrom
fix/1196-stage-temps-outside-run-tree
Sep 29, 2026
Merged

brettheap merged 8 commits into
mainfrom
fix/1196-stage-temps-outside-run-tree

Conversation

@brettheap

@brettheap brettheap commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Lane: openxfactory-1

DRAFT for #1196, the follow-up to #1186 (PR #1189 → 73c50410). Authorized as a draft under Brett Heap's word of 2026-09-28; it lands only on his separate landing word, and only the lane coordinator lands it.

The gap (main b9742534)

_write_rendered staged every render with tempfile.mkstemp(dir=path.parent, …), that is inside the run directory write_run's preflight walks. So _refuse_foreign_descendants carried an admission clause (_is_writer_temp) for any regular file named <final-name>.<random>.tmp beside an allowed file, to spare a concurrent writer's temp in flight (Codex's P1 on #1189) and one a crash left behind. A foreign file merely shaped like that passed too. That is the residual Copilot's last round on #1189 left open (thread on catalog.py:925).

The change

  • Staging outside the scanned tree. Every write is staged in health/document-catalog/runs/.staging/ (catalog.STAGING_DIR). It sits beside the day directories, on the run tree's own filesystem. It is dot-named like .sequence, so _iter_runs skips it by name before any stat. It is outside every run and day directory, so neither preflight walk (_refuse_links_inside, _refuse_foreign_descendants) ever meets it.

  • Admission deleted. _is_writer_temp is gone. _refuse_foreign_descendants admits no .tmp sibling at all.

  • _write_rendered(root, path, text) keeps the unique per-invocation mkstemp name (the shared-fixed-name hazard Preflight every run-directory descendant against the exact allowed set #1189 removed stays removed) and mkstemp's 0600 mode (git normalises modes on commit). It re-checks the staging directory when it stages: a symlink or a non-directory is refused, with nothing written through it. It checks rename compatibility again before staging. Then the durable order, pinned by a test, is:

    1. write the temp in full, flush it and fsync it;
    2. os.replace it into place;
    3. fsync the directory it landed in and every directory from it up to the runs directory (_fsync_publish).

    All three steps complete before the run's next file is staged. os.replace never falls back to a copy: across mounts it fails with EXDEV, and the temp is removed.

  • Preflight, before any claim. _refuse_unsafe_run_paths checks the staging directory with every other catalog directory: it must be a real directory or absent, never a link. It also requires every directory the run publishes into to be rename-compatible with the staging directory (_rename_compatible): one st_dev (_device_id) and one mount (_mount_id, Linux's mnt_id from /proc/self/fdinfo through an O_PATH descriptor, which is the identity rename(2)'s EXDEV check compares). A directory not made yet counts as its nearest existing ancestor. Where the platform gives no mount id, the check falls back to st_dev alone. The refusal names tree-relative paths only.

  • The claim is durable before its run. _claim_sequence fsyncs its claim file and its entry before anything of the run is written, so no durable run.yaml can name a claim that a power loss took.

  • Accepting another writer's file is durable too (46098f89, Copilot's round 5). A rename is visible before its writer's directory sync runs, so an identical writer can find the file in that window, or after its writer died there. Every path in write_snapshot that accepts a file it did not publish itself now runs _fsync_publish first, before it publishes anything after that file or reports the run recorded: the completed no-op, the complete-run no-op, the mid-write re-check (another writer's snapshot, synced before this call's run.yaml names it), and a run another writer recorded after this call claimed. A run already recorded when the call started is covered by the snapshot's own chain sync, which passes through the run directory.

  • Stale staging content is IGNORED, never swept. Nothing tells a crash's leftover apart from a concurrent writer's temp in flight, whose os.replace a sweep would break with the FileNotFoundError Preflight every run-directory descendant against the exact allowed set #1189 removed; an age test would read the wall clock, which this module never does. It is never read, so it is never admitted as a snapshot: only its own writer's rename could carry it into a run, and the crash never made that rename. The document-catalog family already reports any file there as immutable-path (a misplaced artifact), so a person sees it and removes it; a crash-orphaned temp inside a run directory drew the same finding before this change.

  • Why the move is load-bearing, measured (a scratch probe, not committed). Main's code with only the admission removed (temps still staged inside the run): an identical writer started while another sits between mkstemp and os.replace is REFUSED (catalog run directory holds a path this run does not record (alpha.yaml.k_shon9s.tmp)). With the admission (main as it is), it completes. On this branch it completes with no admission at all.

Ownership (split with #1197's parallel writer): this PR changes _write_rendered, the staging path and the admission clause, plus their tests, and adds the rename-compatibility and durability steps the review asked for. That adds a check in _refuse_unsafe_run_paths, an fsync in _claim_sequence and syncs on write_snapshot's acceptance paths, none of them in #1197's scope. It calls _refuse_foreign_node without changing it, and does not touch the probe helpers, the os.walk loops' error paths, or the run_dir.exists() checks. Whichever PR lands second merges main first.

Review

  • Copilot round 1 (0ba9078e, catalog.py:691): the cross-filesystem refusal came after the claim. Moved into the preflight in 29e19c47; answered and resolved.
  • Copilot round 2 (29e19c47, catalog.py:650, High): st_dev alone passes two bind mounts of one filesystem. Mount ids added in 4a37c83d, with a same-device/different-mount test; answered and resolved.
  • Copilot round 3 (4a37c83d, "Findings: None", one "previously missed" note, no thread): write_run preflight: stage temp files outside the scanned run tree and drop the temp-shape admission (follow-up to #1186) #1196's fsync-then-rename order had no fsync. Added in 2265f8d1; answered in a PR comment.
  • Copilot round 4 (2265f8d1, catalog.py:774): the rename itself was not durable. Directory chain fsync, plus the claim's, added in 8461f205; answered and resolved.
  • Copilot at 8461f205: Findings: None. Its overview asks for final human validation of the concurrency, mount-detection and crash-durability behaviour.
  • Copilot round 5 (caf0c029, the lane coordinator's merge of main f56c87c6; catalog.py:816, High): a writer that found another writer's rename could accept it before that writer's directory sync. Fixed in 46098f89; answered and resolved.
  • Copilot at 46098f89: Findings: None ("Resolved since last review (1)"). Its overview again asks for final human validation of mount detection, concurrent publication and crash durability.
  • Codex: "Didn't find any major issues" at 0ba9078e, at 8461f205 and at 46098f89. 4 review threads, all resolved.

Tests

  • test_write_run_refuses_a_temp_shaped_stranger_in_the_run replaces test_write_run_tolerates_a_writer_owned_temp_file, because that test pinned the admission this change deletes. A <final-name>.<random>.tmp beside a snapshot, beside a nested snapshot, or beside run.yaml refuses before any claim or write and is named in the refusal. Beside a crashed partial run it refuses, and the run heals once the file is gone. Fails on main (DID NOT RAISE CatalogError).
  • test_the_writers_staged_temp_is_never_inside_the_scanned_tree: at every rename the temp is in STAGING_DIR, named for its target, on the target's filesystem, and complete; the scan lists nothing for it, and the preflight walk passes. Under Codex's publish-time interleave both identical writers complete (4 publishes; staging held 1 and then 2 temps and is empty afterwards). Fails on main, where the temp is inside the run.
  • test_stale_staging_content_is_ignored_and_never_admitted: stale content shaped as a complete snapshot, a conflicting one, a run.yaml naming sequence 7, and a whole run's layout. The first write claims 1 (not 8) with the clean tree's exact bytes, the retry is a no-op, and the stale files are byte-identical afterwards. This one is a regression pin: main never writes there.
  • test_write_run_refuses_a_foreign_staging_directory_before_any_write: a symlink escaping the root, one into a day directory, a dangling one, and a regular file. write_run and write_snapshot refuse before any claim, stage or write. Fails on main.
  • test_write_run_refuses_a_cross_mount_run_before_any_claim: another filesystem (_device_id shifted) and a bind mount of the same one (_mount_id shifted, st_dev untouched), at the staging, day or crashed run directory. Each is refused by both writers with no claim and nothing made, and a tree mounted whole still records. At 0ba9078e the same layout left claim 000001.yaml and a run directory behind.
  • test_write_rendered_publishes_only_by_an_atomic_rename: a symlinked staging directory is refused at write time; an incompatible target is refused before staging, with a tree-relative message; an EXDEV rename leaves neither target nor temp. On Linux the mount id is really read.
  • test_every_publish_is_durable_before_the_next_is_staged: a whole write_run with a nested repository, pinning every durable step in order: the claim and its chain; then, for each of the three files, the complete temp's fsync, its rename, and its directory chain up to the runs directory. Fails against 2265f8d1.
  • test_a_writer_accepts_another_writers_publish_only_once_durable (46098f89): two identical writers of a run with a nested repository, one paused at the exact moment. Paused right after its snapshot's rename (case 1) or its run.yaml's rename (case 2), the first writer dies while the second runs; the second must sync the directory chain up to the runs directory before it publishes run.yaml (case 1) or returns (case 2). Paused partway through its snapshot's sync (case 3), the first lets the second publish run.yaml and die right after that rename; the first must sync run.yaml's chain before it returns. In case 4 another writer renames the last snapshot of a recorded partial run into place just as the call finds the run complete; the call syncs that snapshot's chain before it returns. Against caf0c029 it fails at case 1; with each path's fix added in turn it fails at the next case, and it passes with all four.
  • Amended: test_write_rendered_is_concurrency_safe_across_distinct_content (the new signature; also asserts nothing is left in staging). test_write_run_refuses_a_stranger_merely_shaped_like_a_writer_temp keeps its assertions; only its comment changed, since the function it named is gone.
  • test_document_catalog.py::test_a_stale_staged_write_is_reported_as_a_misplaced_artifact: a clean write leaves staging empty and the family clean; a stale staged temp is exactly one immutable-path ERROR at runs/.staging/<name>, the same finding the same temp draws inside a run.

Verification

Python 3.12.3, a full clone, with openXwallet, openXdox and openDox materialized as CI does.

  • tests/doc-health at 46098f89: 2017 passed, 0 failed. At 8461f205: 2016 passed (the doc-health subset of the full run below). Main b9742534, same clone: 2009 passed.
  • Full CI-equivalent python3 -m pytest tests/ -q -m "not postgres" at 8461f205, with the pinned OpenSpec CLI 1.12.0 on PATH and the ambient git identity denied: 8834 passed, 20 skipped, 338 deselected, 0 failed, 391 subtests passed, in 1494 s. The local skips are all environmental (pinned validators, the decision-core checkout, a sibling checkout not reachable here); none is in doc-health, and none is new.
  • CI at 46098f89 (main f56c87c6 merged in): all 14 check-runs green, among them pytest-suite run 36564678244: 8907 passed, 5 skipped (the pinned 5), 338 deselected, 0 failures, 0 errors (selected=9324 passed=9319 skipped=5), and the freshness verifier and vector replay passed. At 8461f205, pytest-suite run 36501510753: 8849 passed, 5 skipped, 0 failures.
  • Run locally at 0ba9078e (my later commits touch only catalog.py and test_catalog.py; the required gates re-ran in CI at 46098f89):
    • validate-former-id-arrival.py over the PR range on the merge commit: passed, with 45 active and 184 archived packets swept.
    • validate-release-tag-gate.py: no release surface change.
    • verify-openxwallet-pin.py, wallet-yaml-syntax-gate.py and validate-openxwallet.py (all five log assertions hold), and validate-factory-identity.py: 0 errors.
    • validate-signed-execution-chain.py --require-pinned-wallet-vocabulary: 95/95 closed refusal codes red-proven.
    • validate-openspec-cli-pin.py --all --no-cache: 0 undispositioned failures, with the 1 accepted exception (add-chain-attestation).
    • verify-openxdox-pin.py, verify-opendox-pin.py: OK.
  • validate-document-catalog.py --strict: 0 errors, 0 warnings on this tree; on a read-only clone of opensoft/xFactory main e56dec68, 237 artifacts, 0 errors, 0 warnings.
  • The aggregation's real runs, on that clone, with this branch's final code:
    • 298 tracked files under runs/, all .yaml, no .tmp, and only .sequence as a dot entry, so dropping the admission newly refuses nothing.
    • All 31 recorded runs pass the new preflight.
    • End to end on a scratch copy: recording the latest run's content on a later date claims sequence 32 and leaves .staging/ empty. The scan yields 32 entries, none refused, and never lists staging. The new run verifies content-addressed, with 0 immutable-path findings, and staging and the run share one mount id.

Residual gaps (not fixed here)

  • The reusable nightly delivers reports with git add health/, so a temp a crash leaves in runs/.staging/ would be committed, exactly as an in-run orphan would have been before. The family flags it either way. A .gitignore entry in the aggregation (or an exclude in that step) would stop it; that is outside this PR's two files.
  • Mount identity is read only where Linux exposes mnt_id; elsewhere the check is st_dev alone, with EXDEV at the rename as the backstop. Directory fsync is POSIX-only. No live bind mount could be created in the sandbox (unprivileged namespaces are refused), so the kernel side rests on the rename(2) contract.
  • The fsyncs cost time: test_catalog.py plus test_document_catalog.py went from about 6.2 s to 10.6 s. A nightly writes about 9 files per run.

🤖 Generated with Claude Code

…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]>
Copilot AI balanced review requested due to automatic review settings September 28, 2026 23:38
@brettheap

Copy link
Copy Markdown
Contributor Author

@codex review

@sourcery-ai

sourcery-ai Bot commented Sep 28, 2026

Copy link
Copy Markdown

Reviewer's Guide

The PR relocates rendered-write temporary files to runs/.staging, validates that path and its filesystem before writing, removes the unsafe in-run temp admission, and adds coverage proving concurrent writes remain atomic while stale or foreign artifacts cannot influence catalog discovery or claims.

Sequence diagram for staged atomic catalog writes

sequenceDiagram
    participant Writer as Catalog writer
    participant Staging as runs/.staging
    participant Target as Run target
    participant Scan as Run preflight and scan

    Writer->>Staging: _refuse_foreign_node
    Writer->>Staging: _same_filesystem
    Writer->>Staging: mkstemp
    Writer->>Staging: write and close complete rendering
    Writer->>Target: os.replace
    Scan->>Target: _refuse_foreign_descendants
    Scan->>Target: _iter_runs
    Note over Scan,Staging: Staging is outside run directories and skipped by dot name
Loading

Flow diagram for catalog staging validation

flowchart TD
    A["_write_rendered(root, path, text)"] --> B[_refuse_foreign_node]
    B --> C[_same_filesystem]
    C -->|valid| D[mkstemp in runs/.staging]
    C -->|different device| E[CatalogError before staging]
    D --> F[Write and close rendering]
    F --> G{os.replace}
    G -->|same filesystem| H[Atomic publish to target]
    G -->|EXDEV or failure| I[Remove staging temp]
    J[Foreign or temp-shaped file inside run] --> K[_refuse_foreign_descendants]
    K --> L[CatalogError before claim or write]
Loading

File-Level Changes

Change Details Files
Moves atomic write staging out of scanned run directories into a catalog-level staging directory.
  • Adds runs/.staging as the shared staging location.
  • Updates _write_rendered to validate the staging node, require the same filesystem, write complete contents, and publish only via os.replace.
  • Passes the catalog root through snapshot and run write paths.
scripts/doc_health/catalog.py
tests/doc-health/test_catalog.py
Makes run preflight and discovery reject or ignore temporary artifacts according to their new location.
  • Removes _is_writer_temp and no longer admits temp-shaped siblings inside runs.
  • Preflights the staging directory for symlinks, foreign nodes, and non-directory replacements before claiming.
  • Keeps dot-named staging content out of run iteration while leaving stale content untouched and unread.
scripts/doc_health/catalog.py
tests/doc-health/test_catalog.py
tests/doc-health/test_document_catalog.py
Expands regression coverage for staging safety, concurrency, atomic publication, and artifact reporting.
  • Replaces tolerance of in-run writer temps with refusal of all temp-shaped strangers.
  • Tests overlapping writers, distinct-content races, stale staging data, unsafe staging paths, cross-device failures, and atomic rename cleanup.
  • Verifies stale staging files are reported as immutable-path artifacts without affecting catalog snapshots.
tests/doc-health/test_catalog.py
tests/doc-health/test_document_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

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 0ba9078efd

ℹ️ 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".

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

Cross-filesystem staging is detected only after a sequence claim and directories have already been created.

Review effort: Balanced
Findings: 1 Medium severity

Open (1)
What changed in this PR

Moves catalog write staging outside individual run directories and removes temp-file admission from run preflight.

Changes:

  • Adds shared .staging atomic-write storage.
  • Refuses temp-shaped files within runs.
  • Adds concurrency, stale-content, path-safety, and catalog-health tests.
File Description
scripts/​doc_health/​catalog.py Implements external staging and stricter preflight.
tests/​doc-health/​test_catalog.py Tests staging, concurrency, cleanup, and refusal behavior.
tests/​doc-health/​test_document_catalog.py Verifies stale staged files produce findings.

💡 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
…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]>
Copilot AI review requested due to automatic review settings September 28, 2026 23:45

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 st_dev check can miss cross-mount rename failures and leave orphaned claims.

Review effort: Balanced
Findings: 1 High severity

Open (1)
Resolved since last review (1)

Comment thread scripts/doc_health/catalog.py Resolved
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]>
Copilot AI review requested due to automatic review settings September 28, 2026 23:53

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

The implementation omits the fsync-before-rename durability explicitly required by linked issue #1196.

Review effort: Balanced
Findings: None

Resolved since last review (1)
Previously missed (1)

In code that hasn't changed since last review

Medium severity Fsync temp file before rename to ensure durability

scripts/​doc_health/​catalog.py:767

The linked #1196 explicitly requires preserving the fsync-before-rename ordering, but this closes and renames the temp without calling os.fsync. Closing flushes Python buffers but does not make the bytes durable, so a power loss can leave a published catalog record without the promised durability. Flush and fsync the temp before os.replace (or clarify #1196 if only process-crash atomicity is intended).

        with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
            handle.write(text)
        os.replace(tmp, path)  # atomic publish; consumes this temp only

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]>
Copilot AI review requested due to automatic review settings September 28, 2026 23:58
@brettheap

Copy link
Copy Markdown
Contributor Author

Lane: openxfactory-1

On Copilot's round-3 overview at 4a37c83 ("Findings: None", with one "previously missed" note, not posted as a thread): the note was right. #1196 keeps the fsync-then-rename order, but _write_rendered had never fsynced (git log -S fsync on catalog.py was empty); closing the temp flushes Python's buffer and makes nothing durable. 2265f8d flushes and fsyncs the temp through its own descriptor, complete, before its handle closes and os.replace publishes it. The directory is deliberately not fsynced: a rename a power loss undoes leaves the record absent, which is the crash window every retry already heals, never a torn record. New test test_write_rendered_fsyncs_the_complete_temp_before_the_rename pins the order (one fsync of the temp's own descriptor holding the complete bytes, then the one replace), and it fails against 4a37c83 with the replace as the only event. Cost measured: test_catalog.py plus test_document_catalog.py go from about 6.2 s to 8.0 s.

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

Publication is not fully crash-durable because destination directories are not fsynced after rename.

Review effort: Balanced
Findings: 1 High severity

Open (1)

Comment thread scripts/doc_health/catalog.py Resolved
…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]>
Copilot AI review requested due to automatic review settings September 29, 2026 00:07

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

The low-level concurrency, mount detection, and crash-durability behavior warrants final human validation despite comprehensive tests.

Review effort: Balanced
Findings: None

Resolved since last review (1)

@brettheap

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 8461f205ff

ℹ️ 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".

Copilot AI review requested due to automatic review settings September 29, 2026 11:22

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

A concurrent writer can accept an exact target before its directory entry has been durably synced.

Review effort: Balanced
Findings: 1 High severity

Open (1)

Comment thread scripts/doc_health/catalog.py Resolved
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]>
Copilot AI review requested due to automatic review settings September 29, 2026 11:54

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

Filesystem mount detection, concurrent publication, and crash-durability guarantees require final human validation.

Review effort: Balanced
Findings: None

Resolved since last review (1)

@brettheap

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 46098f898a

ℹ️ 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".

Copilot AI review requested due to automatic review settings September 29, 2026 12:37

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

No concrete defect was found, but concurrent publication, platform-specific mount detection, and crash-durability semantics warrant final human validation.

Review effort: Balanced
Findings: None

@sonarqubecloud

Copy link
Copy Markdown

@brettheap
brettheap marked this pull request as ready for review September 29, 2026 13:01

@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 3 days and 1 hour by commenting @sourcery-ai review. Upgrade to get a review now.

@brettheap
brettheap merged commit 7daaf0f into main Sep 29, 2026
16 checks passed
brettheap added a commit that referenced this pull request Sep 30, 2026
Brings the branch current with main after #1198 (51887c6), #1199
(7daaf0f, the catalog staging directory, the deleted _is_writer_temp,
the fsync-then-rename durability work), #1202-#1206 and #1181.

The merge applied without conflicts. #1199 did not reshape any function
this branch touches: _own_mode, _refuse_links_inside and the os.walk
error path of _refuse_foreign_descendants are as this branch left them,
and main's rewrite of _refuse_foreign_descendants' docstring (no temp
admitted, STAGING_DIR) and its body (the _is_writer_temp clause gone)
sits beside this branch's shared _refuse_unreadable_walk onerror
unchanged. The diff against main is still exactly this branch's two
files, at the same size as before the merge.

Lane: openxfactory-1
Co-Authored-By: Claude Opus 5.5 <[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