Skip to content

Add SYSTEM RESET FILELOG to read the files of a FileLog table again or skip them - #123545

Merged
alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/filelog-system-reset
Oct 4, 2026
Merged

alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/filelog-system-reset

Conversation

@groeneai

@groeneai groeneai commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #123368

Changelog category (leave one):

  • New Feature

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

Added SYSTEM RESET FILELOG [db.]table [FILE 'file_name' [OFFSET n | TO END]]: a FileLog table reads all its files again from the beginning, or one file from the beginning, from a given offset, or only from data appended after the command, without recreating the table. Requires the new SYSTEM RESET FILELOG privilege.

Description

Part of "Recovery without recreating the table" in #123368: re-reading a FileLog table's files, or skipping a file or part of it, needed recreating the table with its views and grants.

SYSTEM RESET FILELOG [ON CLUSTER cluster] [db.]table [FILE 'file_name' [OFFSET n | TO END]]
  • without FILE: every file is read again from offset 0;
  • FILE 'name' (as in _filename): that file from 0, from byte n (at most the file size), or, with TO END, only data appended later;
  • the position is saved and survives restarts.

StorageFileLog::resetReadPosition runs under file_infos_mutex (after a running round), applies pending directory events, writes each affected file's new offset to its meta file (temporary file + rename, before memory), marks the file for reopening and wakes or schedules the background task, so a table streaming to views re-reads at once. During a direct SELECT it fails with QUERY_NOT_ALLOWED.

New TABLE-level privilege SYSTEM RESET FILELOG, like SYSTEM FLUSH OBJECT STORAGE QUEUE: re-reading or skipping inserts or drops data, unlike the start/stop controls of SYSTEM STREAMING ENGINES. I can reuse SYSTEM STREAMING ENGINES if you prefer.

Recovering by itself once the cause is gone comes from the other #123368 PRs (#123395, #123404, #123390; per-file isolation to come). Until #123395 merges, a table already stuck with "Another select query is running" also gets QUERY_NOT_ALLOWED here.

Validation: the new test fails on master with SYNTAX_ERROR and passes 50/50 with randomized settings. It covers every form, the errors, persistence across DETACH/ATTACH, materialized views over a directory and one file, a lazily loaded table, and both privilege checks; removing the wake-up, the schedule, the offset write or a privilege check turns it red. By hand: a reset during a running round returns once it ends.

🤖 Generated with Claude Code


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

Version info

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

…r skip them

SYSTEM RESET FILELOG [ON CLUSTER c] [db.]table [FILE 'name' [OFFSET n | TO END]]
changes where a FileLog table continues reading without recreating it:
every file from the beginning, one file from the beginning or from byte n,
or one file only from data appended after the command. Until now the only
way to re-read or skip was to drop and recreate the table (and its views,
grants and comments).

StorageFileLog::resetReadPosition applies pending directory events first
(as makePipe does), then writes the new offset of each affected file to its
meta file and only then changes the in-memory meta and marks the file
UPDATED, so the next round reopens and seeks it. It takes file_infos_mutex,
so it runs between background rounds, and refuses while a direct SELECT has
sources alive (running_streams > 0), because those sources use file_infos
without the mutex. serialize() gets allow_lower_offset, because it otherwise
refuses to store an offset smaller than the stored one (checkOffsetIsValid);
the meta file is replaced through a temporary file and a rename, so a failed
write leaves both the old meta file and the in-memory offset unchanged, and
a crash leaves either the old or the new offset on disk. Afterwards the
background thread is woken (a directory table streaming to views waits for
a directory event) and the task is scheduled (a single-file table, or a
table on the reschedule path, sleeps until its next poll, up to
poll_directory_watch_events_backoff_max), so an idle table that streams to
materialized views re-reads at once.
The interpreter resolves the TableProxy stand-in of a lazily loaded table
(lazy_load_tables) to its FileLog storage before the type check.

New TABLE-level privilege SYSTEM RESET FILELOG (child of SYSTEM), like the
engine-specific SYSTEM FLUSH OBJECT STORAGE QUEUE: rewinding or skipping
offsets re-inserts or drops data, which is a different risk class than the
start/stop/pause controls behind SYSTEM STREAMING ENGINES.

Related: ClickHouse#123368

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 2, 2026
@groeneai

groeneai commented Oct 2, 2026

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

Pre-publication review by an independent model (engine: codex; 5 rounds, 9 findings, the last round clean) plus my own review (5 rounds).

# Sev Finding Verdict Evidence / action
1 ⚠️ A failed or interrupted reset deleted the meta file before writing the new one and changed memory first (StorageFileLog::resetReadPosition) AGREE, fixed (r1) write .tmp + rename first, change memory after
2 ⚠️ A single-file table (or one sleeping until its next poll) was not woken by the reset AGREE, fixed (r1) also schedule() the background task
3 ⚠️ The test did not cover the materialized-view path AGREE, fixed (r1) directory and single-file arms with a materialized view
4 ⚠️ The test did not prove that ON CLUSTER checks the new privilege AGREE, fixed (r1) CLUSTER-only user is denied
5 ❌ A JSON AST could run a different reset than it displays DISAGREE formatter and interpreter apply the same precedence, so the logged statement is what runs; the JSON dialect is experimental and validates no other parser-impossible combination
6 ❌ A lazily loaded FileLog table (lazy_load_tables = 1, no views) is a TableProxy, so the command said it is not a FileLog table AGREE, fixed (r2) unwrapStorageProxy + a test arm that checks the table is a TableProxy before the reset
7 ⚠️ The randomized query cache could serve stale results to the test's repeated reads DISAGREE only the stress job enables use_query_cache, and it does not compare reference output; no stateless flavor enables it
8 💡 TO END on an incomplete last line starts in the middle of it noted documented: TO END is the current end of the file
9 💡 The command waits for a running background round (up to about 60 s under continuous ingestion) noted documented
10 💡 ON CLUSTER is accepted before or right after the table, not after FILE noted same shape as SYSTEM FLUSH OBJECT STORAGE QUEUE ... PATH
11 ⚠️ The materialized-view arms wait on the shared BackgroundSchedulePool and can time out under parallel load AGREE, fixed (r3) no-parallel with the rationale of the other FileLog view tests (02968, 04242, ...); an untagged one timed out in a flaky check; the wait is now bounded by time
12 ⚠️ The test never ran an authorized ON CLUSTER reset, so worker-side execution and its FILE/OFFSET modifiers were unproven AGREE, fixed (r4) a cluster user with the table grant resets one file from an offset ON CLUSTER; the exact rows are asserted

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-10:20261002-133100

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: 05316_file_log_system_reset fails on master on every run, SYSTEM RESET FILELOG is a SYNTAX_ERROR.
b Root cause explained? A missing command: nothing in StorageFileLog sets a file's read position (in-memory meta plus the meta file), and no SQL reaches one, so re-reading or skipping needed DROP and CREATE.
c Fix matches root cause? Yes: StorageFileLog::resetReadPosition plus the statement and privilege that reach it; no setting, no guard.
d Test intent preserved / new tests added? New shell test: whole table, one file, OFFSET, TO END kept after DETACH/ATTACH, three error classes, the table and ON CLUSTER privilege checks, a successful ON CLUSTER reset with FILE ... OFFSET, formatting, a directory and a single-file table streaming to a materialized view, and a lazily loaded (TableProxy) table. Mutations of the status update, the lower-offset write, the meta write, the size check, both access checks, the wake-up, the schedule, the proxy unwrap and the worker-side execution each turn it red.
e Both directions demonstrated? Master: FAIL (SYNTAX_ERROR). Fix: OK, 50/50 with randomized settings (the test is no-parallel).
f Fix is general across code paths? Background round (waits on file_infos_mutex; a directory table waiting for an event is woken, a single-file table sleeping until its next poll is scheduled), direct SELECT (refused while running_streams > 0), restart (meta written by the command), ON CLUSTER (access check), a lazily loaded table (the TableProxy stand-in is unwrapped before the type check), JSON AST (fields round-trip, table required). No other engine keeps byte offsets into local files.
g Fix generalizes across inputs (params/datatypes/wrappers)? Whole table, FILE alone, OFFSET inside and at the end of the data, TO END, offset beyond the size, unknown file, non-FileLog table; directory, single-file and lazily loaded tables, all tested.
h Backward compatible? (maintainer-approved exception only) Yes: a new statement and a new privilege only; no setting, default or metadata format change. 01271_show_privileges and the integration SHOW GRANTS string are updated.
i Invariants and contracts preserved? file_infos changes only under file_infos_mutex with no direct reader; the meta file is replaced (temporary file + rename) before memory changes, so a failed write changes nothing, and the monotonicity check is skipped only for the reset; the file maps keep their sizes; the single-file form rejects bad input before any change.

Session id: cron:clickhouse-impl-slot-40:20261002-124200

@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d267846]

Summary: ✅


AI Review

Summary

This PR adds SYSTEM RESET FILELOG, wires a dedicated table-level privilege through parsing and ON CLUSTER access checks, persists the new read positions in StorageFileLog, updates the generated docs, and covers the feature with focused stateless tests. After reading the current diff, prior discussion, and the touched FileLog concurrency and persistence paths, I do not see any unresolved correctness, privilege, or concurrency issues in the current code.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit d267846.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 161/186 (86.56%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Oct 2, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). label Oct 2, 2026
Comment thread src/Storages/FileLog/StorageFileLog.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d2678466e with master 37a251ffa (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

17 object files changed (+37.92 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/FileLog/StorageFileLog.cpp.o 622.09 KiB 648.09 KiB +25.99 KiB (+4.18%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

The FileLog reset fields grew sizeof(ASTSystemQuery) from 976 to 1032
bytes, which moved every SYSTEM query AST from jemalloc's 1024-byte size
class to 1280 (Parser memory check: `SYSTEM FLUSH LOGS` +256 bytes).
Placing the `TO END` flag in the padding after the other bool members
brings it to 1024 bytes on x86_64 and aarch64.

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

@alexey-milovidov alexey-milovidov left a comment

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.

Thanks! Good implementation.

@alexey-milovidov alexey-milovidov self-assigned this Oct 3, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 3, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 3, 2026
The merge-queue `Style check` (`storage_casts` leg) rejects a `dynamic_cast`
to a deferrable storage engine on a catalog pointer. The statement names the
table, so `castStorage<StorageFileLog>(..., DeferredTable::Load)` loads a lazy
`StorageTableProxy` exactly like the previous `unwrapStorageProxy` did, and the
lazily loaded table arm of 05316_file_log_system_reset still passes. The
duplicate `StorageProxy.h` include is dropped: master now includes it
unconditionally.

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

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

I fixed the merge-queue Style check failure (storage_casts: the dynamic_cast in resetFileLog) in b9463a2 by switching to castStorage<StorageFileLog>(..., DeferredTable::Load) after merging master, so the PR can go into the merge queue again.

alexey-milovidov and others added 3 commits October 4, 2026 00:26
Write the new meta files of all target files to temporary paths first and
only publish them (rename and update the in-memory offsets) after every
write succeeded. A failed write, e.g. on a full metadata disk, now leaves
the whole table at its old position instead of rewinding a subset of files.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The Build (amd_fuzzers) failure was a linker relocation overflow (R_X86_64_PC32 out of range in clickhouse_fuzzer), unrelated to this PR and fixed on master by #123738. I merged master (d267846) to pull the fix in; the merge was clean and the PR's changed files still compile.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 4, 2026
Merged via the queue into ClickHouse:master with commit 95b3c5c Oct 4, 2026
149 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 4, 2026
Bartok9 pushed a commit to Bartok9/ClickHouse that referenced this pull request Oct 9, 2026
The benchmark looked each row's group up in a constant array,
`groups[number % 4096 + 1]`. About half of its CPU went to that lookup
(`arrayElement` over a constant array copies row by row through a virtual
`insertFrom`), not to the sampling-key code the test measures. On arm some
builds run that loop about twice as slow in every server process: in the
job profiles of the slow runs on ClickHouse#98708, ClickHouse#116376, ClickHouse#117754, ClickHouse#123545 and
ClickHouse#123188 only that frame grew (x1.4 to x2.2) while every other frame stayed
flat, so the query moved 20-27% and the confirmation restart reproduced it.

The per-query tags collector numbers groups 0, 1, 2, ... with 0 reserved for
the empty tag set (`ContextTimeSeriesTagsCollector.h`), so the 4096 groups
the subquery creates are 1..4096 and the query can pass
`number % length(groups) + 1` directly. `length(groups)` keeps the scalar
subquery referenced: without it the analyzer drops the subquery, no group is
registered and the function throws `Group 1 is out of bounds`.

Checked on x86 with an official master build: the same keys over the 20M
rows (`sum` and `groupBitXor` equal, 0 rows differ), 84 -> 52 ms, and the
per-process medians of 24 processes span 79-91 ms before and 52-53 ms after.

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

can be tested Allows running workflows for external contributors comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

3 participants