Skip to content

Fix Logical error "Incorrect mark rows for part" for non-adaptive parts - #103538

Merged
PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-stid-5629-validateColumnOfFixedSize
May 13, 2026
Merged

PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-stid-5629-validateColumnOfFixedSize

Conversation

@groeneai

@groeneai groeneai commented Apr 25, 2026 •

Copy link
Copy Markdown
Collaborator

This is a separate PR per @alexey-milovidov's request in #100941 (comment)... — I picked up the BuzzHouse Logical error: Incorrect mark rows for part ... finding (STID 5629-58bc) caught on the BuzzHouse (amd_debug) run of #100941 and on the master BuzzHouse (amd_debug) runs over the past 60 days (11 hits, 9 unrelated PRs, 1 master hit on 2026-04-01).

Why it's not the same fix as #102592

#102592 (open, by @Desel72) attributes the bug to MutateAllPartColumnsTask and only fixes the granularity reuse path there. After reproducing the minimal example from the linked issue locally, the abort fires on the MutateSomePartColumnsTask::finalize → MergeTreeDataPartWriterWide::finishDataSerialization path instead, because DELETE FROM t WHERE TRUE ends up as ALTER UPDATE _row_exists = 0 for tables that support lightweight delete (affectsAllColumns() is false for the resulting UPDATE command). That's why #102592's regression test "passed" with a flaky having stderror — the SELECT count() returns before the background mutation has even reached the validator. The actual abort happened in the background task.

The real bug is in the validator itself, which is a debug-only #ifndef NDEBUG sanity check — that's also why the failure has only ever surfaced in BuzzHouse / debug builds.

Root cause

MergeTreeDataPartWriterWide::validateColumnOfFixedSize reads per-mark row counts from the freshly-written mark file. For non-adaptive marks (no row count on disk) it used to fall back to index_granularity_info.fixed_index_granularity. That fallback predates MergeTreeIndexGranularityConstant, which allows last_mark_granularity < constant_granularity (incomplete last mark). After a DETACH/ATTACH the in-memory granularity goes through fixFromRowsCount(rows_count), so getMarkRows(last) returns the real row count (e.g. 1) while the validator keeps comparing it to the constant (e.g. 8192), and the comparison

if (index_granularity_rows != index_granularity->getMarkRows(mark_num))
    throw LOGICAL_ERROR;

aborts the next mutation.

Fix

Use the in-memory granularity directly when the mark file does not store per-mark row counts. That's what the writer already used to size the data, so by construction the comparison can no longer false-positive. The downstream column size check (which actually deserializes the bin file) still validates the data file's row count.

if (settings.can_use_adaptive_granularity)
    readBinaryLittleEndian(index_granularity_rows, *mrk_in);
else
    index_granularity_rows = index_granularity->getMarkRows(mark_num);

Reproduction

PedroTadim's minimal reproduction from #98585 reliably aborts the server in a debug build before this patch:

CREATE TABLE t0 (c0 Int) ENGINE = MergeTree() ORDER BY tuple()
SETTINGS index_granularity_bytes = 0;
INSERT INTO t0 VALUES (1);
DETACH TABLE t0 SYNC; ATTACH TABLE t0;
DELETE FROM t0 WHERE TRUE;

After this patch the same statements complete cleanly. I've added a stateless regression test (04117_lightweight_delete_nonadaptive_granularity) that covers both the empty-after-delete case and the partial-delete-with-incomplete-last-mark case, and it passed 50/50 runs locally with --test-runs 50.

CI report

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100941&sha=642670753747a79a56f585e1160a93f6f982d344&name_0=PR&name_1=BuzzHouse%20%28amd_debug%29

Related

Closes #98585
Originating thread: #100941
Alternative fix: #102592 (different code path, see above)

cc @alexey-milovidov

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix Logical error: Incorrect mark rows for part ... (debug-only assertion) that was triggered by mutations on MergeTree tables with non-adaptive index granularity (index_granularity_bytes = 0) whose last data mark was incomplete (most reliably reproduced via DETACH/ATTACH followed by a lightweight DELETE).

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

No documentation changes are needed for this bug fix.

Version info

  • Merged into: 26.5.1.628

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @CurtizJ @alesapin — could you review this? It fixes a debug-only Logical error: Incorrect mark rows (STID 5629-58bc, issue #98585) by reading the per-mark row count from the in-memory MergeTreeIndexGranularityConstant instead of fixed_index_granularity in validateColumnOfFixedSize, so an incomplete last mark on a non-adaptive part no longer false-positives the assertion. Separate from #102592 because the actual abort path is MutateSomePartColumnsTask, not MutateAllPartColumnsTask. Tests run 50/50 locally.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (session cron:clickhouse-ci-task-worker:20260425-191500):

a) Deterministic repro? Yes. PedroTadim's minimal repro from #98585 reproduces the abort 100% of the time on a debug build:

CREATE TABLE t0 (c0 Int) ENGINE = MergeTree() ORDER BY tuple()
SETTINGS index_granularity_bytes = 0, min_rows_for_wide_part = 0, min_bytes_for_wide_part = 0;
INSERT INTO t0 VALUES (1);
DETACH TABLE t0 SYNC; ATTACH TABLE t0;
DELETE FROM t0 WHERE TRUE SETTINGS lightweight_deletes_sync = 2;

b) Root cause explained? Yes. Non-adaptive mark files store no per-mark row count, so the validator falls back to fixed_index_granularity. MergeTreeIndexGranularityConstant allows the last data mark to have fewer rows (last_mark_granularity), and fixFromRowsCount populates that value during part load (e.g. after DETACH/ATTACH). The validator then compares the constant (8192) to the in-memory getMarkRows(last) (1) and aborts. The writer wrote the part correctly using the in-memory granularity — only the read-back assumption was stale.

c) Fix matches root cause? Yes. The patch reads the per-mark row count from the same in-memory granularity the writer used, so the validator now compares apples to apples. It does not weaken the bin-file check at line 703 (column size still has to match the expected count).

d) Test intent preserved? / New tests added? Yes. New 04117_lightweight_delete_nonadaptive_granularity.sql covers (1) the empty-after-delete case from the issue and (2) a partial-delete with an incomplete last mark, both with explicit min_rows_for_wide_part = 0, min_bytes_for_wide_part = 0 to keep the test green under randomized MergeTree settings without using a coarse no-random-merge-tree-settings tag.

e) Demonstrated in both directions? Yes. With the C++ change reverted on the same branch, 04117_lightweight_delete_nonadaptive_granularity aborts the server with Logical error: 'Incorrect mark rows for part .../tmp_mut_all_1_1_0_2/ ... in-memory 1, on disk 56113, total marks 1'. With the fix in place the same test passes 50/50 runs (PATH=build/programs:$PATH tests/clickhouse-test --test-runs 50 04117_lightweight_delete_nonadaptive_granularity). Sanity-ran 01457_min_index_granularity_bytes_setting, 02932_lwd_and_mutations, 03725_json_dynamic_subcolumn_prewhere_zero_index_granularity_bytes, 03725_variant_element_null_map_subcolumn_prewhere_zero_index_granularity_bytes — all pass.

f) Fix is general, not a narrow patch? Yes. The same incomplete-last-mark reasoning applies to every non-adaptive call site of the validator (debug-only). No symmetric writer in the codebase has the same hardcoded fixed_index_granularity fallback against an in-memory granularity that may differ — MergeTreeDataPartWriterCompact does not validate marks this way, and adaptive parts read the row count from disk. The fix is at the validator's root assumption, not the symptom site.

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

clickhouse-gh Bot commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [74bff69]

Summary: ❌

job_name test_name status info comment
Bugfix validation (functional tests) FAIL
04117_lightweight_delete_nonadaptive_granularity FAIL cidb IGNORED

AI Review

Summary

This PR fixes a debug-only false-positive LOGICAL_ERROR in MergeTreeDataPartWriterWide::validateColumnOfFixedSize for non-adaptive granularity parts with an incomplete last mark, and adds a focused stateless regression test for both full and partial lightweight-delete scenarios after DETACH/ATTACH. I found no correctness, safety, concurrency, performance, or test-coverage issues that require code changes.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 26, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai can you check the failing tests?

`MergeTreeDataPartWriterWide::validateColumnOfFixedSize` is a debug-only
sanity check that aborts the server on mismatch, so the failure only ever
showed up in BuzzHouse / debug builds (issue ClickHouse#98585, STID 5629-58bc).

For non-adaptive parts the mark file does not store per-mark row counts,
so the validator falls back to `index_granularity_info.fixed_index_granularity`.
That assumption is stale: `MergeTreeIndexGranularityConstant` allows the
last data mark to have fewer rows (`last_mark_granularity`), and during
part load `fixFromRowsCount` adjusts it to the actual row count from
`count.txt`. After a DETACH/ATTACH cycle the in-memory granularity
correctly reports the incomplete last mark while the validator still
asserts `fixed_index_granularity`, so the comparison

    if (index_granularity_rows != index_granularity->getMarkRows(mark_num))
        throw LOGICAL_ERROR;

fires for any subsequent mutation that goes through the wide writer (we
hit it via `MutateSomePartColumnsTask::finalize` for lightweight DELETE).
Read the per-mark row count from the in-memory granularity (which is
what the writer used to size the data) so the assertion matches reality.
The downstream check on the deserialized column size still validates
that the data file matches the expected row count.

Closes ClickHouse#98585

Co-authored-by: Claude Opus 4.7 <[email protected]>
@groeneai
groeneai force-pushed the fix-stid-5629-validateColumnOfFixedSize branch from 8580e06 to 74bff69 Compare May 7, 2026 11:49
@groeneai

groeneai commented May 7, 2026

Copy link
Copy Markdown
Collaborator Author

@PedroTadim — investigated all 5 failing CI checks from the previous run (commit 8580e06b, 2026-04-26). All are non-PR-caused. I rebased onto current master (74bff692b54) to trigger fresh CI; here's the analysis:

1. AST fuzzer (arm_asan_ubsan) — Logical error: Bad cast from type A to B (STID: 1635-2ab2)
Chronic trunk bug — 13 unrelated PRs hit it in the last 30 days. Stack trace bottoms out in PlannerContext::getColumnNodeIdentifierOrNull (PlannerContext.cpp:169) via CollectColumnIdentifiers — completely unrelated to my one-line change in MergeTreeDataPartWriterWide::validateColumnOfFixedSize. External fix is in flight: PR #103879 ("Reject MATERIALIZED CTE references with inconsistent inferred types").

2. Bugfix validation (functional tests) / 04117_lightweight_delete_nonadaptive_granularity
Known limitation, not a real failure. The fix is debug-only (#ifndef NDEBUG guard around validateColumnOfFixedSize). Bugfix validation downloads the master release binary (NDEBUG defined), so the assertion never fires — the regression test passes on master regardless of the fix. The validator interprets "test passes on master" as "regression test doesn't catch the bug" and reports FAIL. Same pattern as PR #102289 (merged 2026-04-20 by @alexey-milovidov). Not actionable — the bug genuinely cannot be reproduced on a release build.

3. Performance Comparison (arm_release, master_head, 1/6, 3/6, 6/6) — assert cidb.is_ready()
Pure CI infrastructure noise. The CIDB cluster (play.clickhouse.com) hit Code 202: Too many simultaneous queries. Maximum: 1000 while CI tried to upload performance metrics. Unrelated to the PR.

4. Finish Workflow — Cascade rollup from the above.

Branch rebased onto current master at 74bff692b54. Fresh CI is running now and should be green on all PR-caused signals. Awaiting reviewer approval (cc @alexey-milovidov, @CurtizJ, @alesapin).

@clickhouse-gh

clickhouse-gh Bot commented May 7, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 0.00% (0/4) · Uncovered code

Full report · Diff report

@PedroTadim

Copy link
Copy Markdown
Member

@alexey-milovidov I think this can be merged?

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai why the 04117_lightweight_delete_nonadaptive_granularity test failed?

@groeneai

groeneai commented May 8, 2026

Copy link
Copy Markdown
Collaborator Author

@PedroTadim — short answer: the 04117_lightweight_delete_nonadaptive_granularity failure is the known release-binary limitation of Bugfix validation, not a real failure. Same pattern as PR #102289 (merged 2026-04-20). All other CI is green.

Why it fails in Bugfix validation specifically

Bugfix validation runs the new regression test against the master release binary and expects it to fail (otherwise the test "doesn't catch the bug"). Concretely, ci/jobs/functional_tests.py downloads:

https://clickhouse-builds.s3.us-east-1.amazonaws.com/master/${arch}/clickhouse

…which is a release build (NDEBUG defined).

The bug from #98585 is a LOGICAL_ERROR thrown by MergeTreeDataPartWriterWide::validateColumnOfFixedSize. That validator is only called in debug builds — it lives behind #ifndef NDEBUG at MergeTreeDataPartWriterWide.cpp:821-833:

#ifndef NDEBUG
    /// Heavy weight validation of written data. Checks that we are able to read
    /// data according to marks. Otherwise throws LOGICAL_ERROR (equal to abort in debug mode)
    for (const auto & column : columns_list)
    {
        if (column.type->isValueRepresentedByNumber()
            && !column.type->haveSubtypes()
            && getSerialization(column.name)->getKindStack() == ISerialization::KindStack{ISerialization::Kind::DEFAULT})
        {
            validateColumnOfFixedSize(column);
        }
    }
#endif

So on the master release binary the validator never runs, the LOGICAL_ERROR is never thrown, and the test passes — exactly the same on PR-head and on master. Bugfix validation interprets "test passes on master release" as "regression test doesn't catch the bug" and reports FAIL. There is no way for this specific check to demonstrate the bug, because the bug genuinely only manifests in debug builds.

Verification on a debug build (where the bug actually lives)

The fix is correctly exercised by every other CI job that uses a debug/sanitizer binary:

  • All Stateless tests (amd_debug, …) runs ✅ — 04117_lightweight_delete_nonadaptive_granularity passes
  • All Stateless tests (amd_asan_ubsan, amd_tsan, amd_msan, …) ✅
  • All 4 BuzzHouse variants ✅
  • Stress test (*) ✅

Locally on debug build:

  • Without the one-line fix: server aborts with Incorrect mark rows for part .../tmp_mut_*/, in-memory N, on disk 8192 — exactly the original STID 5629-58bc failure.
  • With the fix: 50/50 passes.

Precedent

PR #102289 ("Fix logical error when parsing incorrect empty tuples") had the same situation — the fix lived behind #ifndef NDEBUG so Bugfix validation reported FAIL while every debug/sanitizer run was green. It was merged anyway. Same shape here.

Current CI state on 74bff692b54

143 SUCCESS · 17 SKIPPED · 4 not-run-yet · 1 FAILURE = Bugfix validation (functional tests) (this one).

@PedroTadim
PedroTadim added this pull request to the merge queue May 13, 2026
Merged via the queue into ClickHouse:master with commit b603b4b May 13, 2026
163 of 165 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 May 13, 2026
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 pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

4 participants