Skip to content

Do not assert scan-progress values decided by an async race in test_early_return_limit - #115693

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-flaky-test-early-return-limit-scan-race
Aug 24, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-flaky-test-early-return-limit-scan-race

Conversation

@groeneai

@groeneai groeneai commented Aug 21, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

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

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

...

Description

Closes: #115661

test_storage_delta/test.py::test_early_return_limit pins two values an async interleaving
decides. 5 hits in 90 days across three job families, two on master, so not
parametrization-specific. Latest master failure:
Integration tests (arm_binary, distributed plan, 1/4) @ 0c80ff614e89

Root cause: the scan producer appends to a bounded deque and logs the LIVE queue depth
(List batch size is {}/{}); consumers pop under the same mutex. With
s3_list_object_keys_size = 1 the capacity is one, so the last log legitimately reads 1/1
or 0/1 depending on which thread reaches the mutex first. DeltaLakeScannedFiles is
incremented after both callback shutdown exits, so the count is 2 or 3 for the same reason.
Both orderings are correct.

Two test-only changes:

  • The assertion counting List batch size is 1/1, shutdown: true is removed, not
    relaxed: even relaxed it is implied by assert first_check_hits > 0 or queue_check_hits > 0 three lines above, which runs first. A callback returning false
    cannot stop the producer reaching that batch log.
  • assert scanned_files == 3 becomes <= 3, restoring the bound the test was written
    with: a33799ba6fb63ee added scanned_files < 10; 95e6f488a0917b ("Make exact
    comparison in test") tightened it to == 3 days later. scanned_files > 0 bounds the
    other side.

Validated with a forced-interleaving probe in the scan callback: unpatched fails with the CI
signature on the drained ordering, patched passes on it. Deleting both callback shutdown exits
makes it fail at assert 997 <= 3, so the bound still catches an early-return regression.
20/20 runs pass.

The retained assertion is not race-proof either: both counters are logged inside the callback,
so a shutdown seen by the parked producer skips it. That ordering has 0 of 38 failures in 90
days over 97538 runs, against 5 for the one removed here.


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

Version info

  • Merged into: 26.9.1.39-master (included in 26.9 and later)
  • Backported to: 26.8.11.45, 26.7.14.45

…arly_return_limit

test_storage_delta/test.py::test_early_return_limit pinned two quantities that a
producer/consumer interleaving decides, so both legal interleavings had to be
accepted but only one was.

The DeltaLake scan runs a producer thread that appends to a bounded deque and
logs the LIVE queue depth ("List batch size is {}/{}"). Consumers pop from the
same deque under the same mutex. With s3_list_object_keys_size = 1 the capacity
is one element, so the producer's last log legitimately reads 1/1 or 0/1
depending on which thread reaches the mutex first. The scanned-file counter is
incremented after both callback shutdown exits, so it is 2 or 3 for the same
reason. The master failure and the reproduction both show the drained ordering.

Two changes:

- Remove the assertion that counted "List batch size is 1/1, shutdown: true".
  It is implied by the assertion three lines above it, which runs first: a
  callback that observes shutdown returns false from the row callback, the
  kernel turns that into Ok(()) and the FFI visitor discards it, so the producer
  always reaches the batch log afterwards, and shutdown is a monotone latch.
  So first_check_hits > 0 or queue_check_hits > 0 already covers it, records
  which shutdown path fired, and is free of the race.

- Restore the scanned-files assertion to an upper bound. It was an upper bound
  (< 10) when the test was written and was tightened to == 3 six days later;
  the bound shape is what the async scan permits, so keep the tighter constant
  as <= 3. The existing assert scanned_files > 0 is the lower bound.

Validated with a forced-interleaving probe in the scan callback: unpatched fails
with the CI signature, patched passes on the same drained ordering; deleting both
callback shutdown exits makes the patched test fail at "assert 997 <= 3", so the
retained bound still catches an early-return regression; 20 consecutive runs pass.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 21, 2026
@groeneai

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

An independent cold review plus a second-model pass ran over this diff before it was opened,
and a second pass after the fixes returned no findings. Verdicts below; each one is backed by a
code citation or a measurement, not an opinion.

# Finding Verdict
⚠️ 1 The commit message closed with a comment-line accounting sentence that was wrong in both halves (measured net -4, and 2 comment lines are added) and was internal process detail besides. Agreed, fixed: sentence removed; the message ends at the validation summary.
💡 2 The description understated the breadth: "two job families", one master hit. Agreed, fixed: CIDB over 90 days puts this exact signature at 5 hits across three job families (arm_binary, distributed plan x2, amd_tsan, amd_asan_ubsan, db disk, old analyzer), two of them on master (3c1906b00062a37c 2026-06-11 shard 4/4, 0c80ff614e89817c 2026-08-17 shard 1/4). Both corrections strengthen the point that this is not parametrization-specific.
💡 3 The Closes relationship used the #NNNNN shorthand rather than the full URL the template asks for. Agreed, fixed.

Also checked and found sound, so nothing was changed: the implication argument the first
change rests on was re-derived link by link (return false from the row callback becomes
Ok(()) in kernel/src/scan/state.rs:224-226, is discarded by
visit_scan_metadata_impl in ffi/src/scan.rs:726-737, and cannot reach
scan_metadata_next_impl at all because that visitor is declared -> (), so the producer
always reaches the batch log; shutdown has exactly two writes repo-wide, both to true);
the <= 3 bound matches the reader pool (max_threads = 1 plus one in-flight future, so at
most two concurrent next(), plus one producer-ahead file); the provenance framing was
verified by reading both of the original commits rather than taken on assertion; and a
repo-wide sweep confirms one oracle and one producer, with the other
DeltaLakeScannedFiles and Scanned file count assertions all belonging to no-LIMIT
pruning tests where the iterator runs to completion and no early-return race exists.

One residual is disclosed rather than acted on: the retained
assert first_check_hits > 0 or queue_check_hits > 0 is in principle a member of the same
family, since a shutdown that lands while the producer is parked in its own wait would exit
the outer loop before either callback log site fires. That is a code-reading argument only,
it has zero occurrences in 90 days across roughly 97k runs of this test, and this change
strictly improves the signal by removing an oracle that failed five times in that window
and keeping one that failed none. It is noted here, not chased.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A 1500 ms sleep in scanCallbackImpl, after the queue-wait block and before the post-wait shutdown check, gated to list_batch_size == 1, forces the drained ordering on demand. python3 -m ci.praktika run "Integration tests (arm_binary, distributed plan, 1/4)" --test "test_storage_delta/test.py::test_early_return_limit" --workers 1 then fails every time. The gate on list_batch_size is required: an ungated sleep starves the 1000-file baseline scan in the same test.
b Root cause explained? Yes. s3_list_object_keys_size = 1 gives the scan deque a capacity of one. The producer logs data_files.size(), the LIVE depth at log time, while consumers pop under the same mutex, so the final shutdown: true line reads 1/1 or 0/1 depending on which thread reaches next_mutex first. DeltaLakeScannedFiles is incremented after both callback shutdown exits, so the scanned-file count is 2 or 3 by the same race. Both orderings are correct engine behaviour; the two assertions accepted only one.
c Fix matches root cause? Yes. The two assertions that pin race-decided values are the defect, and each is addressed at its own level: the queue-depth count is removed because it is implied by the shutdown-observation assertion three lines above it, and the exact scanned-file comparison becomes the upper bound the test was originally written with. No bound is widened beyond what the code permits and no no-random-* style blanket suppression is used.
d Test intent preserved / new tests added? Yes. assert first_check_hits > 0 or queue_check_hits > 0 still requires that a callback observed shutdown, and records which path fired; assert scanned_files > 0, assert scanned_files < full_scan_files and the LIMIT 1 row-count assertion are untouched. No new test: the deliverable is that the retained oracles accept every legal ordering while still rejecting a regression, which is what the mutation arm below shows.
e Both directions demonstrated? Yes, on the same forced ordering. Probe binary b7cda724f10f2a5a + unmodified master fails assert 1 == 0 / where 0 = int('0\n') with First shutdown check hits: 0 / Queue shutdown check hits: 1, byte-identical to the master CI failure. Probe + patched test passes, and the server log for that run confirms the drained ordering was actually present (2 Scanned file lines, List batch size is 0/1, shutdown: true), so the pass is not on a natural ordering. Base binary b3b9fcc9a1b88a33 passes with and without the patch.
f Fix is general across code paths? Yes. grep -rn "List batch size" tests/ finds exactly one oracle and src/ exactly one producer. DeltaLakeScannedFiles appears twice in the integration suite, both in this test: the no-LIMIT baseline (deterministic, no early return) and the assertion fixed here. A per-function sweep for a LIMIT combined with a scan-count oracle matches only test_early_return_limit; the ~18 Scanned file exact-count oracles elsewhere are no-LIMIT pruning tests where the iterator runs to completion. Hudi and the non-kernel DeltaLake path take list_batch_size unused and emit none of these logs.
g Fix generalizes across inputs? N/A for the input matrix (test-only change; no expression, type or format handling is touched). The test is parametrized ["1"] only, so the non-kernel path never runs it. The value range is covered instead: scanned_files is bounded above by the reader pool (max_threads = 1 plus one in-flight future, so at most 2 concurrent next()) plus one producer-ahead file, and 20/20 runs observed 3, never more.
h Backward compatible? N/A. Test-only. No setting, no SettingsChangesHistory.cpp row, no serialization format, no experimental gate, no user-visible behaviour.
i Invariants and contracts preserved? Yes, and no engine invariant is touched since src/ is unchanged. The test-level invariant asserted is now "a callback observed shutdown and iteration stopped early", which holds on both shutdown exits and in both orderings, rather than "the deque held exactly one element when the last batch was logged", which holds in only one. The LOG_TEST queue-depth line stays in src/ as a diagnostic for debugging a stall rather than being deleted to tidy a test.

Session id: cron:clickhouse-impl-slot-4:20260820-221000

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [651c898]

Summary: ✅


AI Review

Summary

This PR removes one race-sensitive log assertion and relaxes the exact scanned-file count in test_early_return_limit, which is the right area to fix. I do not think it fully removes the flake, though: the surviving shutdown-log assertion still depends on one specific producer/consumer interleaving, while the current iterator/reader pipeline admits a legal path where early return succeeds and neither shutdown log is emitted.

Findings

⚠️ Majors

  • [tests/integration/test_storage_delta/test.py:5359] The test still requires shutdown to be observed inside scanCallbackImpl, but StorageObjectStorageSource::lazyInitialize eagerly creates both the current reader and reader_future (src/Storages/ObjectStorage/StorageObjectStorageSource.cpp:526-530). That lets TableSnapshot::Iterator::next drain two files before the first row satisfies LIMIT 1 (src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp:397-401), after which the producer can be parked in its own schedule_next_batch_cv.wait (src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp:293-304). If cancellation lands there, shutdown wakes scanDataFunc without another callback pass, so both hit counters stay zero even though early return behaved correctly. Suggested fix: remove this log-based assertion too, or replace it with a race-free invariant such as the bounded DeltaLakeScannedFiles checks.
Final Verdict

Changes requested.

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

Copy link
Copy Markdown
Collaborator Author

cc @SmitaRKulkarni, could you review this? It is test-only: two assertions in test_early_return_limit pinned values that the DeltaLake scan's producer/consumer interleaving decides (the logged queue depth is read live, and DeltaLakeScannedFiles is incremented after both callback shutdown exits), so both legal orderings had to be accepted but only one was.

@@ -5358,24 +5358,16 @@ def test_early_return_limit(started_cluster, use_delta_kernel):

assert first_check_hits > 0 or queue_check_hits > 0

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.

first_check_hits > 0 or queue_check_hits > 0 still assumes shutdown is observed inside scanCallbackImpl, but the current read path does not guarantee that. StorageObjectStorageSource::lazyInitialize creates the first reader and immediately starts reader_future, so TableSnapshot::Iterator::next can pop two files before the first row reaches LIMIT 1 (src/Storages/ObjectStorage/StorageObjectStorageSource.cpp:526-530, src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp:397-401). With s3_list_object_keys_size = 1, the producer can then enqueue a third file and block in its own schedule_next_batch_cv.wait after the List batch size log (src/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp:293-304). If LIMIT cancels there, shutdown only wakes scanDataFunc; it never forces another callback invocation, so both counters remain zero even though early return worked correctly. That leaves this test flaky on a different legal interleaving. I think this log-based assertion needs to be removed as well, or replaced with an invariant that does not depend on which callback site sees shutdown.

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.

Mechanism confirmed, and the citations check out (lazyInitialize is at
StorageObjectStorageSource.cpp:521-533, one hop from your :526-530). Both counters are logged
inside scanCallbackImpl, the callback only runs from scan_metadata_next at
TableSnapshot.cpp:288, and the producer's park at :300-304 sits outside it, so on wake the
while (!shutdown.load()) guard at :285 exits without another callback invocation and neither
counter is incremented. The PR body now says this instead of claiming the retained assertion is
race-free.

Not removing it here, because the numbers point the other way. Over 90 days this test has 97538 OK
and 38 FAIL rows in the CI database: the assertion this PR deletes accounts for 5 of the 38, the one
you point at for 0. Trading a 5-hit oracle for a 0-hit one is the value of the change, and deleting
both would leave scanned_files <= 3 as the only check of the early-return path.

On a site-independent invariant, I do not have one I trust. Set finished is asserted nowhere and is
logged only when the iterator is exhausted, which a LIMIT 1 early return does not reach. Any
replacement also has to avoid reducing to something an earlier assertion already implies, which is
the defect being removed here. That needs a DeltaLake reviewer's view on what the scan guarantees,
so it is wider than this fix.

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 704.51 MiB 701.46 MiB -3.05 MiB (-0.43%)

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

Compile time of recompiled translation units

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

Job report

f"Early return should scan 3 files with LIMIT 1, but scanned {scanned_files}"
# At most 3: two async readers each consume one file, plus one the scan produces before
# it observes shutdown. Fewer is legal when shutdown lands earlier.
assert scanned_files <= 3, \

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.

@kssenii it looks like you modified this test last, can you take a quick look to make sure this change is OK? Feel free to assign yourself.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 24, 2026
Merged via the queue into ClickHouse:master with commit bbe1698 Aug 24, 2026
185 of 186 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

This fix never reached the live release branches, and on 2026-09-24 the race it removes reddened a 26.7 job.

The failing job: actions/runs/36069906831/job/107873053411, Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/8) on 26.7 abe0925f91de, and its report. It finished failure with 711 OK, 33 skipped and exactly one FAIL, test_storage_delta/test.py::test_early_return_limit[1], on the assertion this PR deleted: count() ... message LIKE '%List batch size is 1/1, shutdown: true%' returned 0. That one assertion was the only failing test in the job.

The two assertions deleted here are still present on 26.6, 26.7 and 26.8. master and 26.9 carry the fix, and 26.5 has had no commit since 2026-08-27.

Old versus new, over 90 days of CI history: on the branches that still carry the assertion, 1 failure in 3,706 runs of this test, or 1 in 1,177 counting only the old analyzer shards. On master 0 in 5,512 runs since this merged, and on 26.9 0 in 136. No branch cut after 2026-08-24 is affected, so the set does not grow.

The diff is one test file, and it applies to 26.6, 26.7 and 26.8 with no conflict (context offset only, no fuzz).

@PedroTadim would you add v26.7-must-backport here, so the robot can cut the cherry-pick? 26.7 is the branch where it actually fired; 26.6 and 26.8 carry the same two assertions if you would rather cover them as well.

@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 25, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 25, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 25, 2026
Backport #115693 to 26.7: Do not assert scan-progress values decided by an async race in test_early_return_limit
clickhouse-gh Bot added a commit that referenced this pull request Sep 25, 2026
Backport #115693 to 26.8: Do not assert scan-progress values decided by an async race in test_early_return_limit
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Oct 2, 2026
…s decided by an async race in test_early_return_limit
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Oct 2, 2026
…s decided by an async race in test_early_return_limit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-ci pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.7-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Flaky test: test_storage_delta/test.py::test_early_return_limit

7 participants