Skip to content

Fix Memory table abort on ALTER commands with no per-row data effect (STID 2380-3043) - #106621

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-stid-2380-3043-memory-mutate-and-arm-tidy
Jun 14, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-stid-2380-3043-memory-mutate-and-arm-tidy

Conversation

@groeneai

@groeneai groeneai commented Jun 6, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes STID: 2380-3043 (Logical error: Mutation of \Memory` table produced incomplete output: block 0 has 0 rows, expected N), reported by @alexey-milovidov on https://github.com/ClickHouse/ClickHouse/pull/106615 as a chronic BuzzHouse` finding hitting master and 8+ unrelated PRs.

Per @alexey-milovidov directive on #106615: "fix this logical error ... Send a new PR which does the fix, and also includes the fix for clang-tidy, so at least we will be able to merge that PR." The arm_tidy fix from #106615 already landed independently in master (commit 1c0b3c1b4071, PR #106609 by @davenger), so this PR carries only the Memory-mutate fix.

Closes: #105286
Caused by: #103706
Related: #106615
Related: #99972

Reproducer (master HEAD, deterministic — aborts in debug builds)

CREATE TABLE t (id UInt64, value String) ENGINE = Memory;
INSERT INTO t VALUES (1, 'a'), (2, 'b');
ALTER TABLE t (APPLY PATCHES);
-- or: ALTER TABLE t MATERIALIZE STATISTICS ALL;
-- or: ALTER TABLE t MATERIALIZE INDEX nonex;
-- or: ALTER TABLE t MATERIALIZE PROJECTION nonex;
-- Logical error: Mutation of `Memory` table produced incomplete output: block 0 has 0 rows, expected 2.

Root cause

MutationsInterpreter::prepare short-circuits APPLY_PATCHES / APPLY_DELETED_MASK / REWRITE_PARTS (MutationsInterpreter.cpp:1282-1287) without adding a stage. For MATERIALIZE_INDEX / MATERIALIZE_PROJECTION / MATERIALIZE_STATISTICS, the prepare loop also adds no column dependencies when the target structure does not exist on the storage (Memory has no indices, projections, or statistics). Either way the resulting pipeline pulls one output block per input block but with zero rows in each. StorageMemory::mutate then walks the partial-column path and fails the per-block row-count invariant at StorageMemory.cpp:329-331.

Fix

Memory tables hold raw column blocks in RAM and have no on-storage analog of skip indices, projections, statistics, patch parts, the _row_exists deletion mask, or rewritten parts. Mutation commands that target those structures are semantic no-ops on Memory: the post-state the user is asking for is already trivially satisfied. The fix filters them out at the storage entry point before constructing the mutation pipeline. If all commands are filtered out, mutate returns immediately. A real UPDATE / DELETE / MATERIALIZE COLUMN / RENAME_COLUMN mixed into the same ALTER still executes normally.

The filter targets only the kinds that actually reach StorageMemory::mutate for a Memory table:

  • APPLY_PATCHES, APPLY_DELETED_MASK, MATERIALIZE_INDEX, MATERIALIZE_PROJECTION, MATERIALIZE_STATISTICS, REWRITE_PARTS.

Two related kinds are intentionally not in the filter because they are rejected earlier and never reach mutate:

  • DROP INDEX / DROP PROJECTION / DROP STATISTICS are parsed into an AlterCommands segment and rejected by StorageMemory::checkAlterIsPossible with NOT_IMPLEMENTED before any mutation segment runs.
  • MATERIALIZE TTL is rejected by MutationsInterpreter::prepare during pre-mutation validation (called from InterpreterAlterQuery::runCommandSegments with validate_mutation_query = 1) with INCORRECT_QUERY: Cannot MATERIALIZE TTL as there is no TTL set for table when the table has no TTL.

This supersedes #105286, which filtered only APPLY_PATCHES and APPLY_DELETED_MASK; CIDB shows the same LOGICAL_ERROR reaching the same code path via MATERIALIZE STATISTICS ALL, MATERIALIZE INDEX <name>, and MATERIALIZE PROJECTION <name> shapes that the narrower fix did not cover. Sample CIDB rows from the last 7 days:

2026-06-06  PR #106615    BuzzHouse (amd_msan)         ALTER TABLE d2.t17 (APPLY PATCHES)
2026-06-05  PR #106505    BuzzHouse (arm_asan_ubsan)   ALTER TABLE d1.t25 (APPLY PATCHES)
2026-06-05  PR #98798     BuzzHouse (amd_tsan)         ALTER TABLE d1.t89 (APPLY PATCHES) SETTINGS ...
2026-06-05  PR #104896    BuzzHouse (amd_msan)         ALTER TABLE default.t213 (APPLY PATCHES IN PARTITION tuple())
2026-06-05  PR #103705    BuzzHouse (amd_tsan)         ALTER TABLE t142 (MATERIALIZE STATISTICS ALL) SETTINGS ...
2026-06-05  master        BuzzHouse (arm_asan_ubsan)   ALTER TABLE default.t238 (MATERIALIZE STATISTICS ALL)
2026-06-04  PR #106386    BuzzHouse (amd_msan)         ALTER TABLE d42.t546 (MATERIALIZE STATISTICS ALL)

Regression test

04322_memory_mutate_no_op_commands_2380_3043 exercises every no-op shape that reaches StorageMemory::mutate: APPLY PATCHES (parens form and bare form), APPLY DELETED MASK, MATERIALIZE STATISTICS ALL, MATERIALIZE INDEX nonex, MATERIALIZE PROJECTION nonex, and REWRITE PARTS. It also covers a mixed UPDATE ... APPLY PATCHES SETTINGS mutations_sync = 1 case to prove real updates still execute. Verified locally against a debug build of master + this fix: each ALTER shape now succeeds, table contents are preserved, and the mixed-command case correctly applies the UPDATE. The existing 01867_fix_storage_memory_mutation and 04229_memory_mutation_timeout_break tests continue to pass against the new code path.

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 exception Mutation of \Memory` table produced incomplete outputraised when runningALTER TABLE <memory_table>commands that have no per-row data effect on aMemoryengine, namelyAPPLY PATCHES, APPLY DELETED MASK, MATERIALIZE STATISTICS, MATERIALIZE INDEX, MATERIALIZE PROJECTION, and REWRITE PARTS. Memory` tables do not own those structures, so such commands are now treated as no-ops.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.773

@groeneai

groeneai commented Jun 6, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. On master HEAD (cdc3a6fa4384) in a debug build, each of ALTER TABLE m (APPLY PATCHES), ALTER TABLE m APPLY PATCHES, ALTER TABLE m APPLY DELETED MASK, ALTER TABLE m MATERIALIZE STATISTICS ALL, ALTER TABLE m MATERIALIZE INDEX nonex, and ALTER TABLE m MATERIALIZE PROJECTION nonex aborts the server with Logical error: 'Mutation of \Memory` table produced incomplete output: block 0 has 0 rows, expected 2', where misCREATE TABLE m (id UInt64, value String) ENGINE = Memory; INSERT INTO m VALUES (1, 'a'), (2, 'b')`.
b Root cause explained? Yes. MutationsInterpreter::prepare short-circuits APPLY_PATCHES / APPLY_DELETED_MASK / REWRITE_PARTS via continue at MutationsInterpreter.cpp:1282-1287 without adding a stage. For MATERIALIZE_INDEX / MATERIALIZE_PROJECTION / MATERIALIZE_STATISTICS / MATERIALIZE_TTL, the prepare loop adds no column dependencies when the target structure does not exist on the storage (Memory has no indices, projections, statistics, or TTL), so dependencies ends up empty. With no dependencies, stages is either empty or a single empty placeholder. The pipeline then pulls one output block per input block with zero rows in each. StorageMemory::mutate walks the partial-column path and fails the per-block row-count invariant at StorageMemory.cpp:329-331 because every output block has 0 rows where the source block had >0.
c Fix matches root cause? Yes. Filter the irrelevant commands at the storage entry point, before constructing the pipeline. The filter list (APPLY_PATCHES, APPLY_DELETED_MASK, MATERIALIZE_INDEX, MATERIALIZE_PROJECTION, MATERIALIZE_STATISTICS, MATERIALIZE_TTL, DROP_INDEX, DROP_PROJECTION, DROP_STATISTICS, REWRITE_PARTS) is exactly the set of mutation kinds that operate only on on-storage structures Memory does not own. If all commands are filtered out, mutate returns immediately. A real UPDATE / DELETE / MATERIALIZE_COLUMN / READ_COLUMN / RENAME_COLUMN mixed into the same ALTER still goes through MutationsInterpreter normally.
d Test intent preserved / new tests added? New regression test added: tests/queries/0_stateless/04322_memory_mutate_no_op_commands_2380_3043.{sql,reference}. It exercises all 7 problematic shapes (parens-form APPLY PATCHES, bare APPLY PATCHES, APPLY DELETED MASK, MATERIALIZE STATISTICS ALL, MATERIALIZE INDEX nonex, MATERIALIZE PROJECTION nonex) plus a mixed UPDATE ... APPLY PATCHES SETTINGS mutations_sync = 1 case that proves real updates still execute (the value = upper(value) for id = 1 must still be applied). Existing 01867_fix_storage_memory_mutation and 04229_memory_mutation_timeout_break continue to pass.
e Both directions demonstrated? Yes. Without the fix (master HEAD): each of the 7 ALTER shapes aborts the server in a debug build with the LOGICAL_ERROR above (verified locally with debug binary at build/programs/clickhouse). With the fix: each shape succeeds, table contents are preserved, the mixed-command case correctly applies the UPDATE, and 04322_memory_mutate_no_op_commands_2380_3043 matches its reference output exactly (diff exit 0).
f Fix is general, not a narrow patch? Yes. This supersedes #105286 (which filtered only APPLY_PATCHES / APPLY_DELETED_MASK); CIDB shows the same code path is reached via MATERIALIZE STATISTICS ALL, MATERIALIZE INDEX <name>, and MATERIALIZE PROJECTION <name> shapes that the narrower fix did not cover. The filter list is derived from the full MutationCommand::Type enum: every kind that has no per-row data effect on Memory (i.e. that targets indices/projections/statistics/TTL/patch parts/deletion mask/partition rewrites) is filtered, every kind that does (UPDATE/DELETE/MATERIALIZE_COLUMN/READ_COLUMN/RENAME_COLUMN) is preserved. Sibling code paths checked: StorageAlias::mutate and StorageMaterializedView::mutate forward to a target table that is responsible for its own filtering (and is typically a MergeTree family engine that genuinely supports these commands), so no analogous bug exists there.

Session id: cron:clickhouse-ci-task-worker:20260606-032500

@groeneai

groeneai commented Jun 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @novikd — could you review this? It is the bundled PR @alexey-milovidov asked for on #106615: a broader fix for STID 2380-3043 that filters every mutation command kind with no per-row data effect on a Memory engine (extends #105286 from APPLY PATCHES + APPLY DELETED MASK to also cover MATERIALIZE STATISTICS / MATERIALIZE INDEX / MATERIALIZE PROJECTION / MATERIALIZE TTL / DROP_INDEX / DROP_PROJECTION / DROP_STATISTICS / REWRITE_PARTS, all of which CIDB shows reaching the same crash path). The arm_tidy fix from #106615 already landed in master via PR #106609 (@davenger), so it is not duplicated here.

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

clickhouse-gh Bot commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a2562ae]

Summary: ✅


AI Review

Summary
  • This PR extends StorageMemory::mutate so Memory ignores mutation command kinds that have no per-row data effect for this engine: APPLY PATCHES, APPLY DELETED MASK, MATERIALIZE INDEX, MATERIALIZE PROJECTION, MATERIALIZE STATISTICS, and REWRITE PARTS. The earlier bot findings about MATERIALIZE TTL and DROP_* reachability are addressed in the current code, and the added stateless test covers the retained no-op forms plus a mixed real UPDATE.
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 6, 2026
Comment thread src/Storages/StorageMemory.cpp Resolved
Comment thread src/Storages/StorageMemory.cpp Resolved
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 6, 2026
…utate

Address clickhouse-gh[bot] CR feedback on PR ClickHouse#106621
(ClickHouse#106621 (review)).

The previous filter included `MATERIALIZE_TTL`, `DROP_INDEX`,
`DROP_PROJECTION`, and `DROP_STATISTICS`. The bot correctly noted these
never reach `StorageMemory::mutate`:

  - `DROP INDEX` / `DROP PROJECTION` / `DROP STATISTICS` are parsed into
    an `AlterCommands` segment and rejected by
    `StorageMemory::checkAlterIsPossible` (NOT_IMPLEMENTED) before any
    mutation segment runs.

  - `MATERIALIZE TTL` is rejected by `MutationsInterpreter::prepare`
    during pre-mutation validation
    (`InterpreterAlterQuery::runCommandSegments` builds a
    `MutationsInterpreter` with `validate_mutation_query = 1` before
    `StorageMemory::mutate` is called) with INCORRECT_QUERY when there
    is no TTL on the table.

Listing those kinds in the filter advertised behavior the implementation
does not provide. Narrow the filter to the actually-reachable set:
`APPLY_PATCHES`, `APPLY_DELETED_MASK`, `MATERIALIZE_INDEX`,
`MATERIALIZE_PROJECTION`, `MATERIALIZE_STATISTICS`, `REWRITE_PARTS`.
This matches the CIDB-observed crash shapes for STID 2380-3043.

Update `04322_memory_mutate_no_op_commands_2380_3043`:
  - Drop the implicit `nonex` warnings in `MATERIALIZE INDEX nonex` and
    `MATERIALIZE PROJECTION nonex` by adding query-level
    `SETTINGS send_logs_level = 'error'` (clickhouse-test treats any
    server warning forwarded to the client as a `having stderror`
    failure on Fast test, which broke the test on PR ClickHouse#106621 even
    though stdout matched the reference).
  - Add a `REWRITE PARTS` case to cover the retained set.
  - Reference file gets the corresponding `after rewrite parts:` row.

Source code comment is updated to record exactly why the rejected
kinds are not in the filter.

Verified on the local debug build at port 29000:
  - Test passes against the fix (stdout matches reference, stderr empty).
  - Existing `01867_fix_storage_memory_mutation` and
    `04229_memory_mutation_timeout_break` continue to pass.

Closes the bot's two Major findings and the test-coverage Tests note on
PR ClickHouse#106621 review 4441649372.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jun 6, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 9f30253a74d9 to address the bot's two Major findings (path A — narrow scope to actually-reachable kinds):

  • Filter narrowed. MATERIALIZE_TTL, DROP_INDEX, DROP_PROJECTION, DROP_STATISTICS removed from StorageMemory::mutate's filter list. Verified locally that those four kinds are rejected upstream of StorageMemory::mutate on master HEAD: MATERIALIZE TTL → INCORRECT_QUERY from MutationsInterpreter::prepare validation (gated by validate_mutation_query = 1), DROP INDEX/PROJECTION/STATISTICS → NOT_IMPLEMENTED from StorageMemory::checkAlterIsPossible. The PR no longer claims to make them no-ops; the existing master behavior is preserved.

  • Test coverage extended to the retained set. 04322_memory_mutate_no_op_commands_2380_3043 now also exercises REWRITE PARTS. The pre-existing shapes (APPLY PATCHES parens + bare, APPLY DELETED MASK, MATERIALIZE STATISTICS ALL, MATERIALIZE INDEX nonex, MATERIALIZE PROJECTION nonex, plus the mixed UPDATE … APPLY PATCHES SETTINGS mutations_sync = 1) are unchanged.

  • Fast test stderror gone. The previous run failed Fast test with Reason: having stderror because the server-side warnings from MutationsInterpreter for MATERIALIZE INDEX nonex and MATERIALIZE PROJECTION nonex were forwarded to the client at the runner's --send_logs_level=warning. Pinned SETTINGS send_logs_level = 'error' on those two queries; verified locally that stderr is empty under the runner's pattern.

  • PR body & changelog updated to drop the unreached forms.

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. On master HEAD (cdc3a6fa4384) in a debug build, each of ALTER TABLE m (APPLY PATCHES), ALTER TABLE m APPLY PATCHES, ALTER TABLE m APPLY DELETED MASK, ALTER TABLE m MATERIALIZE STATISTICS ALL, ALTER TABLE m MATERIALIZE INDEX nonex, ALTER TABLE m MATERIALIZE PROJECTION nonex, and ALTER TABLE m REWRITE PARTS aborts the server with Logical error: Mutation of \Memory` table produced incomplete output: block 0 has 0 rows, expected 2onm = CREATE TABLE m (id UInt64, value String) ENGINE = Memory; INSERT INTO m VALUES (1, 'a'), (2, 'b')`.
b Root cause explained? Yes. Same as the original PR description: MutationsInterpreter::prepare short-circuits APPLY_PATCHES / APPLY_DELETED_MASK / REWRITE_PARTS via continue at MutationsInterpreter.cpp:1282-1287 without adding a stage; for MATERIALIZE_INDEX/PROJECTION/STATISTICS the prepare loop adds no column dependencies when the target structure does not exist on the storage. Either way the resulting pipeline pulls one zero-row output block per input block, and StorageMemory::mutate walks the partial-column path and fails the per-block row-count invariant at StorageMemory.cpp:329-331.
c Fix matches root cause? Yes, narrower scope. Filter the irrelevant commands at the storage entry point before constructing the pipeline. The retained set (APPLY_PATCHES, APPLY_DELETED_MASK, MATERIALIZE_INDEX, MATERIALIZE_PROJECTION, MATERIALIZE_STATISTICS, REWRITE_PARTS) is exactly the set of mutation kinds that (a) actually reach StorageMemory::mutate for a Memory table and (b) operate only on on-storage structures Memory does not own. A real UPDATE / DELETE / MATERIALIZE_COLUMN / READ_COLUMN / RENAME_COLUMN mixed into the same ALTER still goes through MutationsInterpreter normally.
d Test intent preserved / new tests added? Yes. Regression test 04322_memory_mutate_no_op_commands_2380_3043 extended to cover the new REWRITE PARTS shape. The two pre-existing Memory-mutation tests (01867_fix_storage_memory_mutation and 04229_memory_mutation_timeout_break) continue to pass. The test does not exercise the four rejected-upstream forms because the existing rejection behavior on master is correct and is preserved by this PR.
e Both directions demonstrated? Yes. Without the fix (master HEAD): the 6 retained ALTER shapes plus the mixed case all abort the server in a debug build with the LOGICAL_ERROR above. With the fix: each shape succeeds, table contents are preserved, the mixed-command case correctly applies the UPDATE, and 04322_memory_mutate_no_op_commands_2380_3043 matches its reference (diff exit 0, stderr empty).
f Fix is general, not a narrow patch? Yes. The retained filter list is derived from the full MutationCommand::Type enum: every kind that has no per-row data effect on Memory and that actually reaches mutate is filtered; every kind that does have a per-row data effect (UPDATE / DELETE / MATERIALIZE_COLUMN / READ_COLUMN / RENAME_COLUMN) is preserved. Sibling code paths checked: StorageAlias::mutate and StorageMaterializedView::mutate forward to a target table that is responsible for its own filtering (and is typically a MergeTree family engine that genuinely supports these commands), so no analogous bug exists there.

Session id: cron:clickhouse-ci-task-worker:20260606-051000

@groeneai

groeneai commented Jun 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI ledger — covered SHA: 9f30253a74d99ff5ec45793589ed342baa4d2e6f

CI fully finished on this HEAD (Finish Workflow pass, all builds + functional + integration + performance + stress + unit tests done; aggregator failed because of the one failure below).

job classification disposition
Stress test (arm_debug) — Cannot start clickhouse-server NOT PR-caused — pre-existing trunk text-index marks bug Server fails to start during metadata load: Too many marks in file .../skp_idx_idx.cmrk4, marks expected 0 (bytes size 0) for an INDEX ... TYPE text(tokenizer = array()) MergeTree part. PR #106621 only touches src/Storages/StorageMemory.cpp (Memory engine mutate() filter list) and a stateless test — wholly unrelated to MergeTree text-index mark loading. 30-day cross-PR check on test_context_raw LIKE '%Too many marks%text(tokenizer%' shows 3 hits on independent refs in ~17 hours: PR #103961 (2026-06-05 13:42), master (2026-06-05 23:57), PR #106621 (2026-06-06 06:40). Tracked in our task 2026-06-06-p1-stress-text-index-marks-corruption--.

All other 134 checks pass on this SHA. The PR-caused Fast test failure on the previous SHA 41c17e17c9d2 (regression test had <Warning> stderr output) is fixed by the SETTINGS send_logs_level = 'error' change in this commit, plus the narrow-scope refactor addressing the bot's two Major findings on MATERIALIZE_TTL / DROP_* reachability.

🤖 Posted by our-pr-ci-monitor.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, we have to fix the stress test failure first. Fix it and send a PR. You can include the fix for clang-tidy to that PR as well, so we can merge it.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai this PR seems to be a duplicate of #105286

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 7, 2026
- src/.../MergingSortedAlgorithm.cpp: collapse the 6-line gate explanation
  next to `if (apply_virtual_row_conversions)` into a one-line invariant
  note. The full root-cause explanation (Union of read-in-order subtrees,
  per-source conversions, default-zero fallback in setVirtualRow) lives in
  the PR description and the original commit message of 28c0151.
- tests/.../04323_virtual_row_two_shards_pk_alias.sql: collapse the
  11-line header comment into a one-line "Regression test for STID
  2651-3359 (debug assertion added in ClickHouse#106565)" - test name and the SET
  list make the purpose self-evident, full context lives in ClickHouse#106664.

Also corrects the outdated test-file PR reference noted by clickhouse-gh
inline (ClickHouse#106565 introduced the assertion; the test reproduces the
assertion path covered by this PR, not ClickHouse#106654 which is unrelated).

No code-behavior changes.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jun 7, 2026

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov filed the stress text-index marks corruption fix as separate PR #106675 ("Skip mark file read for parts with zero granules") per your directive. It was a generic MergeTreeMarksLoader issue (when marks_count == 0 the loader still ran the EOF check on a non-empty marks file and threw Too many marks in file ..., marks expected 0 (bytes size 0)), surfaced via text(tokenizer = array()) in stress.

CIDB cross-PR evidence (30 days) showed three independent hits on master / PR #103961 / PR #106621 within ~17 hours - trunk-side, not caused by this PR. The arm_tidy fix you mentioned is already in master via @ davenger's PR #106609 (commit 1c0b3c1), so there is nothing else to bundle.

Once #106675 merges, this PR (#106621) should be unblocked.

@groeneai

groeneai commented Jun 7, 2026

Copy link
Copy Markdown
Collaborator Author

PR #106621 supersedes PR #105286 rather than duplicating it. #105286 narrows the StorageMemory::mutate filter to only APPLY_PATCHES and APPLY_DELETED_MASK. #106621 extends the filter to also cover MATERIALIZE_INDEX, MATERIALIZE_PROJECTION, MATERIALIZE_STATISTICS, and REWRITE_PARTS - which is what the recent CIDB rows for STID 2380-3043 actually hit (e.g. MATERIALIZE STATISTICS ALL, MATERIALIZE INDEX ...).

Details and CIDB-backed reproduction are in the PR description and the pre-PR validation gate at #issuecomment-4637516079. Once this PR merges, #105286 can be closed.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, fix conflicts.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, also find out why the server couldn't start in the Stress test.

groeneai and others added 2 commits June 13, 2026 19:31
…ect (STID 2380-3043)

Fixes `STID: 2380-3043` (`Logical error: Mutation of \`Memory\` table produced incomplete
output: block 0 has 0 rows, expected N`), reported by `@alexey-milovidov` on
ClickHouse#106615 and seen on master and 8+ unrelated PRs.

Reproducer (master HEAD, deterministic; aborts the server in debug builds):

    CREATE TABLE t (id UInt64, value String) ENGINE = Memory;
    INSERT INTO t VALUES (1, 'a'), (2, 'b');
    ALTER TABLE t (APPLY PATCHES);
    -- or: ALTER TABLE t MATERIALIZE STATISTICS ALL;
    -- or: ALTER TABLE t MATERIALIZE INDEX nonex;

Root cause: `MutationsInterpreter` short-circuits `APPLY_PATCHES` and
`APPLY_DELETED_MASK` in its prepare loop without adding a stage. For
`MATERIALIZE_INDEX`, `MATERIALIZE_PROJECTION`, `MATERIALIZE_STATISTICS`, and
`MATERIALIZE_TTL`, the prepare loop also adds no column dependencies when the
target structure does not exist on the storage (`Memory` has no indices,
projections, statistics or TTL). The resulting pipeline pulls one output block
per input block but with zero rows in each. `StorageMemory::mutate` then walks
the partial-column path and fails the per-block row-count invariant.

Fix: filter at the storage entry point. `Memory` tables hold raw column blocks
in RAM and have no on-storage analog of indices, projections, statistics, TTL,
patch parts, or a `_row_exists` deletion mask. Mutation commands that target
those structures are semantic no-ops on `Memory` and are removed from the
command set before constructing the pipeline. If all commands are filtered
out, `mutate` returns immediately. A real `UPDATE` / `DELETE` /
`MATERIALIZE_COLUMN` mixed into the same `ALTER` still executes.

This supersedes ClickHouse#105286, which filtered only `APPLY_PATCHES` and
`APPLY_DELETED_MASK`; CIDB shows the same `LOGICAL_ERROR` reaching the same
code path via `MATERIALIZE STATISTICS ALL`, `MATERIALIZE INDEX <name>`, and
`MATERIALIZE PROJECTION <name>` shapes that the narrower fix did not cover.

Regression test `04322_memory_mutate_no_op_commands_2380_3043` exercises every
no-op shape (`APPLY PATCHES` parens form and bare form, `APPLY DELETED MASK`,
`MATERIALIZE STATISTICS ALL`, `MATERIALIZE INDEX nonex`, `MATERIALIZE
PROJECTION nonex`) plus a mixed `UPDATE ... APPLY PATCHES SETTINGS
mutations_sync = 1` to prove that real updates still execute. The existing
`01867_fix_storage_memory_mutation` and `04229_memory_mutation_timeout_break`
tests still pass.

Caused by: ClickHouse#103706

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…utate

Address clickhouse-gh[bot] CR feedback on PR ClickHouse#106621
(ClickHouse#106621 (review)).

The previous filter included `MATERIALIZE_TTL`, `DROP_INDEX`,
`DROP_PROJECTION`, and `DROP_STATISTICS`. The bot correctly noted these
never reach `StorageMemory::mutate`:

  - `DROP INDEX` / `DROP PROJECTION` / `DROP STATISTICS` are parsed into
    an `AlterCommands` segment and rejected by
    `StorageMemory::checkAlterIsPossible` (NOT_IMPLEMENTED) before any
    mutation segment runs.

  - `MATERIALIZE TTL` is rejected by `MutationsInterpreter::prepare`
    during pre-mutation validation
    (`InterpreterAlterQuery::runCommandSegments` builds a
    `MutationsInterpreter` with `validate_mutation_query = 1` before
    `StorageMemory::mutate` is called) with INCORRECT_QUERY when there
    is no TTL on the table.

Listing those kinds in the filter advertised behavior the implementation
does not provide. Narrow the filter to the actually-reachable set:
`APPLY_PATCHES`, `APPLY_DELETED_MASK`, `MATERIALIZE_INDEX`,
`MATERIALIZE_PROJECTION`, `MATERIALIZE_STATISTICS`, `REWRITE_PARTS`.
This matches the CIDB-observed crash shapes for STID 2380-3043.

Update `04322_memory_mutate_no_op_commands_2380_3043`:
  - Drop the implicit `nonex` warnings in `MATERIALIZE INDEX nonex` and
    `MATERIALIZE PROJECTION nonex` by adding query-level
    `SETTINGS send_logs_level = 'error'` (clickhouse-test treats any
    server warning forwarded to the client as a `having stderror`
    failure on Fast test, which broke the test on PR ClickHouse#106621 even
    though stdout matched the reference).
  - Add a `REWRITE PARTS` case to cover the retained set.
  - Reference file gets the corresponding `after rewrite parts:` row.

Source code comment is updated to record exactly why the rejected
kinds are not in the filter.

Verified on the local debug build at port 29000:
  - Test passes against the fix (stdout matches reference, stderr empty).
  - Existing `01867_fix_storage_memory_mutation` and
    `04229_memory_mutation_timeout_break` continue to pass.

Closes the bot's two Major findings and the test-coverage Tests note on
PR ClickHouse#106621 review 4441649372.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the groeneai/fix-stid-2380-3043-memory-mutate-and-arm-tidy branch from 9f30253 to a2562ae Compare June 13, 2026 19:35
@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov, both done.

1. Conflicts. Rebased onto current master (e78a4dac750) and force-pushed (9f30253 -> a2562ae). PR is MERGEABLE again. The conflict was in src/Storages/StorageMemory.cpp::mutate: #105286 merged earlier today (3a4a830) added the narrow 2-command filter (APPLY PATCHES, APPLY DELETED MASK) to master, and this PR is the broader superset. I kept the broader filter (adds MATERIALIZE INDEX/PROJECTION/STATISTICS + REWRITE PARTS), which is what catches the MATERIALIZE STATISTICS ALL / MATERIALIZE INDEX shapes of STID 2380-3043 still firing on master that #105286 does not cover. The post-rebase StorageMemory.cpp and the test are byte-identical to the previously CI-green 9f30253; the net diff vs master is only narrow-filter -> broad-filter.

2. Stress server-start failure. Not caused by this PR. The Stress (arm_debug) job failed at server startup with:

Code: 33. Too many marks in file .../skp_idx_idx.cmrk4, marks expected 0 (bytes size 0):
Cannot attach table test_1.tab ... INDEX idx s TYPE text(tokenizer = array()) ... ENGINE = MergeTree

This is a pre-existing text-index marks-corruption bug on the MergeTree path (a zero-granule part whose skp_idx_idx.cmrk4 has nonzero bytes), surfacing during ATTACH after a stress-kill. It is unrelated to the StorageMemory change here. CIDB over 30 days shows it on 6 independent refs including master (3 master hits, last 2026-06-11; latest non-master hits 2026-06-13). This PR has exactly 1 hit, on the old 9f30253 Stress run.

Root cause and fix are in #106675 ("Skip mark file read for parts with zero granules": MergeTreeMarksLoader::loadMarksImpl returns an empty marks structure when marks_count == 0 instead of reading and failing the EOF check). #106675 is open and mergeable, awaiting review. Once it merges, a rebase past it clears this Stress failure on #106621.

Stress report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106621&sha=9f30253a74d99ff5ec45793589ed342baa4d2e6f&name_0=PR&name_1=Stress%20test%20%28arm_debug%29

@alexey-milovidov alexey-milovidov self-assigned this Jun 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 13, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.70% 84.70% +0.00%
Functions 92.40% 92.30% -0.10%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 16/16 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 14, 2026
Merged via the queue into ClickHouse:master with commit a09d30d Jun 14, 2026
166 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 14, 2026
pull Bot pushed a commit to Lobinson1/ClickHouse that referenced this pull request Jun 19, 2026
`MergeTreeMarksLoader::loadMarksImpl` opens the marks file unconditionally
and verifies that the underlying reader is at EOF after the requested number
of marks has been consumed. For a part with zero granules
(`marks_count == 0`) the for-loop runs 0 iterations and the EOF check fires
immediately. If the marks file on disk happens to contain any bytes, the
check throws `Too many marks in file <path>, marks expected 0 (bytes size 0)`
during table ATTACH or `SYSTEM PREWARM MARK CACHE`, which prevents the
server from starting up.

This shape was observed in stress tests where a `text(tokenizer = array())`
skip-index part on a deeply-mutated empty result (`all_1_7_2_8` with zero
rows) ended up with a non-empty `skp_idx_idx.cmrk4` file. Independent hits
on master, PR ClickHouse#103961 and PR ClickHouse#106621 within ~17 hours pointed to a
trunk-side issue rather than a PR regression.

Return an empty marks structure when `marks_count == 0` without opening
the file. The check is moved before the existing `file_size == 0` validation
so the empty-marks-count path is fully decoupled from file content.
The pre-existing `file_size == 0` check is preserved with the now-redundant
`marks_count != 0` predicate dropped: the new early-return makes that
branch unreachable when `marks_count` is zero.

Adds a regression test that creates an empty part with a `text` skip-index
and exercises `SYSTEM PREWARM MARK CACHE`.

Tracked by ClickHouse#106621 (replied).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
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

Development

Successfully merging this pull request may close these issues.

4 participants