Skip to content

Stop a full disk from killing a perf-comparison shard silently - #112145

Merged
alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-perf-comparison-shard-error
Jul 28, 2026
Merged

alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-perf-comparison-shard-error

Conversation

@groeneai

@groeneai groeneai commented Jul 27, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #111377

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):

Reduces the disk usage of the performance comparison check by dumping only the system.trace_log columns the report reads and by dropping an unused intermediate file, and makes a truncated ci-checks.tsv a reported warning instead of an uncaught exception that killed the shard before it uploaded any artifacts.

Description

A Performance Comparison (<arch>_release, <base>, N/6) shard sometimes reports a job-level
ERROR with info: '', links: [], and every S3 artifact (job.log, report.html,
all-queries.html, logs.tar.zst) returning HTTP 403 because nothing was ever uploaded.
CIDB then has no query rows at all, so the red check names no query and cannot be acted on.

The runner root filesystem fills up completely. From the harness's own df -h
(ci/praktika/runner.py:323 at job start, :513 at job end) on run 30208735413,
sha 6c5c34bf727ee7, arm_release release_base 2/6:

start 17:07:36   /dev/root 194G    8.8G used   185G avail    5%
end   18:26:16   /dev/root 194G    194G used   4.0M avail  100%

185 GB in 79 minutes. The chain, in log order:

  1. get_profiles launches ten concurrent log dumps, two of which are
    select * from system.trace_log.
  2. Both die on Code: 159 TIMEOUT_EXCEEDED: elapsed 300011 ms after streaming TSV to disk
    for the full 300 s. They run as ||: &, so the failure is swallowed and the partial
    multi-GB files stay on disk.
  3. Code: 75 ... errno: 28, No space left on device writing
    unstable-run-traces.{left,right}.rep, then sort: write failed.
  4. The same errno 28 hits the clickhouse-local that recreates ci-checks.tsv, leaving
    that file present but 0 bytes.
  5. performance_tests.py checks only Path(...).is_file() (true for a 0-byte file) and then
    does a bare next(f), so StopIteration escapes main() before praktika uploads the
    artifacts
    - which is the reported no-artifact signature.

So there are two separate problems: a dump that writes far more than anything reads, and a
parse that turns a disk failure into an invisible one.

Three changes:

  • Project the trace_log dump. The only consumer is the stacks table, which reads
    exactly query_id, trace, trace_type, size. The dropped columns include the per-frame
    symbols and lines arrays, by far the largest fields in the table, and unused because the
    harness resolves symbols separately through *-addresses.tsv. This applies the rule the
    same function already follows for query_log ("The other ~70 columns are dropped to keep
    the artifact smaller"), and finishes what 4f8806c started - that commit excluded
    *-trace-log.tsv from the archive while it was still written to disk in full.
    On a 3000-row fixture carrying the real trace_log schema the dump shrinks 23.5x, and the
    resulting report/stacks.$version.tsv is byte-identical (same md5) to the one built from
    the full dump, over seven of the nine trace_type values and both arms of the byte-weighted
    multiIf (the two not in the fixture, MemoryAllocatedWithoutCheck and Instrumentation,
    both fall in the count() arm the other seven already exercise).
    Removing size from the projection as well makes stacks fail with
    Code: 47 UNKNOWN_IDENTIFIER, so the column list is minimal.

  • Delete unstable-run-traces.$version.rep. Nothing in the repository reads it: after
    removal, grep -rn "unstable-run-traces\|unstable_run_traces" . returns no hits. It is not
    referenced by any report - the flamegraphs use report/stacks.$version.tsv - and it is the
    first file to hit errno 28 above. If it is wanted as a debugging artifact, restoring it is
    a one-line revert; I removed it because it costs a large write plus an extra full pass over
    the trace data for no reader.

  • Publish ci-checks.tsv by rename, and contain its parse. compare.sh now writes the
    file to a sibling ci-checks.tsv.tmp and publishes it with && mv, so the final path is
    only ever absent or complete. The chaining is load-bearing rather than stylistic: this write
    is the last thing the job does and its failure is swallowed by the ||: on the call, which
    suppresses errexit for the whole function body, so a separate next-line mv would run
    after a failed write and publish the torn file. A same-directory rename allocates no data
    blocks, so it still works on the full disk that caused the problem. With the final path
    absent, the importer warns and imports nothing - the pre-existing warning, now raised
    inside import_ci_checks_results so that all three outcomes (absent, no importable row,
    importable) are behaviourally testable rather than split between the caller and the helper;
    the shard's
    verdict comes from report.html, not from this file.

    The parse is contained as well, both for a legacy file and for a write interrupted before
    the rename. An ENOSPC failure in the clickhouse-local that writes this file leaves an
    arbitrary byte prefix on disk, not only an empty file: a partial header line, or a row cut
    mid-field. The parse moves into read_ci_checks_results, which
    reads the file as bytes and decodes leniently, because a prefix can end inside a multi-byte
    character; treats an unterminated final line as cut and drops it, because the file is written
    through a File(TSVWithNamesAndTypes) table and every complete row is newline-terminated;
    accepts a row only when every column is present; reads every field with .get so a truncated
    header line cannot raise; guards the duration conversion; and reports separately whether the
    file was importable at all and how many rows it had to skip. Both warning branches that
    already existed are reused. Dropping the unterminated line matters because a number cut after
    its first digits still parses: sweeping every truncation offset of a realistic file, prefixes
    previously either raised an uncaught exception or were reported clean while carrying a
    duration that differed from the truth; now neither happens, the only prefixes reported clean
    are the genuine row boundaries at or after the summary row (3 of the 1287 offsets of the
    fixture the tests sweep), and a complete file parses
    identically. A future disk failure
    then still fails the shard, but with artifacts and the real verdict compare.sh had already
    written into report.html, instead of an opaque no-artifact ERROR.
    ci/tests/test_perf_ci_checks_parse.py covers those shapes and the offset sweep, and
    ci/tests/test_perf_upload_results_atomic.py runs the real publish block from compare.sh
    under bash to pin both directions of the rename, and that the publish is a rename rather than
    a copy - a copy satisfies every terminal-state assertion while re-opening the torn-file
    window on a full disk. Both run on every PR through the existing CI Tests job, whose digest
    includes ./ci.

Two documentation files described the trace dump by column index ($7, $19) and told the
reader to extract *-trace-log.tsv from logs.tar.zst. Both claims were already wrong before
this PR, since 4f8806c removed that file from the archive, and the projection also
invalidates the indices. They now point at report/stacks.$version.tsv, which is what the
report's own flamegraphs are built from.

Scope, plainly: the first two changes reduce disk consumption, they do not prove the shard
stays green. All six release_base shards currently finish with single-digit-percent
headroom, and two master_head shards do as well (end-of-job usage on one commit:
release_base 93/97/92/91/96/92 %, master_head arm 89/68/81/68/59/96 %, amd
63/84/59/97/67/85 %), so the remaining capacity question is fleet-side, not a repo change. The third change is what guarantees a recurrence is visible.

Two things this deliberately does not touch: the 300 s trace-dump timeout swallowed by
||: & (pre-existing, and profile data is silently partial today because of it), and the
separate release_base failure where the baseline commit's perf.py rejects --binary /
--http-port (Code: 125 then Code: 107), which fails all six release_base shards
uniformly and is a harness-design question for the perf owner.

Version info

  • Merged into: 26.8.1.324 (included in 26.8 and later)

groeneai added 8 commits July 27, 2026 01:02
A perf-comparison shard could fill the runner root filesystem and then die in a
way that uploaded no artifacts at all, so the red check named no query and could
not be acted on. From the harness's own df -h on run 30208735413
(arm_release release_base 2/6): 8.8G used / 185G avail / 5% at job start,
194G used / 4.0M avail / 100% at job end, i.e. 185 GB in 79 minutes.

Chain: get_profiles runs two `select * from system.trace_log` dumps; both die on
Code 159 TIMEOUT_EXCEEDED after streaming TSV for the full 300 s, and because
they are `||: &` the failure is swallowed while the partial multi-GB files stay
on disk. errno 28 then hits unstable-run-traces.*.rep, and finally the
clickhouse-local that recreates ci-checks.tsv, leaving that file present but 0
bytes. performance_tests.py checks only Path(...).is_file(), which is true for a
0-byte file, and then calls a bare next(f), so StopIteration escapes main()
before praktika uploads the artifacts.

Project the trace_log dump to the four columns its only consumer (the `stacks`
table) reads. The dropped columns include the per-frame `symbols` and `lines`
arrays, the largest fields in the table and unused because symbols are resolved
separately through *-addresses.tsv. This is the rule the same function already
applies to query_log, and it finishes what 4f8806c started: that commit
excluded *-trace-log.tsv from the archive while it was still written to disk in
full. On a 3000-row fixture with the real trace_log schema the dump shrinks
23.5x and report/stacks.$version.tsv is byte-identical; dropping `size` as well
makes the query fail with Code 47, so the column list is minimal.

Delete unstable-run-traces.$version.rep: no code in the repository reads it, it
appears in no report (flamegraphs use report/stacks.$version.tsv), and it is the
first file to hit errno 28 above.

Read the two ci-checks.tsv header lines defensively and reuse the warning branch
that already exists for a missing file, so a future disk failure still fails the
shard but with artifacts and the verdict compare.sh had already written into
report.html.

The first two changes reduce consumption; they do not by themselves guarantee
headroom, since every shard of this check currently ends with single-digit-percent
free space. The third makes a recurrence visible.
The previous commit guarded only the two header lines of ci-checks.tsv, which
covers a 0-byte and a header-only file. Those are two points in the space of
byte prefixes an ENOSPC failure can leave behind, and not the common one.

compare.sh recreates ci-checks.tsv through a ClickHouse File-engine table, and
WriteBufferFromFileDescriptor::nextImpl loops on ::write and throws only after
a partial write has been flushed, so the leftover prefix has arbitrary length
and usually ends mid-row. csv.DictReader fills a short row's missing fields
with restval, which defaults to None, so float(row["test_duration_ms"]) then
raises TypeError; a cut inside the duration field raises ValueError; and a
truncated header line yields fewer field names than a data row has cells, so
subscripting the row raises KeyError. Each of those escapes main() and kills
the job before praktika uploads the artifacts, which is the exact failure the
guard was added to remove. Sweeping every truncation offset of a realistic
1685-byte file, 150 of 3147 offsets died that way.

Extract the parse into read_ci_checks_results and contain the row loop there,
following read_test_results in stress_job.py: read each consumed field with
.get, skip and count a row that was cut short, and guard the numeric
conversion. Rows that did parse are still reported, since degrading beats
dying. Passing restval="" instead would only turn the TypeError into a
ValueError, so the guard belongs on the consuming code.

The helper is also what makes this testable. ci/tests runs in every PR through
ci_tests_job.py with include_paths=["./ci"], so ci/tests/test_perf_ci_checks_parse.py
covers the absent, empty, header-only, headers-without-rows, well-formed,
mid-row-truncated, truncated-header and summary-row shapes, plus a sweep of
every truncation offset. Reverting either guard makes it fail.

Finally, two skill docs described the trace-log dump positionally, by a symbols
column that the previous commit's projection removes and that logs.tar.zst has
not shipped since 4f8806c. Point both at report/stacks.$version.tsv,
which is symbolized and is what the report's own flamegraphs use.
The parse guard added earlier only rejected a file with fewer than two lines.
An ENOSPC prefix usually ends mid-row, and csv.DictReader fills the missing
fields with restval, so a row cut inside test_duration_ms after its first
digits was accepted with a corrupt value: 25 of the 3147 truncation offsets of
a realistic file were reported clean while carrying a wrong duration, and an
unterminated types line counted as a header, so a truncated file was reported
clean with no warning at all. A byte prefix can also end inside a multi-byte
character, which the strict decode rejected with UnicodeDecodeError, escaping
main() before praktika uploads the artifacts.

compare.sh writes ci-checks.tsv through a File(TSVWithNamesAndTypes) table,
which terminates every row, so a non-empty trailing fragment is a line cut
mid-write: drop it and report the file as not clean. A row is accepted only
when every column is present, not only the three that are read. The decode is
lenient, as in stress_job.read_test_results.

The new tests also pin the call site in main(): the earlier tests all called
the helper directly, so deleting either warning or the results[-2] assignment
left the suite green.

The perf-report skill's stacks.tsv recipe keyed on math.query2, which is the
perf.py query-id spelling and never appears in that file, so the command
silently produced an empty file. Key on the test, query_index and trace_type
columns the file actually carries, and keep the trace types apart: CPU and Real
count samples while MemorySample and JemallocSample sum bytes.
The import block lived inline in main(), so the only thing that could test it
was a set of substring assertions over inspect.getsource(main). Those cannot
see branch semantics: inverting `if not complete:` there leaves all five
assertions passing, while an incomplete file would be imported with no warning
and a complete one skipped.

Extract the block into import_ci_checks_results and drive it directly, so the
warnings and the assignment are asserted as behaviour. The inverted branch now
fails three tests. The warning strings and the assignment target stay pinned
textually as well, so a rewrite cannot quietly drop a log line operators grep
for.

Two parser tests documented a guard they did not reach. Both built their
fixture without a trailing newline, so the cut row was the unterminated final
line and was dropped by the trailing-fragment rule before reaching any row
guard; the malformed count they asserted came from that rule. Terminate both
fixtures so the cut row is a complete line and does reach the guards, and
correct the comments to name the branch actually taken.

That leaves one branch the suite could not reach, the float() conversion guard.
Sweeping the cross product of a truncated names line and a truncated data row
(29670 shapes) finds exactly one shape that reaches it: a names line cut so
that test_duration_ms is the last field, over a row whose duration cell is
empty. Every field the header declares is then present, so the all-columns
guard passes and float("") raises ValueError. Added as a test.

Also pin main()'s is_file() guard, which keeps the importer away from a shard
that died before compare.sh wrote the file at all.

No behaviour change to the parser or to compare.sh.
The parse guards added in this PR cover a prefix that ends mid-row, but not one
that ends on a line boundary. Driving the parser over the newline-terminated
prefixes of a realistic file, all of them are reported clean: headers only,
headers plus the summary row, and headers plus summary plus one of two query
rows. The third is the damaging one, a strict subset of the shard's queries
assigned into CIDB with nothing in the log saying so.

Fix it at the write. compare.sh created the File-engine table straight at the
final path, and upload_results is invoked as `time upload_results ||:`, which
suppresses errexit for the whole function body, so the failure of that write was
swallowed and a torn file was left where the importer would find it. Write to a
sibling ci-checks.tsv.tmp and publish with `&& mv`: a same-directory rename
allocates no data blocks, so the final path is only ever absent or complete, and
the absent case already prints a warning from main(). The rename is chained with
`&&` rather than written as the next statement precisely because errexit is
suppressed here; as a separate statement it would publish the torn file after a
failed write, which is worse than the status quo. clickhouse-local exits
non-zero on a failed flush in both dispositions, 75 with
CANNOT_WRITE_TO_FILE_DESCRIPTOR when SIGXFSZ is ignored and 153 otherwise, so
the guard holds. Same idiom as analyze-confirm's raw.tsv.tmp earlier in the file.

The parser also documented a run that cannot happen. upload_results unions an
unconditional single-row summary select into every ci-checks.tsv, with no WHERE
on either side, so the shortest file a completed run can write is two header
lines plus that row: a zero-query run writes three lines, verified against the
File engine. A file with no data row is therefore a prefix, not an empty run.
Tighten the completeness predicate from two lines to three and correct the
docstring and the test that asserted the opposite.

The parser's prefix tolerance stays as belt-and-braces for a legacy file or an
interrupted rename.
Two behaviours this PR relies on had no assertion of their own.

The parser drops an unterminated final line because a complete ci-checks.tsv is
newline-terminated, so a final line without its newline was cut mid-write no
matter how much of it arrived. Every existing test for that rule cut the row
somewhere a row guard would also have rejected it, so the rule itself was
unpinned: a prefix ending exactly at a row's last byte carries every declared
column, each value parses, and the value it would import is the correct one -
nothing but the framing can catch it. Appending the fragment back instead of
counting it left the whole suite green. A test for that shape now fails under
each of three ways of trusting the fragment.

The publish protocol has no Python surface at all. compare.sh writes the file to
a sibling .tmp path and renames it with `&&`, which is what keeps the final path
either absent or complete when the write dies on a full disk - and for a prefix
that ends on a line boundary at or after the summary row, that protocol is the
only thing standing between a torn file and an import that looks clean, because
two header lines plus the summary row is byte-for-byte what a zero-query run
writes. Reverting the rename left all twenty tests green. The new test extracts
the real block from compare.sh between anchor comments and runs it under bash
with a stubbed clickhouse-local: on success the file is published and no .tmp is
left, on a failed write the final path is absent and the partial .tmp remains,
and the script still exits 0 as the call site's `||:` dictates. It fails against
the form this commit's parent replaced and against a separate-`mv` variant, so
it measures the chaining rather than describing it.
Both of these behaviours are introduced or made load-bearing by this PR and
neither was covered by a test that could see it break.

The publish block opens with `rm -f ci-checks.tsv ci-checks.tsv.tmp`. Deleting
that line leaves a previous run's complete-looking ci-checks.tsv at the final
path when a write fails, so the importer reports the wrong run's queries with
nothing warning - worse than the truncation this change fixes. Dropping only the
`.tmp` half lets a previous attempt's torn temporary file be prepended to the new
content and then renamed into place: the File engine opens with O_APPEND and
`engine_file_truncate_on_insert` defaults to false, so an insert adds to whatever
is already there. Both modes are reachable because perf_wd is never wiped at job
start and main supports --param re-entry. The test stub now appends rather than
truncates, so it models the real writer, and two seeded-directory tests pin both
halves of the line; the pre-existing fresh-directory tests cannot see either
mutant, which is why the pair is needed.

The presence check for ci-checks.tsv moves from main() into
import_ci_checks_results, so all three outcomes - absent, truncated, complete -
are behaviourally testable instead of split between the caller and the helper.
This matters more here than before: the atomic publish deliberately leaves the
final path absent on a failed write, so absent is now an expected outcome, and an
unguarded open() on that path raises FileNotFoundError out of main() before
praktika uploads the artifacts, which is the failure being fixed. The warning
string is unchanged and was moved, not duplicated. Verified byte-for-byte
behaviour-preserving on all three outcomes against the previous head.
Asserting only the terminal file states of the publish block cannot tell a
rename from a copy. Replacing `&& mv ci-checks.tsv.tmp ci-checks.tsv` with
`&& cp ci-checks.tsv.tmp ci-checks.tsv && rm -f ci-checks.tsv.tmp` satisfies
every path, absence and content assertion in
ci/tests/test_perf_upload_results_atomic.py, and it re-opens the failure this
change exists to close: with `ulimit -f 0` standing in for a full filesystem,
`mv src dst` still publishes the complete file whereas `cp src dst` leaves dst
at size 0 with src intact - a torn file at the exact path the importer reads.
A same-directory rename allocates no data blocks, which is the whole reason it
survives the full disk.

Inode identity is what separates the two mechanisms: `mv` preserves the inode
the writer produced, `cp` plus `rm` allocates a new one. The stub now records
`stat -c %i` of the target it wrote, derived from the SQL as before, and both
success-direction tests assert that the published file carries that inode. The
copy substitution now fails both of them on that assertion and nothing else,
while the two failed-write tests still pass.

The import_ci_checks_results docstring said a truncated or empty file is not
imported. Only a file with no importable data row is skipped; one that lost
individual rows imports the intact ones and reports the count, which is what
the shipped test asserts. The prose is narrowed to match the behaviour; no
behaviour, warning string or test changed.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110844&sha=5103f6e068af287dd2d3cf67d86c8297234416dd&name_0=PR
@groeneai

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

An independent reviewer read the resulting code cold, without the author's evidence, and a
second model re-reviewed the diff. Over 7 fix rounds that is 8 review passes and 18 findings
from the second model, plus 24 from the cold reviews. The substantive ones and their verdicts:

# Finding Verdict
❌ select * from system.trace_log writes columns nothing reads; the dump can exhaust the runner disk Agreed - projected to the four columns the stacks table selects; output verified byte-identical
❌ unstable-run-traces.$version.rep has no reader and is the first file to hit errno 28 Agreed - deleted; repo-wide grep for it returns no hits
❌ A disk-full truncation after the two header lines still escapes main before artifacts are uploaded Agreed - the parse moved into a helper that tolerates any byte prefix
❌ An ENOSPC prefix ending inside a multi-byte character still raises UnicodeDecodeError Agreed - the file is read as bytes and decoded leniently, as stress_job.read_test_results does
❌ A row cut after the first digits of test_duration_ms parses, so a truncated file was reported clean with a wrong duration Agreed - an unterminated final line is dropped, and a row is accepted only with every column present
⚠️ The documented stacks.$version.tsv command keyed on math.query2, which is a query id and never appears in that file, so it silently produced an empty profile Agreed - keyed on the test, query_index and trace_type columns the file carries
⚠️ No test would fail if a truncation guard were reverted or stopped warning Agreed - guards are mutation-proven individually, and the import branch semantics are now exercised rather than only grepped for
⚠️ Two truncation tests documented a guard their fixture never reaches Agreed - fixtures corrected so each row reaches the guard its comment names
⚠️ Asserting only the terminal file states cannot tell the publish's rename from a copy, so a copy-based publish would pass every test while re-opening the torn-file window Agreed - both success-direction tests now assert the published file carries the inode the writer produced, which a copy cannot satisfy
⚠️ Nothing pinned the stale-output cleanup or the absent-file branch Agreed - the test stub now appends as the real File engine does, and seeded-workspace tests cover both halves of the rm -f
⚠️ --param report re-entry can make results[-2] raise IndexError, or attach query rows to Select historical data Disagreed as a defect of this change - the indexing is byte-identical to master (origin/master:ci/jobs/performance_tests.py:1597-1598), and on the exact shape named this branch is same-or-better: for a complete file both revisions raise, for a truncated file master raises while this branch warns and imports nothing. --param is never passed by CI (both perf job configs pass only --test-options; praktika documents it as "Useful for local tests"), and under every CI-reachable stage set results[-2] is the Tests subtask. Worth fixing on its own, so it is filed separately rather than widened into this PR
⚠️ A failure before upload_results still lets main import a previous run's ci-checks.tsv Disagreed as a defect of this change - all three necessary steps are identical on master: the cleanup is inside upload_results on both (origin/master:1855, here :1860), report.py > report.html is unguarded by ||: on both (:2018 / :2025) so set -e can skip the function identically, and main imports before checking the Report result on both. What this PR claims is scoped to the publish, and there it holds: the leading rm -f of both paths runs first, which test_a_failed_write_does_not_publish_a_previous_runs_file pins by seeding a previous run's complete file and asserting it is gone. Also filed separately
✅ Continued disk exhaustion could still prevent the praktika result from being written Disagreed - each write after this point is either inside a Result.from_commands_run callable, which catches every exception, or already inside a try, or a non-raising Shell.check; and if the final result dump itself fails, the runner records an ERROR result with job.log attached
✅ The disk reduction and the byte-identical flamegraph stacks need reviewable verification Disagreed as a defect, but the measurements are in the description: the dump shrinks 23.5x on a fixture carrying the real schema, stacks has the same md5 from the full and the projected dump, and dropping size as well makes it fail with UNKNOWN_IDENTIFIER, so the column list is minimal

Two remarks noted and deliberately not acted on: read_ci_checks_results documents "Never
raises" unconditionally, while a bare CR inside an unquoted field or a field above
csv.field_size_limit() does raise csv.Error - neither is producible by the writer, since
the TSV format escapes control characters, the display name is truncated to 1000 characters
and test_status comes from a fixed vocabulary; and the next(f) guard in the wiring test
pins one spelling, with the behavioural call-site assertion beside it doing the real work.

Rejected during design: a free-space pre-check, a shard retry, and reducing the query workload.
None addresses why the job writes more than it reads, and the first two would hide a recurrence
rather than make it visible.

Session id: cron:clickhouse-review-slot-48:20260727-150900

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, and swept exhaustively rather than sampled. Driving the pre-fix parse block (transcribed line-for-line from the base blob's main(), and asserted against that blob's text) over EVERY truncation offset of a realistic 3146-byte ci-checks.tsv built from the real 17 columns: 366 of 3147 offsets die uncaught - 216 StopIteration (a prefix shorter than the two header lines), 145 TypeError (a row cut past its duration, so float(None)) and 5 ValueError (a cut inside the duration digits). is_file() passes while the parse dies. No randomization involved. The disk exhaustion itself is measured from the harness's own df -h on run 30208735413 (5% used at start, 100% / 4.0M free at end). Two further defects were each reproduced on the then-committed code before being fixed, both measured on the same 3147-offset fixture: at e3c587e22ba2 25 offsets were reported CLEAN while carrying a duration differing from the truth (a number cut after its first digits still parses), and the non-ASCII variant of the in-test fixture (1289 offsets) raised 2 uncaught UnicodeDecodeError. Every figure in this table names the fixture it belongs to: the 3147-offset sweep fixture (.scratch/r1/fixture.py, 5 query rows) or the 1287-offset in-test fixture (2 query rows, the one the committed sweep tests use).
b Root cause explained? Yes. select * from system.trace_log dumps all 25 columns, whose per-frame symbols/lines arrays dominate; both dumps die on Code: 159 TIMEOUT_EXCEEDED at 300 s but are ||: &, so the partial multi-GB files stay on disk; the disk reaches 100%; errno 28 then truncates ci-checks.tsv to an arbitrary byte prefix; is_file() returns true and the parse dies out of main() before praktika uploads artifacts, producing info:'' / links:[] / 403. The prefix ends mid-row far more often than at a line boundary, because WriteBufferFromFileDescriptor::nextImpl loops on ::write and throws only after a partial write has been flushed; csv.DictReader then fills the missing fields with restval (None), so float(None) raises TypeError (a cut inside the duration gives ValueError, and a cut header gives fewer field names than a row has cells).
c Fix matches root cause? Yes. Fixed at the producer (write only the four columns that are read; drop a file with no reader), matching the two existing precedents in this area (4f8806c6ec9cbc, #111377), plus a guard at the exact unguarded parse, and the ci-checks.tsv write is published by rename from a sibling .tmp path so the final path is only ever absent or complete. Explicitly not a capacity pre-check, not a shard retry, and not a workload reduction.
d Test intent preserved / new tests added? Yes. No existing check is weakened: report/stacks.$version.tsv is byte-identical before/after, and the well-formed ci-checks.tsv path still yields exactly the same parsed rows as before. In-tree tests: ci/tests/test_perf_ci_checks_parse.py has 22 tests (14 named file shapes, 2 exhaustive offset sweeps, 6 import/coupling tests) and the new ci/tests/test_perf_upload_results_atomic.py has 4, which run the real publish block from compare.sh under bash. Those 4 tests now carry 18 assertions (was 16): the two success-direction tests additionally pin that the publish is a same-directory RENAME rather than a copy, by asserting the published file carries the inode the writer produced (the stub records stat -c %i of its own target). Terminal-state assertions alone cannot distinguish the two mechanisms: a cp ci-checks.tsv.tmp ci-checks.tsv && rm -f ci-checks.tsv.tmp substitution for the && mv satisfies every path/absence/content assertion in the file, and it re-opens the exact failure this PR closes - with ulimit -f 0 standing in for a full filesystem, mv src dst still publishes the complete file whereas cp src dst leaves dst at size 0. Each asserted file shape is mapped to the branch it actually reaches, measured with an instrumented copy of the parser rather than inferred from the test name: 0 bytes -> completeness guard (fewer than three lines); names line only -> completeness guard; unterminated types line -> completeness guard; both headers, no data row -> completeness guard, because compare.sh's upload_results unions an unconditional single-row summary select into every ci-checks.tsv (measured: a zero-query run still writes 3 lines), so a data-row-less file is necessarily truncated; well formed -> no rejection - both rows accepted; summary row only -> summary skip; row cut mid-field, complete line -> row guard (test_status is None); row cut at the start of the duration, complete line -> row guard (all-columns); row cut inside the duration digits, unterminated last line -> trailing-fragment rule; short row carrying every consumed field -> row guard (all-columns); names line cut short -> row guard (test_name is None) + trailing-fragment rule; names line cut just past test_status -> row guard (test_duration_ms is None); duration present but unparsable -> float() conversion guard. One more named shape pins the trailing-fragment rule for a fragment carrying EVERY declared column (a prefix ending exactly at a row's last byte): no row guard can reject it and the value it would import is the correct one, so only that rule can catch it. On top of those, every truncation offset of the in-test fixture is swept (1287 offsets ASCII, 1289 non-ASCII). The import step is tested behaviourally as well as textually: four tests drive import_ci_checks_results and assert both its printed output and whether it assigns, so an inverted if not complete: is caught (it fails three of them) and so is an inverted presence check (it fails all four, with the FileNotFoundError the guard exists to prevent); the previous getsource-only assertions could not see either. The presence check itself lives in the helper rather than in main(), so all three outcomes - absent, truncated, complete - are behaviourally testable; that move is byte-for-byte behaviour-preserving, measured on each of the three against the previous head's main()-side if/else driving the previous head's helper (identical printed output and identical assignment in all three). Every guard in the parser and every branch of the importer is mutation-proven individually; the two guards that no output-based assertion can pin (test_name is None and test_status is None, each subsumed by the all-columns guard on every one of 128140 measured shapes - the full cross product of a truncated names line and a truncated data row, with and without a terminating newline, re-measured against the committed control flow; deleting either guard, or both, changes no observable on any of them) are documented as subsumed rather than claimed as individually covered - a per-branch probe over the committed suite confirms every branch of the parser is now reached at least once, test_status is None twice and the float() guard once. ci/tests/test_perf_slow_gate.py still passes, including its getsource(main) couplings (all four cidb.is_ready() call sites still guarded).
e Both directions demonstrated? Yes. Across all 3147 truncation offsets of the sweep fixture: 366 uncaught before, 0 after, with the intact rows still returned and the skipped rows counted; 0-byte and header-only prefixes are the 216 StopIteration cases before, and warn cleanly after. Both guards are mutation-proven load-bearing (reverting each one fails exactly its own cases, so no assertion is vacuous), and the well-formed file yields output identical to the committed baseline. For the atomic publish, ci/tests/test_perf_upload_results_atomic.py extracts the REAL block from compare.sh between stable anchor comments and runs it under bash with a stubbed clickhouse-local, in both directions: on success the final path holds the written file and no .tmp is left; on a failed write the final path is absent while the partial .tmp remains, and the script still exits 0 because of the call site's ||:. That test is discriminating, not decorative: run against the pre-atomic block from 80e5dca79a9de9 its failure direction FAILS (final=PRESENT - the torn file published), and so does the && mv -> separate mv mutation of the current block, which is exactly the anti-pattern the in-source comment warns about. Two further tests run the same real block in a working directory that already holds a previous run's complete ci-checks.tsv and a previous attempt's torn ci-checks.tsv.tmp - perf_wd is never wiped at job start and main supports --param <stage> re-entry - and they pin the block's leading rm -f ci-checks.tsv ci-checks.tsv.tmp, whose .tmp half is new here. Both halves are mutation-proven: deleting the whole line publishes a PREVIOUS run's file on a failed write (final='STALE-OLD-FINAL', so the importer would silently report the wrong run's queries, with nothing warning), and dropping only the .tmp half lets the stale temporary content be prepended to the new one and then renamed into place (final='STALE-TORN-TMPtorn-partial-row') - the File engine opens with O_WRONLY | O_APPEND | O_CREAT and engine_file_truncate_on_insert defaults to false, verified on a live binary, so the stub appends too rather than truncating. Both mutants leave the two fresh-directory tests passing, which is why the seeded pair is needed. The rename MECHANISM is mutation-proven separately: substituting the publish step with && cp ci-checks.tsv.tmp ci-checks.tsv && rm -f ci-checks.tsv.tmp makes both success-direction tests FAIL on the inode assertion (recorded 7091407 vs published 7091409; seeded: 7091411 vs 7091415), while every terminal-state assertion in the file still passes and the two failed-write tests still pass - i.e. before this assertion existed the mutant was invisible. With the real mv block the recorded and published inodes are EQUAL on both success directions (7091223 and 7091233), so the recording line is not vacuous. The presence check moved into the importer is likewise pinned in both directions: inverting it makes the new absent-file test die with FileNotFoundError at the unguarded open(path, "rb") - the exact job-killing failure - and making that branch return True instead of False fails the same test and no other. Earlier rounds also confirmed the real failure out of band with ulimit -f 1, where clickhouse-local exits 75 (CANNOT_WRITE_TO_FILE_DESCRIPTOR, SIGXFSZ ignored) or 153. For the projection: stacks output has the same md5 from the full and the projected dump, while dropping size too makes it fail with Code: 47 UNKNOWN_IDENTIFIER, proving the column list is both sufficient and minimal. For the two later defects the same exhaustive sweeps go from 25 clean-but-wrong-value prefixes to 0 (3147-offset fixture) and from 2 uncaught UnicodeDecodeError to 0 (1289-offset non-ASCII fixture). The count of prefixes reported clean falls across the branch as each defect is closed - on the 3147-offset fixture 2781 (base) -> 1962 -> 7 -> 6, and on the 1287-offset in-test fixture 1009 -> 595 -> 4 -> 3 - ending at exactly the offsets that are genuine newline-terminated row boundaries at or past the summary row (688, 986 and 1286 of 1287, re-derived this round).
f Fix is general across code paths? Yes. Swept for the same defect class: grep -n "next(" ci/jobs/performance_tests.py now returns no matches at all (count 0) - the raw parse that owned both next() calls is gone from the file - and grep -rn "next(f)|= next(" ci/jobs/ ci/praktika/ finds 5 other call sites, all next(<genexpr>) over in-memory lists rather than file objects, so no sibling carrier exists. The nearby raw_query_metrics_path read uses f.read() (safe when empty) and the report.html scrape already has fallbacks. Both perf job configs share one command, so master_head and release_base, amd and arm, are covered by one change.
g Fix generalizes across inputs? Yes. The file-shape space is asserted exhaustively rather than sampled: the 14 named shapes listed in row (d), each pinned to the branch it reaches, plus every truncation offset of the in-test fixture (1287 ASCII offsets and 1289 non-ASCII offsets, the latter covering a prefix that ends inside a multi-byte character). Reachability was measured, not assumed: across the full cross product of a truncated names line and a truncated data row (128140 shapes at this head: 215 names-line prefixes x 298 row prefixes x {no newline, newline}), the float() conversion guard is reachable by exactly one shape - a names line cut so that test_duration_ms is the last field, over a row whose duration cell is empty - and that shape is now a test. The absent-file input is now covered too: it is an EXPECTED outcome of the atomic publish rather than a freak one, and it is asserted behaviourally (warns, returns False, assigns nothing) rather than by grepping main()'s source. The stale-input space of the publish block is covered in both directions as well - a reused working directory holding a previous run's final file and/or a previous attempt's temporary file, on both a successful and a failed write. The projection was validated over 7 of the 9 trace_type values, covering both arms of the byte-weighted multiIf (the two absent from the fixture, MemoryAllocatedWithoutCheck and Instrumentation, both fall in the count() arm the other seven already exercise), negative/zero/positive size so the where size >= 0 filter stays live, and 1..4-frame traces.
h Backward compatible? N/A - CI-harness only. No setting, no default, no serialization format, no user-visible behavior, so no SettingsChangesHistory.cpp entry applies. *-trace-log.tsv is already excluded from logs.tar.zst, so no downloadable artifact loses content.
i Invariants and contracts preserved? Yes. Projection invariant ("every dumped column is consumed downstream") is exactly closed: a scan of the report region for all 25 real trace_log column names (plus the build_id alias) leaves only symbols, which occurs solely in English comment prose. The trace_log view stays select * over the file and its consumer selects by name. Parse invariant ("a missing, empty or truncated reporting artifact degrades to a warning, never kills the job before upload") holds on every path, verified across all 3147 truncation offsets: the parser never raises, and it reports whether the file was importable at all (complete) separately from how many rows it had to skip (malformed). That separation is what keeps a run which legitimately produced zero query rows from being reported as a truncated file, and vice versa; the subtask's results are assigned exactly when both header lines and at least one data row were present. Two contract gaps closed: "never raises" now holds for an arbitrary BYTE prefix (the decode is lenient, as in stress_job.read_test_results), and "reported clean" now implies "no returned value differs from the truth" - a complete file is newline-terminated (upload_results in compare.sh writes it through a File(TSVWithNamesAndTypes) table, verified empirically to terminate both the populated and the empty-result case, the latter at 2 header lines plus the unconditional summary row), so an unterminated trailing line is dropped rather than trusted, and a row is accepted only with all 17 columns present. Returning FEWER rows for a shorter prefix remains correct and is asserted as such.

Session id: cron:clickhouse-impl-slot-40:20260727-115200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @maxknv — could you review this? A perf-comparison shard that fills the runner disk currently dies before praktika uploads anything, so the red check has no artifacts and no query rows: ci-checks.tsv is left 0 bytes and the bare next(f) on it throws StopIteration out of main(). This projects the system.trace_log dump to the four columns the stacks table actually reads, drops an intermediate file with no reader, and publishes ci-checks.tsv by same-directory rename so the final path is only ever absent or complete.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [610a4b9]

Summary: ✅


AI Review

Summary

This PR hardens the perf-comparison reporting path against disk-full failures by shrinking the system.trace_log dump, removing an unused intermediate artifact, and making ci-checks.tsv publication/import tolerant to torn writes. I did not find a correctness or operational regression in the current PR head; the Python-side parser and shell-side rename contract are consistent, and the two added regression suites passed via direct Python execution in this workspace (pytest is not installed here).

Final Verdict

✅ No new findings on the current PR head.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 27, 2026
Comment thread ci/jobs/performance_tests.py Resolved
groeneai added 2 commits July 27, 2026 19:16
The docstring on import_ci_checks_results justified the `if not complete`
branch as data preservation: "assigning an empty row set would silently drop
every query the shard ran". That is not what the branch does.

Every subtask main() appends before the import site is constructed without a
`results=` argument - Result.from_commands_run's own create_from call passes
none, and the one plain Result(...) append does not either - so the assignment
target's row list is empty regardless of what the parse returned. There is
nothing an empty assignment could drop. The branch is worth keeping because it
reports the real cause instead of leaving the shard red with no explanation,
which is the whole point of the change, but it preserves nothing.

Stating it the other way round invites the inverse "fix": treating a partial
parse as non-importable in order to avoid overwriting the target, which trades
a reported warning for a silent one and, on the offsets where a prefix cuts
the first query row, gives up the only signal there is. Measured over the 298
truncation offsets inside that row, master's inline parse imports a query row
carrying a wrong duration on 5 of them, raises TypeError on 29 and ValueError
on 1; this parser reports every one of them as a skipped malformed row.

The new test asserts the property the docstring now claims, over the append
sites themselves rather than one simulated run, so it holds for every stage
entry point --param can select and fails loudly if a subtask ever starts
carrying sub-results of its own.

No behaviour change: comments plus one added test.
The recipe's closing line offered `analyze-assembly.py --perf-map` as a consumer
of the folded `.collapsed` file. That flag reads JSONL records keyed by
instruction address (`load_perf_map` json-decodes every line and requires an
`ip` field), so each folded `symbol;...;symbol count` line is rejected as a JSON
parse error. Measured on a two-line collapsed file: 0 of 2 rows accepted, both
counted under `json_parse_error`. The rejection tally is only printed under
`verbose`, so the weighting silently comes out empty rather than failing.

The claim predates this PR, but the line it sits on is one this PR rewrites, so
it ships either way. `flamegraph.pl` is the compatible consumer and stays.
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Jul 27, 2026
@maxknv
maxknv requested a review from egor-click July 28, 2026 11:54
@maxknv

maxknv commented Jul 28, 2026

Copy link
Copy Markdown
Member

LGTM, cc @egor-click

@egor-click

Copy link
Copy Markdown
Contributor

yes, looks great!

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 610a4b9

CI has fully finished on this head: 174 check-runs, 0 queued, 0 in progress, Finish Workflow
success at 13:56:45Z. Zero failing checks (12 success, 162 skipped), so there is nothing to
assign an owner to. CIDB reports 0 FAIL/ERROR rows for this commit.

Check / test Reason Owner / fixing PR
(none) - no failures on this head

The large skipped count is expected for this head: the change is confined to the perf-comparison
runner script, so the config workflow deselects the build and test matrix that the previous head
had already run green.

Session id: cron:our-pr-ci-monitor:20260728-140000

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 28, 2026
Merged via the queue into ClickHouse:master with commit 5853d88 Jul 28, 2026
179 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 28, 2026
@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

Correction to one premise I stated in this PR's review table, plus the disposal of the
follow-up it produced.

In row (e) of the a-i table above I justified the two seeded tests with "perf_wd is never
wiped at job start". That is wrong for CI, and I am withdrawing it. Every
praktika-generated job carries a GitHub Actions step, emitted before praktika is invoked,
that removes the whole temp dir:

      - name: Prepare env script
        run: |
          rm -rf ./ci/tmp
          mkdir -p ./ci/tmp

It comes from ci/praktika/yaml_generator.py:175-176 in TEMPLATE_JOB_0, expanded from
UNIQUE_WORK_DIRS=" ".join({Settings.TEMP_DIR, Settings.INPUT_DIR, Settings.OUTPUT_DIR})
at :464-466; all three settings are ./ci/tmp (ci/praktika/settings.py:52-55) and the
set literal collapses them to one token. TEMPLATE_JOB_0 is the generator's only job
template, so no generated job can omit it. Measured on the committed workflows: all
30 Performance Comparison job blocks (12 in pull_request.yml, 18 in master.yml)
contain that step, and in all 30 it precedes python3 -m praktika run. It has been there
since 8632cda0ad7198273780e77f74f32e709c6e5e02 (2025-02-06), so it long predates this PR.
What I had checked was git clean -ffd (ci/praktika/runner.py:158, no -x), which indeed
leaves ci/tmp alone because ci/.gitignore is /tmp - but git clean is not the
mechanism that clears it.

Two arms on a seeded ci/tmp/perf_wd/ci-checks.tsv: after git clean -ffd the stale file
survives; after rm -rf ./ci/tmp && mkdir -p ./ci/tmp it is gone and perf_wd does not
exist.

The premise does still hold for the case the tests were actually written around - a local
main --param <stage> re-entry, which reuses the directory and is never passed by CI (both
perf job configs pass only --test-options). So the tests keep their value and the block's
leading rm -f ci-checks.tsv ci-checks.tsv.tmp stays load-bearing; only the CI-wide
generalisation was false. Two comments in
ci/tests/test_perf_upload_results_atomic.py (:72, :112) repeat it and overstate the
same way.

Consequently the follow-up I said I had "filed separately" - a shard importing a previous
run's ci-checks.tsv when compare.sh exits before upload_results - is not
actionable, and I am closing it without a PR
. Its three necessary steps are all real and
all still on master (cleanup only inside upload_results at compare.sh:1860;
report.py > report.html unguarded by ||: at :2025; the import at
performance_tests.py:1680 preceding res = results[-1].is_ok() at :1682), but they are
not sufficient: the window needs a surviving perf_wd, and no path that writes to CIDB has
one. The one path without the YAML wipe is a local run, and there the CIDB insert is
unreachable - it lives in _post_run, whose only call site is guarded by
if not local_run: at ci/praktika/runner.py:1144. A job re-run replays the wipe step, and
praktika has no within-job retry.

The sibling follow-up about the positional results[-2] lookup is unaffected by this
correction and stays open on its own merits.

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 manual approve Manual approve required to run CI pr-ci pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants