Skip to content

Fix FileLog reading a file twice when it has a hard link or a symbolic link in the watched directory - #123673

Closed
groeneai wants to merge 25 commits into
ClickHouse:masterfrom
groeneai:filelog-hard-link-read-once
Closed

groeneai wants to merge 25 commits into
ClickHouse:masterfrom
groeneai:filelog-hard-link-read-once

Conversation

@groeneai

@groeneai groeneai commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #123590 (comment)
Related: #123368

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):

Fixed FileLog delivering a file's rows again when a hard link or a symbolic link to that file appears in the watched directory. Such a file is now read once, under one of its names, and when that name is removed it is read on from the same position under another of its names that the table has already seen. On macOS, the file can still be read again from the beginning when one of its hard links is removed or replaced.

Description

On 26.8.10.6, a hard link to a file that a FileLog directory table already reads (ln app.log alias.log) makes the next read deliver consumed rows again: alias.log 1, 2, 3, app.log 1, 2, 3 instead of app.log 3. A symbolic link does the same. Debug builds abort (master stress test STID 2508-417e).

Cause: StorageFileLog assumed one name per inode.

Change: a file is read under one name; its other names are recorded, not read, and writes through them are read under the read name. Skipping the second name (master since #123590) fails: after ln app.log new.log; rm app.log master stops reading the file. When the read name goes away, another recorded name reads on from the same offset, hard links first, even one the glob excludes. A hard link counts until removed or renamed over, so batching does not matter. A file renamed in over a name drops that name's stale meta file (master: LOGICAL_ERROR on the next read). A symbolic link counts while stat shows it points to the file, unless it resolves through a name in the directory that the table reads or records, which it follows. CREATE and ATTACH do the same.

Limit: a name already gone when its event is processed is not recorded, so rm a; ln b c; rm b; ln c d; rm c in one batch reads d from the start. These are an inode reuse's events, where keeping the offset loses rows. On macOS the snapshot watcher reports the other names as new when one name is removed, so the file is read again there.

Validation: the new test aborts on master and passes 50/50; each rule has an arm failing without it.

Upgrade: of the meta files 26.8 left per name, startup keeps the one with the larger offset.

🤖 Generated with Claude Code


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

groeneai and others added 9 commits October 2, 2026 23:26
A hard link or a symbolic link to a file that a FileLog table already reads
gave the inode a second tracked name. Both names were then read from the
same shared offset (reset to 0 on DW_ITEM_ADDED), so consumed rows were
delivered again, and debug builds aborted on the file_names/meta_by_inode
chasserts. With such a link present at CREATE, loadFiles renamed a meta
file that did not exist yet and CREATE failed with ENOENT.

The inode is now read under one name. Its other names are kept in
FileInfos::inode_by_other_name and are not read. When the read name loses
the inode (removed, replaced, or becoming an other name itself), the file
is handed over to its smallest other name that still stats to the inode,
at the same offset. loadFiles groups listed names by inode and reads each
inode under the name stored in its meta, else the smallest name. A write
through an other name marks the read name updated.

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

The other names of a file read under another name were checked with stat
when the table processed the events, which is after the fact. In
`rm app.log; ln alias.log new.log; rm alias.log`, alias.log is already
gone when ADDED new.log is processed, although its own REMOVED event comes
later, so the file was taken for a new one and read again from the start.
The watcher can also deliver such a sequence in two batches, so the answer
must not depend on where a batch ends.

A hard link is now a name of the file from the event that records it until
its own removal event is processed, with no stat: a drained batch is a
prefix of the kernel's event order, and an inode can only be reused once
all of its names were removed. A symbolic link can stop pointing to the
file with no event, so it is still checked with stat. When the read name
loses the file, the file goes to an other name that still has it, a hard
link before a symbolic link, then the smallest name. A hard link whose
removal is still pending takes the file over without being read, so a read
does not fail on it, and its removal event hands the file on.

loadFiles and the handover prefer a hard link as the read name. A file read
under a symbolic link moves to a new name of it: the link becomes an other
name if it still points to the file, else it is dropped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…link in the directory

A symbolic link that took the read name's place (renamed over it, or added
right after the read name's removal in the same batch) became the read name
even when hard links of the file were recorded. Once its target was removed
the link dangled, and a write through another hard link then failed every
read of the table with CANNOT_READ_ALL_DATA. addOtherName now records such a
link as an other name whenever a present hard link of the file is recorded;
the read name is handed to that hard link at the same position.

The engine documentation promised that a file keeps its position while it
has any name in the directory. A name whose addition is processed after it
is already gone is never recorded, and that sequence has the same events as
an inode reuse, so the sentence now states what holds: the file is read on
under a name the table has already seen.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ed file's offset

A symbolic link to the read name (`s.log -> a.log`) was checked with `stat`
only, so after `a.log` was removed and re-created with the same inode (inode
reuse, or relinking a pin held outside the directory) the link still counted
as a present other name. The re-created file then kept the old offset, both
when the events came in one batch and when the removal was handed over first,
and its head was never read.

A symbolic link whose target is directly in the watched directory never needs
to carry the file: its target is a name the table tracks with its own events.
`findOtherName` now drops such a link, like a gone one. A link that resolves
outside the directory is still checked with `stat`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… directory follow that name

`resolvesIntoDirectory` looked only at the final target, so in a chain
`s.log -> a.log -> ../outside.log` the link `s.log` stayed a stat-checked
carrier although it reaches the file only through the watched name `a.log`.
Removing `a.log`, rewriting the outside file and linking `a.log` again kept
the old offset, and the head of the new content was never read. The same
chain made the link the read name at runtime (the swap path) and at
`CREATE`/`ATTACH` (the `loadFiles` ranking), with the same outcome.

`resolvesIntoDirectory` now walks the link hop by hop and is true as soon as
a hop's target is directly in the directory. Such a link is only an other
name (`addOtherName`), never a carrier (`findOtherName`), and ranks after a
link whose whole chain stays outside (`loadFiles`). The walk uses
`FS::isSymlinkNoThrow` and `FS::readSymlink` (the style check forbids the
`std::filesystem` ones) and still never throws: a `filesystem_error` from
`readSymlink` returns `false`, so the `stat` check decides, as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`releaseInode` changed `meta_by_inode`, `other_names` and `context_by_name`
before its fallible disk call (`moveMetaFile` is a `rename`, the no-other
branch a `removeFileIfExists`), so a failed meta move left a meta with no
read name. The cleanup loop made it worse: it had already swapped
`file_names` out and erased the removed name's context, so a throw dropped
every later name from `file_names`. Those files stayed in the other maps and
were not read again until `ATTACH`; a debug build aborted on the next 1:1
`chassert`. The symbolic-link swap and the ADDED "kept another name" path
had the same order: re-point the maps, then move the meta file.

Now every site this change adds moves or removes the meta file before the
maps change, so a throw leaves them as they were:
- `releaseInode` moves or removes the meta file first.
- The new `untrackReadName` (releasing a name before it becomes another
  name) is shared by the swap, the `addOtherName` tail and the kept path.
- The swap and kept paths move the meta file before re-pointing the maps.
- On a throw the cleanup loop keeps the failing name, which is still
  `REMOVED`, and every name after it in `file_names`, so the next call
  retries.

Checked by local fault injection with the table's metadata directory made
read-only (a non-root server): a failed handover rename, and a failed meta
removal before two more files. The previous head aborts on the next read;
now the read fails with the disk error, and after the directory is writable
again the next read returns the appended rows.

The test sets `poll_timeout_ms = 100`: a direct SELECT waits the poll
timeout per read file, one stream after another under a low random
`max_threads`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…cked when its meta file move fails

The directory watcher keeps one modification event per name and batch.
When a name that was another name of file A is removed and linked to file
B in the same batch ([MODIFIED x, REMOVED x, ADDED x, MODIFIED x]), the
second MODIFIED is dropped. The ADDED recorded `x` as another name of B but
did not mark B's read name, so a write through `x` was not read until B's
next event. Recording another name now marks the file's read name updated,
through the `markReadNameUpdated` helper that the MODIFIED mapping uses too.

At the symbolic-link swap and the ADDED "kept another name" path, the new
name was untracked first and recorded only after `moveMetaFile` succeeded,
so a failed move left it in no map and later writes through it were ignored
until another structural event or `ATTACH`. The new name is now another
name of the file until its meta file has moved: a failed move leaves it a
carrier, the kept path retries the handover in the cleanup loop, and in
the swap writes through it reach the symbolic-link read name.

The new test arm first lets the watcher record the hard link (a read of
the row written through it), so the re-link batch has the shape above.
Checked by local fault injection with the table's metadata directory made
read-only: at the swap and at the kept path the previous head reads
nothing after the directory is writable again, and now the appended row
is read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Recording another name of a read file marks the file's read name updated
(the watcher keeps one modification event per name and batch), and so
does a write through another name. Neither checked that the read name
still had the file. In `ln new.log next.log; rm new.log` and in
`ln next.log keep.log; mv tmp next.log` the new name's event comes before
the read name's removal or replacement in kernel order, so when a watcher
batch ends after it, the read name is marked although it is already gone
or holds another file: the next read failed with `CANNOT_READ_ALL_DATA`,
or read the replacement file with the old file's meta, after which the
old file's consumed rows were delivered again under the surviving name.

A read name that no longer has the file is now not marked. A hard link
has a pending removal or rename event that hands the file over to
another name, which reads it on from the offset. A symbolic link gets no
such event when its target leaves, so it is set removed, as recording
another name already does for a gone symbolic link, and the cleanup loop
hands the file over. This also covers a symbolic read name kept after a
failed meta file move while a hard link exists: once its target moved
away, every write through the hard link failed every read until `ATTACH`.

Checked with a throwaway build whose watcher sleeps after each read()
buffer (the trace log shows the first read's batch holds only the new
name's event): the previous head fails the first read or re-delivers
consumed rows, and now the first read returns nothing and the next ones
return each new row once. The symbolic-link case was checked by local
fault injection with the table's metadata directory made read-only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove five comment lines in StorageFileLog.cpp that narrate the new code (two duplicated untrackReadName notes, the findOtherName preference already given by the tuple order, an ordering note, and the MODIFIED mapping note).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR labels Oct 3, 2026
@groeneai

groeneai commented Oct 3, 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; six rounds, 14 findings) plus my own review (seven rounds, 3 majors, 9 nits).

Bounce cap reached: published as-is. The last fix round (row 16) was checked by my own review and by watcher-delay and fault-injection probes, not by another second-model run. Residual findings are the noted and DISAGREE rows below.

# Sev Finding Verdict Evidence / action
1 ⚠️ A symbolic link moved over the read name (or added right after its removal) became the read name while a hard link of the file was in the directory; once the link dangled, a write through another hard link failed every read of the table AGREE, fixed @ 18daf6e a symbolic link is recorded as an other name while a present hard link exists; test arm
2 ❌ A symbolic link to the read name kept the file through a same-name delete+recreate that reused the inode, so the new file was read from the old offset and its first rows were skipped AGREE, fixed @ 584ba0b a symbolic link that resolves into the directory no longer carries the file; test arm with the 04342 relink
3 ❌ The same through a chain (s.log -> a.log -> ../outside.log): only the final target was checked AGREE, fixed @ f7c54ef a link that resolves through any name in the directory follows that name: it never carries the file and is not the read name; test arms at runtime and at ATTACH
4 ❌ A metadata-file rename that fails during a handover (e.g. an unwritable metadata directory) left the name maps inconsistent, and the cleanup loop dropped every file listed after it AGREE, fixed @ 33d43b5 the meta file is moved before the maps change, and a failed removal stays tracked and is retried on the next read; checked by fault injection
5 ❌ A name already gone when its creation is processed is never seen, so rm a; ln b c; rm b; ln c d; rm c in one batch re-reads d AGREE (contract) inotify events carry no inode: an inode-reuse sequence gives the same events, and keeping the offset there would skip rows. The documented guarantee is narrowed to names the table has already seen
6 ❌ On macOS a single directory scan reports removals before additions, so two names collapsing into a new one re-read the file AGREE (contract) covered by the narrowed docs sentence; reordering the macOS watcher would drop a same-name delete+recreate
7 ❌ A file moved in from outside the directory keeps a matching inode's offset DISAGREE unchanged master behavior of DW_ITEM_MOVED_TO; #123593 reports an unpaired IN_MOVED_TO as an added file, which this PR then reads from the start
8 ❌ After the file is handed to a symbolic link to a file outside the directory, later appends are not seen DISAGREE a write through such a link gives no event in the watched directory on master either (the reviewer's own control run, with that link as the only name, shows the same); the handover reads the rows pending at the removal
9 ❌ A link chain through a directory the server cannot search (permission error) still counts as a carrier, so a same-inode re-creation of its watched target keeps the old offset DISAGREE a link the server cannot inspect is kept on purpose: failing closed cannot tell this chain from a plain link to a file in a locked outside directory, where dropping it would stop reading the file with no event to recover it. Today such a read fails loudly until the permission returns, then resumes at the offset
10 💡 Names are grouped by inode number only AGREE, noted same keying as meta_by_inode on master
11 💡 With two watcher-batch splits, a write through a removed name can fail one read before its removal event arrives AGREE, noted the next read heals it; master fails one read the same way for a file written and removed across a batch boundary
12 💡 The test got slow when one SELECT polled many files one after another AGREE, fixed @ 33d43b5 poll_timeout_ms = 100 on the test tables
13 ❌ The watcher keeps one modification event per name per batch, so a write through a name that was re-linked to another file in the same batch was not seen, and that file's rows waited for its next event AGREE, fixed @ 5c9c7cd a name recorded as another name of a file marks the file's read name for reading; test arm
14 ❌ When moving the meta file failed while a new name took the file over, the new name was tracked nowhere, so writes through it were not seen after the disk recovered AGREE, fixed @ 5c9c7cd the new name stays another name of the file until its meta file has moved, so the handover is retried; checked by fault injection.
15 💡 After a partial disk failure in the cleanup loop, a removed rename source listed after the failing name is kept, which a debug build's size check rejects on the next read AGREE, noted release builds recover on the next read; master broke the same check on every failed cleanup
16 ❌ A new name of a file marked the file's read name for reading even when that name had already been removed or replaced on disk with its event not yet processed; one watcher-batch split then failed a read, or read the replacement file at the old file's offset, so the old file's rows were delivered again AGREE, fixed @ a20e90b a read name that no longer has the file is not marked: its pending event hands the file over (a symbolic link, which gets no such event, is handed over at once); checked with a watcher-delay probe and fault injection, both directions
17 ⚠️ The re-link test arm could pass without the fix if the watcher delivered its two writes in different batches DISAGREE all four operations finish before the first read starts, and the watcher reads queued events at once; the arm fails 3/3 on the previous head and 3/3 with the mark deleted. The risk is a false pass under a watcher stall, never a false failure

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

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On master, ln app.log alias.log plus an append aborts every time on file_names.size() == meta_by_inode.size(); the new test aborts in its first arm.
b Root cause explained? StorageFileLog treats a name and an inode as one-to-one. A second name of a read inode reset the shared offset (added) or moved it (renamed) and left the old name tracked, so both names were read.
c Fix matches root cause? Yes. The file model records other names of a read file, and every entry path (added, renamed, CREATE/ATTACH) and every way a read name loses its file goes through one set of helpers.
d Test intent preserved / new tests added? New test 05320_file_log_hard_links (hard links, symbolic links, CREATE, ATTACH). Each rule has an arm that fails when the rule is removed.
e Both directions demonstrated? Master: abort in the first arm. Fix: 50/50 with randomized settings; all FileLog tests 5x in parallel.
f Fix is general across code paths? Added, renamed in, modified through another name, removed, CREATE/ATTACH. A single-file table has one name and is unaffected.
g Fix generalizes across inputs (params/datatypes/wrappers)? Hard and symbolic links (inside and outside the directory, dangling, chains, made while detached), link and unlink, re-linking a name to another file, a read name replaced by another file, a same-inode delete and re-create, and split watcher batches (checked with a throwaway delayed-watcher build). Data types do not apply.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or metadata format change.
i Invariants and contracts preserved? The one-to-one invariant of file_names, contexts and metas holds on every path (the debug assertions pass in all runs); one meta file per read name. A failed disk call leaves the maps consistent and the next read retries (checked by fault injection with a read-only metadata directory).

Session id: cron:clickhouse-impl-slot-4:20261003-090026

@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d569b02]

Summary: ❌

job_name test_name status info comment
Stress test (amd_msan) FAIL
Logical error: Cannot write to canceled buffer (STID: 4158-2b4c) FAIL cidb

AI Review

Summary

The PR fixes duplicate delivery for FileLog aliases and preserves offsets during handover, with a documented macOS limitation. At head d569b0232c8c, the previous review findings are addressed, including invalidating overwritten aliases before skipping non-final events. No new actionable findings remain. The full 05320_file_log_hard_links regression passed locally with the PR-head binary and exactly matched its reference output.

Final Verdict

✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 3, 2026
Comment thread src/Storages/FileLog/StorageFileLog.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). label Oct 3, 2026
…inode

Releases before this change wrote a meta file under every name of a file
that had a hard link or a symbolic link in the watched directory: 26.8.10.6
leaves `alias.log` at offset 6 and `app.log` at offset 4 for one inode.
`deserialize` kept whichever it listed first and left the other on disk, so
an upgraded table could re-deliver consumed rows on the first ATTACH, and the
surviving file could win again on a later one: after `mv alias.log b.log`
the next ATTACH re-delivered `app.log 3, 4, 5` (measured on xfs).

Keep the meta with the larger offset, which is how far the file was read,
and remove the others.

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

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d569b0232 with master bee6deac1 (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

7 object files changed (+67.76 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/FileLog/StorageFileLog.cpp.o 750.53 KiB 818.28 KiB +67.75 KiB (+9.03%)

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

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

Job report

The test checks the order-dependent handover between the names of one
file, which needs the directory events in the order they happened. The
macOS watcher builds its events from a diff of two directory snapshots:
it emits every removal before every addition in a pass, and a name whose
watch saw a delete is reported as removed and added again. In the
`Fast test (arm_darwin)` run, `rm a.log` with a hard link `b.log` in the
directory re-read `b.log` from the start (`b.log 1, 2, 3` instead of
`b.log 3`), and the other handover arms re-read the same way. The first
arms (a hard link is not read, a write through it is read under the read
name) pass there.

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

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2ad8d29

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (amd_fuzzers) / Build ClickHouse not from this PR: the same job is red on master and on 116 PRs in 24h; the clickhouse_fuzzer link outgrows the 2 GiB reach of the small code model #122521 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 04825_quantile_deterministic_alter_add_modify_column not from this PR: the -Merge state crosses the replicas at version 0 and loses the reservoir's skip degree (506014 instead of 492708); 16 PRs in 48h #123070 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 04896_orfill_merge_group_by_overflow_any not from this PR: each parallel replica applies max_rows_to_group_by to its own hash table, so an overflow arm counts too many rows; 18 PRs in 48h #123679 (mine, merged after this run was built; the next master merge picks it up)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05237_time_series_old_metric_family_name_inner_column not from this PR: a replica resolves the unqualified timeSeriesMetricFamilies(ts_v5) argument in default (UNKNOWN_TABLE); 10 PRs in 48h #118518 (external, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05257_sql_security_view_sealed not from this PR: a replica cannot run the SQL SECURITY DEFINER view's read as the definer, so the row policy check fails with ACCESS_DENIED; 58 PRs in 48h #123729 (mine, open)
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05237_with_expression_alias_scope_descendant deterministic under a Replicated database: the replicated CREATE VIEW qualifies a nested WITH alias with the database, so the view reads the same-named table; 124 PRs in 48h a fix task is created (fix in progress, fixing-PR link to follow here)
Mergeable Check, PR rollups, red only because of the rows above #122521, #123070, #123679, #118518, #123729 and the fix task above

None of these touches FileLog, and 05320_file_log_hard_links passed. All 157 checks completed; CIDB has no other FAIL or ERROR on this head.

Session id: cron:our-pr-ci-monitor:20261003-200032

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 05237_with_expression_alias_scope_descendant (DBReplicated): #123774

@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

This also fixes a master abort: Stress test (arm_asan_ubsan) on fb091ad hit file_infos.file_names.size() == file_infos.meta_by_inode.size() (STID 2508-417e) in updateFileInfos.

The table was an AST fuzzer copy of the 05318_file_log_one_bad_file table, created while the symbolic link broken.jsonl still pointed to its target. Before its first read, the target was deleted and created again, and bad.jsonl, moved into the directory, got the old target's inode number. On master that gives one inode two read names. With this PR, addOtherName drops a symbolic read name that no longer has the inode, so bad.jsonl is read as a new file. The 05320 case "a symbolic link that no longer points to the file does not keep it either when it is the read name" is the same state with a dangling link.

groeneai and others added 2 commits October 6, 2026 05:40
…ead-once

Conflicts with ClickHouse#123590 (FileLog path globs) in StorageFileLog.cpp, resolved by hand:

- loadFiles: one ranking for every candidate name of a file (matching names and
  the rotated non-matching names whose inode has a stored meta). A hard link comes
  before a symbolic link, then the stored read name, then a matching name, then the
  smallest; the other candidates become other names of the file.
- DW_ITEM_ADDED / DW_ITEM_MOVED_TO: isReadUnderOtherName is replaced by
  addOtherName, which records a new name of a read file whether or not it matches
  the glob, so removing the read name hands the file over instead of dropping it.
  The glob filter applies to a file that is new to the table.
- Docs: the several-names sentence keeps this PR's wording.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
After the merge with the glob support, a new name of a read file is
recorded as another name whether or not it matches the glob, so removing
the read name hands the file to that name at its offset. Before, the
glob filter ran first, the name was dropped, and the file stopped being
read once its read name was removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/FileLog/StorageFileLog.cpp Resolved
The macOS directory watcher diffs two directory snapshots and reports
every name of an unlinked inode as removed, so when one hard link of a
file is removed the other names are reported as removed and added again,
and the file is read from the beginning. This is why 05320 is
`no-darwin`; the engine documentation now says so.

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

Copy link
Copy Markdown
Member

@groeneai, it's merged. Update the branch.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master (34e2636) into the branch as e310718, which brings in #124289. The merge had no conflicts, and 05320_file_log_hard_links passes 20/20 locally with randomized settings on the merged head.

Comment thread src/Storages/FileLog/StorageFileLog.cpp Resolved
…ectory

With a glob, a matching symbolic link whose target in the directory is a
name the glob excludes is read under the link, as on master: the excluded
name's events are not applied, so the link does not follow that name.
The sentence said it always does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/FileLog/StorageFileLog.cpp Resolved
With `FileLog('*.log')` and `alias.log -> hidden.txt` in the directory, the
live table reads the file under `alias.log`, because the glob excludes
`hidden.txt`. On `DETACH`/`ATTACH`, `loadFiles` found `hidden.txt` through
`rotated_files` (its inode has a stored meta) and ranked the hard link over
the stored symbolic link name, so the meta moved to `hidden.txt` and later
rows were reported with `_filename = hidden.txt`. Master keeps `alias.log`.

Now a name the glob excludes does not outrank the name the file was read
under while that name is found; it is still recorded as another name, so a
write through it is read under the read name, and it still takes over when
the read name is gone (rotation through a hard link across a restart).

The test step fails on the previous head with `hidden.txt 3` instead of
`alias.log 3`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/FileLog/StorageFileLog.cpp Resolved
Comment thread src/Storages/FileLog/StorageFileLog.cpp Resolved
…nk to an untracked one

With a glob, `loadFiles` took a name the glob excludes only when its inode
already had stored meta. So on a fresh CREATE over `app.log` plus a hard link
`app.log.1`, only `app.log` was recorded, and after `rm app.log` the file was
dropped and rows appended to `app.log.1` were never read, although the same
link made after CREATE reads on. Now an excluded name is also recorded when it
shares the inode of a matching name in the same scan. It is ranked after the
matching names unless the name the file was read under is gone, so CREATE
keeps reading a symbolic link to an excluded name under the link, as the
runtime path does.

`resolvesIntoDirectory` vetoed a symbolic link whose in-directory target the
glob excludes, although that target has no events the table handles. With
`hidden.txt`, a hard link `app.log` and `alias.log -> hidden.txt`, removing
the read name dropped the file and a later reload delivered its first rows
again. The veto now applies only to a target the glob does not exclude or the
table records, as the docs say.

Measured against the previous head (761fe560) in .scratch/m15: both cases
lost all appended rows there, and the second re-delivered row 1 after
DETACH/ATTACH; with this change every row is read once and on time.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/FileLog/StorageFileLog.cpp Resolved
A symbolic link follows an in-directory name the glob excludes when
the table already records that name, for example a hard link of a
matching file: `resolvesIntoDirectory` checks the recorded names as
well as the glob. The `05320_file_log_hard_links` step d6 shows it
(`alias.log -> hidden.txt`, with `hidden.txt` a hard link of `b.log`,
reads on under `hidden.txt` after `rm b.log`), so the exception in the
docs holds only for a name the table has not seen.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/FileLog/StorageFileLog.cpp Resolved
A rename over a name emits no removal event for what it replaces, and a
rename from outside the directory is reported as DW_ITEM_ADDED. Both
appearance branches dropped a recorded hard link only after
`is_regular_file` succeeded, and DW_ITEM_MOVED_TO also kept the read name,
so a dangling symbolic link renamed over either one left it recorded:
- over a hard link: removing the read name then handed the file to that
  stale alias as NO_CHANGE, waiting for a removal event that never comes,
  and appends through a name linked back later were not read until the
  table was reloaded;
- over the read name, from inside the directory: writes through a
  surviving hard link were not read until the dangling link was removed.

Drop the alias in both non-regular branches, and mark the read name
removed in DW_ITEM_MOVED_TO as DW_ITEM_ADDED already does. 05320 gains a
step that renames dangling symbolic links over two hard links, one from
outside the directory (ADDED) and one from inside it (MOVED_TO), removes
the read name and links the file back, and a step that renames one over
the read name. Without any one of the three changes a step fails.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/FileLog/StorageFileLog.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5917576

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_asan_ubsan, azure, sequential, 1/2) / 05239_workload_drop_memory_reservation_in_use flaky, not from this PR (it changes only FileLog): KILL QUERY ... SYNC got NOTHING_TO_KILL because DROP WORKLOAD had already failed the running query; 1 of 3 reruns failed #127158 (mine, open)
PR rollup, red only because of the row above #127158 (mine, open)

All 175 check runs completed and CH Inc sync is green. CIDB has no other FAIL or ERROR on this head; the FileLog tests, including 05320_file_log_hard_links, passed.

Session id: cron:our-pr-ci-monitor:20261021-193005

alexey-milovidov and others added 3 commits October 28, 2026 21:53
…der another name

When a symbolic link read name that failed to open leads to another file on
the retry, `openFilesAndSetPos` replaced its inode and metadata
unconditionally. If that file was already read under another name, both
names shared one `FileMeta`: its rows were read again under the link, and
removing the link dropped the other name's metadata, so every later read
failed with `The key ... doesn't exist`.

Now such a link keeps waiting like one that leads to no file.

Addresses review: ClickHouse#123673 (comment)

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

Copy link
Copy Markdown
Member

🕵 Merged master (b1eff66) as 1c1c986. The only CI failure, 05397_clickhouse_local_locked_path_untouched in Fast test (arm_darwin), has nothing to do with this PR. Master already fixes it in 59f220c ("Skip 05397_clickhouse_local_locked_path_untouched on macOS"), and the merge brings that in. The merge was clean, and StorageFileLog.cpp still compiles.

Comment thread src/Storages/FileLog/StorageFileLog.cpp Resolved
Only the last add, removal or rename of a name in one watcher batch is applied
to the file found there now, and the earlier ones were skipped entirely. So when
a name was replaced twice in one batch, the first replacement did not take the
name from the file it had: a replaced hard link still counted as a name of the
file, and a replaced read name still looked like it held the file. A file whose
last name in the directory was then removed, and which was linked back from
outside, kept its old offset instead of being read from the start, so the rows
written before it was linked back were lost.

Now every add and rename into the directory drops what the name had (its other
name record, and the read name), also when it is not the last event of the name.

A file renamed into the directory over a read name whose file had been re-keyed
to a new name then reaches the branch for an untracked rename source, which kept
the stale meta file under the name, and the next read failed with "Last stored
last_written_position in meta file ... is bigger than current last_written_pos".
Like an added file, such a file is read from offset 0, so its stale meta file is
removed too. The same LOGICAL_ERROR is reachable on master without hard links in
the directory: `rm a.log; ln ../held c.log; mv x.tmp a.log` in one batch, with
`../held` a hard link of `a.log`.

Addresses review: ClickHouse#123673 (comment)

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d569b02

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_msan) / Logical error: Cannot write to canceled buffer (STID: 4158-2b4c) not from this PR (it changes only FileLog): the client embedded in the server writes INSERT progress into its canceled terminal buffer (ProgressIndication::writeProgress from ClientBase::onProgress in receiveEndOfQueryForInsert, under ClientEmbedded::run); seen on 11 other PRs and master since 2026-10-27 #127834 (external, open)
Mergeable Check, PR rollups, red only because of the row above #127834 (external, open)

All 179 check runs completed and CH Inc sync is green. The per-job reports show no other failed test on this head; every FileLog test, including 05320_file_log_hard_links, passed.

Session id: cron:our-pr-ci-monitor:20261030-063003

@antaljanosbenjamin

Copy link
Copy Markdown
Member

Do we really need this? It seems like a very niche problem and nobody really complained about this apart from AI.

@groeneai

Copy link
Copy Markdown
Collaborator Author

No user has reported it. It came from a bot finding on my earlier FileLog PR #123590.

I re-checked on today's master: the case in the title (a hard link or a symbolic link to a file that is being read) is already handled there since #123590, also in 26.10. What still goes wrong on master is link-then-unlink, ln app.log new.log; rm app.log: the table stops reading the file, or reads it again from the start when both events come in one batch.

The stress test aborts on file_names.size() == meta_by_inode.size() (13 runs from 2026-10-03 to 2026-10-08, 1 of them on master) stopped after #122461, with none since.

So what is left is a niche case, for +377/-99 lines in StorageFileLog and a 393-line test. I'm fine with closing it; if you agree, I'll close it.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 6, 2026
A name that leads, with no directory event, to a file whose offset is kept
for another name was skipped and never visited again. When that other name
then moved on to a new file, as with symlink targets rotated by logrotate,
no name read the file until the table was attached again (master reads it).
The open now marks such a name to be retried, and so does a reset of all
names that skips it.

The rotated file's old offset is still not passed to the new name; that is
the releaseInode follow-up agreed with ClickHouse#123673.

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-review-bot PR origin: review-bot finding on a groeneai PR pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants