Skip to content

CI: emit each matched S3 key's object lifecycle next to the "No such key" match - #120101

Merged
alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:ci-s3-key-lifecycle-report
Sep 19, 2026
Merged

alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:ci-s3-key-lifecycle-report

Conversation

@groeneai

@groeneai groeneai commented Sep 14, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #119849
Related: #111188
Related: #113243

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

Requested in #119849 (comment).
Diagnostics only; the red behind it was a flake whose logs are gone.

What breaks. A Code: 499 ... The specified key does not exist red keeps only the failing
read: the artifact names the victim, never the culprit, though both sit in the same logs
under the same key.

Change. ci/jobs/scripts/s3_key_lifecycle.py makes one grep -F pass over the logs
and prints each matched key's lines under its own header in time order. Grouping is
delimiter-aware, so a nesting path is not misfiled; a key runs to the emitter's
, from bucket:, so a space or comma in it is kept. Keys, and the tests that assign
and select a line, read only what follows the first } <level> boundary, which the formatter
always writes: the cut can land early, inside a hostile id, but never inside the message, so query
text can neither name a key nor forge a logger. A key with
nothing to show says so. Both harness sites call it; the three jobs' digests list it. The upload line is LOG_TEST, raised only by the stress phase, so elsewhere groups hold deletes.

Validation. One fixture end to end: the artifact goes from the match line alone to that
plus its upload and delete, verdicts and CIDB row text unchanged; a failing
collection leaves a marker instead of greening a real failure. Real repro logs cross-check it (below).
ci/tests/test_s3_key_lifecycle.py covers the join, isolation, ordering and caps. Nothing
runs ci/tests today; I will drop it if you prefer.

tee /dev/stderr | grep -q . becomes cat >&2 plus an emptiness test: grep -q exits on its
first line, so tee takes SIGPIPE and loses the tail the report is appended to. #113243 rewrites
the same call sites; whichever lands second rebases.

What the prefix parse guarantees, and what it does not (measured)

The formatter writes {query_id} unescaped before <level> logger: , and writes it even when it
is empty (src/Loggers/OwnPatternFormatter.cpp:41-49), so the first } <level> on a line is its
own boundary unless the id spells one too. The query text follows that boundary, so it can never be
the first candidate; an id precedes it, and nothing validates ids.

Against the previous whole-line parse, over a local repro of 6417 log lines in 8 files: the same 541
lifecycle lines are selected, none lost and none gained; keys identical on all 16 match lines; all
278 kept group decisions of 33001 pairs identical; report unchanged.

forged by before now
query text spelling <level> logger: selected; 49 copies held a key's 50-line cap and its upload line was dropped rejected
query id spelling <level> before 205 key suffixes real key past the 200-key cap, unexpanded real key first
query id spelling } <level> logger: selected selected
genuine line whose id holds <level> selected selected
genuine line whose id holds } <level> selected not attributed

The last two rows are the residual: an id holding } <level> is byte-identical to the boundary, so
the parse either believes it or, when a logger name does not follow, leaves that line unattributed.
No test in the tree sets such an id. If you would rather have a line carrying more than one
candidate reported as ambiguous instead of parsed, that is about ten lines plus a test; your call.
The same lever applies to grouping: a space, comma or bracket is an exact boundary and the whole
message is read, so a matched dir can inherit a line naming dir with space/file, or a key equal
to an upload's local path that upload. Neither is reachable in the real corpus, and keying on
key <K> would let a wording nobody enumerated drop its line.


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

A `Code: 499 ... The specified key does not exist` red records only the failing
read: `no_such_key_errors.txt` holds the matched error line and nothing else, so
the artifact names the victim and never the culprit. It does not say when the
object was written, whether it was deleted, by which thread, or whether the
delete was a batch removal. By the time the question is asked the server logs
are usually gone, and the investigation dead-ends on lines that were in the log
at the time.

Those lines are in the same logs, keyed by the same string.
`ReadBufferFromS3::key` is `splitBucketAndKey(remote_path).second`, which for a
non-qualified path returns `remote_path` verbatim, and that is also the key that
`Writing blob for path` and `deleteFileFromS3` print. They were simply never
selected.

`ci/jobs/scripts/s3_key_lifecycle.py` extracts each matched key with
`while reading key: (...)`, makes one `grep -F` pass over the enumerated logs
for all keys at once, and prints each key's lines under its own header in
timestamp order (grep reports one file at a time, so file order is not time
order and an upload would otherwise print after the delete that followed it).
Lines are kept by logger name rather than by message wording, so rewording a log
message cannot silently empty the report. A key with nothing to show says so:
an empty report and "no lifecycle exists" must not look alike. Every distinct
key always gets a header and only the per-key line expansion is capped, so no
key can vanish from the largest incident, which is the one worth attributing.

Both harness sites that run the grep call it. Note that `no_such_key_command`
in `clickhouse_proc.py` is fed to TWO `Result` rows, `Lost s3 keys` and
`S3_ERROR No such key thrown (in clickhouse-server.log or
clickhouse-server.err.log)`, so the single edit moves both.

The verdicts are unchanged. The appender's status is discarded and the group's
status comes from the trailing `echo`, so a failed collection cannot turn a real
failure into `No lost s3 keys`; it leaves a marker in the artifact instead. Both
row texts are left alone deliberately, because those strings are the CIDB
`test_name`s and renaming them would break every query keyed on the signature.

Replacing `tee /dev/stderr | grep -q .` with `cat >&2` plus an explicit
emptiness test also repairs a pre-existing truncation of those two rows' `info`:
`grep -q` exits on its first line, so `tee` takes SIGPIPE and the copy to stderr
is cut off once the content grows. Measured on a 133,848-byte report, the old
shape delivered 28,200 bytes and the new one delivers all of it. The appended
section sits at the end, which is exactly the part that was being lost.

Commissioned in
ClickHouse#119849 (comment)
Review round on the previous commit found four ways the report could mislead,
plus one pre-existing fail-open in the check it feeds.

The scan was bounded only in what it PRINTED. `capture_output=True` buffered
every line matching any key before either the logger filter or the per-key line
cap was applied, so the caps bounded the report while the process held the whole
match volume of the largest log set CI produces. It now streams: grep's stdout
is read line by line, filtered by logger name and assigned to its keys as it
arrives, with grep's stderr going to a temporary file because a pipe nobody
drains until the end can fill up and deadlock. Measured on 200 keys over one log
file, the peak RSS goes from 202,772 KB to 15,444 KB at 46.8 MB of log and from
399,436 KB to 15,420 KB at 93.6 MB: linear in the log before, flat after. The
report is byte-identical in both runs and holds exactly the advertised
`MAX_EXPANDED_KEYS * MAX_LINES_PER_KEY` lines.

Grouping was `key in line`. On the plain families the key IS the object's path
and nothing keeps one path from nesting another, so a bare substring test files
the containing key's upload and delete under the contained key. A line now
belongs to a key where the key occurs delimited on both sides by a non-key
character or a line edge, which all six real emit forms satisfy and which stays
independent of the message wording. A key with no delimited line but a raw
substring match still reports those lines, under a note saying how they were
matched: the delimited test must not be able to empty a group on its own, since
that is the failure mode this report exists to remove.

Two paths returned no lines where a real condition existed: a non-empty match
set from which no key could be extracted, and a match set with no log file to
scan. Both now name what happened. The guard is the matches file's content, not
the key list, because a job with no "No such key" error runs this same code and
its verdict is that the file stayed empty; a single line printed there turns
`Lost s3 keys` red everywhere. `no lifecycle line found` now also states the
second reading: the absence of a `deleteFileFromS3` line is present at every log
level, so it is itself the finding, not just a consequence of `LOG_TEST`.

Finally, `! [ -s <matches>` returns 0 for a path that does not exist, so a
failure to create the artifact read as PASS where the base shape's
`cd ... && ! grep` had failed closed. It is now
`[ -f <matches> ] && ! [ -s <matches> ]`. Neither reachable verdict moves: a
match still means a non-empty file and FAIL, no match still means an empty file
and PASS.

Five cases join the shipped suite (wording independence, nesting isolation, the
two explicit diagnostics, and the empty-match-set invariant asserted as `== []`),
each checked against the mutation that must redden it.
The lifecycle report joined a match to a log line by requiring the key to be
flanked by a character outside an enumerated key alphabet. `%` was outside that
alphabet, and `%` is exactly what ClickHouse puts into object keys: a plain or
plain_rewritable key is the caller path run through `escapeForFileName`, which
emits `%XX` for every byte outside [A-Za-z0-9_]. Sibling names `x` and `x.y`
therefore become the keys `<p>/x` and `<p>/x%2Ey`, and a match on `<p>/x`
reported the other object's upload and delete as an exact occurrence of its own,
with no substring warning: a cross-attribution in the one report whose entire
purpose is attribution. A key alphabet can never be completed, because an S3 key
alphabet is open-ended, while the separator set the emit sites use is closed. The
boundary now comes from that set, written as a negated complement so that a line
edge satisfies it exactly as a separator does. A key that occurs only
undelimited still reaches the report, under the existing substring note.

Second, `collect_lifecycle_lines` raised only above grep's exit 1, but
`Popen.wait()` returns a NEGATIVE number when a signal killed the child. The
scan runs at the end of a stress job over the largest log set CI produces, where
an OOM kill is the ordinary failure and the runners TERM the process group, so a
killed grep passed the guard and its partial, usually empty output was published
as "no deleteFileFromS3 line recorded a delete of this object on this server": a
false negative that reads as a positive finding, and the opposite of what the
module's docstring promises. Only grep's own 0 and 1 are accepted now, so the
caller marks its report incomplete instead of publishing an empty one as clean.

Two cases pin both, each checked against the mutation that must redden it: keys
diverging on a percent-escape, whose group is a bare exact listing under the old
alphabet, and a grep that drains its input and then kills itself with SIGTERM,
which does not raise under the old exit-status predicate.

Also resets `loose_total` with `loose`, so the counter cannot read as live to the
next reader, and drops the motivation clause from the call-site comment.
Two statements in the report module decided its output and had no oracle.

The dispatch over every key group in collect_lifecycle_lines is what makes
the report "each matched key's lifecycle" rather than the first key's, but
every content-bearing case named exactly one key in the matches file, and
the 250-key cap case has no lifecycle line in its fixture, so each of its
groups reports "no lifecycle line found" whether or not it was ever offered
a line. Narrowing the dispatch to list(groups.values())[:1] therefore kept
the whole suite green. The two-key case added here fails on that mutation
and passes with the dispatch intact, and the other fourteen cases pass
under the mutation, which is what shows they could not see it.

The per-key line cap is the same gap one level down: MAX_EXPANDED_KEYS had
a test, while MAX_LINES_PER_KEY and the "N more lifecycle line(s) omitted"
note appended by _in_time_order had none, so a truncated key history read
as a complete one. The second case writes twelve lines over the cap and
pins the note's position and its count, reading both bounds from the
imported constants so the oracle follows a cap change. Neutralising the
note reddens only that case.

Tests only: no source file changes.
praktika's cache digest is a strict allowlist: Digest.calc_job_digest hashes
only the files traverse_paths reaches from digest_config.include_paths, and the
cache record is keyed <job_name>/<job_digest>. There is no ci/-wide fallback,
and no job command string names this script.

Three job families execute ci/jobs/scripts/s3_key_lifecycle.py and listed it in
none of their digests: the stateless jobs through functional_tests.py ->
check_fatal_messages_in_logs -> clickhouse_proc.py, and the stress and upgrade
jobs through check_logs_for_critical_errors in stress_tests.lib. The stress
list's ./tests/docker_scripts/ entry covers the .lib that invokes the script,
not the script itself under ci/.

Without these entries a later commit touching only s3_key_lifecycle.py leaves
all three digests bit-identical, so praktika serves the pre-change cached
result and CI reports success for a code state that was never run. The script
runs on every stateless, stress and upgrade job, so a regression in it is
either a fleet-wide red or a fleet-wide blind spot, and the digest is the only
mechanism that forces the re-run which would catch it.

Verified through the real machinery on the real job configs: with the entries a
commit touching only the script moves all three job digests; with only the
entries removed the same commit leaves them byte-identical, so no other list
member pulls the file in.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 14, 2026
@groeneai

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

Pre-publication review by an independent model over five rounds (engine: codex; 4 findings, then
3, 2, 0 and 0), plus five cold passes of my own over the resulting diff. 34 findings: 18 fixed
here, 11 refused with recorded evidence, 5 dropped or withdrawn; the last round added none. Severity: ❌ blocker / ⚠️ major / 💡 nit.

# Sev Finding Verdict Evidence / action
1 ⚠️ Lifecycle lines are joined to keys by a bare substring test, so a key that nests inside another logged key picks up its lines AGREE, fixed Real on the path-keyed families (s3_plain, s3_plain_rewritable), where the key IS the local path, so a part directory nests the object below it. Grouping now requires a delimited occurrence, with a substring fallback that says how it matched, so precision costs no wording-independence. Two sub-claims rejected: a key containing a comma or space only ever yields a SHORTER pattern (no line lost, and no CI storage config produces such a key), and an executeQuery line passing the logger filter would need an object key containing the literal deleteFileFromS3. Parsing message fields instead was rejected: the batch delete has no field, only a bracketed list, and it would reintroduce the wording dependency this design removes
2 ⚠️ The first delimiter test was built from the key alphabet, so a percent-extended key still matched as exact AGREE, fixed Raised again after round 1 and confirmed: escapeForFileName emits %XX for every byte outside [A-Za-z0-9_], and a plain-family key is the escaped caller path, so siblings x and x.y become .../x and .../x%2Ey; the longer key's upload and delete were reported under the shorter one. An alphabet is open-ended and cannot be completed, so the boundary now comes from the separators the emit sites actually use (space, comma, bracket, line edge), a closed set. Checked against all nine real emit forms: only the two percent rows change
3 ⚠️ The caps bounded the report, not the process: every line matching any key was buffered before the logger filter ran AGREE, fixed The filter now runs during a streaming read and retention is capped per key, so what is held is bounded by the caps the report already advertises: 202,772 KB to 15,444 KB at 46.8 MB of log, and flat rather than linear thereafter. The trigger named (a one-character key) is unreachable: a matched key is a remote_path read back out of while reading key:, and the one short key CI produces (a.myext) is in both ignore lists
4 ⚠️ A signal-killed grep was treated as a successful scan AGREE, fixed The guard raised only above return code 1, but a child killed by a signal reports a negative status, so a SIGTERM or an OOM-kill passed it and empty output was published as "no lifecycle line found": a false negative that reads as a positive finding, and worst exactly where the scan runs, at the end of a stress job over the largest log set CI produces. Only 0 and 1 are accepted now, so a killed scan leaves the collection-failure marker the callers already handle
5 ⚠️ The per-key dispatch was unproved: a collector serving only the first matched key kept every test green AGREE, fixed Confirmed independently. Every content-bearing case built a one-key match set, and the one 250-key case gave none of its keys a lifecycle line, so each group reported "no lifecycle" whether or not it was ever offered a line. Since "each matched key" is the literal request, the case that pins it now uses two matched keys that each have an upload and a delete, asserts each group holds only its own events, and is controlled by the mutation that truncates the dispatch to the first group
6 ⚠️ The per-key line cap could shorten one key's history without saying so AGREE, fixed Of the two caps only the per-report key cap had a shipped case. A shortened history that does not announce itself reads as a complete one, so the notice is now pinned with its own count, controlled by the mutation that removes it
7 ⚠️ extract_keys scans the whole log line, and executeQuery puts user-controlled query text there, so a literal while reading key: fake/key, can fabricate a group DISAGREE The over-match is real, the harm is not, and the prescribed remedy fails unsafe. No key can be lost: a --- key: header is emitted for EVERY extracted key and the tail is labelled with the cap, which is the invariant the cap case pins. No verdict can move: both sites take their status from the MATCH set, and the report returns nothing at all before extracting anything when that set is empty, so no spoof can redden a green job. The real key is always first: logException appends the query text after the exception, and ReadBufferFromS3 appends while reading key: to the exception itself. And no seed exists in the corpus: the only tests containing while reading key say "truncated while reading key", with no colon. The worst realized outcome is one spurious header inside a report that is only ever produced next to a failure
8 ⚠️ No checked-in test drives the helper through either harness or proves the unchanged verdicts and the failure marker DISAGREE All four of the finding's own closing criteria are met by recorded evidence: the real chain, extracted from the shipped .lib, run under set -ex in three configurations asserting test_results.tsv gets exactly one row and the right one (17 checks); the base-versus-fix artifact on one fixture (1 line and 0 lifecycle lines against 5 lines carrying the upload and the batch delete); an injected collector failure leaving the marker with the row still FAIL; and the tail measurement, 28,200 bytes of 133,848 delivered by tee /dev/stderr | grep -q . against 133,848 by cat >&2. A checked-in shell test is not owed: there is no bats or shellcheck harness for tests/docker_scripts/*.lib
9 ⚠️ The new script is executed by three job families but registered in none of their cache digests AGREE, fixed Found on the fourth cold pass. praktika's digest is a strict allowlist (only the files reached from include_paths, plus the job config), and the cache record is keyed by it, so a later commit touching only this script would leave all three digests bit-identical: the pre-change result would be served from cache and CI would report success for a state it never ran. The script's empty-match path runs on every stateless, stress and upgrade job, so a regression in it is either a fleet-wide red or a fleet-wide blind spot, and the digest is the only thing that forces the re-run which catches it. Registered in the three lists that already carry every other script those jobs run. Also noticed while there, and deliberately left alone as pre-existing and none of this PR's business: the upgrade job's digest does not list clickhouse_proc.py either, although its runner executes it
10 ❌ A failing cd would leave the match file empty and PASS, where the base form propagated the failure DISAGREE Self-raised, then refuted against the code rather than against a different mechanism. The shell reading is right: the command is a ;-separated list whose status is the trailing test. But the necessary step fails: cd <log_dir> cannot fail, because clean_dir is rmtree plus mkdir(parents=True, exist_ok=True) and runs at the end of the server object's constructor, clean_logs re-creates the directory identically, and the check is an instance method, so the directory exists on every reachable path
11 💡 The added test file lives in ci/tests, which has been removed three times Noted, disclosed in the description Not a defect, and the call is yours, so I am flagging it rather than deciding it. Nothing runs the suite today: the job that ran it went with the directory. Against that, master still carries three files there, two of them extended in seven commits this month, one restored deliberately, and another open PR adds a ci/tests case for this same check; there is no other live Python suite for CI scripts, so relocating is not an option. The characteristic failure of this change is a silently empty report, which no job can detect, and the file pins exactly that. I will drop it on request
12 💡 Sixteen further nits from my own four passes AGREE (11), DISAGREE (5) Fixed: two silent paths in the report (a non-empty match set yielding no key, and no log file found) now state their reason; the "nothing to show" message no longer blames the log level alone, since a missing delete line is itself the finding; the emptiness test at the second site fails closed on a missing file; the call-site comments are trimmed to their local invariants; a stale counter is reset with the buffer it belongs to. Refused with evidence: prioritising which lines survive the per-key cap (single-digit lifecycle lines per object against a cap of 50, and the omission is announced); bounding the read of the match set (no verdict can move, and grep -f consumes its whole pattern list before opening any input, so the write cannot deadlock); the check summary keeping its last 300 lines rather than its first (that same path attaches the full log to the result); and a scan whose grep itself errors reading as PASS (identical on base at both sites, so outside this PR's contract)

DISAGREE verdicts carry recorded evidence and are terminal per finding. Findings on hunks a fix
round did not change are dropped.

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Sep 14, 2026
@clickhouse-gh clickhouse-gh Bot closed this Sep 14, 2026
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Sep 14, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3dcc6cb]

Summary: ✅


AI Review

Summary

This PR adds ci/jobs/scripts/s3_key_lifecycle.py and wires it into the Code: 499 ... The specified key does not exist checks so the CI artifact shows upload/delete history for the matched S3 keys. The idea is useful, but the current parser still has reachable cases where it attributes the wrong history to a key, so I would not merge it yet.

Findings

❌ Blockers

  • [ci/jobs/scripts/s3_key_lifecycle.py:73-83] message_in still trusts the first } <Level> on the line, even though query_id is written verbatim before the real level slot in src/Loggers/OwnPatternFormatter.cpp:43-49. A query_id like evil} <Debug> while reading key: spoof/k0000, from bucket: b ... makes keys_in start inside the id, so the helper invents spoofed keys and can push the real key past MAX_EXPANDED_KEYS. I reproduced this on the current code with 205 spoofed suffixes in query_id: the report ended with --- key: real/key followed by not expanded: per-report key cap 200 reached. Suggested fix: extract the match payload from the outer executeQuery slot specifically, or fail closed on lines where query_id contains an earlier } <Level> candidate. The current tests cover has}brace, bare <Debug>, and a spoof without the closing brace, but not the reachable } <Level> case.
  • [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/120101#discussion_r4012765788] [ci/jobs/scripts/s3_key_lifecycle.py:73-78, 191-197] The same boundary bug still revives the lifecycle-line spoof path when query_id contains } <Level> deleteFileFromS3: ...: the report starts parsing inside the id, selects the 499 line itself as lifecycle history, and can mislabel upload lines as delete lines. I still consider this real because the current code deliberately cuts at the first matching boundary and query_id remains unescaped.
  • [ci/jobs/scripts/s3_key_lifecycle.py:147-152] Group membership is still decided by any delimited occurrence anywhere in the lifecycle message, not by the actual remote-key field. That makes the report confidently attribute another object's history to the matched key: a missing key dir inherits dir with space/file.txt and dir,comma/file.txt as exact matches, and a missing key all_1_1_0/data.bin matches the upload line Writing blob for path all_1_1_0/data.bin, key remote/other/object, ... even though the remote key is different. Suggested fix: parse the logger-specific key positions instead of scanning the whole message with a delimiter heuristic.
Tests
  • ⚠️ ci/tests/test_s3_key_lifecycle.py does not exercise a query_id containing the exact } <Level> boundary that message_in trusts, nor a case where the matched key collides with Writing blob for path ... or with a longer key beginning <key><space|comma>. One focused regression for each path would close the gap.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions: make key extraction/lifecycle parsing robust against query_id values containing } <Level> , match the actual remote-key fields rather than any delimited substring in the whole message, and add focused regressions for both cases.

LLVM Coverage Report

Measured on commit 3dcc6cb.

Metric Baseline Current Δ
Lines 89.10% 89.10% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.50% 81.50% +0.00%

Changed lines: Uncovered code analysis did not run: No coverable C/C++ source files changed (contrib/ is excluded from coverage).

Newly covered: +140 lines in 48 files (-102 lines lost coverage) · Details

Full report

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Sep 14, 2026
@groeneai
groeneai requested a review from leshikus September 14, 2026 23:57
@clickhouse-gh clickhouse-gh Bot added the comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). label Sep 15, 2026
Comment thread ci/jobs/scripts/s3_key_lifecycle.py Outdated
"""The keys named by the match lines, de-duplicated, in first-seen order."""
keys = []
seen = set()
for key in KEY_PATTERN.findall(matches_text):

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.

extract_keys is scanning the whole match line, not the actual ReadBufferFromS3 suffix. Because (in query: ...) is logged before : while reading key: ..., query text that contains repeated while reading key: fake/... tokens is treated as a long list of extra keys. With MAX_EXPANDED_KEYS = 200, 200 such tokens push the real key to slot 201 and the report ends up at not expanded: per-report key cap 200 reached for the actual object, so the lifecycle never gets appended next to the failure this PR is trying to explain. Please parse each match line structurally, or at least take only the last while reading key: occurrence on the line, and add a regression test for spoofed query text.

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.

Confirmed as a real defect, but the mechanism and the suggested remedy are both inverted, so I fixed it differently.

executeQuery formats "{exception} (from {}){}{} (in query: {})" (src/Interpreters/executeQuery.cpp:396) and the while reading key: {}, from bucket: {} suffix is appended to the exception itself (src/IO/ReadBufferFromS3.cpp:378). The key therefore comes before the query text, not after it. Taking "only the last while reading key: occurrence on the line" would have selected the query's last spoofed token and discarded the real key.

Measured against a real server log, with a real object deleted from minio behind ClickHouse's back and both spoof shapes in the query text: 252 keys extracted for 2 real objects. The poisoned line's own key sat at slot 1 and was expanded fine. The victim was a second, entirely clean failure whose query named nothing: its key landed at slot 251 and its stanza read not expanded: per-report key cap 200 reached. So the report does lose a real object's lifecycle, just never the one whose query did the spoofing.

Fixed by requiring the whole suffix, , from bucket: included, instead of its first field: 500 spoofed keys go to 0 and the 14 real ones are unchanged. Regression test added (test_keys_named_by_the_failing_query_text_are_not_treated_as_matched_keys), plus one for a spoofing query id, which is untrusted in the same way.

One further correction worth recording: the fixture in this PR had the query text before the key suffix, which is not the order executeQuery produces. That fixture is what made the inverted reading look right, so I corrected it; two tests redden if it is put back.

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 whole-line parsing issue is still reachable through query_id. KEY_PATTERN at ci/jobs/scripts/s3_key_lifecycle.py:31 still scans the entire match line, and OwnPatternFormatter writes query_id verbatim before the exception text at src/Loggers/OwnPatternFormatter.cpp:40-58. If the query_id contains repeated full suffixes like while reading key: spoof/k0000, from bucket: b, extract_keys still treats them as real keys before it reaches the actual ReadBufferFromS3 suffix. In a local reproduction with 205 such tokens, the real key landed at index 205 and was capped out again. The new regression at ci/tests/test_s3_key_lifecycle.py:361-377 only spoofs while reading key: without the , from bucket: tail, so it does not cover this remaining path.

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.

Confirmed and fixed.

I reproduced it exactly as described: 205 complete suffixes in the query id put the real key at index 205, the report answered not expanded: per-report key cap 200 reached, and the object's lifecycle line was absent. My earlier arm spoofed only the prefix, so it could not reach this path.

Keys, and the test that assigns a lifecycle line to a key, now read only what follows the level slot, which the formatter writes after the id (OwnPatternFormatter.cpp:43-65). The whole-line key test was mis-attributing as well: a genuine deleteFileFromS3 of a different object was printed as this object's history whenever the id happened to name it. Over the real repro logs the change costs nothing: extraction is unchanged on all 15 lines naming a key, and all 278 group decisions over 541 emitter lines and 61 keys are identical. The arms now carry the bucket tail and cover both new cases, and 7 mutations each redden their own arm.

One residual, stated in the PR body rather than claimed away: an id that forges a complete <Level> logger: slot can still stand in for the message. A single line cannot be parsed against that, since both ends are client-controlled (the first candidate comes from the id, the last from the query text), and failing closed on the ambiguity drops real data: anchoring across the id kept only 199 of 224 real lifecycle lines.

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.

This is still reachable through query_id if it embeds its own fake level slot, not just raw while reading key: suffixes.

message_in still cuts at the first bare <Level> anywhere on the line (ci/jobs/scripts/s3_key_lifecycle.py:73-83), so a query_id like qid <Error> while reading key: spoof/k0000, from bucket: b ... is treated as part of the message and keys_in returns those spoofed keys before the real ReadBufferFromS3 suffix. On the current code, a single match line with MAX_EXPANDED_KEYS + 5 such tokens still puts the real key at index 205 and its stanza is:

--- key: test/hbh/aaaaaaaaaaaaaaaaaaaaaaaaa
not expanded: per-report key cap 200 reached

The current regression at ci/tests/test_s3_key_lifecycle.py:360-375 only spoofs raw suffixes in query_id; it never forges the <Level> marker that message_in trusts, so this path is still uncovered.

Comment thread ci/jobs/scripts/s3_key_lifecycle.py Outdated
# Filtered and retained line by line, so the caps bound what is held in memory too.
for line in grep.stdout:
line = line.rstrip("\n")
if not any(logger in line for logger in LIFECYCLE_LOGGERS):

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.

This logger in line test is still matching the entire log line, not the logger field. A failing query like SELECT 'deleteFileFromS3' makes the original executeQuery 499 line satisfy the filter, so the report prints the failure itself as if it were part of the object's lifecycle. That also lets user text consume the per-key line cap before the real write/delete lines. Please match the <Level> LoggerName: slot explicitly, and add a regression test where the query text contains one of the lifecycle logger names.

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.

Correct, and reproduced: this was the one finding that contradicted a claim in the PR body, so it mattered which of the two was wrong. It was the claim.

With a query reading a genuinely missing blob while its text mentioned deleteFileFromS3, the report showed 400 lines of the failure itself presented as that object's history. Fixed by anchoring to the level and logger slots, "<<level>> <logger>: ", so the name has to occupy the logger field.

I deliberately stopped the anchor there rather than matching the full outer field, and the reason is worth stating because the stricter-looking version is worse. A client may set any query_id and it is written unescaped between braces (src/Loggers/OwnPatternFormatter.cpp:43-49; no validation in Context::setCurrentQueryId), so a pattern spanning that field breaks on an id containing a brace. Measured over 224 real DiskObjectStorageTransaction and deleteFileFromS3 lines from a server writing to S3, 107 of them logged under such an id:

filter real lifecycle lines kept poisoned lines admitted
logger in line (before) 224/224 2/16
anchored across the query id 199/224 0/16
level and logger slots (shipped) 224/224 0/16

Dropping 25 real lines to gain nothing is the wrong trade for a report whose characteristic failure is silence. The residual is the reverse and I am leaving it: text that replicates a whole field is indistinguishable from the field, so it can still add a spurious line, which costs a stanza rather than hiding one. Regression test added, and a second test pins the brace-bearing id so the anchor cannot be widened later without reddening.

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.

LIFECYCLE_LINE_PATTERN is still searching the entire log line, not the actual logger field. At ci/jobs/scripts/s3_key_lifecycle.py:49-50 and ci/jobs/scripts/s3_key_lifecycle.py:193, a query like SELECT '<Debug> deleteFileFromS3: Object with path <key> was removed from S3' makes the executeQuery 499 line satisfy the lifecycle filter and get reported as if it were this object's history.

That disproves the claim that the name now has to occupy the logger field. Matching against the start of message_in(line) instead of doing LIFECYCLE_LINE_PATTERN.search(line) would close this query-text path without reintroducing the brace-bearing query_id problem.

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.

Correct, and reproduced: the filter matched <level> logger: anywhere on the line, so my earlier sentence in this thread ("the name has to occupy the logger field") was wrong. The shape had to appear somewhere, not the field.

The consequence is worse than one extra line. With the failure line repeated 51 times ahead of the upload, the key's stanza held 49 copies of it and the genuine Writing blob for path line was pushed out by the per-key cap of 50, which is the silence this report exists to remove.

Fixed in 86b6c22b8a58, though not quite as suggested. Matching the start of message_in(line) alone rejects a genuine line whose id merely holds a level-shaped token, because the cut then lands inside the id; I tried that first and measured it dropping real upload lines. So the boundary now also requires the } that the formatter always writes, empty id included (src/Loggers/OwnPatternFormatter.cpp:41-49). Query text always follows that boundary, so it can never be the first candidate and your example cannot select a lifecycle line at all. Over 6417 real log lines the same 541 lifecycle lines are selected as before, none lost and none gained, keys identical on all 16 match lines, and all 278 kept group decisions of 33001 pairs identical. The query-text arm now carries your spelling and asserts that the upload line survives the cap; two further arms pin the level-token id.

What is left: an id spelling } <level> logger: is byte-identical to the boundary, so it can still stand in for the message, and a genuine line whose id spells it is not attributed. Nothing validates a query id and no single-line parse separates the two, so I am leaving that one, with the numbers in the PR body.

Comment thread ci/defs/job_configs.py Resolved
groeneai and others added 4 commits September 15, 2026 02:05
A match line is a whole executeQuery error line, so besides the exception it
carries the failing query's text and its id, and neither is escaped: executeQuery
formats "{exception} (from {}){}{} (in query: {})"
(src/Interpreters/executeQuery.cpp) and the formatter writes the id verbatim
between braces (src/Loggers/OwnPatternFormatter.cpp). The report read that
untrusted text as data twice.

extract_keys took any "while reading key: ..." token, so tokens inside a query
counted as matched keys. Measured on a real server log with one poisoned query
and one entirely clean failure: 252 keys for 2 real objects, and the clean
failure's key landed at slot 251, past MAX_EXPANDED_KEYS, so its stanza read
"not expanded: per-report key cap 200 reached" - the report dropped the
lifecycle of an object whose own query named nothing. The pattern now requires
the whole suffix ReadBufferFromS3 appends, ", from bucket:" included.

Note the exception precedes the query, so taking the LAST occurrence on the line
would have selected the query's last spoofed token and discarded the real key.

The logger filter tested "logger in line", which that same text satisfies: a
failing SELECT mentioning deleteFileFromS3 made its own 499 line pass as that
object's history (400 such lines in the same measurement) and spend the per-key
line cap. The filter now anchors to the level and logger slots, "<<level>>
<logger>: ", and deliberately stops there. Anchoring the fields before them
looks stricter and is worse: a client may set any query id, so an id holding a
brace makes a real upload line fail the pattern. Measured over 224 real
DiskObjectStorageTransaction and deleteFileFromS3 lines, 107 of them logged
under such an id, the wider anchor kept 199 and this one keeps all 224, while
both admit 0 of the 16 poisoned lines. Losing a real line is the failure this
script exists to prevent, so the residual is the reverse: a query or id that
replicates a whole field is indistinguishable from the real thing and can still
add a spurious key, which costs a stanza and never a real one.

The test fixture had the query text BEFORE the key suffix, which is not the
order executeQuery produces; reverting it to the real order is what makes the
new cases meaningful.

Also register the script in the stateless harness path list, so a change to it
selects the harness smoke tests instead of returning none.
… log line

A "No such key" match line carries the query id before the level and the query text
after the exception, both unescaped. Scanning the whole line for the
"while reading key: K, from bucket: B" suffix therefore counts whatever those two
spell out: with 205 complete replicas of the suffix in the query id, the read's own
key lands at index 205 and the report answers "not expanded: per-report key cap 200
reached" for the very object the artifact exists to explain. The same whole-line test
decided group membership, so a genuine delete of a different object was attributed to
the matched key when the id happened to name it, which is a worse answer than an
empty history: it says the object was removed at a time nothing removed it.

Keys, and the key test that assigns a lifecycle line to a key, now read the part of
the line after its level slot, which the formatter writes after the id
(OwnPatternFormatter). The first occurrence of that slot is the line's own, so the cut
can land early, inside a hostile id, but never past the start of the message: over the
real repro logs, extraction is unchanged and all 278 (key, line) group decisions over
541 emitter lines and 61 keys are identical. Keys are also taken one per line before
any line's second, so a query that does spell a complete suffix out in its own text
names keys on its own line only and can no longer push the next failure's key past the
cap.

The regression arms use the full suffix, bucket tail included, which is the shape a
prefix-only arm cannot reach, add the cross-attribution case, and cover the silent
direction too: a continuation line with no level slot at all must still name its key.

Co-Authored-By: Claude Opus 5 <[email protected]>
The filter searched the whole log line for "<level> logger: ", so a query whose
text replicated that slot selected its own failure line. Measured on the 499
match line itself: with 51 copies of it ahead of the upload line, the key's
stanza held 49 copies of the failure and the real "Writing blob for path" line
was pushed out by the per-key cap, so this is not about noise but about the
silence the report exists to remove.

The name is now looked for at the start of the message, and the message starts
after the first "} <level> " rather than the first " <level> ". The formatter
writes "{query_id} " unconditionally (src/Loggers/OwnPatternFormatter.cpp:41-65),
so every emitted line carries that boundary, and the query text, which follows
it, can no longer move the cut or reach the logger position. An id must hold "}"
as well as a level slot to stand in for the message.

Measured against the previous parse over the 6417 real log lines of a local
repro (8 files): the same 541 lifecycle lines are selected, none lost and none
gained; keys are identical on all 16 real match lines; all 278 kept group
decisions out of 33001 pairs are identical; the end-to-end report is unchanged.
Comment thread ci/jobs/scripts/s3_key_lifecycle.py Resolved
`ReadBufferFromS3` appends "while reading key: {}, from bucket: {}" with the key
verbatim, and an S3 key may hold a space or a comma: `s3()` takes its key from the
percent-decoded URL path, so a `%20` reaches the read as a space, and
`S3::URI::validateKey` rejects only "//" and a lone "/". Reading the key as
`[^\s,]+` therefore failed to match such a line at all. Next to a line whose key
does parse, the unparsed line contributed no key and got no header, so the report
read as complete while silently omitting the failing read it was appended to
explain, along with that object's `Writing blob for path` and `deleteFileFromS3`
lines.

Measured on real 499 lines emitted by a debug build against an S3 endpoint whose
HEAD succeeds and whose GET returns NoSuchKey, run through the caller's own grep
pipeline: `dir with space/file.txt` and `dir,comma/file.txt` got no header before
and both get one now. Over 7265 real log lines in 10 files key extraction is
unchanged on every other line (0 lost, 0 changed, 6 gained, the six space/comma
lines), and the earlier rounds' hostile-corpus report is byte-identical.

The delimiter is matched non-greedily because the first ", from bucket:" on the
line is the emitter's own: the query text, the only client-controlled part after
the level slot, is appended after the suffix. A greedy match takes the last one
instead and reddens both
test_one_match_lines_keys_do_not_crowd_out_another_lines_key and the new
delimiter-bearing-key case. A key that itself spells the suffix is still cut at
its first occurrence, exactly as before; the second test pins that its events stay
attributed to that prefix rather than going unreported.
Comment on lines +147 to +152
def offer(self, line, message):
# Matched in the emitter's own text, so a key the client put in a field before the
# level cannot pull an event of a different object into this key's history.
if self.key not in message:
return
if self.pattern.search(message):

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.

This still decides group membership by “does the byte sequence appear somewhere in the lifecycle message with a separator on each side?”, not by the actual remote-key field. That makes the report confidently attribute another object's history to the matched key:

  • a missing key dir inherits Writing blob ... key dir with space/file.txt, ... and Object with path dir,comma/file.txt ... as exact matches
  • a missing key all_1_1_0/data.bin inherits Writing blob for path all_1_1_0/data.bin, key remote/other/object, ... even though the remote key is different

Both reproduce on the current code and neither goes through the matched as a substring only fallback. If this helper is meant to explain which object was uploaded/deleted, matching any delimited occurrence in the whole message is too loose. Please parse the logger-specific key fields instead (key <K>, for DiskObjectStorageTransaction, Object with path <K> / batch list items for deleteFileFromS3) and add a regression for the path collision or the <key><space|comma> prefix case.

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.

Confirmed on 3dcc6cbf11294, including the delete shape: key dir takes both key dir with space/file.txt, and Object with path dir,comma/file.txt; dir/x takes [dir/x[1], ...]; all_1_1_0/data.bin takes path all_1_1_0/data.bin, key remote/other/object. All as exact matches, none through the substring fallback.

I am not switching to a per-logger key field, and the reason is measured.

Incidence, over 7457 lines in 10 local repro logs (376 genuine lifecycle lines, earlier hostile-probe output excluded by its second } <level> slot): 234 exact key-to-line attributions, and in all 234 the key is one of that line's own remote-key fields. Mis-attributions 0. Among the 54 real keys, 0 pairs where one is a separator-delimited occurrence inside another and 0 local paths equal to a remote key.

Cost of the field parse: these two loggers name a key in ten wordings today (src/IO/S3/deleteFileFromS3.cpp:49,58,63,69,154,172,186,259, src/Disks/DiskObjectStorage/DiskObjectStorageTransaction.cpp:383,389). The fields you name cover 140 of the 154 attributed lines; the other 14 are No blob storage log, not writing blob(s) (deleteFileFromS3.cpp:58,172), which a field-only parse drops. :58 is also the only line naming the key when a delete fails without a blob storage log, since :63 runs on success only, and Skipping writing empty blob for path <p>, key <k> (DiskObjectStorageTransaction.cpp:389) puts no comma after the key while being a good explanation for a key that later cannot be read.

So this trades a mis-attribution the artifact shows, since the raw line is printed under the key header and names its own key, for a drop it cannot show. In a helper that exists because the artifact was silent, I would keep the visible failure mode.

The description carries the question with its cost, and I corrected one sentence there: it said both arms "predate this PR", which is wrong, because the file is new here. If the precision is wanted, the shape I would ship is the field parse as a preference with the delimited test as fallback, so a wording nobody enumerated still keeps its line.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Ok, we can try it.

@alexey-milovidov alexey-milovidov self-assigned this Sep 19, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
Merged via the queue into ClickHouse:master with commit 940ab10 Sep 19, 2026
177 checks passed
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 comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

3 participants