Skip to content

Refuse a second praktika run against a temp directory already in use - #116121

Closed
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:praktika-refuse-concurrent-temp-dir
Closed

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:praktika-refuse-concurrent-temp-dir

Conversation

@groeneai

@groeneai groeneai commented Aug 24, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

...

Description

On PR #116044 the Code Review job posted its full review, then went red anyway: praktika
reported Job killed or terminated, no Result provided, the step exited 1 with
TypeError: 'NoneType' object is not iterable, and 82% of its own job.log was NUL.

The job's review agent runs with -s workspace-write and elected to verify the PR by running
a nested python3 -m ci.praktika run "integration" ... inside the live job's own checkout.
praktika's state files are per-directory (Settings.TEMP_DIR, i.e. ./ci/tmp), so the nested
run wrote over the outer job's files. It opens RUN_LOG in "w" mode, truncating job.log
while the outer writer still held a large offset, and the kernel zero-filled the hole - that
is the NUL log. It also rewrote environment.json with its own JOB_NAME and an empty
JOB_KV_DATA, and _Environment.get() re-reads that file on every call, so the clobber was
permanent: the outer job wrote its real result under the wrong filename,
result_code_review.json stayed PENDING, and praktika truthfully reported no result. That
not-ok result opened the Slack-feed branch, where the erased commit_authors raised the
TypeError.

This takes the temp directory as a non-blocking flock at the top of the run branch, held
for the invocation, so a second run against the same directory refuses at once while a run in
any other checkout is unaffected. It sits before workflow discovery, which already writes
environment.json. Only BlockingIOError is contention; any other OSError propagates,
mirroring StatusFile.cpp.

A/B harness: without the change the outer log ends 96.8% NUL, with it 0% and byte-identical.
Refusal is independent of --ci, covers pre_hooks, and survives SIGKILL. Blast radius is
bounded: each job step already runs rm -rf ./ci/tmp before praktika run and flock is
per-inode, so a leaked lock cannot block the next job, and the empty lock file changes no
digest.

Validation matrix and deliberate omissions
arm result
A/B log corruption, 507000-byte offset (real log 510578) before 96.8% NUL (490748/507040) / after 0%, prefix md5 intact
nested run reached open(RUN_LOG, "w") (arming assertion) yes before / no after
the 3 shared files under refusal all md5-identical
absent environment.json stays absent yes; unlocked control does create it
fresh checkout, temp dir absent proceeds, no FileNotFoundError
same arm with --ci refuses, files identical
unrelated setsid sibling holder refuses
pre_hooks shape (child of the holder) nested refuses, outer proceeds
different temp directory while first holds proceeds; same-dir control refuses
holder SIGKILLed next run acquires
pre-existing content in the lock file survives (mode "a")
contention vs bad descriptor BlockingIOError 11 vs plain OSError 9, uncaught
docker bind mount, host holds BUSY 11; holder killed: ACQUIRED
temp-dir spellings (relative, absolute, trailing /, .., symlink) one lock identity
leaked holder + the job step's rm -rf ./ci/tmp next job acquires (fresh inode)
job digest with and without the empty lock file md5 identical

Two adjacent changes are deliberately not made. The unguarded
for commit_author in commit_authors is left alone: with the clobber prevented, an absent
commit_authors means malformed state and should keep failing loudly. The conditional store
in native_jobs.py is not the cause - _Environment seeds that key unconditionally on both
the Config-job and no-Config-job paths, and the real job log shows it present and empty.

No automated test is added: a ci/tests/ arm would be removed with that directory.


Workflow [PR]
Sync PR [sync-upstream/pr/116121]

praktika's state files are per-directory: Settings.TEMP_DIR (./ci/tmp) holds
job.log, environment.json and result_<job>.json, and nothing arbitrates access
to them. A second run in the same checkout therefore overwrites the state of
the one already running.

On PR ClickHouse#116044 that happened for real. The Code Review job's review agent runs
with -s workspace-write and elected to verify the PR by running a nested
`python3 -m ci.praktika run "integration" ...` inside the live job's own
checkout. Three things followed:

  - __main__.py opens RUN_LOG in "w" mode, truncating job.log while the outer
    writer still held a large offset, so the kernel zero-filled the hole. 82%
    of the uploaded job.log was NUL, which also made the failure hard to triage
    (the system grep classifies the file as binary and prints nothing).
  - generate_local_run_environment rewrote environment.json with
    JOB_NAME="integration" and an empty JOB_KV_DATA. _Environment.get() re-reads
    that file on every call and caches nothing, so the clobber was permanent.
  - The outer job then wrote its real, successful result under the wrong
    filename, because Result.create_from() falls back to the clobbered JOB_NAME.
    result_code_review.json stayed PENDING, so praktika truthfully reported
    "Job killed or terminated, no Result provided" for a job that had already
    posted its full review, and the resulting not-ok status opened the
    Slack-feed branch where the erased commit_authors raised
    TypeError: 'NoneType' object is not iterable.

Take the temp directory as a non-blocking flock at the top of the run branch and
hold it for the invocation. The placement is load-bearing: workflow discovery
itself writes environment.json (_Environment.get() creates and dumps it when
absent, on both fallback branches), so a lock taken just before the log open
would leave a real window uncovered. It is also independent of --ci, since a
nested --ci run truncates the log and rewrites JOB_NAME just the same.

Scoping by resolved directory rather than by process ancestry is deliberate: an
inherited marker would miss a concurrent run from an unrelated shell in the same
checkout, would wrongly reject a safe run in a different checkout, and is set
too late to cover pre_hooks. A kernel lock also releases on SIGKILL, which
matters because praktika killpg's its own children on timeout.

Only BlockingIOError is treated as contention; every other OSError propagates
with its own errno, since Utils.exit_with_error discards the original exception
and would otherwise turn an unsupported filesystem or a permission fault into a
permanent and false "another run is using this directory". This mirrors
StatusFile.cpp, which special-cases EWOULDBLOCK the same way and throws from
errno otherwise.

Validated with an A/B harness against a throwaway temp directory: without the
change the outer log ends 96.8% NUL with its prefix broken, with the change 0%
and byte-identical, and an arming assertion confirms the nested run reached the
truncating open in the first arm and not in the second. Also measured: the three
shared files are byte-identical after a refusal; an absent environment.json
stays absent (an unlocked control does create it); a fresh checkout with the
directory absent proceeds; --ci refuses too; an unrelated setsid holder is
caught; a pre_hook-shaped child refuses while its parent proceeds; a different
temp directory proceeds; a SIGKILLed holder leaves no stale lock; mode "a" does
not truncate a pre-existing lock file; and the lock is visible across a docker
bind mount, so run_in_docker jobs are covered as well.

The unguarded iteration over commit_authors is deliberately left as is: with the
clobber prevented, an absent key means malformed state and should keep failing
loudly rather than being silently defaulted. The conditional store in
native_jobs.py is not the cause either, since _Environment seeds that key
unconditionally on both the Config-job and no-Config-job paths and the real job
log shows it present and empty.

No automated test accompanies this: an arm under ci/tests would be removed along
with that directory.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Aug 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

An independent cold review plus a second-model gate ran against this diff before it was
pushed. Both came back with no blocking findings; the two nits below were fixed in the PR
text, not in the code.

# Finding Verdict
💡 The A/B corruption figure was written as 96.4% in the description but 96.8% elsewhere. Agreed. 490748/507040 is 96.8%; the description and the matrix now carry that, with the raw fraction shown so it can be checked. Two harness runs measured 488982 and 490748 NUL bytes of 507040, so the gate table gives the range rather than one figure.
💡 The description did not answer the first question a new global lock in ci/ raises: can a leaked lock wedge a later job? Agreed, and now stated. Every generated job step already runs rm -rf ./ci/tmp before praktika run (174/174 steps in pull_request.yml, 162/162 in master.yml, 8/8 in merge_queue.yml, from yaml_generator.py), and flock is per-inode, so the fresh mkdir yields a new inode. Measured: holder alive on the same inode refuses with EAGAIN; after the step's own rm -rf with that holder still alive the next run acquires.

Additional checks the review made independently of the change's own evidence:

  • The lock file cannot move a cache key. ci/tmp files are inside the ./ci digest walk
    (Utils.traverse_path uses os.walk, and no exclude_paths in ci/defs/job_configs.py
    excludes tmp), but Digest._calc_file_digest hashes content only, never names, and the
    lock file is always empty, so the md5 is identical with and without it. This is the one
    ci/ failure mode worth ruling out explicitly, since a caching or scheduling change has
    every PR in its blast radius rather than just this one.
  • No legitimate re-entry exists to break: no job command, pre_hooks, post_hooks or
    workflow hook in the tree invokes praktika run, and the one nested praktika invocation
    that does exist (praktika yaml, from _config_workflow) takes a different subcommand
    and is not gated.
  • git clean -ffd at runner.py:164 does not delete the gitignored ci/tmp, so a holder's
    own descriptor is never orphaned mid-run.
  • The carrier list was rebuilt from source before being compared with the change's own: the
    log open, workflow discovery's environment.json write, the local-env dump, _pre_run's
    result dump, pre_hooks/post_hooks, result_<job>.json and the artifact report are all
    dominated by the lock; yaml and infrastructure reach none of them. No divergence.
  • fcntl is safe here: every praktika runner is Linux or macOS, and praktika already
    depends on POSIX os.killpg, os.setsid and os.getuid.

@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ff791fe]

Summary: ❌

job_name test_name status info comment
CI Tests FAIL
ci/tests/test_settings_history_source_gate.py::test_renaming_a_record_in_place_is_allowed FAIL cidb

AI Review

Summary

This PR prevents concurrent praktika run invocations from sharing one temp directory by taking a non-blocking exclusive lock on .praktika.lock before workflow discovery and before job.log / environment.json are touched. The lock placement and failure mode look correct, but I do not think this should merge without a focused regression test because the only proof of the new refusal path currently lives in the PR description.

Tests
  • ⚠️ Add a small ci/tests regression that holds .praktika.lock in a helper process, monkeypatches Settings.TEMP_DIR to a temporary directory, and asserts that ci.praktika.__main__.main() exits with the refusal before workflow discovery. This path is now explicitly testable in isolation, and without coverage a later refactor of the run prologue can silently reintroduce the job.log / environment.json clobber.
Final Verdict

Request changes: the implementation looks sound, but the missing regression test leaves an important CI-corruption fix unpinned.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. An A/B harness where the outer job holds an open job.log at a 507000-byte offset (the real S3 log is 510578) and a nested praktika run fires against the same temp directory through the real CLI. Reproduces every run. Sizing was measured, not guessed: the nested run writes 16237 bytes, so a smaller outer offset leaves no hole (my first fixture used 7400 bytes and wrongly reported no corruption).
b Root cause explained? Yes. praktika's state files are per-directory. A nested run in the same checkout opens RUN_LOG in "w" mode, truncating job.log under a writer holding a large offset, so the kernel zero-fills the hole; it also rewrites environment.json with its own JOB_NAME and an empty JOB_KV_DATA, and _Environment.get() re-reads that file every call. The outer job then wrote its real result under the wrong filename, result_code_review.json stayed PENDING, praktika truthfully reported no result under the name it owns, and the resulting not-ok status opened the Slack-feed branch where the erased commit_authors raised TypeError.
c Fix matches root cause? Yes. The cause is two runs writing one state directory, so the fix enforces one writer per directory at the CLI entry, before the first shared write. Not a symptom guard: the or [] at the site that raised was considered and deliberately dropped, because with the clobber prevented an absent key means malformed state and should keep failing loudly.
d Test intent preserved / new tests added? No existing test is weakened or removed. No automated arm is added: a ci/tests/ file would be deleted along with that directory, which is being removed. 19 manual arms were run instead and the coverage loss is stated in the PR body.
e Both directions demonstrated? Yes. Unfixed tree: outer log ends 96.4-96.8% NUL across runs (488982-490748 of 507040 bytes; the nested run's own write size varies a little), prefix md5 broken, and an arming assertion confirms the nested run reached the truncating open. Fixed tree: 0% NUL, prefix md5 intact, nested run refused before the open. A guard control that asks the outer to lock on the unfixed tree self-aborts rather than producing a comparable-looking number.
f Fix is general across code paths? Yes. The lock sits at the CLI entry, which dominates every shared writer: workflow discovery (which itself creates environment.json), the log open, the local-env dump, the JOB_NAME rewrite on the --ci path, pre_hooks, post_hooks and _post_run. pre_hooks matter specifically because they run before the PRAKTIKA marker is set, so a marker-based design could not reach them. The sibling yaml and infrastructure subcommands were checked and reach none of the shared writes.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Seven temp-directory spellings (relative with and without ./, absolute, trailing slash, .., a symlinked directory and its target) all resolve to one lock identity. Refusal is independent of --ci, independent of process ancestry (an unrelated setsid holder is caught), and a fresh checkout with the directory absent proceeds rather than raising FileNotFoundError.
h Backward compatible? Yes. No setting, no serialization format, no user-visible behaviour, so no SettingsChangesHistory.cpp entry applies. The only new artifact is a zero-byte dotfile inside a temp directory; every consumer that scans that directory was checked and none matches it (the three globs are *.deb, *.rpm, *64.tgz*; two iterators filter on .deb and .log; the cache addresses a named file).
i Invariants and contracts preserved? Yes. Invariant: at most one run at a time writes into a given temp directory. The lock handle is assigned once, never closed and never reassigned, so it lives for the whole invocation and the kernel releases it at exit, including SIGKILL (verified, which matters because praktika killpgs on timeout). Mode "a" never truncates a pre-existing file (verified). On the error path only contention is treated as contention: BlockingIOError (errno 11) refuses, while a non-contention OSError (errno 9 measured) propagates with its own errno, since the exit helper discards the original exception and would otherwise render a real errno unrecoverable.

Session id: cron:clickhouse-impl-slot-40:20260824-121800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @maxknv, could you review this? A Code Review job posted its review and then went red, because its agent ran a nested praktika run in the same checkout: the nested run truncated the outer job.log and rewrote environment.json, so the outer result landed under the wrong filename and praktika reported no result. This takes the temp directory as a non-blocking flock at the top of the run branch, so a second run against the same directory refuses instead of clobbering it.

Comment thread ci/praktika/__main__.py
# discovery below already writes environment.json, so the lock precedes it.
temp_dir = Path(Settings.TEMP_DIR).resolve()
os.makedirs(temp_dir, exist_ok=True)
lock_file = open(temp_dir / ".praktika.lock", "a")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The new refusal path is one of the rare praktika run fixes that is cheap to lock down with an automated test, because it fires before workflow discovery or any real job setup. A focused ci/tests case can hold .praktika.lock in a helper process, monkeypatch Settings.TEMP_DIR to a temporary directory, call ci.praktika.__main__.main(), and assert that it exits with this error instead of touching the workflow loader.

Right now the only proof of the guard lives in the PR description. Without a regression test here, a later refactor of the run prologue can silently re-open the job.log / environment.json clobber this PR is fixing.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed on the fact: this guard has no automated regression test, and a later refactor of the run prologue could re-open the clobber silently. That risk is real and correctly identified.

I am declining the remedy, because it names ci/tests. That directory is being removed: #115650 ("Remove ci/tests (attempt 2)") deletes it wholesale (68 files, -22,695 lines), including the CI Tests job wiring in ci/defs/job_configs.py, and the standing instruction from @ alexey-milovidov is "We don't use ci/tests, they will be removed." A cell added there would be deleted with the rest.

There is also no sanctioned alternative home for a praktika-level assertion today: 31 of the 32 pytest files in this repo that import praktika live in ci/tests, and the only other one is vendored (contrib/silk). So I am leaving the guard covered by the manual arms recorded in the PR description, and stating the coverage loss there rather than putting the assertion somewhere unsanctioned.

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ff791fe32 with master 95607bfa9 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of a15a2423f; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 709.21 MiB 706.16 MiB -3.04 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

6 translation units recompiled, 4 s compile time in total, 6 of them have a recent master baseline.

Job report

@maxknv

maxknv commented Aug 24, 2026

Copy link
Copy Markdown
Member

fix is comming in ai review job. it must not allow it.

@maxknv maxknv closed this Aug 24, 2026
@groeneai

groeneai commented Aug 24, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ff791fe

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
CI Tests / test_settings_history_source_gate.py::test_renaming_a_record_in_place_is_allowed pre-existing trunk gate failure after the 26.9 version bump, not reachable from this diff #116107 (mine, open)
request-reviews-fork superseded run cancelled by a newer push of the same workflow; 4 later runs of the same job on this head are skipped not a test failure; no owner needed

Not caused by this PR: my diff is one file (ci/praktika/__main__.py, +17) and the failing test
has zero references to it, so it cannot reach the change. The test file blob is identical to
master's. Onset was 2026-08-24 10:49:41Z across 16 distinct PRs, 3 h 35 min before this head was
published at 14:24Z. Locally the whole file goes 12/12 with #116107's patch applied and fails
without it.

Finish Workflow succeeded, Style check and CH Inc sync succeeded, 0 checks queued or
in progress on this head.

Session id: cron:our-pr-ci-monitor:20260824-160000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood, and I will not reopen or re-push.

One scope note for the job-side fix: the clobber is not specific to the integration job the agent tried to run. job.log and environment.json are fixed paths under Settings.TEMP_DIR (ci/praktika/settings.py:62-63), so any nested praktika run in the same checkout truncates the outer job's log and rewrites its environment, which is what put the outer job's real result under the wrong filename (result.py:139-140 falls back to the clobbered JOB_NAME) and left result_code_review.json at PENDING. So blocking praktika run in general, rather than that one job name, is what closes all three symptoms.

@groeneai

Copy link
Copy Markdown
Collaborator Author

This recurred on 2026-09-23. The Code Review job on #121820 finished its review with
Status: Approve and then went red and discarded it:
https://github.com/ClickHouse/ClickHouse/actions/runs/35899265893/job/107313105965

Same mechanism as here. At 18:06:15Z the codex agent ran
python3 -m ci.praktika run "integration" --test test_replicated_database_active_node_taken
in the job's own checkout, which is the command .claude/CLAUDE.md documents for running
integration tests. Without --ci that is the local path: Runner.run truncates
ci/tmp/job.log at runner.py:1335, then generate_local_run_environment dumps
PR_NUMBER=-1 over ci/tmp/environment.json. After that post-or-update skipped the comment
("got -1"), the CIDB insert was rejected (Code: 72, unsigned column), and the job.log upload
hit assert pr_number > 0 or branch, so the approving review, the CIDB row and the job log were
all lost.

While looking for your job-side fix I found ci/praktika/ai_review.py, which you added on
2026-08-26, two days after your comment above. Its praktika review entry point gives the model
read-only tools and applies the GitHub writes in trusted code, so a nested shell command is not
possible at all. But ClickHouse's Code Review job is still on
python3 ./ci/jobs/copilot_review_job.py --codex (ci/defs/job_configs.py:296), nothing in the
repo invokes praktika review, and there is no ci/prompts/ directory for its --prompt file.

So I do not think the choice is mine, @maxknv. Which would you prefer?

  1. Wire the job to praktika review. The provider/model and a ci/prompts/code_review.md are
    your call, and it drops the agent's shell, its gh access and its ability to run anything
    locally.
  2. Keep the codex reviewer and give each attempt a disposable clone as its workspace, the way
    investigation_clone does in revert_ci_regressions.py, so the job's ci/tmp is not inside
    the agent's writable workspace.

I have option 2 planned and I will not push anything until you say which one you want.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect manual approve Manual approve required to run CI pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants