Skip to content

Keep the leading separator in _path when the storage prefix is empty - #116252

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-path-virtual-column-empty-namespace
Aug 27, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-path-virtual-column-empty-namespace

Conversation

@groeneai

@groeneai groeneai commented Aug 25, 2026 •

Copy link
Copy Markdown
Collaborator

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 the _path virtual column and the listing prefilters composing a path inconsistently, so WHERE _path = '<path>' could match no rows. Affected object storages with an empty namespace, such as IcebergLocal and HDFS, and keys that keep a leading separator on azureBlobStorage.

Description

Related: #116089

getUniqueStoragePathIdentifier stripped a leading separator unconditionally
before joining under the namespace. The strip is needed only when there is a
prefix to join under, because fs::path("bucket") / "/key" would otherwise
discard the prefix, so it lost information exactly for the empty-namespace
backends, Local and HDFS.

Four sites share that rule. The data lake listing prefilter evaluates a _path
predicate before an object is read, so a column-only fix would have left it
dropping the object (confirmed with such a build). A third site inverts the rule,
mapping a filter's _path back to a storage key, where fs::relative against an
empty prefix yields the empty path and would discard every value this fix makes
absolute. The fourth, the non-glob listing prefilter, joined raw and so diverged
in the opposite direction: with a namespace present, a key keeping a leading
separator lost the prefix, so _path reported cont/blob while the prefilter
saw /blob and filtered out the only file before reading it. Azure reaches it;
S3 rejects such a key in S3::URI::validateKey.

Rule and inverse now live in one place each, joinPathUnderPrefix and
relativizePathUnderPrefix, which also turns
hdfs('.../dir/file*') WHERE _path = '/dir/file1' into the row it should return.
An empty prefix returns the path unchanged rather than adding a separator: a
relative engine argument is legal and is resolved against user_files_path only
at read time, so a separator would invent an unrelated root (test arm pins it).

S3, Azure and Web are byte identical at the first three sites, checked against
both builds. For Local and HDFS the value changes as intended; HDFS expectations
are updated and pass.

Note #90740 rewrites this function and repeats the strip; whichever merges second
should adopt the shared helper.


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

Version info

  • Merged into: 26.9.1.202 (included in 26.9 and later)

For an object storage whose namespace is empty, `_path` came back without its
leading separator: `IcebergLocal('/var/lib/clickhouse/user_files/lakes/ice1/')`
reported `var/lib/.../data-x.parquet`, which is not absolute and names no file.
`_iceberg_metadata_file_path` reported the same file with the separator, so two
columns of one query disagreed, and `WHERE _path = '<the absolute path>'`
matched zero rows.

`getUniqueStoragePathIdentifier` stripped a leading separator unconditionally
before joining the path under the namespace. That strip is needed only when
there is a prefix to join under: `fs::path("bucket") / "/key"` discards the
prefix and yields `/key`, whereas `fs::path("") / "/abs"` preserves the
separator on its own. So the strip lost information exactly for the two
backends whose namespace is empty, Local and HDFS, and nothing put it back.

The same strip-then-join rule was also duplicated in the data lake listing
prefilter, which evaluates a `_path` predicate before an object is read. Fixing
only the column would have left that prefilter comparing against the
separator-less string and dropping the object, so the reported symptom would
have survived. Introduce the rule once as `joinPathUnderPrefix` and have both
sites call it.

A third site turns a `_path` value from a filter back into a storage key, so it
has to invert the same rule; with an empty prefix `fs::relative` of an absolute
path is the empty path, which would have discarded every value the fix makes
absolute. `relativizePathUnderPrefix` is that inverse, and it is what makes the
glob shortcut for `hdfs(...) WHERE _path = '/dir/file'` return the row rather
than nothing.

A path is returned unchanged when the prefix is empty rather than being given a
separator: a relative engine argument is legal, and `LocalObjectStorage`
resolves it against `user_files_path` (or the root under clickhouse-local) only
at read time, so prepending one would invent an unrelated root.

S3, Azure and Web have non-empty prefixes at all three sites and are byte
identical. For Local and HDFS this changes a user visible value, which is the
point of the fix: the HDFS integration expectations are updated accordingly.

Related: ClickHouse#116089
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 findings, both resolved without a code change)

An independent model reviewed this branch cold against the frozen description. It read all seven
changed files but did not execute tests. Both findings are recorded with the measurement that
settles them.

⚠️ test_path_filter_pushdown and 05043 do not assert which iterator ran. Correct as
stated, and I disagree that it makes either check vacuous. Two mutants already measured on this
branch redden exactly those checks:

  • Reverting only the inverse site in StorageObjectStorageSource.cpp makes
    test_path_filter_pushdown fail assert '' == '2\n'. That site is reachable only through the
    KeysIterator branch, so if path extraction had declined to GlobIterator the mutant could not
    have reddened. It did, so extraction does not decline for this fixture.
  • On a partial build with the emitter fixed and the listing prefilter reverted, 05043 arm 3 goes
    10 to 0 while arms 1, 2 and 4 stay green. Arm 3 is the only arm that reaches the prefilter.

The suggested ProfileEvents assertion would not discriminate either: ObjectStorageListedObjects
is incremented at all three candidate sites, and ObjectStorageGlobFilteredObjects reads 0 for
both iterators here because the glob excludes nothing. An exact listing count (1 versus 2) would
discriminate, and is worth adding when this area next gets touched, but it needs query_log
plumbing and covers iterator selection rather than the separator bug this change fixes.

💡 Use the full issue URL on its own visible line. The full URL is already present verbatim in
the leading comment block, which is where the template asks for it, and Related: #116089 in the
description is what renders for a reader. No CI job parses either line.

@clickhouse-gh clickhouse-gh Bot closed this Aug 25, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On an IcebergLocal('<absolute path>/') table, SELECT DISTINCT _path returns a path with no leading separator on every run, _iceberg_metadata_file_path returns the same file with one, and a filter on the absolute path returns 0 rows.
b Root cause explained? Yes. getUniqueStoragePathIdentifier stripped a leading separator unconditionally before joining under the namespace. The strip is only needed when there is a prefix to join under: measured, fs::path("bucket") / "/key" discards the prefix while fs::path("") / "/abs" preserves the separator by itself. So it lost information exactly for the two backends whose namespace is empty, Local and HDFS.
c Fix matches root cause? Yes. The strip becomes conditional on a non-empty prefix, keyed on the prefix rather than the backend type, and the inverse mapping is made conditional the same way. The nearby site that joins with no strip at all was already correct and is left alone.
d Test intent preserved / new tests added? New test 05043_object_storage_path_virtual_column_empty_namespace.sh, four arms: the absolute path, cross-column agreement with _iceberg_metadata_file_path, the listing prefilter, and a relative engine argument staying relative. New HDFS integration test test_path_filter_pushdown covers the glob shortcut. The eight updated HDFS _path literals are the intended behaviour change; reverting one makes that test fail, so they are load-bearing. A user column also named _path in the same file is deliberately unchanged.
e Both directions demonstrated? Yes. On pristine master the stateless test fails 1,1 -> 0,0; with the fix it passes. A build fixing only the emitter reddens the prefilter arm (10 -> 0), proving that arm reaches the second carrier rather than only the column. For the inverse: reverting only the third site makes test_path_filter_pushdown fail '' == '2\n', the exact fs::relative degeneracy, while test_virtual_columns still passes. All builds identity-checked by SELECT lower(buildId()), and each restore re-verified bit-for-bit.
f Fix is general across code paths? Yes, and the earlier closure argument was incomplete. A starts_with("/") grep found the two forward sites but missed the inverse, which expresses the same rule through fs::relative. Searching by rule rather than by idiom gives three sites: two forward (column emitter, data lake prefilter) and one inverse (filter value to storage key). All three now route through the shared pair. The fourth candidate joins with no strip and is already correct.
g Fix generalizes across inputs? Yes. Absolute and relative local paths, empty and non-empty prefixes, both values of include_connection_info, and Local plus HDFS through the same condition. S3, Azure and Web are byte identical across nine _path equality, IN, NOT IN and s3_path_filter_limit shapes; a mutant that makes the inverse unconditional reddens three of those nine, so that comparison is a measurement rather than a blind pass.
h Backward compatible? No setting, default, or serialization format changes, so no SettingsChangesHistory.cpp entry. This does change a user-visible value for Local and HDFS, which is the intent of the fix and is stated in the description: a query filtering on today's separator-less string stops matching.
i Invariants and contracts preserved? Yes. The two helpers are inverses of each other under a given prefix, which is what makes the column and the predicate agree at all three sites. The read_source_index suffix logic is untouched, and both helpers are pure functions with no lifetime implications. Schema and count cache keys shift consistently for writer and reader since both route through the same function, so the cost is one cache miss per table.

Session id: cron:clickhouse-impl-slot-7:20260825-053800

@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [78c2b8f]

Summary: ✅


AI Review

Summary

This PR centralizes _path formatting for object-storage reads and fixes the empty-namespace and non-glob prefilter mismatches around Local, HDFS, and Azure leading-slash keys. One blocker remains: the glob _path pushdown path still assumes that this formatting is invertible under a non-empty namespace, which leaves a reachable wrong-results case for Azure blobs whose stored key begins with /.

Findings

❌ Blockers

  • [src/Storages/ObjectStorage/StorageObjectStorageSource.cpp:408] relativizePathUnderPrefix is used as though it were the inverse of joinPathUnderPrefix, but with a non-empty namespace both "blob" and "/blob" collapse to the same visible _path (cont/blob). In the reachable Azure case, azureBlobStorage(..., '/*') WHERE _path = 'cont/slashed.csv' still gets optimized into an empty KeysIterator, so the query returns 0 rows even though GlobIterator would find the object. Suggested fix: make this optimization conservative for ambiguous _path values under a namespace, for example by falling back to GlobIterator or by validating both candidate keys instead of reconstructing just one with fs::relative.
Final Verdict

❌ Changes required before merge: the touched _path pushdown path still has a definite wrong-results case on Azure glob reads.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.20% 87.20% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 28/28 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Michicosun @hanfei1991, could you review this? getUniqueStoragePathIdentifier stripped a leading separator unconditionally before joining under the namespace, so for the two backends whose namespace is empty, Local and HDFS, _path came back not absolute and a filter on the real path matched nothing. Three sites share that rule, including one that inverts it, where fs::relative against an empty prefix yields the empty path.

@PedroTadim PedroTadim self-assigned this Aug 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 78c2b8f81 with master e0ba6036e (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
Binary Master PR Δ
programs/clickhouse-stripped 709.96 MiB 706.91 MiB -3.04 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

The `_path` virtual column and the non-glob `getPaths()` listing prefilter composed the
same value two different ways. The column joined the object path under the namespace via
`getUniqueStoragePathIdentifier`, stripping a leading separator first; the prefilter joined
it raw with `fs::path(getNamespace()) / key`. `fs::path("cont") / "/blob"` discards the
prefix and yields `/blob`, so for a key that keeps a leading separator the prefilter
evaluated predicates against a different string than the column reported, and a filter on
`_path` dropped the only matching file before it was read.

Azure is the reachable backend: it applies no key validation, so a blob named `/slashed.csv`
reproduces it, while S3 rejects such a key outright in `S3::URI::validateKey`.

Reusing `joinPathUnderPrefix` here makes the prefilter agree with the column for both the
empty-prefix and the namespace-bearing case. Reported by review on ClickHouse#116252; this join is a
fourth carrier of the same defect, invisible to an idiom search because it contains neither
`starts_with("/")` nor `fs::relative`.

The new test arm compares `_path` against itself across the two spellings, so it pins them
agreeing rather than pinning either literal.
const auto relative_path = fs::relative(path, configuration->getNamespace()).string();
/// `path` is a `_path` column value, so it needs that column's formatter
/// inverted rather than a plain relative().
const auto relative_path = relativizePathUnderPrefix(configuration->getNamespace(), path);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

joinPathUnderPrefix is not actually invertible once configuration->getNamespace() is non-empty: both "blob" and "/blob" materialize as the same visible _path ("cont/blob"). This branch assumes a true inverse exists and reconstructs only "blob" via fs::relative, so the _path pushdown is still wrong for the reachable Azure case where the stored key keeps its leading slash (AzureStorageParsedArguments preserves "/..." in setPaths).

With azureBlobStorage(..., '/*') WHERE _path = 'cont/slashed.csv', extractPathValuesFromFilter yields "cont/slashed.csv", relativizePathUnderPrefix turns it into "slashed.csv", the glob validator rejects it against /*, and KeysIterator returns no rows even though GlobIterator would find the blob. This optimization needs to stay conservative for ambiguous _path values under a non-empty namespace, e.g. by falling back to GlobIterator or by validating both "blob" and "/blob" candidates instead of assuming _path -> key is one-to-one.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed on the mechanism, and this is the residual I flagged in my previous reply rather than a
new one: under a non-empty namespace the _path -> key map is not injective, so relativizing a
_path value back to a key cannot recover a leading separator, and a /-requiring pattern then
rejects the reconstruction. Not fixing it here, for a reason I can measure rather than assert.

The line you cite is unchanged in behaviour for a non-empty namespace. relativizePathUnderPrefix
returns path when the prefix is empty and otherwise evaluates fs::relative(path, prefix), which
is exactly what master already had at that site. getNamespace() is non-empty throughout your
scenario, so the early return cannot fire and the expression is master's.

Measured on Azurite, container holding both plain.csv and a blob named /slashed.csv, this head
against a pristine master build:

arm this PR pristine master
glob /*, WHERE _path = '<cont>/slashed.csv', extraction on 0 0
same with s3_path_filter_limit = 0, so GlobIterator (ground truth) 1 1
control: glob *, WHERE _path = '<cont>/plain.csv', extraction on 1 1

The 0 against 1 confirms the pushdown drops a row the glob iterator finds. Identical in both
builds, so this change neither introduces nor widens it, and the control moving to 1 shows the
harness discriminates.

One correction to the reachability. I checked fillBlobsFromURLCommon and it does keep the
separator, blob_path = container_blob_path.substr(pos_blob_path) taken from the slash inclusive,
so a URL-form argument always yields a key starting /. I expected that to make the defect
reachable for ordinary blob names, which would be much broader than what you described. It does
not: asking which blob the pattern actually lists returns only <cont>/slashed.csv, never
<cont>/plain.csv. A /-requiring pattern matches only a key that really carries the separator,
which is why the control arm is unaffected.

On the two remedies. Every _path value is ambiguous under a non-empty namespace, since that is
the non-injectivity itself, so falling back to GlobIterator on ambiguity is not a narrow guard,
it retires the extraction for all namespace-bearing backends. Validating both candidates doubles
the candidate set of a validator whose stated job is to prevent scanning unallowed data, so it is
an access-control widening rather than a formatting fix. Both are decisions about the pushdown
optimization's contract, not about the path formatter this PR corrects, and neither is verifiable
as an increment on this branch. I would rather leave the optimization's owner a measured
description than pick one of those directions here.

Leaving the thread for a human at this point rather than continuing to trade rounds on it.

@PedroTadim

Copy link
Copy Markdown
Member

@scanhex12 @SmitaRKulkarni easy to review

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 27, 2026
@PedroTadim

Copy link
Copy Markdown
Member

This PR is good to merge

Merged via the queue into ClickHouse:master with commit 4606a6e Aug 27, 2026
178 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 27, 2026
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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

3 participants