Skip to content

fix(tests): isolate concurrent pytest runs with per-run tmpfs basetemp - #1785

Merged
Sinity merged 1 commit into
masterfrom
feature/fix/pytest-basetemp-per-run-isolation
Jun 5, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/fix/pytest-basetemp-per-run-isolation

Conversation

@Sinity

@Sinity Sinity commented Jun 5, 2026 •

Copy link
Copy Markdown
Owner

Summary

pytest's tmpfs basetemp (#1026) was keyed only on the checkout, so two runs
from the same checkout shared one path and clobbered each other. This makes
the basetemp per-run while preserving per-checkout worktree isolation and
cross-run seeded-corpus reuse.

Problem

#1026 routes pytest temp dirs onto /dev/shm with
basetemp = pytest-polylogue-{sha1(rootpath)[:8]} — unique per checkout, but
identical for two concurrent runs from the same checkout. pytest
ensure_reset_dir()s an explicit basetemp at startup, so a second same-checkout
run rmtrees the first's xdist worker dirs mid-flight, surfacing as spurious
FileNotFoundError under setup.

This forced an undocumented "one pytest at a time per checkout" constraint and
manufactured false failures whenever two suites overlapped — e.g. an agent
launching background suites, or a manual run alongside a git-hook run. (This bit
hard in a recent session: every "let me re-run to be sure" launch made results
less trustworthy because the runs overwrote each other's tmpfs.)

Mechanism confirmed empirically: two concurrent invocations both resolve to
/dev/shm/pytest-polylogue-9b40a785.

Solution

tests/conftest.py:

  • Per-run basetemp. pytest-polylogue-{checkout}-{run_id}. The controller
    mints run_id once (pid + uuid4) and exports POLYLOGUE_PYTEST_RUN_ID
    (+ POLYLOGUE_PYTEST_CHECKOUT) so this run's xdist workers inherit the
    identical path while a concurrent run gets its own. The per-checkout hash
    (worktree isolation from verification runtime: outlier tests slow full baseline to ~6 min #1026) stays as the first component.
  • Seeded reuse preserved. The shared seeded_db root is re-keyed on the
    checkout hash instead of the now per-run basetemp. The seeded corpus is
    read-only after build and the build is flock-serialized, so cross-run and
    concurrent-run sharing is safe; without this re-key the corpus would rebuild
    every run.
  • Bounded RAM. Per-run basetemps are freed on sessionfinish (controller
    only — workers share it); a startup sweep reclaims orphans from SIGKILLed
    runs (>6h, excluding the shared seeded roots).

No production code touched; conftest.py is excluded from the clock-hygiene
lint, so the sweep's time.time() is in-policy.

Verification

# Concurrent same-checkout load test (the exact prior collision):
pytest tests/unit/pipeline -n 4   (x2 concurrent)
  -> both "403 passed", distinct basetemps (-{pid}-{uuid}), zero FileNotFoundError

# Seeded reuse across runs:
pytest tests/unit/core/test_schema_generation.py -n 2   (x2)
  -> build 27.06s -> reuse 17.73s (.build.done hit)
  -> root pytest-polylogue-seeded-<checkout> kept; per-run basetemps cleaned

devtools verify --quick  -> ruff/mypy --strict/render-all green

Follow-ups

The behavioral guard (don't launch overlapping suites) is documented separately
in global agent instructions; this PR removes the underlying hazard so an
accidental overlap no longer corrupts results.

Summary by CodeRabbit

  • Tests
    • Improved test execution infrastructure with optimized temporary directory management and automatic cleanup of stale test artifacts, enhancing test suite efficiency and resource utilization.

Problem: #1026 routed pytest temp dirs onto /dev/shm with a basetemp keyed
on sha1(rootpath)[:8] — unique per checkout, but IDENTICAL for two runs from
the same checkout. pytest ensure_reset_dir()s an explicit basetemp at startup,
so a second same-checkout run wipes the first's xdist worker dirs mid-flight,
surfacing as spurious FileNotFoundError. This forced a "one pytest at a time"
constraint and produced false failures whenever two suites ran concurrently
(agent background runs, a manual run alongside a hook run).

What changed:
- basetemp is now pytest-polylogue-{checkout}-{run_id}. The controller mints
  run_id once (pid + uuid) and exports POLYLOGUE_PYTEST_RUN_ID +
  POLYLOGUE_PYTEST_CHECKOUT so this run's xdist workers inherit the identical
  path while a concurrent run gets its own. Per-checkout grouping (worktree
  isolation from #1026) is preserved as the first component.
- The shared seeded_db root is re-keyed on the checkout hash instead of the
  now per-run basetemp, so cross-run reuse survives (the corpus is read-only
  after build and the build is flock-serialized). Concurrent runs share one
  seeded corpus safely.
- Per-run basetemps are freed on sessionfinish (controller only); a startup
  sweep reclaims orphans from SIGKILLed runs (>6h, excluding seeded roots),
  keeping /dev/shm bounded.

Verification:
- nix develop -c pytest tests/unit/pipeline -n 4 (x2 concurrent, same
  checkout): both 403 passed, distinct basetemps, zero FileNotFoundError.
- seeded_db consumer run twice: build 27.06s -> reuse 17.73s (.build.done),
  root pytest-polylogue-seeded-<checkout> kept; per-run basetemps cleaned.
- nix develop -c devtools verify --quick: ruff/mypy/render-all green.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Copilot AI review requested due to automatic review settings June 5, 2026 07:52
@coderabbitai

coderabbitai Bot commented Jun 5, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 349fea83-884b-4754-9ba5-ddcaf537b84d

📥 Commits

Reviewing files that changed from the base of the PR and between fb6b274 and d8bf6bd.

📒 Files selected for processing (1)
  • tests/conftest.py

📝 Walkthrough

Walkthrough

This PR refactors how pytest manages RAM-backed temporary directories in tests/conftest.py. The configuration now derives per-checkout and per-run identifiers to isolate test execution directories, sweeps stale basetemp directories from previous crashed runs, and adjusts the seeded database cache key to be checkout-based rather than run-based for improved cache reuse.

Changes

Tmpfs Basetemp Lifecycle

Layer / File(s) Summary
Basetemp lifecycle management and cleanup
tests/conftest.py
Import shutil, time, and uuid modules. Rework pytest_configure to derive POLYLOGUE_PYTEST_CHECKOUT (per-checkout hash) and POLYLOGUE_PYTEST_RUN_ID (per-run UUID), set config.option.basetemp to a unique per-run directory under /dev/shm, add helper _sweep_stale_tmpfs_basetemps to remove stale directories older than _STALE_BASETEMP_MAX_AGE_S, and introduce pytest_sessionfinish hook to clean up the controller's per-run basetemp on shutdown (skipping xdist workers and "seeded" directories).
Seeded database key alignment
tests/conftest.py
Update seeded-database shared-root suffix derivation to prefer POLYLOGUE_PYTEST_CHECKOUT environment variable over hashing the per-run basetemp, enabling the seeded database cache key to track checkout state for cross-run reuse.

🎯 3 (Moderate) | ⏱️ ~20 minutes

A rabbit hops through temp dirs with care,
Per-checkout and per-run, the state's laid bare,
Stale dirs swept clean, no clutter to fear,
Seeded caches dance 'cross runs, bright and clear! 🐰✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: fixing concurrent pytest run isolation via per-run tmpfs basetemp allocation.
Description check ✅ Passed The description comprehensively covers all required template sections with detailed problem statement, solution explanation, verification commands, and follow-ups; it is thorough and well-structured.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/pytest-basetemp-per-run-isolation

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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.

Pull request overview

This PR fixes flaky failures from concurrent pytest runs sharing the same tmpfs basetemp by making the tmpfs basetemp per-run (while retaining per-checkout isolation) and preserving cross-run reuse of the seeded corpus by re-keying it on the checkout hash instead of the basetemp.

Changes:

  • Make /dev/shm basetemp unique per run via {checkout_hash}-{run_id} and export env vars so xdist workers share the same run basetemp.
  • Add best-effort startup sweeping of stale per-run tmpfs basetemps and controller-only cleanup on pytest_sessionfinish.
  • Re-key seeded_db shared tmpfs root by checkout hash to preserve cross-run seeded corpus reuse.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread tests/conftest.py
Comment on lines +90 to +95
run_id = os.environ.get("POLYLOGUE_PYTEST_RUN_ID")
if run_id is None:
run_id = f"{os.getpid()}-{uuid.uuid4().hex[:8]}"
os.environ["POLYLOGUE_PYTEST_RUN_ID"] = run_id
_sweep_stale_tmpfs_basetemps(shm)
config.option.basetemp = str(shm / f"pytest-polylogue-{checkout}-{run_id}")
Comment thread tests/conftest.py
Comment on lines +130 to +134
if os.environ.get("PYTEST_XDIST_WORKER"):
return
if not os.environ.get("POLYLOGUE_PYTEST_RUN_ID"):
return
basetemp = session.config.option.basetemp
Comment thread tests/conftest.py
Comment on lines +111 to +117
cutoff = time.time() - max_age_s
for entry in shm.glob("pytest-polylogue-*"):
if "-seeded-" in entry.name:
continue
try:
if entry.is_dir() and entry.stat().st_mtime < cutoff:
shutil.rmtree(entry, ignore_errors=True)

@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: d8bf6bd036

ℹ️ 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 tests/conftest.py Resolved
@Sinity
Sinity merged commit e789ca5 into master Jun 5, 2026
5 checks passed
@Sinity
Sinity deleted the feature/fix/pytest-basetemp-per-run-isolation branch June 5, 2026 08:05
Sinity added a commit that referenced this pull request Jun 5, 2026
…w pytest (#1786)

## Summary

Adds `devtools test <pytest args>` — a focused inner-loop runner that
routes a
selection through the managed harness, so agents and humans never
hand-roll raw
`pytest`. Complements `devtools verify` (the full gate); it is not a
substitute.

## Problem

`devtools` owned the full verification gate (`verify`) but had no
comfortable
entrypoint for "run this file / `-k` expr / directory." The result:
agents reach
for raw `pytest`, hand-rolling worker counts, env, and tmpfs handling —
exactly
the ad-hoc path that, in a recent session, led to launching overlapping
suites
that raced on shared test state and produced false failures.

## Solution

`devtools/run_tests.py` (`devtools test`):

- Forwards any selection (paths, `-k`/`-m`, `-x`, …) to pytest via the
  control-plane dispatch's existing passthrough (`allow_extra_args` /
  `ignore_unknown_options`).
- Managed environment parity with `verify` (`POLYLOGUE_ROOT`,
  `POLYLOGUE_REPO_ROOT`, repo-local `PYTHONPYCACHEPREFIX`).
- Single-process default (`-n 0`) for fast focused runs; override with
an
  explicit `-n` or `POLYLOGUE_PYTEST_WORKERS`.
- Live, streamed output (unlike `verify`, which captures for
aggregation).
- A checkout-scoped `flock` serializes overlapping `devtools test` runs
so two
suites from one checkout don't burn CPU racing. Correctness under
concurrency
is already guaranteed by the per-run tmpfs basetemp (#1785); this lock
is the
  throughput guard. `POLYLOGUE_TEST_NO_LOCK=1` bypasses it.
- Empty selection prints guidance and exits 2 (does not silently run the
whole
  suite — that's `devtools verify`).

Registered as a featured catalog command; `docs/devtools.md` +
`AGENTS.md`
regenerated; `TESTING.md` steers the inner loop to `devtools test`.

## Verification

```
devtools test tests/unit/devtools/test_run_tests.py   -> 7 passed (dogfooded, -n 0)
# two concurrent runs, same selection:
  -> exactly one printed "waiting for in-flight run"; both passed (lock works)
devtools verify --quick   -> EXIT 0 (ruff/mypy/render-all/verify-doc-commands + all gates)
```

New unit tests in `tests/unit/devtools/test_run_tests.py` cover
worker-default
and override, `--json` stripping, the no-selection guard, exit-code
passthrough, and managed-env contents.

Co-authored-by: Claude Opus 4.8 <[email protected]>
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 77.F079 / P2: fixed-already at the checked revision: The contained runner allocates a new pid/time-based basetemp for each invocation when none is explicitly supplied; it does not reuse the inherited POLYLOGUE_PYTEST_RUN_ID as the directory name. See devtools/pytest_slot.py:382.

Only the rows listed above are dispositioned. Held findings remain open.

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