Skip to content

Fix Memory table abort on ALTER TABLE ... APPLY PATCHES (STID 2380-3043) - #105286

Merged
alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-2380-memory-apply-patches
Jun 13, 2026
Merged

alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-2380-memory-apply-patches

Conversation

@groeneai

@groeneai groeneai commented May 19, 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/99972 as a chronic BuzzHouse finding hitting master and 8+ unrelated PRs (#99804, #100185, #100586, #104606, #105107, #105161, #105233`).

CI report demonstrating the original failure:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=99972&sha=f7959f604f297d728373e5f6ed753d9a0bde5a3c&name_0=PR&name_1=BuzzHouse%20%28amd_tsan%29

Reproducer (master HEAD, deterministic)

CREATE TABLE mem (id UInt64, value String) ENGINE = Memory;
INSERT INTO mem VALUES (1, 'a'), (2, 'b');
INSERT INTO mem VALUES (3, 'c'), (4, 'd');
ALTER TABLE mem (APPLY PATCHES);
-- 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 without adding a mutation stage
(MutationsInterpreter.cpp:1238-1243). The resulting pipeline still pulls one
output block per input block, but each block has zero rows. StorageMemory::mutate
then walks the partial-column path and fails the per-block row-count invariant
at StorageMemory.cpp:317.

Fix

Memory tables do not own patch parts (lightweight updates are a MergeTree
feature — IStorage::supportsLightweightUpdate returns
"Table with engine Memory doesn't support lightweight updates") and do not
maintain a _row_exists deletion mask. Both commands are therefore semantic
no-ops on Memory: the post-state the user is asking for (all patches applied,
all deleted rows physically removed) is already satisfied.

StorageMemory::mutate now filters APPLY_PATCHES / APPLY_DELETED_MASK out
of the command set before constructing the mutation pipeline. If all commands
are filtered out, it returns immediately. A real UPDATE or DELETE mixed
into the same ALTER still executes normally — exercised by the regression
test.

Regression test

04254_memory_apply_patches_no_op covers:

  • parenthesised ALTER TABLE m (APPLY PATCHES) (the BuzzHouse form)
  • bare ALTER TABLE m APPLY PATCHES
  • ALTER TABLE m APPLY DELETED MASK
  • mixed ALTER TABLE m UPDATE value = upper(value) WHERE id = 1, APPLY PATCHES SETTINGS mutations_sync = 1

Verified locally: 50/50 passes with --test-runs 50 (randomised settings on).
01867_fix_storage_memory_mutation and 04229_memory_mutation_timeout_break
still pass.

Closes #106846

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 a logical error Mutation of \Memory` table produced incomplete outputraised when runningALTER TABLE <memory_table> APPLY PATCHESorALTER TABLE <memory_table> APPLY DELETED MASK. Memory` tables do not own patch parts or deletion masks, so both commands are now correctly treated as no-ops.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.751

`ALTER TABLE <memory_tbl> (APPLY PATCHES)` (and the equivalent
`APPLY DELETED MASK`) used to raise

    Logical error: Mutation of `Memory` table produced incomplete output:
    block 0 has 0 rows, expected N

(`STID: 2380-3043`, surfaced by `BuzzHouse` on master and 8+ unrelated PRs
in a 24h window).

`MutationsInterpreter::prepare` short-circuits both commands without adding
a mutation stage (`MutationsInterpreter.cpp:1238-1243`). On a `Memory` table
the resulting pipeline still pulls one output block per input block, but
each one has zero rows. `StorageMemory::mutate` then walks the partial-column
path and fails the per-block row-count invariant.

`Memory` tables do not own patch parts (lightweight updates are a `MergeTree`
feature) and do not maintain a `_row_exists` deletion mask, so both commands
are semantically no-ops here: the post-state the user is asking for (all
patches applied, all deleted rows physically removed) is already satisfied.
Filter them out before constructing the mutation pipeline; if all commands
are filtered, return immediately. A `UPDATE` or `DELETE` mixed in the same
`ALTER` still executes normally.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=99972&sha=f7959f604f297d728373e5f6ed753d9a0bde5a3c&name_0=PR&name_1=BuzzHouse%20%28amd_tsan%29
Reported on ClickHouse#99972

Regression test `04254_memory_apply_patches_no_op` exercises:
- parenthesised `(APPLY PATCHES)` (the `BuzzHouse` form)
- bare `APPLY PATCHES`
- `APPLY DELETED MASK`
- mixed `UPDATE ... , APPLY PATCHES SETTINGS mutations_sync = 1`
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @azat @alexey-milovidov — could you review?

Fix for STID 2380-3043 (Logical error: Mutation of \Memory` table produced incomplete output), reported by Alexey on https://github.com/ClickHouse/ClickHouse/pull/99972#issuecomment-3079655421. Deterministic reproduction in the PR description; minimal change to StorageMemory::mutate` + a regression test.

  • @CurtizJ — comp-mutations / lightweight-updates expert (mutation command filtering)
  • @azat — comp-engines-special (StorageMemory)

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate answers (per groeneai worker policy)

# Answer
a. Deterministic repro? Yes — 100%. CREATE TABLE m (id UInt64, value String) ENGINE = Memory; INSERT ... (2 blocks of 2 rows); ALTER TABLE m (APPLY PATCHES); aborts with the exact STID 2380-3043 signature (Mutation of \Memory` table produced incomplete output: block 0 has 0 rows, expected 2.). Same for bare APPLY PATCHESand forAPPLY DELETED MASK`.
b. Root cause explained? Yes. MutationsInterpreter::prepare (MutationsInterpreter.cpp:1238-1243) short-circuits APPLY_PATCHES / APPLY_DELETED_MASK without producing a mutation stage. The pipeline still pulls one output block per input block, but each block has zero rows. StorageMemory::mutate partial-column path (StorageMemory.cpp:323-332) checks out[i].rows() != old_data[i].rows() and throws LOGICAL_ERROR. Upstream cause is correct — MutationsInterpreter skipping these commands is the documented design — but Memory did not recognise them as no-ops applicable to its storage model.
c. Fix matches root cause? Yes. Memory doesn't own patch parts (lightweight updates are a MergeTree feature; IStorage::supportsLightweightUpdate returns "doesn't support" for Memory) and doesn't maintain _row_exists deletion masks. Both commands are semantic no-ops for Memory. Filtering them out before constructing the mutation pipeline addresses the upstream defect (these commands have no work to do on Memory) instead of widening the partial-column invariant.
d. Test intent preserved? / New tests added? New regression test 04254_memory_apply_patches_no_op covers all four trigger forms: parenthesised (APPLY PATCHES), bare APPLY PATCHES, APPLY DELETED MASK, and mixed UPDATE ... , APPLY PATCHES. Existing 01867_fix_storage_memory_mutation and 04229_memory_mutation_timeout_break still pass — partial-column invariant for real UPDATEs is untouched. No assertion weakening, no tags.
e. Demonstrated in both directions? Yes. Before the fix: server aborts with Received signal Aborted (6) and full stack trace ending at StorageMemory::mutate(...). After the fix: all four trigger forms return cleanly, data is preserved (count + per-row values verified), 50/50 runs of --test-runs 50 pass with random settings on.
f. Fix is general, not a narrow patch? Verified. (1) The same bug pattern could affect any non-MergeTree storage that overrides mutate and is reachable by these commands — checked StorageBuffer, StorageLog family, StorageSet, StorageJoin: none of them override mutate, they inherit IStorage::mutate which throws NOT_IMPLEMENTED. So Memory is the only storage with this exact code path that needed fixing. (2) Not a defensive symptom-guard: the fix removes the bad state at its source (commands that would produce empty pipeline output on Memory) rather than catching empty output downstream. The LOGICAL_ERROR throw at StorageMemory.cpp:317 is kept because it remains the right behaviour for genuine partial-column invariant violations from real UPDATEs.

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

clickhouse-gh Bot commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b6ccaf5]

Summary: ✅


AI Review

Summary

This PR makes ALTER TABLE ... APPLY PATCHES and APPLY DELETED MASK no-ops for Memory tables before constructing the mutation pipeline, while preserving execution of real mixed UPDATE / DELETE commands. The added stateless test covers the original Memory failure shape and rejection behavior for related engines. I did not find unresolved correctness, safety, or metadata issues in the current diff.

Final Verdict

Status: ✅ Approve

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

PedroTadim commented May 19, 2026 •

Copy link
Copy Markdown
Member

@groeneai are there any other table engines that could be tested on this scenario as well?

pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request May 19, 2026
ClickHouse#104081 renamed the `server_died` event to `stop_testing` in
`clickhouse-test` and replaced the parent-side print
`Server died, terminating all processes...` with
`Stopping tests, terminating all processes...`. The functional-tests
results parser still searched for the old string, so when a Bugfix
validation run actually killed the server it failed to emit the
synthetic `Server died` leaf that the inversion step in
`ci/jobs/functional_tests.py` flips to OK — and the job reported
`Failed to reproduce the bug` even though the bug had reproduced.

Realign the two SIGN constants to the wording the runner now emits
and rename the carried variable/field to `stop_testing` to match.

Observed on the `Bugfix validation (functional tests)` job of
ClickHouse#105286
(server crashed under the test, log: `Stopping tests, terminating all processes...`).

Refs ClickHouse#104081
Per @PedroTadim's question on PR ClickHouse#105286: audit every storage that overrides `mutate`
and verify only `Memory` was vulnerable to the LOGICAL_ERROR. Other engines either own
patches natively (`MergeTree` family), forward (`Alias`, `MaterializedView`), or reject
unsupported commands upstream in `checkMutationIsPossible` -- the `IStorage` default
for `Log`/`StripeLog`/`TinyLog`/`Null`/`Set`, or a per-engine override for `Join`/
`KeeperMap`/`EmbeddedRocksDB`/`Redis`. `Memory` was the unique outlier: an overridden
`mutate` with a row-count invariant, paired with an effectively empty
`checkMutationIsPossible`.

Lock that contract in so a future refactor cannot silently let `APPLY PATCHES` reach an
engine without lightweight-update support. Engines covered: `Log`, `StripeLog`,
`TinyLog`, `Null`, `Set`, `Join`. `KeeperMap`/`Redis`/`EmbeddedRocksDB` need external
services and are out of scope for a stateless test.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Audit and update pushed.

I went through every storage that overrides mutate and through checkMutationIsPossible for each. Memory was the unique outlier: an overridden mutate that uses MutationsInterpreter and asserts a row-count invariant, paired with an effectively empty checkMutationIsPossible. That triad let APPLY PATCHES reach the pipeline and trigger the LOGICAL_ERROR.

Every other engine is already safe:

  • MergeTree family (MergeTree, ReplicatedMergeTree): owns patches natively.
  • Alias, MaterializedView: forward to the target storage.
  • Log, StripeLog, TinyLog, Null, Set (no mutate override): rejected by the IStorage default checkMutationIsPossible with NOT_IMPLEMENTED.
  • Join: overrides checkMutationIsPossible to throw NOT_IMPLEMENTED for everything except DELETE.
  • EmbeddedRocksDB, Redis, KeeperMap: override checkMutationIsPossible to throw BAD_ARGUMENTS for anything that is not UPDATE or DELETE.
  • ObjectStorage: delegates to its configuration. Datalakes have their own lightweight-update path.

To lock the contract in so a future refactor cannot silently let APPLY PATCHES reach an engine without lightweight-update support, I extended 04254_memory_apply_patches_no_op.sql with assertions that ALTER TABLE <t> APPLY PATCHES throws NOT_IMPLEMENTED for Log, StripeLog, TinyLog, Null, Set, and Join. (KeeperMap, Redis, EmbeddedRocksDB need external services and are out of scope for a stateless test.)

Verified locally: 50/50 passes under full randomization with the fix; reproduces the original LOGICAL_ERROR on Memory without the fix. Commit 1666ce80a03e.

@tuanpach tuanpach self-assigned this May 20, 2026
@tuanpach

Copy link
Copy Markdown
Member

@groeneai

Check the CI failure.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@tuanpach — triage result for Stress test (amd_debug) on 1666ce80:

Failure is not PR-caused. It is the chronic StorageTimeSeries.cpp:171 null deref. All 62 fatal frames in fatal.log and 31 in clickhouse-server.err.log share the same top frame:

3. /ClickHouse/src/Storages/StorageTimeSeries.cpp:171:36:
   DB::StorageTimeSeries::StorageTimeSeries(...)

The two StorageMemory.cpp:312 entries in the log are not crashes; they are expected TIMEOUT_EXCEEDED exceptions thrown by the mutation timeout path, which the PR does not modify.

Cross-PR data (CIDB, 30d):

Upstream fix: #104905 (UBSan null deref in StorageTimeSeries ctor) merged at 2026-05-20 07:10 UTC, ~4 minutes after your ping. The PR's commit 1666ce80 predates the fix.

Action taken: merged master into this branch (7c074183c7d8) to pull in #104905. CI will rerun against the merged commit.

No fix-up to the Memory APPLY PATCHES change is needed.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai merge with master one more time

@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim master merged in 6739104. CI will re-run automatically.

void StorageMemory::mutate(const MutationCommands & commands, ContextPtr context)
{
std::lock_guard lock(mutex);

@antaljanosbenjamin antaljanosbenjamin May 27, 2026 •

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.

Wouldn't it be better to throw an error? This way we just silently don't do anything.

Okay, I see that Memory engine just silently ignores things, so this should be good.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai check the CI failure

@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim CI triage for 849b83a8:

Fast test (arm_darwin) Server died: chronic macOS runner infrastructure. CIDB (14d): 600+ hits across 400+ distinct PRs (spike days 2026-05-20/21 around 130/day). This run's scope shows 0 failed / 25 passed / 36 skipped, only the Server died infrastructure event with no actual test failures.

Bugfix validation (functional tests) "test runner was terminated unexpectedly": chronic job orchestrator abort, same string on 30+ unrelated PRs in 14d (#105041 8 hits, #91784 / #104966 4 hits each, #103627 / #105470 3 hits each, etc.).

Both checks are unrelated infra. No fix-up needed.

(And thanks antaljanosbenjamin for the double-check on the no-op semantics. The engine audit in the earlier reply confirms every other engine either owns patches natively or rejects via IStorage::checkMutationIsPossible; Memory was the unique outlier.)

@groeneai

groeneai commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI ledger — covered SHA: d6676e4dca07e274de1c42dea9998af42cfdd16b

CI fully finished (Mergeable Check completed; 0 pending checks).

Check Test Disposition
Stateless tests (amd_tsan, parallel, 1/2) 00096_obfuscator_save_load, 00175_obfuscator_schema_inference flaky chronic trunk — tasks 2026-06-02-ci-00096obfuscatorsaveload-chronic-f / 2026-06-02-ci-00175obfuscatorschemainference-ab
Unit tests (asan_ubsan) (check-level) infra/chronic UBSan UntrackedMemoryCounter — task 2026-06-03-ci-p1-chronic-ubsan-in-untrackedmemoryc

No PR-caused failures. tuanpach approved 2026-05-21. Awaiting maintainer merge.

Session: cron:our-pr-ci-monitor:20260604-213000

@groeneai

groeneai commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI Ledger — covered SHA: d6676e4

CI fully finished on this HEAD (master-merge of 2026-06-03 05:54Z, ~46h ago). Finish Workflow SUCCESS @ 2026-06-03T10:58:24Z, Mergeable Check SUCCESS, PR aggregator SUCCESS. 141 pass + 19 skipped + 2 failures, all non-PR-caused:

Both classes are pre-existing chronic/trunk noise, not introduced by this PR. The Memory APPLY PATCHES no-op fix itself (StorageMemory::mutate filter for APPLY_DELETED_MASK/APPLY_PATCHES) is intact and verified by every test pass on this HEAD.

posted-comment self-reference: #105286 (this comment)

@ tuanpach approved 2026-05-21 + 2026-05-22 (last approval predates this master-merge, but the merge is master-only and didn't touch this PR's files). Awaiting final merge.

Session: cron:our-pr-ci-monitor:20260605-033000

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai merge with master one more time

@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim master merged in b6ccaf5 (clean, zero conflicts). CI will re-run automatically.

@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.60% 84.60% +0.00%
Functions 92.40% 92.40% +0.00%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 18/18 (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 13, 2026
Merged via the queue into ClickHouse:master with commit 3a4a830 Jun 13, 2026
166 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 13, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 13, 2026
…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]>
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.

Logical error: Mutation of Memory table produced incomplete output: A (STID: 2380-3043)

6 participants