Skip to content

Bind timeout= on RealGit's two raw subprocess.run call sites - #1102

Merged
brettheap merged 1 commit into
mainfrom
fix/1098-realgit-subprocess-timeouts
Sep 18, 2026
Merged

brettheap merged 1 commit into
mainfrom
fix/1098-realgit-subprocess-timeouts

Conversation

@brettheap

@brettheap brettheap commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Lane: openxfactory-5 (openXfactory-5)

What

scripts/doc_health/corpus.py's class RealGit has exactly two raw
subprocess.run call sites and neither bound a timeout:

  • _run (every other reader's shared primitive) had no timeout= and no
    try/except at all, so a missing git binary raised uncaught.
  • blobs_at (the git cat-file --batch reader) had no timeout=, and
    caught only bare OSError.

A blocked promisor remote can hang either call before
release_inventory.py's repository-level skip is ever reached, since that
skip only fires once the call returns.

Fix mirrors carved_reach.py's _git_run (#1048 round 5, PR #1051): a new
module constant _GIT_TIMEOUT_SECONDS = 30, bound at both call sites, with
subprocess.TimeoutExpired caught beside OSError and mapped to the same
None each already returns on a non-zero exit. No caller-visible change of
type, only of promptness.

Regression

Three new tests in tests/doc-health/test_release_inventory.py, written
before the fix and run against the unfixed code first:

tests/doc-health/test_release_inventory.py::test_run_hits_the_timeout_rather_than_hanging FAILED
tests/doc-health/test_release_inventory.py::test_blobs_at_hits_the_timeout_rather_than_hanging FAILED
tests/doc-health/test_release_inventory.py::test_a_missing_git_binary_answers_none_not_a_crash FAILED

E   AttributeError: <module 'doc_health.corpus' from '.../corpus.py'> has no attribute '_GIT_TIMEOUT_SECONDS'
E   AttributeError: <module 'doc_health.corpus' from '.../corpus.py'> has no attribute '_GIT_TIMEOUT_SECONDS'

    assert RealGit()._run(tmp_path, "log", "-1") is None
E   FileNotFoundError: [Errno 2] No such file or directory: 'git'

3 failed in 0.33s

The first two fail on the missing constant (proving no bound exists yet);
the third is the documented uncaught-exception gap in _run firing for
real. All three fail fast, never hang, against the unfixed tree.

After the fix (same three tests, _GIT_TIMEOUT_SECONDS monkeypatched to
0.2 so a fake git shim that sleeps 2s on $PATH proves the bound fired
rather than merely that the shim exited on its own):

tests/doc-health/test_release_inventory.py::test_run_hits_the_timeout_rather_than_hanging PASSED
tests/doc-health/test_release_inventory.py::test_blobs_at_hits_the_timeout_rather_than_hanging PASSED
tests/doc-health/test_release_inventory.py::test_a_missing_git_binary_answers_none_not_a_crash PASSED

3 passed in 0.93s

Full validation on this branch (fresh clone, submodules initialized):

Not widened

  • Only the two named call sites change; no other subprocess.run site in
    this file or elsewhere is touched.
  • release_inventory.py's LegUnavailable / skip path is unchanged: it
    already treats None from these readers as "git could not be consulted",
    so a timeout is just one more way that None happens.
  • Timeout value (30s) and catch shape match carved_reach._git_run exactly;
    no new configurability is introduced beyond the module constant the tests
    need to monkeypatch.

Refs #1098

Lane: openxfactory-5 (openXfactory-5)
🤖 Generated with Claude Code

Summary by Sourcery

Bound RealGit Git subprocess calls and preserve skip-on-failure behavior when Git is unavailable or unresponsive.

Bug Fixes:

  • Prevent RealGit subprocess operations from hanging indefinitely by applying a 30-second timeout to both raw Git readers and returning the existing failure result on timeout.
  • Make the shared RealGit command runner gracefully handle missing Git binaries instead of propagating operating-system errors.

Tests:

  • Add regression coverage for timeout handling in both Git readers and missing-binary behavior.

Lane: openxfactory-5 (openXfactory-5)

`corpus.py`'s `RealGit._run` (every other reader's shared primitive) and
`RealGit.blobs_at` (the `git cat-file --batch` reader) are the only two raw
`subprocess.run` call sites in the file, and neither bound a timeout: a
blocked promisor remote could hang before release_inventory.py's
repository-level skip is ever reached, since that skip only fires once the
call RETURNS. `_run` also had no try/except at all, so a missing git binary
raised uncaught.

Mirrors carved_reach.py's `_git_run` (#1048 round 5, PR #1051): a module
constant `_GIT_TIMEOUT_SECONDS = 30`, bound at both call sites, with
subprocess.TimeoutExpired caught beside OSError and mapped to the same None
each already returns on a non-zero exit. No caller-visible change of type,
only of promptness; release_inventory.py's LegUnavailable path needs no
change.

Refs #1098
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Sonnet 5 <[email protected]>
Copilot AI lite review requested due to automatic review settings September 18, 2026 10:13
@sourcery-ai

sourcery-ai Bot commented Sep 18, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR hardens RealGit's two raw subprocess.run call sites with a shared 30-second timeout and consistent failure handling, preventing blocked Git operations from hanging repository checks while preserving existing None-based skip behavior. Focus review on timeout placement, exception coverage, and the regression tests that distinguish an enforced timeout from a subprocess exiting naturally.

Sequence diagram for RealGit timeout handling

sequenceDiagram
    participant Caller
    participant RealGit
    participant Git as git subprocess

    Caller->>RealGit: _run(repo, args)
    RealGit->>Git: subprocess.run(timeout=_GIT_TIMEOUT_SECONDS)
    alt command completes successfully
        Git-->>RealGit: returncode 0 and stdout
        RealGit-->>Caller: stdout
    else non-zero exit, OSError, or TimeoutExpired
        Git-->>RealGit: failure
        RealGit-->>Caller: None
    end

    Caller->>RealGit: blobs_at(repo, commit, paths)
    RealGit->>Git: subprocess.run(cat-file --batch, timeout=_GIT_TIMEOUT_SECONDS)
    alt command completes successfully
        Git-->>RealGit: batch output
        RealGit-->>Caller: parsed blobs
    else non-zero exit, OSError, or TimeoutExpired
        Git-->>RealGit: failure
        RealGit-->>Caller: None
    end
Loading

File-Level Changes

Change Details Files
Bound both RealGit subprocess invocations and normalized timeout or launch failures to the existing None-based failure behavior.
  • Added a shared 30-second Git subprocess timeout constant.
  • Applied the timeout to the shared Git runner and batch blob reader.
  • Caught TimeoutExpired alongside OSError at both call sites, including the previously uncaught missing-binary case.
scripts/doc_health/corpus.py
Added regression coverage proving slow Git processes are interrupted and unavailable Git binaries degrade safely.
  • Added PATH-injected sleeping Git shim tests for both subprocess paths with a shortened monkeypatched timeout.
  • Added missing-binary assertions for both readers.
  • Verified bounded completion and unchanged None results.
tests/doc-health/test_release_inventory.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

@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.

Hey - I've reviewed your changes and they look great!

Sourcery assessment

Approved.


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

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.

🟢 Approval recommended

Both call sites and regression scenarios are covered with no unresolved correctness issues.

Pull request overview

Adds bounded Git subprocess execution to prevent doc-health hangs while preserving existing skip behavior.

Changes:

  • Applies a shared 30-second timeout and handles missing binaries/timeouts.
  • Adds regression tests for both readers and missing Git.
File summaries
File Description
scripts/doc_health/corpus.py Bounds both raw Git subprocess calls and returns None on failure.
tests/doc-health/test_release_inventory.py Tests timeout and missing-binary handling.
Review details
  • Files reviewed: 2/2 changed files
  • Comments generated: 0
  • Review effort level: Lite

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

@sonarqubecloud

Copy link
Copy Markdown

@brettheap

Copy link
Copy Markdown
Contributor Author

Lane: openxfactory-5 (openXfactory-5)

LANDING — lane openXfactory-5, session 651195c7-1854-491e-894a-e6542ef5e9f4@Eagle, 2026-09-18T12:37:19Z, PR #1102 into opensoft/openxFactory main

@brettheap
brettheap merged commit aea1e6c into main Sep 18, 2026
15 checks passed
@brettheap

Copy link
Copy Markdown
Contributor Author

Lane: openxfactory-5 (openXfactory-5)

LANDED — lane openXfactory-5, session 651195c7-1854-491e-894a-e6542ef5e9f4@Eagle, 2026-09-18T12:37:36Z, PR #1102 into opensoft/openxFactory main → merge aea1e6c; Bind timeout= on RealGit's two raw subprocess.run call sites

brettheap added a commit that referenced this pull request Sep 22, 2026
…ass, preflight, ideation_readiness (#1128) (#1142)

Lane: openxfactory-2 (openXfactory-2)

**On Brett Heap's words.** *"do 1 and 2, claim 5"* (#745 comment 5767008640) and *"merge both when green, then fix 5 and merge when green"* (#745 comment 5767058861, recorded on #1128 as comment 5767206176). Both #745 PRs have landed, so finding 5 — #1128 — is next.

**What this binds.** The three call sites #1128 measured inside `scripts/doc_health/`: the last unbounded git subprocesses there after #1098 / PR #1102 bound `corpus.RealGit`'s pair. Each now binds a timeout and catches `subprocess.TimeoutExpired` beside `OSError`, mapped to the failure its caller **already** produces — never a new exception type for a caller to learn, never a silent success, never a hang. No contract, schema or policy text moves (#1128 declares `code_surface: openxFactory`, code-only), so no OpenSpec packet is owed.

## Per site: before → after

### 1. `scripts/doc_health/pin_class.py` — `_git` (`:1685`)

| | |
|---|---|
| **Before** | `subprocess.run(["git", "-C", str(repo), *args], capture_output=True, check=check, text=True, encoding="utf-8", errors="replace")` — no `timeout=`, and **no `try`/`except` at all**, not even a bare `OSError`. Nine call sites route through it, including `verify()`'s first act (`:2451`). |
| **What it caught** | Nothing. A missing `git` raised `FileNotFoundError` out of whatever reachability read was in progress; a hung `git` never returned at all. |
| **The caller's own handling** | Every one of the nine reads `.returncode` / `.stdout` / `.stderr`; not one checks for `None`. `verify()` raises `GitUnavailable` (a `RuntimeError` subclass whose docstring is *"Never silently a pass"*) when `_git(...).returncode != 0`. |
| **After** | `timeout=_GIT_TIMEOUT_SECONDS` (**30 s**, the sibling bound) and `except (OSError, subprocess.TimeoutExpired)` answering `CompletedProcess(args=argv, returncode=1, stdout="", stderr=<reason>)` — the only "failed" shape this module has, so all nine callers are untouched. On the hot path that is the designed failure: `verify()`'s `rev-parse` raises `GitUnavailable`, exactly as it does for a git that said no. `check=True` is **re-raised** rather than translated, because that caller never reads the returncode and handing it a non-zero `CompletedProcess` would be the silent success this bound exists to prevent (no caller passes `check=` today — measured across `scripts/` and `tests/`). |

### 2. `scripts/doc_health/preflight.py` — `run_preflight` (`:57`)

| | |
|---|---|
| **Before** | `subprocess.run(cmd, cwd=repo_path, capture_output=True, text=True, env={...})` — no `timeout=`; the whole 72-line file contained zero `try` and zero `except`. |
| **What it caught** | Nothing. And `cmd` is not fixed to `git`: `_entrypoints()` builds `python3 <validator>`, `bash scripts/validate-docs.sh` or `make validate` per discovered repository. |
| **The caller's own handling** | A non-zero exit becomes `Finding(ERROR, "preflight", repo, <path>, ...)`. But `run_preflight` is the **first** act of `run_suite` (`runner.py:227`) whenever no `--family` is passed — which is how the nightly invokes it — so a hang blocked every family before one ran, and never reached the `Finding`-producing branch at all. |
| **After** | `timeout=_ENTRYPOINT_TIMEOUT_SECONDS` and `except (OSError, subprocess.TimeoutExpired)` producing the **same** `Finding(ERROR, "preflight", ...)`, same family and same path so regression matching between two reports is unchanged, with the reason (`timed out after 120s` / `could not be run: …`) standing in for the output tail there is none of. |

**The 120 s here is a decision, not a slip, and the constant says so in the file.** It is deliberately **not** the 30 s the two git sites bind. Those are single git plumbing calls; a preflight entrypoint is a *whole repository's validator suite* (`make validate`, `bash scripts/validate-docs.sh`, or a python validator that spawns git subprocesses of its own — `validate-domain-openxfactory-pins.py` does). A bound tight enough to cut an honest slow validator would convert a green nightly into an ERROR finding, i.e. a defect this PR would have *introduced*. The number is measured: the slowest entrypoint this repository can run is `scripts/validate-memory-gateway.py` at **3.26 s** (the four openxFactory no-arg validators measured 0.12 / 0.49 / 0.77 / 3.26 s on 2026-09-21), so 120 s carries ~37x headroom over the slowest thing actually observed — while still being small enough that the whole preflight fits inside its own job: `.github/workflows/doc-health-reusable.yml` bounds that job at `timeout-minutes: 45`, and even if all ~13 entrypoints an aggregation run discovers timed out, 13 x 120 s = 26 min, so the timeouts surface as Findings rather than as a killed job with no report at all.

### 3. `scripts/doc_health/ideation_readiness.py` — `index_reproduces_at` (`:884`)

| | |
|---|---|
| **Before** | `subprocess.run(["git", "-C", str(root), "archive", pin, "ideation"], capture_output=True)` — no `timeout=`, no `try`/`except`. The third in-package site, which #1098's own 2026-09-17 sweep did not name. |
| **What it caught** | Nothing. |
| **The caller's own handling** | A non-zero return already answers `(None, "the corpus at <pin> could not be reconstructed, so reproduction was NOT ASKED rather than answered: …")` — the function's documented third outcome. |
| **After** | `timeout=_GIT_TIMEOUT_SECONDS` (**30 s**) and `except (OSError, subprocess.TimeoutExpired)` returning that **same** `(None, "NOT ASKED rather than answered")`. Never `False`: `False` would blame the committed body for a question nobody could put, which is the distinction `test_reproduction_that_cannot_be_asked_is_neither_pass_nor_fail` exists to keep. |

## Regression tests, failing → passing

Nine new tests: five appended to `tests/doc-health/test_pin_reachability.py` and a new `tests/doc-health/test_preflight.py` (#1128 measured that **nothing** tested that file). They assert the bound the call actually carries (`kwargs["timeout"] == 30` / `== 120`, and that it is the module's declared constant) and raise `TimeoutExpired`, rather than timing a sleeping shim — a shim that sleeps proves only that the shim exited. Each then compares the timed-out result against the one a **real** unrunnable git or unspawnable entrypoint already produces (an emptied `PATH`), which is #1098's second, separate gap.

With the three source files swapped for `origin/main`'s and the new tests present: **6 failed, 3 passed**.

```
FAILED test_preflight.py::test_an_entrypoint_that_never_returns_times_out_into_that_same_finding
FAILED test_preflight.py::test_an_unrunnable_entrypoint_is_a_finding_rather_than_a_raised_OSError
FAILED test_pin_reachability.py::test_git_binds_the_timeout_and_answers_the_failed_read_shape
FAILED test_pin_reachability.py::test_a_timed_out_git_is_the_same_failure_an_unrunnable_git_already_gave
FAILED test_pin_reachability.py::test_the_lower_readers_degrade_rather_than_raise_through_a_timeout
FAILED test_pin_reachability.py::test_the_reproduction_archive_is_NOT_ASKED_rather_than_a_hang
```

Restored: **9 passed**. The three that pass on `main` too are contract pins rather than defect pins, and are there so the bind cannot move the surrounding contract: the two preflight baselines (an ordinary validator failure is still the Finding it always was; a clean validator still reports none) and the `check=True` guard, which `main` satisfies by catching nothing at all.

## Validation

All foreground, private `--basetemp`, in a fresh clone.

| Check | Result |
|---|---|
| `pytest -q -p no:cacheprovider tests/doc-health` (whole) | **7 failed, 1909 passed, 1 skipped** (440.69 s) |
| …the same, on a **pristine `origin/main` clone** (@ `0f23341f`) | **7 failed, 1900 passed, 1 skipped** (452.08 s) — the **same seven names**, all container-local (`validate_index` / pinned-validator / real-lines cases). +9 passed on this branch = the nine new tests. |
| touched test files (`test_pin_reachability.py`, `test_preflight.py`, `test_ideation_readiness.py`) | 3 failed, 122 passed (151.02 s) — the three container-local `test_ideation_readiness.py` ones, which fail identically on the pristine clone (3 failed, 42 passed for that file alone) |
| `python3 scripts/doc-health.py --single-repo . --as-of 2026-09-22` (no `--family`, so `run_preflight` runs), before vs after | **byte-identical** — the whole 376-line report; `diff` empty; **113** `- severity=` finding lines unchanged |
| `verify_pin_reachability(".", allow_remote=False)` before vs after | **byte-identical**, 130 lines. (`families.py` names neither `pin_class` nor `ideation_readiness`, so these two sites feed no doc-health family — the pin-reachability probe is their surface, and it is compared directly instead.) |
| `OPENSPEC_TELEMETRY=0 openspec validate --all --strict` | **106 passed, 1 failed** (`add-chain-attestation`) — identical totals on the pristine main clone; that item carries a recorded disposition in `contracts/openspec-cli-pin.yaml` |
| `python3 scripts/proposal-support.py . verify` | `proposal support verification ok` |

Both before/after comparisons swap **only** the three source files inside this one clone (`git show origin/main:<path> > <path>`, run, restore), so the corpus and the checkout kind are identical and the only variable is the code.

## Out of scope

The **61** unbounded `subprocess.run` call sites #1128 mechanically scanned **outside** `scripts/doc_health/` — across 29 files, `scripts/proposal-support.py` alone holding 14, `scripts/sequenced_after.py` 6, `scripts/attest-openspec-cli-pin-lockfile.py` 4 — are **out of scope for this PR and untouched**. That scan is textual only (it cannot resolve kwargs-indirection such as `validate-openspec-cli-pin.py`'s `_run(argv, **kwargs)`), and #1128 names it as a separate finding if it is taken at all.

Lands under Rule 6 on the word when the eight required checks are green and Copilot is clean.

refs #1128
refs #1098

---

## Review round by lane `openxfactory-4` (openXfactory-4-openDox_extraction)

**Driven to the gate by a second lane on the holder's assignment, with Brett Heap's landing word of 2026-09-22 — verbatim *"land #1142 too when green"*, recorded at `#656` comment `5779648105`.** The original authorship above is lane `openxfactory-2`'s and is left as written. **This PR is NOT ratified and needs no ratification**: code-only, no `openspec/changes/` path, no README OpenSpec Records edit — it lands on a **plain gate**, not in a Rule 6 window, and takes no place in the `#1140 → #1141` order.

Two Copilot findings at `d78efc7c`, **both correctness, both taken as fixes** at `9a6dd963`.

### `r4073457110` — the bound turned an unaskable question into a confident answer

`merge-base --is-ancestor` reports *"not an ancestor"* by **exiting non-zero**, which is the same shape the timeout translation produces. So a bound that fired became a confident `False`, and `verify()` published it as **ORPHAN or HISTORICAL** — a pin declared unreached by `main` on a question nobody got to ask. `is_truncated` was worse in kind: it fell through to *"`--is-shallow-repository` is false for `<repo>` and it declares no promisor remote"*, **asserting two observations that were never made**, under a docstring whose first line promises *"OBSERVED not conjectured"*.

**The module's own doctrine had already decided this**, which is what makes the finding decisive rather than arguable:

- `remote_retention_refs` refuses an empty dict for an unaskable namespace, because it *"would be indistinguishable from the namespace is empty, and would silently convert an unaskable question into an answer"*;
- `retention_holder`'s unconsultable remote is reported *"as INCONCLUSIVE rather than as an orphan"*;
- `verify()` already renders `could not be performed` as INCONCLUSIVE for the retention read.

**The fix.** `_git` returns an `_Unavailable` subclass of `CompletedProcess` — still non-zero, so the seven callers that only ever needed *"this did not succeed"* are unchanged, exactly as the translation intends. **A subclass rather than a sentinel returncode**: an exit code would collide the day a real `git` chose the same number, and `isinstance` cannot be spoofed. `reachable_from_main` and `is_truncated` answer `None` for *"could not be asked"*, and `verify()` renders both INCONCLUSIVE at three call sites.

**This reverses a scoping decision this branch had PINNED IN A TEST** — that a third state *"would change a caller contract this fix is not allowed to move"*. The cost the review measured is not payable: **the bound introduced the path, so the bound owns it.** The test is rewritten to pin the corrected behaviour and carries the reversal with its reason.

**The new regression test is proved, not asserted.** `test_an_unaskable_ancestry_is_INCONCLUSIVE_and_never_orphan_or_historical` lets the opening `rev-parse` succeed with **real git** and makes only `merge-base --is-ancestor` unaskable — the scenario the review named, and the only way to reach it, since `verify()` raises `GitUnavailable` on the first probe under a blanket timeout. **Run against the pre-fix reader it FAILS with `assert 'orphan' != 'orphan'`; with the fix it passes.** Both runs were performed.

`ideation_readiness` is **not** in this class and was checked: it handles its timeouts with named errors rather than translating them into a returncode.

### `r4073457175` — the fallback must not raise the race it is the fallback for

Every caller of `_terminate_group` sits inside `_run_entrypoint`'s `except subprocess.TimeoutExpired` handler, **whose whole job is to re-raise that timeout so `run_preflight` can turn it into a finding**. If the child exits between `communicate()` timing out and cleanup, `os.getpgid()` raises `ProcessLookupError` — which is why the fallback exists — and a bare `proc.kill()` can then raise the **same** `ProcessLookupError` from inside the `except` handling it. That second exception **replaces** the `TimeoutExpired`, escapes the handler, and takes the run down at the moment a preflight finding was owed.

`_kill_direct(proc)` swallows `OSError` **and nothing else**; every other exception still propagates and the original timeout is re-raised unchanged. Both call sites use it, including the non-POSIX branch, which carried the same exposure.

### Measurement

`python3 -m pytest tests/doc-health -q` → **1905 passed, 8 failed**. Those 8 are the **same 8 that fail on clean `main` `ac50d70d` in this clone** (`test_ideation_readiness` ×3, `test_readiness_dispatch` ×1, `test_sentinel_vocabulary` ×3, `test_status_reader_real_lines` ×1) — proven by running them on `main` in the same checkout. **Zero new failures.**

**Both threads answered and resolved.**

### Round 2 — the same defect in two more readers, found by the review of the fix

The first round corrected `reachable_from_main` and `is_truncated` and **left two more readers in the same state**. The review caught both; they are taken rather than argued, because the defect is identical and the argument was already made.

| finding | what it was |
| --- | --- |
| `r4073820387` `committed_text` | `git show` reports *"no such path in that revision"* by exiting NON-ZERO — the same shape the bound produces — so a fired bound **silently dropped pin sites from the sweep** and made `index_reproduces_at` report a committed index as uncommitted. **False negatives that look exactly like a clean answer.** Now raises `GitUnavailable`, whose docstring is the doctrine verbatim: *"The repository could not be asked. Never silently a pass."* `list_committed` already raises it for the identical condition **one call earlier in the same walk**, so the two readers now agree. |
| `r4073820387` `retention_holder` | `rev-parse --verify --quiet` reports absence by exiting non-zero, so an unavailable LOCAL read fell through, consulted the remote, and — where the namespace legitimately does not advertise the pin — **published ORPHAN on the strength of a local read that never happened**. Now returns the unavailability, with the detail carrying the exact phrase `verify()` matches to render it INCONCLUSIVE. |
| `r4073820457` `PinClassReport.truncated` | Annotated `bool` while `verify()` assigned the `None` the previous commit made possible — **an API that lied about itself**, introduced by that same commit. Now `bool | None`, with a test pinning the annotation beside the behaviour. |

**Three more regression tests, each failing against the pre-fix reader** — and the `committed_text` one also asserts that a genuinely uncommitted path still answers `None`, so the fix cannot over-reach.

**Measured:** `pytest tests/doc-health` → **1908 passed, 8 failed** — the same 8 that fail on clean `main` `ac50d70d` in this clone, and three more passing than before because of the tests added here. **Zero new failures.**

### Round 3 — the finding a zero-thread count would never have caught

The review at `bf90d87c` reported **"Findings: None"** with **zero unresolved threads**, and carried a **"previously missed"** item in its body — in code this branch had not touched — that was a real defect **this branch had introduced**:

> `is_truncated()` answers THREE states since this branch, and `None` is **FALSEY**. Two real-repository helpers tested `if truncated:`, so an unobservable truncation fell through to `verify()` and asserted `report.clean` — which **deliberately excludes `inconclusive`**. The required reachability proof could therefore pass over unanswered results whenever the remaining pins happened to be reachable.

Fixed at `18dd8158`: both helpers now test `is not False` / `is None` explicitly, and the second says **which** of the two conditions it hit, because *"could not observe"* and *"observed, and it is truncated"* send a reader to different remedies.

**The pattern is worth naming, because it appeared three times on one branch:** introducing a third state into a two-state reader leaves **every truth test on that reader silently wrong**, since the new state is falsey and reads as the old negative. The two production callers were corrected when the state was introduced; two test helpers were not.

**This is also why the review BODY gets read and not just the thread count** — a 0-unresolved count was true and told me nothing.

### Round 4 — the new failure mode had a caller nobody had walked to

`r4074075244`, **HIGH**, at `d78efc7c`: rounds 2–3 made `committed_text` **raise** `GitUnavailable` where it had returned `None`, and **did not walk its callers**. `ideation_readiness.index_reproduces_at` and `_committed_status` both call it, neither caught the new exception, so an unavailable git **took the readiness probe down** instead of answering the NOT-ASKED outcome each of them already has.

Fixed at `3c3deef2`. `index_reproduces_at` returns `(None, "…could not be read at…")` — its own unanswered shape, distinct in wording from *"is not committed"*, because an unreadable file and an absent one send a reader to different remedies. `_committed_status` returns `None`; its docstring now states **why the conflation is acceptable in that one place and nowhere else** — its single caller uses it only to choose a repair route to *print* for a pin already judged a defect.

**Named, because this branch has now produced it twice:** *changing a reader's failure shape is not finished until its callers are walked.* Round 2 caught it for the two production readers; this caught it for the two readiness probes.

### Round 5 — an unreadable ref is not an absent one, and `not None` is not a proof

Two findings at `3c3deef2`, **both correctness, both taken as fixes** at `c3fa4da6`. Both are the **same class this branch exists to remove**: an unaskable question silently converted into an answer.

| finding | disposition |
| --- | --- |
| `r4074256405` `resolve_main()` still treats an unavailable probe as an ordinary missing ref | **FIXED.** `MAIN_REF_ORDER` tries `refs/remotes/origin/main` first because it is the authoritative spelling; `refs/heads/main` is its stand-in **only in a clone that HAS no remote-tracking ref** — the one condition the fallback was written for. `--verify --quiet` spells *"not there"* with the same non-zero exit `_Unavailable` carries, so a probe that TIMED OUT on the authoritative ref promoted the local branch to the authority **for the whole run**, and `verify()` published every reachability verdict in the report against it. A pin that IS an ancestor of `origin/main` but not yet of a stale local `main` comes back **ORPHAN or HISTORICAL** from that. The loop now **stops** at an unavailable ref; `verify()` already answers a `None` `main` with INCONCLUSIVE at every site, so no new verdict was needed downstream. |
| `r4074256452` `not pc.reachable_from_main(...)` passes on the new `None` | **FIXED at both sites.** The reader returns `True`, `False` or `None` and nothing else, so `not X` and `X is False` differ on **exactly one value — `None`**, which is the value this branch introduced. `not None` is true, so **an ancestry read that never happened would have satisfied the very assertion written to prove one did.** Both now demand `is False`; the truthy sibling at the digest-collision fixture is spelled `is True` for the same reason, where it had been failing correctly only by accident. |

**The signature moves to `(value, detail)`** — this module's own shape, already carried by `is_truncated`, `remote_retention_refs` and `retention_holder` — because the two `None`s are **different facts and the report has to say which one it met**. A bare `None` would have left `verify()` printing `no \`main\` in this clone (looked for ...)` over a clone whose `main` may be sitting right there unread: one unmade observation traded for another. Nine call sites moved; measured, there are no others.

**Proved both ways.** `test_an_unreadable_origin_main_does_not_promote_the_local_branch` makes the WRONG answer **available** — `refs/heads/main` is real and readable, only the origin spelling times out — which is the only way to prove the right one is chosen. The module-wide timeout test cannot catch this, because it stops *every* probe: the case the old loop happened to get right. Against the pre-fix fall-through it fails with the defect in its own message:

```
AssertionError: the authoritative ref could not be READ, so the branch half of the
ref set is unknown — not ('refs/heads/main', '5e23da84...'), which is the stale
local branch answering a question that was put to origin
```

A second test pins that the fallback the ORDER exists for **still works**, so the narrowing did not swap one defect for another.

**Where round 5's second fix runs.** Those two assertions sit in `test_every_declared_repo_local_pin_in_this_repository_resolves`, which **skips in the authoring checkout** — a partial clone (`remote.origin.promisor true`), reported as such by the test's own skip reason — so **CI** is what exercises them. That is also why the change is safe there rather than merely intended: the return domain is three-valued, so `is False` can only fail where `not` passed on a `None`.

### Measurement at the head `c3fa4da6`

`pytest tests/doc-health/test_pin_reachability.py` → **77 passed, 8 skipped** (partial-clone skips, self-reported). `pytest tests/doc-health` → **1911 passed, 8 failed** — and those 8 were proved this round rather than recalled: the run was repeated **with these two files stashed**, and the two `FAILED` lists are **byte-identical** (`diff` clean, 8 vs 8). They are this environment's, not this commit's.

*(Round-5 tally as of `c3fa4da6`: five rounds, nine findings. Superseded by the round-6 tally below, stated as of the landing head.)*


### Round 6 — the same class again, and this time it predated the branch

One finding at `c3fa4da6`, **taken as a fix** at `77bc7ef9`. `verify_pin_reachability` called `pin_class.verify()` **with no handler for `GitUnavailable`**, which `verify()` raises from its opening `rev-parse` *and from every later inventory read*. A bound firing on the twentieth `git show` of a sweep therefore escaped as an **uncaught crash** and took down whatever surface called in — a pytest run, a preflight pass, a nightly — **at the moment a SKIP was owed and available**. The function's own contract already had the answer: a three-valued verdict whose third value is `PIN_PROBE_SKIP`, already returned for `report.inconclusive` one branch below.

**WIDENED, NOT CREATED — measured on `origin/main` rather than assumed.** `main` raises `GitUnavailable` in exactly two places: `committed_paths` (`main`:1834) and `verify()`'s opening `rev-parse` (`main`:2453). **`committed_paths` runs AFTER the opening probe**, so the later-read crash was **already reachable on `main`**. What this branch added was a second later raise site, `committed_text`. The regression test proves it **through the OLD site** — the pre-fix failure is raised at `pin_class.py:1976`, inside `committed_paths`, which is `main`'s line:

```
E  doc_health.pin_class.GitUnavailable: cannot list committed paths at bc92d20f...
   could not be performed: Command '[... ls-tree ...]' timed out after 30 seconds
scripts/doc_health/pin_class.py:1976: GitUnavailable
```

**SKIP and not FAIL, deliberately.** Every FAIL this function returns names a defect **in an artifact** and offers the repair route that artifact's class allows; there is no artifact defect here and no route to offer, only a question that could not be put. **The report is `None` because there is no report** — the inventory never completed, and a fabricated empty one would render as a clean sweep of zero sites, the silent pass this branch exists to prevent.

**The test arms the timeout for `ls-tree` ALONE** and asserts that `rev-parse` ran and succeeded first, because a test that stopped every probe would exercise the opening raise — the path that was never in doubt. A second test pins that the same surface still returns a real verdict and a real report when nothing is interfered with.

### Measurement at the head `77bc7ef9`

`pytest tests/doc-health` → **1913 passed, 8 failed**. The 8 `FAILED` lines are **byte-identical** to the list this clone produces with the branch's changes **stashed** (`diff` clean, 8 vs 8) — compared this round rather than recalled. Zero new failures.

*(Round-6 tally as of `77bc7ef9`: six rounds, ten findings. Superseded by the round-7 tally below, stated as of the landing head.)*

**Five of the six rounds found a defect introduced by the round before it**, and the sixth found one that predated the branch entirely. The pattern is worth stating once, since it is this branch's whole lesson: **changing a reader's failure shape is not finished until its callers are walked — and "the caller" includes the caller's caller.** Round 2 walked the two production readers, round 4 the two readiness probes, round 6 the surface above both.

### Round 7 — the group id was a lookup of a number the code already had

One **previously-missed** finding at `77bc7ef9`, `preflight.py:84`, **taken as a fix** at `91ffa6e6` — in code this branch had already touched once, which is the second time a previously-missed item has caught something a zero-thread count would not have.

`_run_entrypoint` spawns with `start_new_session=True` on exactly this path, so the child calls `setsid()` and **IS** the session and process-group leader: **the group id equals the child pid by construction.** `os.getpgid(proc.pid)` was therefore asking the kernel for a number the function already had — **and asking can FAIL where the answer stays valid.** If the leader has exited and been reaped while a descendant still holds the group and the inherited stdout/stderr pipe — which is *what made `communicate()` block into the bound in the first place* — the lookup raises `ProcessLookupError`, cleanup falls through to `_kill_direct`, and `proc.kill()` on an already-gone leader is a **no-op**. **The descendant then survives while the timeout finding is recorded**: precisely the accumulation `_terminate_group` exists to prevent, arriving by the one route the lookup opened. Signalling the group directly cannot meet that failure, because **a process group outlives its leader as long as any member remains**.

**PID reuse is not a risk, and the ordering is what makes that true rather than luck:** `_terminate_group` runs **before** the reaping `communicate()` in every caller, so the direct child is at worst a **zombie still holding its pid**, and an unreaped pid cannot be recycled. That is stated in the docstring, because a future kill-after-reap would *not* be safe and the next reader should not have to rediscover why.

**`_kill_direct`'s own docstring is corrected in the same commit** — it explained the fallback in terms of *"`os.getpgid()` raises `ProcessLookupError`"*, a call that no longer exists. A comment describing a line that is gone is a comment that will mislead.

**Proved both ways.** The test **builds the shape rather than approximating it**: the wrapper backgrounds a long sleep and **exits** rather than waiting, so the leader is gone within milliseconds while the descendant keeps the pipes open. `os.getpgid` is stubbed to raise the `ProcessLookupError` the premise names, since the reap it depends on is a race that cannot be scheduled. Against the pre-fix lookup:

```
E  AssertionError: the descendant (4045338) outlived the timeout: the leader had
   already exited, so a pgid LOOKUP failed and the direct kill hit a process that
   was gone — while the work this bound exists to stop kept running under a group
   nobody signalled
```

**Two assertions, because the behaviour and the design are different claims:** the descendant is dead (the outcome), and the lookup was never consulted (the reason it stays dead in *every* ordering, not only this one).

### Measurement at the landing head `91ffa6e6`

`pytest tests/doc-health/test_preflight.py` → **7 passed**. `pytest tests/doc-health` → **1913 passed, 8 failed**, and the 8 `FAILED` lines are **byte-identical** to the list this clone produces with the branch's changes stashed (`diff` clean, 8 vs 8) — compared again this round rather than carried forward. **Zero new failures.**

**Running tally, as of the landing head `91ffa6e6`: seven rounds, ELEVEN findings, all FIXED, all threads resolved.** The review at `91ffa6e6` reports **Findings: None** with **no Previously-missed block** and **no Suppressed block**, and all 12 checks pass.

**Six of the seven rounds found a defect introduced by the round before it**, and the seventh found one that predated the branch. Stated once, because it is this branch's whole lesson: **changing a reader's failure shape is not finished until its callers are walked — and "the caller" includes the caller's caller.** Round 2 walked the two production readers, round 4 the two readiness probes, round 6 the surface above both, and round 7 the one place that asked the kernel for something it already knew.

## Summary by Sourcery

Bound doc-health subprocesses and preserve honest inconclusive outcomes when git or validator operations cannot be completed.

New Features:
- Add timeout protection and failure handling for the remaining unbounded git and document-validation subprocesses in doc-health checks.

Bug Fixes:
- Prevent hung or unavailable subprocesses from blocking doc-health runs or producing misleading reachability, retention, reproduction, and readiness results.
- Preserve inconclusive or skipped outcomes when repository data cannot be consulted instead of reporting false passes, orphaned pins, or historical pins.
- Ensure timed-out validator process groups and descendants are terminated without masking the original timeout failure.

Enhancements:
- Propagate explicit unavailable states and diagnostic details through pin reachability and readiness checks while preserving existing caller contracts where appropriate.
- Treat authoritative main-ref and ancestry reads as unanswered when unavailable, and require explicit three-state handling in production and regression checks.

Tests:
- Add regression coverage for git and validator timeouts, spawn failures, unavailable repository reads, three-state reachability, readiness mapping, and descendant process cleanup.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
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