Skip to content

Add settings to limit the number and the size of temporary tables - #122165

Merged
alexey-milovidov merged 10 commits into
masterfrom
temporary-table-limits
Oct 8, 2026
Merged

alexey-milovidov merged 10 commits into
masterfrom
temporary-table-limits

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 25, 2026 •

Copy link
Copy Markdown
Member

There was no way to limit how many temporary tables a session creates or how large they grow, so a single session could fill the server's memory or disk with CREATE TEMPORARY TABLE. This PR adds four user/profile/query settings. All of them default to 0, which means unlimited:

  • max_temporary_tables: the number of tables created with CREATE TEMPORARY TABLE in one session. It is checked when a new table is created and throws TOO_MANY_TABLES. CREATE OR REPLACE of an existing table and IF NOT EXISTS do not count as new tables.
  • max_temporary_table_memory_usage: the memory used by one temporary table with the Memory engine, the default temporary engine. MemorySink checks it while data is received, so an oversized INSERT fails early instead of being buffered first, and again before the data is added. It throws TOO_MANY_BYTES.
  • max_temporary_table_size_bytes_compressed / max_temporary_table_size_bytes_uncompressed: the size of one temporary table with a MergeTree-family engine. MergeTreeSink checks them before each part is committed and throws TOO_MANY_BYTES.

Sizes are counted the same way as total_bytes / total_bytes_uncompressed in system.tables. The value is taken from the settings of the INSERT, so readonly or settings constraints in a profile can enforce it.

Existing similar settings: the Memory engine's own max_bytes_to_keep / max_rows_to_keep evict old data rather than reject new data, and max_temporary_data_on_disk_size_* only covers spilling. If both max_bytes_to_keep and the new limit are set, eviction is applied first.

Scope: the settings only apply to tables created with CREATE TEMPORARY TABLE. The internal temporary tables for external data, GLOBAL IN / GLOBAL JOIN and CTEs already have their own limits (max_bytes_to_transfer and others) and are not affected. In the code, only CREATE TEMPORARY TABLE builds a Memory table through StorageFactory inside the temporary database; the internal tables construct StorageMemory directly. The storage is marked in registerStorageMemory.

Known limitations, all documented in the setting descriptions:

  • An INSERT that writes with several threads commits each thread's data separately, so some of the data may already be added when another thread throws. The table still never exceeds the limit.
  • For MergeTree, parts committed earlier by the same INSERT stay in the table, as with any other error during a multi-block INSERT.
  • The checks are not atomic with the commit, so concurrent inserts can overshoot slightly. max_table_num_to_throw has the same best-effort behavior.

Changelog category (leave one):

  • New Feature

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

Add the settings max_temporary_tables, max_temporary_table_memory_usage, max_temporary_table_size_bytes_compressed, and max_temporary_table_size_bytes_uncompressed to limit the number of temporary tables in a session, the memory usage of Memory temporary tables, and the size of MergeTree temporary tables.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.1798-master (included in 26.10 and later)

There was no way to limit how many temporary tables a session creates or how
large they grow. Add four user/profile/query settings, all `0` (unlimited) by
default:

- `max_temporary_tables`: the number of tables created with
  `CREATE TEMPORARY TABLE` in a session, checked when a new one is created
  (`TOO_MANY_TABLES`);
- `max_temporary_table_memory_usage`: the memory of one temporary table with
  the `Memory` engine, checked in `MemorySink` while the data is received and
  before it is added (`TOO_MANY_BYTES`);
- `max_temporary_table_size_bytes_compressed` and
  `max_temporary_table_size_bytes_uncompressed`: the size of one temporary
  table with a `MergeTree`-family engine, checked in `MergeTreeSink` before
  each part is committed (`TOO_MANY_BYTES`).

The sizes are counted as `total_bytes` / `total_bytes_uncompressed` in
`system.tables`. The internal temporary tables for external data, `GLOBAL IN`
and CTEs are not affected: they have their own limits (`max_bytes_to_transfer`
and others). The existing `max_bytes_to_keep` of the `Memory` engine is not
similar: it evicts old data instead of rejecting new data.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [10a7fa6]

Summary: ✅


AI Review

Summary

This PR adds max_temporary_tables plus size caps for temporary Memory and MergeTree tables, and it now covers the main INSERT, ALTER, ATTACH, REPLACE, MOVE, and deduplicated-insert paths. However, the new size limits are still bypassable through RESTORE TEMPORARY TABLE / RESTORE ALL, so the feature does not yet reliably enforce the core contract that a session cannot grow temporary tables past the configured memory/disk caps.

Findings

❌ Blockers

  • [src/Storages/StorageMemory.cpp:748] RESTORE TEMPORARY TABLE still bypasses max_temporary_table_memory_usage: StorageMemory::restoreDataImpl appends restored blocks and calls setData without re-running checkTemporaryTableMemoryUsage, so a backup restore can load an oversized temporary Memory table despite the new setting. Suggested fix: check the final restored size against the restore query's max_temporary_table_memory_usage before setData.
  • [src/Storages/StorageMergeTree.cpp:4391] RESTORE TEMPORARY TABLE still bypasses max_temporary_table_size_bytes_compressed / max_temporary_table_size_bytes_uncompressed: StorageMergeTree::attachRestoredParts publishes restored parts with renameTempPartAndAdd but never calls throwIfTemporaryTableSizeLimitsExceededForReplacement, so a restore can republish an oversized temporary MergeTree table. Suggested fix: precheck the whole restored batch with the same helper used for ATTACH PARTITION, using the restore query's settings before the first part is committed.
Tests
  • ⚠️ Extend tests/integration/test_backup_restore_new/test.py so RESTORE TEMPORARY TABLE is checked against max_temporary_table_memory_usage, and add a focused restore case for a temporary MergeTree table under max_temporary_table_size_bytes_compressed / max_temporary_table_size_bytes_uncompressed.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions: enforce the new temporary-table size settings on the backup/restore paths for both Memory and MergeTree temporary tables, then add targeted restore coverage for those limits.

LLVM Coverage Report

Measured on commit 10a7fa6.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 92.10% +0.30%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 170/182 (93.41%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-feature Pull request with new product feature comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). labels Sep 25, 2026
alexey-milovidov and others added 3 commits September 26, 2026 23:19
Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`StorageMemory` now keeps the row and byte counters together with the blocks
in `BlocksWithCounts`, so the temporary table memory check reads the size from
`data` instead of the removed `total_size_bytes`. Also add the `database = ''`
condition to the queries to `system.tables` in the test, as required by the
style check.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122165&sha=a27d21cccc8519dda99acc90c2704ef981183270&name_0=PR&name_1=Fast%20test
#122165

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 5, 2026 01:20
…geTree` tables

`checkTemporaryTableSize` ran before `commitPart` applied the non-replicated
deduplication, so re-inserting an already seen block could throw `TOO_MANY_BYTES`
although nothing would be added. Skip the check when the block is already in the
deduplication log; the part rebuilt from the remaining rows is checked on the next try.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageMemory.cpp Resolved
…ns of temporary `Memory` tables

`StorageMemory::mutate` rebuilt the data and committed it without the cap check,
so `ALTER TABLE ... UPDATE` could grow a temporary `Memory` table past the limit.
Check the size of the mutated data before `setData`, using the settings of the
`ALTER` query.

For the `MergeTree` family, mutations and merges run in the background and
rewrite parts outside of the insert sink, so document that the
`max_temporary_table_size_bytes_compressed` / `_uncompressed` limits apply only
to `INSERT`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 10a7fa61b3a5791f2d6207e1c2e36844c8dfba08 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception; stopped retrying after the 1250 s read budget).

See the job log for details.

…attaching parts

`max_temporary_table_size_bytes_compressed` and `max_temporary_table_size_bytes_uncompressed`
were only checked in `MergeTreeSink`, so `ATTACH PART`, `ATTACH PARTITION ... FROM`,
`REPLACE PARTITION ... FROM` and `CREATE TEMPORARY TABLE ... CLONE AS` (which goes through
`replacePartitionFrom`) could grow a temporary table past the limit. Check the whole batch of
parts under the parts lock in these paths (and for the destination of `MOVE PARTITION TO TABLE`),
allowing operations that do not increase the size.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageMergeTree.cpp Resolved
…ry table size limit as a whole

`attachPartition` commits the parts loaded from `detached` one by one, so checking
`max_temporary_table_size_bytes_compressed` / `max_temporary_table_size_bytes_uncompressed`
per part could leave a partition half attached. Check the whole batch before the first commit
(each part is still checked again in case the table grows concurrently), and cover this in the test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageMergeTree.cpp Resolved
…lly with the commit

The size check of `INSERT` into a temporary `MergeTree` table is moved into
`MergeTreeSink::commitPart`, under the same parts lock as the deduplication
log update and the commit, so a concurrent insert of the same block cannot
make a deduplicated insert fail with `TOO_MANY_BYTES`, and concurrent inserts
cannot exceed the limit. It reuses `throwIfTemporaryTableSizeLimitsExceededForReplacement`.

`ATTACH PARTITION` no longer re-checks each part, which could leave the
partition half attached under concurrent writes; the whole-batch check
remains, and the setting documentation now says that concurrent writes may
exceed the limit slightly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageMemory.cpp Resolved
Comment thread src/Storages/StorageMergeTree.cpp Resolved

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

All ok.

@alexey-milovidov alexey-milovidov self-assigned this Oct 7, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 8, 2026
Merged via the queue into master with commit c0289e0 Oct 8, 2026
152 checks passed
@alexey-milovidov
alexey-milovidov deleted the temporary-table-limits branch October 8, 2026 06:16
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 8, 2026
clickgapai added a commit to clickgapai/ClickHouse that referenced this pull request Oct 8, 2026
Manerone pushed a commit to groeneai/ClickHouse that referenced this pull request Oct 9, 2026
`RESTORE TEMPORARY TABLE` bypassed `max_temporary_table_memory_usage` for `Memory`
tables (`StorageMemory::restoreDataImpl` called `setData` without a check) and
`max_temporary_table_size_bytes_compressed` / `max_temporary_table_size_bytes_uncompressed`
for `MergeTree` tables (`StorageMergeTree::attachRestoredParts` committed the parts
without a check). Both are now checked with the settings of the `RESTORE` query;
a `MergeTree` restore is checked for the whole batch before the first part is
committed, so it is rejected as a whole.

Addresses the review comments on ClickHouse#122165

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). pr-feature Pull request with new product feature 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.

2 participants