Skip to content

[fix](fe) Resolve column names by ROOT lower case and read non-ASCII file columns - #71211

Open
morningman wants to merge 3 commits into
apache:masterfrom
morningman:b2m-t38i-column-name-case
Open

morningman wants to merge 3 commits into
apache:masterfrom
morningman:b2m-t38i-column-name-case

Conversation

@morningman

@morningman morningman commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Background

Doris resolves column names regardless of case: a table looks a name up in Table.nameToColumn, a map ordered by String.CASE_INSENSITIVE_ORDER, and Nereids binds a name to every slot equal to it ignoring case. A file table function (s3(), hdfs(), file()) takes its schema from a file: for every format but JSON it lower-cases each column name and refuses two names that lower-case alike, and BE then finds each column in the file by its name with ASCII letters folded. Lance datasets, read through the connector plugin, keep their spelling and go through the same duplicate check, as external catalog schemas do in SchemaCacheValue.validateSchema.

What problem does this PR solve?

Issue Number: None
Related PR: #70903 (shared the duplicate check with the Lance plugin path; its review comment r4676105431 reported the mismatch), #51341 (introduced the lower-cased file column names and the check), #67166 (gave nested STRUCT fields their ROOT lower-case runtime names)
PR Type: Bugfix

Problem Summary:

The duplicate checks lower-case names with the JVM's default locale, while resolution compares ignoring case, so columns such as Σ and ς (equal ignoring case, with different lower cases) pass the check and then no name picks out either; on a Turkish-locale FE, so do id and ID. And a Parquet or ORC column named Σ is shown as σ, which BE does not find in the file, so every row reads NULL. This PR tells column names apart as Spark does: two names are the same when they are equal ignoring case and their Locale.ROOT lower cases are equal. A name that is the same as no column still resolves ignoring case, so every spelling that resolved before still does, and file column names fold only their ASCII letters, as BE does.

-- column_case_sigma.lance has the columns row_id, Σ and ς; sigma_only.parquet has row_id and Σ (10, 20)
SELECT row_id, `Σ`, `σ`, `ς` FROM s3("uri" = "s3://warehouse/lance/column_case_sigma.lance", ..., "format" = "lance");
SELECT * FROM s3("uri" = "s3://warehouse/casedemo/sigma_only.parquet", ..., "format" = "parquet");
Statement Before After
Lance SELECT row_id, `Σ`, `σ`, `ς` Σ is ambiguous: Σ#1, Σ#2. 1, 10, 10, 100 and 2, 20, 20, 200
Parquet SELECT * column σ: NULL, NULL column Σ: 10, 20

Details

  • Change map: 749 changed lines in three commits: production code +170/-69 in 7 files; tests +448/-19 (FE unit tests, a new regression suite with its fixtures and their builder, three cases in an existing suite); generated .out +43. The production code has five parts:
    1. The rule, ColumnNames (71 lines), and its users: the binder in ExpressionAnalyzer (+53/-41, the four single-slot binders now share one tiered lookup), Table.getColumn and ExternalTable.getColumn.
    2. The duplicate checks: both callers in the file table function and SchemaCacheValue.validateSchema.
    3. ASCII-only folding of file column names in fillColumns (one line).
    4. The second commit, from review: the pre-lock partition preload in StatementContext (+8/-2) binds the names in a Hive relation's WHERE by the same rule, since it would otherwise prune by a partition column the analyzer no longer binds.
    5. The third commit, from review: the binder tells names apart within one precedence (+35/-24 in ExpressionAnalyzer, and the ColumnNames javadoc), since the first commit filtered by name before ORDER BY's preference for an output alias and could drop the alias it picks.
  • Frequency: Always, for names with non-ASCII letters that have case: a Parquet or ORC column with such an uppercase letter reads NULL, and pairs such as Σ/ς, ı/i, ſ/s or µ/μ cannot be named. On a Turkish- or Azerbaijani-locale FE, also id/ID (by the code; not run under that locale).
  • Root cause: Three comparisons disagree: the duplicate checks (ExternalFileTableValuedFunction.addColumnLowerName, SchemaCacheValue.validateSchema) compare default-locale lower cases; resolution (Table.nameToColumn, ExternalTable.getColumn, the binder) compares ignoring case, under which ς equals σ; and fillColumns names a file column by its Java lower case, while BE folds only ASCII letters (column_has_name in be/src/format_v2/column_mapper.cpp), so σ never finds the file's Σ.
  • Why existing tests missed it: The unit tests of the duplicate checks (S3TableValuedFunctionTest, PluginFileFormatTableValuedFunctionTest) use ASCII pairs only, which every comparison treats alike, and ExpressionAnalyzerTest binds no names that differ in non-ASCII case. The regression suites (test_lance_s3_tvf, test_hdfs_parquet_group6) use ASCII names only.
  • Fix: Duplicate checks refuse names with equal ROOT lower cases. The binder tells names apart within one precedence: when the slots a clause prefers (the output aliases, for a bare name in ORDER BY), or all the slots if it prefers none, include one of the same name, it binds only the slots of the same name; otherwise it binds the slots equal ignoring case, as before, and the existing precedence picks. Both getColumn methods likewise prefer the column of the same name. So a name binds otherwise than before only where it took several candidates of one precedence, which was an ambiguity error, the first of them, or GROUP BY moving on to an output alias; there it takes the one it names (see Behavior change). fillColumns folds only ASCII letters (Guava Ascii.toLowerCase), as BE does. BE is unchanged. The pre-lock partition preload resolves the names in a Hive relation's WHERE the same way, against the full schema, and binds only a partition column.
  • Other paths and branches: Unchanged: CREATE TABLE, VIEW, MTMV and schema change refuse duplicates by CASE_INSENSITIVE_ORDER, which is stricter; connector INSERT column lists (BindSink.findColumn) and SELECT * EXCEPT/REPLACE still match ignoring case, which matters only for tables holding columns like Σ and ς. Not fixed: a STRUCT field named Σ in a Parquet or ORC file still reads NULL (seen before and after), because FE sends nested fields to BE by their ROOT lower-case runtime names ([fix](iceberg) Preserve nested field case in created schemas #67166); that needs BE-side matching, left for a follow-up. branch-4.0, 4.1 and 4.2 lower-case file column names with the default locale since [feature](external) Support reading Hudi/Paimon/Iceberg tables after schema changes. #51341, so they have both bugs.
  • Behavior change: File columns whose names have non-ASCII uppercase letters keep them (Σ, not σ) in DESC FUNCTION, result headers and CTAS tables; ASCII letters still fold. A Turkish-locale FE refuses id/ID in external catalogs and file table functions, as other FEs do. Where several candidates of one precedence match a name only ignoring case, it takes the one it names (seen on a local cluster): select * from (select 1 as Σ, 20 as ς union all select 2, 10) t order by ς sorts by ς where it took the first column, and GROUP BY Σ over columns Σ and ς groups by the column where it fell back to an output alias Σ. An output alias still goes before a column in ORDER BY.

Testing

  • FE unit tests, run locally on the head with checkstyle on: 105 classes and 1102 tests pass, including the new ColumnNamesTest and cases, every nereids/rules/analysis test, the *TableValuedFunctionTest classes, the callers of validateSchema, and the partition preload, pruning and plugin scan tests.
  • StatementContextPartitionPredicateSafetyTest runs a mixed internal and Hive query from collection through PruneFileScanPartition, with the real HiveConnectorMetadata over a mocked metastore: a data column kırmızı or ς beside a partition column kirmizi or σ keeps both partitions (with the old preload binding: expected: <[kirmizi=y, kirmizi=x]> but was: <[]>, and the same for σ), and KIRMIZI, kırmızı and Σ still prefilter to one.
  • Reverting each part of the first commit on a copy fails its tests with the old symptom (Σ is ambiguous: Σ#1, Σ#2., Unknown column 'KIRMIZI', [username, σ, ς], ς returned for Σ, id/ID accepted under tr-TR), and binding only a same-name partition column in the preload fails the kırmızı case; the unmutated controls pass.
  • The third commit: ExpressionAnalyzerTest.testSlotNamesAreToldApartAmongTheSlotsOfOnePrecedence fails on the second commit with expected: <[ς#1]> but was: <[Σ#2]>. Three new cases in nereids_syntax_p0/order_by_bind_priority (P0; .out from -forceGenOut) ran on a local cluster: they pass on the head; with the FE of the first commit, select -t.`Σ` as `ς`, t.`Σ` from (select 1 as `Σ` union all select 2 as `Σ`) t order by `Σ` limit 1 gives (-1, 1) instead of (-2, 2); with the FE before this PR, the select * case sorts by the first column.
  • Regression, run on the first commit on a local cluster (BE at 8ede923c73a, whose column matching is the same as at the base) with a stand-in for the External pipeline's MinIO serving the committed fixtures: the new external_table_p0/tvf/test_s3_tvf_column_name_case (.out from -forceGenOut, matching the fixture values) and test_lance_s3_tvf pass; with the FE before this change, the new suite fails with Σ is ambiguous: Σ#1, Σ#2.. Like test_lance_s3_tvf, it runs in the External pipeline. The second commit changes only the preload, which file table functions do not use; the third leaves this suite's bindings as they were, since each of its names binds among the columns of one relation.
  • By hand, on the first commit: sigma_only.parquet and sigma_only.orc read NULL before and 10, 20 after; on an internal table with columns Σ and kırmızı, σ, ς and KIRMIZI resolve the same before and after.
  • The preload has no regression case: HiveQL CREATE TABLE, which builds the Hive fixtures, refuses a data column and a partition column that are equal ignoring case.

Notes for Reviewers

  • Table.nameToColumn keeps CASE_INSENSITIVE_ORDER: OlapTable uses the map directly, and an internal table cannot hold two names that map takes for one. Table.getColumn scans the full schema only when the map's hit is not the same name, and accepts a hit by getDefineName() because OlapTable keys materialized-index columns by define name.
  • The fallback to the old match goes beyond Spark, which would not resolve KIRMIZI to a column kırmızı; it keeps every existing spelling working.
  • Binders without the precedence of bindExactSlotsByThisScope (a plain expression, HAVING) leave slots of two qualification depths ambiguous or first, as before, when the preferred depth has none of the same name; the first commit had narrowed them.
  • The binder applies the qualifier filter inside each tier, so t2.KIRMIZI still binds t2.kırmızı when another relation has kirmizi. A scope of over 500 slots keeps its ROOT upper-case buckets and filters them.
  • The preload's table mocks in StatementContextTest and PruneFileScanPartitionTest now return their partition columns as the full schema too, as a plugin table does.

Release note

Column names that differ only in non-ASCII letters, such as Σ and ς, are now told apart the way Spark does, so each can be queried by name. A Parquet or ORC column read with s3(), hdfs() or file() whose name has a non-ASCII uppercase letter keeps that letter and reads its values instead of NULL. An FE whose default locale is Turkish now treats id and ID as the same name, like other FEs.

Check List (For Author)

  • Behavior changed: Yes (see Details)
  • Does this need documentation: No
  • Pre-submission status: Ready

AI Disclosure

  • Tool: Claude Code (Claude Opus 5.5)
  • Generated: code, tests, fixtures, this description
  • Human review: not stated

…file columns

### Background

Doris resolves column names regardless of case: a table looks a name up in `Table.nameToColumn`, a map ordered by `String.CASE_INSENSITIVE_ORDER`, and Nereids binds a name to every slot equal to it ignoring case. A file table function (`s3()`, `hdfs()`, `file()`) takes its schema from a file: for every format but JSON it lower-cases each column name and refuses two names that lower-case alike, and BE then finds each column in the file by its name with ASCII letters folded. Lance datasets, read through the connector plugin, keep their spelling and go through the same duplicate check, as external catalog schemas do in `SchemaCacheValue.validateSchema`.

### What problem does this PR solve?

Issue Number: None
Related PR: apache#70903 (shared the duplicate check with the Lance plugin path; its review comment r4676105431 reported the mismatch), apache#51341 (introduced the lower-cased file column names and the check), apache#67166 (gave nested STRUCT fields their ROOT lower-case runtime names)
PR Type: Bugfix

Problem Summary:

The duplicate checks lower-case names with the JVM's default locale, while resolution compares ignoring case, so columns such as `Σ` and `ς` (equal ignoring case, with different lower cases) pass the check and then no name picks out either; on a Turkish-locale FE, so do `id` and `ID`. And a Parquet or ORC column named `Σ` is shown as `σ`, which BE does not find in the file, so every row reads NULL. This PR tells column names apart as Spark does: two names are the same when they are equal ignoring case and their `Locale.ROOT` lower cases are equal. A name that is the same as no column still resolves ignoring case, so every spelling that resolved before still does, and file column names fold only their ASCII letters, as BE does.

```sql
-- column_case_sigma.lance has the columns row_id, Σ and ς; sigma_only.parquet has row_id and Σ (10, 20)
SELECT row_id, `Σ`, `σ`, `ς` FROM s3("uri" = "s3://warehouse/lance/column_case_sigma.lance", ..., "format" = "lance");
SELECT * FROM s3("uri" = "s3://warehouse/casedemo/sigma_only.parquet", ..., "format" = "parquet");
```

| Statement | Before | After |
|---|---|---|
| Lance ``SELECT row_id, `Σ`, `σ`, `ς` `` | `Σ is ambiguous: Σ#1, Σ#2.` | `1, 10, 10, 100` and `2, 20, 20, 200` |
| Parquet `SELECT *` | column `σ`: `NULL`, `NULL` | column `Σ`: `10`, `20` |

### Details

- **Change map:** 577 changed lines: production code +149/-66 in 6 files; tests +320/-8 (FE unit tests, a regression suite, its fixtures and their builder); generated `.out` +34. The production code has three parts:
  1. The rule, `ColumnNames` (70 lines), and its users: the binder in `ExpressionAnalyzer` (+41/-40, the four single-slot binders now share one tiered lookup), `Table.getColumn` and `ExternalTable.getColumn`.
  2. The duplicate checks: both callers in the file table function and `SchemaCacheValue.validateSchema`.
  3. ASCII-only folding of file column names in `fillColumns` (one line).
- **Frequency:** Always, for names with non-ASCII letters that have case: a Parquet or ORC column with such an uppercase letter reads NULL, and pairs such as `Σ`/`ς`, `ı`/`i`, `ſ`/`s` or `µ`/`μ` cannot be named. On a Turkish- or Azerbaijani-locale FE, also `id`/`ID` (by the code; not run under that locale).
- **Root cause:** Three comparisons disagree: the duplicate checks (`ExternalFileTableValuedFunction.addColumnLowerName`, `SchemaCacheValue.validateSchema`) compare default-locale lower cases; resolution (`Table.nameToColumn`, `ExternalTable.getColumn`, the binder) compares ignoring case, under which `ς` equals `σ`; and `fillColumns` names a file column by its Java lower case, while BE folds only ASCII letters (`column_has_name` in `be/src/format_v2/column_mapper.cpp`), so `σ` never finds the file's `Σ`.
- **Why existing tests missed it:** The unit tests of the duplicate checks (`S3TableValuedFunctionTest`, `PluginFileFormatTableValuedFunctionTest`) use ASCII pairs only, which every comparison treats alike, and `ExpressionAnalyzerTest` binds no names that differ in non-ASCII case. The regression suites (`test_lance_s3_tvf`, `test_hdfs_parquet_group6`) use ASCII names only.
- **Fix:** Duplicate checks refuse names with equal ROOT lower cases. The binder first binds the accepted slots of the same name and, only when there are none, the slots equal ignoring case, as before; both `getColumn` methods likewise prefer the column of the same name. A name thus binds a subset of what it bound before: what was unambiguous is unchanged, and a name ambiguous between columns like `Σ` and `ς` now picks the one it names. `fillColumns` folds only ASCII letters (Guava `Ascii.toLowerCase`), as BE does. BE is unchanged.
- **Other paths and branches:** Unchanged: CREATE TABLE, VIEW, MTMV and schema change refuse duplicates by `CASE_INSENSITIVE_ORDER`, which is stricter; connector INSERT column lists (`BindSink.findColumn`) and `SELECT * EXCEPT/REPLACE` still match ignoring case, which matters only for tables holding columns like `Σ` and `ς`. Not fixed: a STRUCT field named `Σ` in a Parquet or ORC file still reads NULL (seen before and after), because FE sends nested fields to BE by their ROOT lower-case runtime names (apache#67166); that needs BE-side matching, left for a follow-up. branch-4.0, 4.1 and 4.2 lower-case file column names with the default locale since apache#51341, so they have both bugs.
- **Behavior change:** File columns whose names have non-ASCII uppercase letters keep them (`Σ`, not `σ`) in `DESC FUNCTION`, result headers and CTAS tables; ASCII letters still fold. A Turkish-locale FE refuses `id`/`ID` in external catalogs and file table functions, as other FEs do.

### Testing

- FE unit tests, run locally on this commit with checkstyle on: 59 classes and 615 tests pass, including the new `ColumnNamesTest` and cases, every `nereids/rules/analysis` test, the `*TableValuedFunctionTest` classes and the callers of `validateSchema`.
- Reverting each part on a copy fails its tests with the old symptom (`Σ is ambiguous: Σ#1, Σ#2.`, `Unknown column 'KIRMIZI'`, `[username, σ, ς]`, `ς` returned for `Σ`, `id`/`ID` accepted under tr-TR); the unmutated controls pass.
- Regression, on a local cluster (BE at `8ede923c73a`, whose column matching is the same as at the base) with a stand-in for the External pipeline's MinIO serving the committed fixtures: the new `external_table_p0/tvf/test_s3_tvf_column_name_case` (`.out` from `-forceGenOut`, matching the fixture values) and `test_lance_s3_tvf` pass; with the FE before this change, the new suite fails with `Σ is ambiguous: Σ#1, Σ#2.`. Like `test_lance_s3_tvf`, it runs in the External pipeline.
- By hand: `sigma_only.parquet` and `sigma_only.orc` read `NULL` before and `10`, `20` after; on an internal table with columns `Σ` and `kırmızı`, `σ`, `ς` and `KIRMIZI` resolve the same before and after.

### Notes for Reviewers

- `Table.nameToColumn` keeps `CASE_INSENSITIVE_ORDER`: `OlapTable` uses the map directly, and an internal table cannot hold two names that map takes for one. `Table.getColumn` scans the full schema only when the map's hit is not the same name, and accepts a hit by `getDefineName()` because `OlapTable` keys materialized-index columns by define name.
- The fallback to the old match goes beyond Spark, which would not resolve `KIRMIZI` to a column `kırmızı`; it keeps every existing spelling working.
- The binder applies the qualifier filter inside each tier, so `t2.KIRMIZI` still binds `t2.kırmızı` when another relation has `kirmizi`. A scope of over 500 slots keeps its ROOT upper-case buckets and filters them.

### Release note

Column names that differ only in non-ASCII letters, such as `Σ` and `ς`, are now told apart the way Spark does, so each can be queried by name. A Parquet or ORC column read with `s3()`, `hdfs()` or `file()` whose name has a non-ASCII uppercase letter keeps that letter and reads its values instead of NULL. An FE whose default locale is Turkish now treats `id` and `ID` as the same name, like other FEs.

### Check List (For Author)

- Behavior changed: Yes (see Details)
- Does this need documentation: No
- Pre-submission status: Ready

### AI Disclosure

- Tool: Claude Code (Claude Opus 5.5)
- Generated: code, tests, fixtures, this description
- Human review: not stated

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@morningman

Copy link
Copy Markdown
Contributor Author

run buildall

@morningman

Copy link
Copy Markdown
Contributor Author

/review

@hello-stephen hello-stephen left a comment

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.

Changes requested: one P1 wrong-result issue remains. Full expression analysis now distinguishes Unicode names such as σ and ς, but preliminary external partition binding still conflates them. In a mixed Hive/internal-table query, this can discard a partition containing matching rows before full analysis runs. The inline comment gives a concrete trigger and fix direction.

No existing review comments were supplied, so there are no previously reported blocking findings to reaffirm or mark resolved.

Critical checkpoint conclusions

  • Goal and evidence: The shared naming rule, source-name preservation, and sigma disambiguation are implemented in ColumnNames, ExpressionAnalyzer.bindSlotsNamed, and ExternalFileTableValuedFunction.fillColumns. ColumnNamesTest, ExpressionAnalyzerTest, and test_s3_tvf_column_name_case cover the intended local behavior. The end-to-end goal remains incomplete because of the preliminary-pruning mismatch below.
  • Scope and clarity: The authoritative diff changes six production Java files and adds focused unit/regression coverage and fixtures. Centralizing the rule in ColumnNames avoids duplicating Unicode comparison logic across the changed lookup paths.
  • Concurrency and locking: No new threads, locks, or shared mutable fields are introduced. Schema lookup keeps the existing cache/metadata lifecycle. Inspection of NereidsPlanner.collectAndLockTable and StatementContext.preloadDeferredScanPartitionViewsBeforeLock confirms that the relevant connector preload occurs before internal locks; the finding concerns its predicate semantics.
  • Lifecycle and initialization: ColumnNames has only stateless static methods. Table.getColumn and ExternalTable.getColumn reuse existing schema ownership; the TVF change retains existing plugin-handle and column lifetimes. No new initialization-order or resource-release dependency was found.
  • Configuration: No configuration items or dynamic-setting behavior are changed in the authoritative diff.
  • Compatibility: ColumnNames preserves the previous case-insensitive fallback when no preferred name exists, and Table.getColumn preserves materialized-index define-name lookup. Unicode ambiguity resolution and non-ASCII native-file column spelling intentionally change. No storage format or wire symbol is changed; rolling-upgrade execution was not tested.
  • Thrift/protobuf compatibility: No gensrc/thrift or gensrc/proto changes occur in the authoritative changed-path list, so field-ID and enum compatibility are unaffected by this patch.
  • Parallel code paths: Issue found. StatementContext.preloadFilteredScanPartitionViews still searches only partition columns using equalsIgnoreCase/findFirst, while ExpressionAnalyzer.bindSlotsNamed now prefers the actual Unicode name. The preloaded filtered view can therefore exclude valid partitions. Native/plugin TVF scans and direct/external table lookup were also traced; no second introduced mismatch was verified there.
  • Special conditions: The new binder applies qualifier acceptance within same-name selection before falling back, preserving qualified lookup and ambiguity for genuinely duplicate names. The added analyzer tests cover those local cases. The define-name exception in Table.getColumn is supported by OlapTable.rebuildFullSchema and Column.getDefineName.
  • Test coverage: Added tests cover ROOT-locale stability, duplicate rejection, Unicode preference, legacy fallback, narrow/wide scopes, native/plugin schema handling, and Lance/Parquet select/filter behavior. The concrete mixed internal/external partition-preload case is missing and should accompany the fix.
  • Changed test results: The new .out names and rows agree with the fixture generator and regression SQL, including σ selecting Σ and the final-sigma filter. order_qt provides deterministic output. Persisted fixture values and automatic result-file generation were not independently verified by execution.
  • Observability: Existing duplicate-name exceptions remain explicit. The partition mismatch produces a valid empty scan rather than an error; this is a correctness defect to fix, and no additional metric requirement was identified for the stateless naming helper.
  • Transactions and persistence: The changed product methods perform schema validation and lookup rather than transaction mutation or journal writing. No new EditLog state, replay format, visible-version handling, or failover protocol is introduced.
  • Data writes and atomicity: No product data-write path is modified. Fixture generation is test-data preparation; database write atomicity, delete bitmaps, and committed/uncommitted visibility mechanisms are unchanged. Query-result correctness is affected by the reported pruning issue.
  • FE/BE variable passing: No new transmitted variable is added. Tracing visitPhysicalTVFRelation, SlotReference.withName, PlanTranslatorContext.createSlotDesc, and FileQueryScanNode shows that the original Column survives SQL spelling changes and reaches native/plugin scan mapping.
  • Performance: The changed helpers remain linear in the candidate/schema size, with the table-map fast path retained for ordinary lookups. Unicode fallback can add a schema scan and ROOT folding allocations; no new asymptotic regression was found. No performance measurements were run.
  • Other invariants: No BE allocation, native ownership, partition visible-version, or MoW delete-bitmap code is changed. Existing wide-scope uppercase-index discrepancies and case-insensitive connector sink lookup predate the patch and were not reported as new findings.

Requester focus

No additional focus was supplied.

Validation and coverage limits

Source coverage is complete for all 18 authoritative changed paths, with a main-agent risk scan and three delegated coverage areas. The second round independently confirmed the partition-pruning finding and found no additional valuable issue. The inline anchor was checked against the supplied pr.diff; no duplicate existing comments were present.

Validation was source inspection only, as requested. No build, FE unit tests, regression suite, fixture generator/self-check, MinIO/Lance cluster run, mixed-version execution, or performance benchmark was run. Consequently, persisted binary fixture values, .out generation provenance, and runtime reproduction of the reported case remain unverified. No source-coverage gaps or unresolved source questions remain.

Review converged after 2 round(s).

List<Slot> equalIgnoringCase = scope.findSlotIgnoreCase(name, all);
List<Slot> sameName = acceptSlots(name, equalIgnoringCase,
slot -> ColumnNames.same(slot.getName(), name) && accepts.test(slot));
return sameName.isEmpty() ? acceptSlots(name, equalIgnoringCase, accepts) : sameName;

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.

[P1] Align preliminary partition binding with the new name resolution

Please update StatementContext.preloadFilteredScanPartitionViews() alongside this change: it still resolves a name against partition columns only using equalsIgnoreCase(...).findFirst().

For a Hive table t(id INT, ς INT) partitioned by σ INT, with a row (id=1, ς=100, σ=1) and a matching internal-table row, run as root:

SELECT e.`ς` FROM hive.db.t e
JOIN internal.db.i i ON e.id = i.id
WHERE e.`ς` = 100;

The relevant plan is:

Project(e.ς)
  Filter(e.ς = 100)
    InnerJoin(e.id = i.id)
      HiveScan(id, ς, partition σ)
      InternalScan(id)

Before full analysis, partition preloading misbinds e.ς to σ, prunes using σ = 100, and discards the matching σ=1 partition. PruneFileScanPartition then reuses that filtered view/handle; an empty selection reaches PluginDrivenScanNode.finishPrunedToZeroScan(). This helper now correctly binds ς, so the query succeeds with missing rows where the old analyzer rejected the reference as ambiguous.

Resolve preliminary references against the full schema with the same naming rule, then push a predicate only when its resolved column is a partition column. Please add a mixed internal/external regression covering this case.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Confirmed and fixed in 976fc27.

The preload now resolves the name against the table's full schema with ColumnNames.find, the analyzer's rule including its case-insensitive fallback, and binds it only when that column is a partition column. A partition column spelled another way is still prefiltered: KIRMIZI or Σ for kirmizi or σ, and kırmızı for kirmizi when the table has no column of that name (the fallback).

Two notes on the trigger. It is wider than a join run as root: any statement that also reads or writes an internal table reaches the preload, INSERT INTO an internal table included, and so does a user without a data mask on the Hive table. And for a non-ASCII key such as σ the Hive connector sends no metastore filter; it lists the partition names and prunes them itself, with the same empty result. An ASCII key next to a non-ASCII data column (kirmizi and kırmızı) goes through the metastore filter.

On the regression: HiveQL CREATE TABLE refuses a data column and a partition column that are equal ignoring case (CreateTableDesc.validate in Hive), and the docker Hive fixtures are built with HiveQL. So the case is in StatementContextPartitionPredicateSafetyTest, next to the preload's other safety cases: it runs a mixed internal and Hive query from collection through PruneFileScanPartition, with the real HiveConnectorMetadata over a mocked metastore, for both connector paths. Without the fix it fails with expected: <[kirmizi=y, kirmizi=x]> but was: <[]>, and the same for σ.

…me rule

### Background

When a statement also reads or writes an internal table, the planner fetches the partitions of a Hive table before it takes the internal tables' read locks, so no metastore call runs under those locks. `StatementContext.preloadFilteredScanPartitionViews` binds the names in the Hive relation's WHERE to partition columns itself, before analysis, and asks the connector for the partitions an equality or IN selects; `PruneFileScanPartition` later takes those partitions as the scan's partition set.

### What problem does this PR solve?

Issue Number: None
Related PR: apache#71211 (follow-up to its first commit)
PR Type: Bugfix

Problem Summary:

The preload bound a name to the first partition column equal to it ignoring case, while the first commit of this PR makes the analyzer tell such names apart. In a Hive table with a data column `kırmızı` and a partition column `kirmizi`, or `ς` and `σ`, `h.kırmızı = 'z'` now binds the data column, but the preload still pruned the partitions by `kirmizi = 'z'`, so a query that failed with `h.kırmızı is ambiguous` before this PR returned fewer rows, silently. The preload now resolves a name against the full schema by the analyzer's rule, `ColumnNames`, and binds it only when that column is a partition column.

### Details

- **Frequency:** Always, with the first commit of this PR, for a Hive table holding a data column and a partition column that are equal ignoring case but are not the same name, in a statement that also reads or writes an internal table (a join with one, tested; by the code also a subquery or `INSERT INTO` one), filtering the data column by an equality or IN. HiveQL `CREATE TABLE` refuses such a pair; the Hive client API and the metastore Thrift API accept it. Found by the review: apache#71211 (comment)
- **Root cause:** `preloadFilteredScanPartitionViews` matched a name against the partition columns only, with `equalsIgnoreCase`, and took the first, and `PruneFileScanPartition` does not check the preloaded partitions against the bound predicate.
- **Why existing tests missed it:** The preload's unit tests (`StatementContextPartitionPredicateSafetyTest`, `StatementContextTest`, `PruneFileScanPartitionTest`) use one partition column `p` and predicates on `p`, and no regression suite reaches the preload with such names.
- **Fix:** Resolve the name with `ColumnNames.find` over the table's full schema, the analyzer's rule including its case-insensitive fallback, so `kırmızı` still prefilters a partition column `kirmizi` when the table has no column of that name. A table's partition columns are part of its full schema, which a precondition asserts; a table without partition columns reads no schema here.
- **Other paths and branches:** The preload is the only place that binds names before analysis. The Hive connector names only ASCII partition keys in a metastore filter, so it prunes `σ` by the partition names it lists; both paths are tested. Only this PR has the bug.

### Testing

- `StatementContextPartitionPredicateSafetyTest` drives a mixed internal and Hive query through collection, the pre-lock preload, binding, filter push-down and `PruneFileScanPartition`, with the real `HiveConnectorMetadata` over a mocked metastore. A data column `kırmızı` or `ς` next to a partition column `kirmizi` or `σ` keeps both partitions; `KIRMIZI`, `kırmızı` (the fallback) and `Σ` still prefilter to one. Without the fix the data-column cases fail with `expected: <[kirmizi=y, kirmizi=x]> but was: <[]>` and the same for `σ`; binding only a partition column of the same name fails the `kırmızı` spelling case.
- The table mocks of `StatementContextTest` and `PruneFileScanPartitionTest` that return partition columns now also return them as the full schema, as a plugin table does.
- FE unit tests, run locally with checkstyle on: 105 classes and 1101 tests pass, the preload, partition pruning and plugin scan tests included.
- No regression suite: HiveQL cannot create such a table.

### Release note

None

### Check List (For Author)

- Behavior changed: No
- Does this need documentation: No

### AI Disclosure

- Tool: Claude Code (Claude Opus 5.5)
- Generated: this change and this message
- Human review: not stated

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@morningman

Copy link
Copy Markdown
Contributor Author

/review

@hello-stephen hello-stephen left a comment

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.

One P2 compatibility regression remains: the new name preference can bypass existing ORDER BY alias precedence and change which row a query returns with LIMIT. Please address the inline finding. No new P0/P1 finding was identified.

The previously reported P1, comment 4750618932, is resolved on head 976fc27dfb079b2a66e20bbac162665a2eb40d65: StatementContext.preloadFilteredScanPartitionViews() now resolves names against the full schema before checking partition membership. StatementContextPartitionPredicateSafetyTest.dataColumnEqualToAPartitionColumnOnlyIgnoringCaseIsNotPrefiltered() covers the mixed internal/Hive query with data column ς and partition column σ. I have not repeated that comment or retained it as blocking.

Critical checkpoint conclusions

  • Goal and evidence: ColumnNames centralizes ROOT-based name preference; metadata lookup, schema duplicate checks and file-TVF inference use it. ColumnNamesTest, ExpressionAnalyzerTest and the new S3 regression cover the main intended behavior. Preserving previously unambiguous binding is incomplete in the ORDER BY case below.
  • Scope and reuse: Changes are focused on a shared helper, its metadata/planner/TVF adapters, and supporting tests/fixtures. The four qualified/unqualified binders share bindSlotsNamed().
  • Concurrency and locking: No threads or locks are added. The additional full-schema lookup stays in StatementContext.preloadFilteredScanPartitionViews(), before internal table locks; snapshot acquisition remains in the existing path. No new lock-order issue was found.
  • Lifecycle: Helper sets/lists are local. SlotReference.withName() preserves ExprId and original Column identity; PlanTranslatorContext.createSlotDesc() carries that Column into scan descriptors. No new resource ownership or static-initialization dependency was found.
  • Configuration: No configuration items are added or changed.
  • Compatibility: File-TVF non-ASCII spelling changes intentionally match BE lookup. Existing ORDER BY alias priority is unintentionally changed at ExpressionAnalyzer.java:1527–1529; this is the new P2. No production storage format is changed.
  • Thrift/protobuf compatibility: No gensrc/thrift or gensrc/proto definitions change.
  • Parallel paths: Checked metadata lookup, preliminary partition binding, full expression binding, USING-join binding, TVF scan lowering and plugin projection/predicate paths. The previous preload mismatch is fixed; the sort-binding caller exposes the new finding. Pre-existing downstream locale limitations were separated from new regressions.
  • Conditional checks and errors: The define-name exception and legacy fallback in Table.getColumn()/ColumnNames.find() have explicit rationale. Schema and path-column conflicts still throw; the full-schema precondition fails loudly. No new silent error handling was found.
  • Test coverage: Added tests cover narrow/wide scopes, qualification, fallback spellings, duplicate names, Turkish default locale, mixed-query partition preloading, and Lance/Parquet projection/filtering. They omit the existing output-alias precedence case in the inline comment. Tests were inspected, not run.
  • Changed expected results: The new regression .out descriptions and rows agree with lance_build_column_case.py; queries use order_qt. Binary references/schema/value bytes were inspected statically. Actual reader decoding and generated-output provenance were not independently verified.
  • Observability: Existing duplicate-name exceptions identify the conflicting name. The local resolution change adds no distributed operation requiring new metrics or logging.
  • Transactions, persistence and writes: No transaction, EditLog, replay or product data-write path is modified; new persisted files are test fixtures.
  • FE/BE propagation: No new transmitted variable is introduced. ASCII-only folding in ExternalFileTableValuedFunction.fillColumns() agrees with be/src/format_v2/column_mapper.cpp name matching; scan descriptors retain physical column spelling independently of SQL labels. CSV uses positional mapping and JSON retains its preserve-case branch.
  • Performance: ASCII table lookup keeps its existing map fast path; Unicode collision fallback scans fullSchema. External lookup and schema validation remain linear. The new full-schema preliminary lookup adds per-reference schema scanning, with no further concrete performance defect established by source inspection.

Requester focus

No additional focus was supplied (focus.txt is empty).

Validation and coverage limits

Source coverage is complete for all 22 authoritative changed paths and the relevant caller/callee paths, after two rounds. Verified the base/head alias-resolution difference, the old P1 fix, physical column-name propagation, fixture provisioning, and expected-result consistency by source inspection. The latest round found no valuable new finding.

No build, checkstyle, FE unit test, regression suite, cluster query or runtime file-reader check was run, as requested. Binary fixture readability and actual .out generation provenance remain unverified because only static source/artifact inspection was performed. The SQL result change in the inline comment is derived from the inspected binding/plan logic. No unresolved source-coverage gap remains.

Review converged after 2 round(s).

List<Slot> equalIgnoringCase = scope.findSlotIgnoreCase(name, all);
List<Slot> sameName = acceptSlots(name, equalIgnoringCase,
slot -> ColumnNames.same(slot.getName(), name) && accepts.test(slot));
return sameName.isEmpty() ? acceptSlots(name, equalIgnoringCase, accepts) : sameName;

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.

[P2] Preserve ORDER BY alias precedence before narrowing name matches

This filtering runs before bindExactSlotsByThisScope() applies the existing priority for unqualified output aliases. It therefore changes a previously unambiguous query:

SELECT -t.`Σ` AS `ς`, t.`Σ`
FROM (SELECT 1 AS `Σ` UNION ALL SELECT 2 AS `Σ`) t
ORDER BY `Σ` LIMIT 1;

The relevant input is:

Limit(1)
  Sort(Σ)
    Project(-t.Σ AS ς#A [qualifier=[]], t.Σ#B [qualifier=[t]])
      SubqueryAlias(t)
        UnionAll(1, 2)

On base, both slots match ignoring case, then bindExactSlotsByThisScope() selects the unqualified alias #A. Here sameName drops #A first, leaving only #B, so that method's single-candidate return bypasses alias precedence. The source-derived result changes from (-2, 2) to (-1, 1), rather than merely resolving a previously ambiguous reference. Preserve the existing alias/qualification priority before applying the new name preference, and add coverage for this ordering case.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Confirmed, thanks. Fixed in fc29691.

bindSlotsNamed now tells names apart only within one precedence. It keeps only the slots of the same name when the slots bindExactSlotsByThisScope prefers (qualified with as many parts as the name puts before the column, or all of them when none is) include one; otherwise it keeps every slot equal to the name ignoring case, as before this PR, and the existing precedence picks. Your query binds the alias ς again and returns (-2, 2).

The same ordering had a second symptom: with t.Σ not selected, Σ still bound the alias through the case-insensitive fallback, so selecting a column changed what ORDER BY sorted by. Both forms now bind the alias. Turkish names were affected too: select upper(t.isim) as İSİM, t.isim from (select 'a' as isim union all select 'B') t order by isim limit 1 returned (B, B) with the first commit and returns (A, a) again, as before this PR.

What still changes from before this PR, on purpose, is a choice among candidates of one precedence: select * from (select 1 as Σ, 20 as ς union all select 2, 10) t order by ς limit 1 took the first column, (1, 20), and now returns (2, 10); GROUP BY Σ over columns Σ and ς fell back to an output alias Σ and now groups by the column. The description no longer says that unambiguous bindings never change; it states this rule instead.

Coverage: ExpressionAnalyzerTest.testSlotNamesAreToldApartAmongTheSlotsOfOnePrecedence, which fails on the previous head with expected: <[ς#1]> but was: <[Σ#2]>, and three cases in nereids_syntax_p0/order_by_bind_priority: your query, the alias alone, and the select * case. On a local cluster they pass on this head; the FE of the first commit fails your query (-1 for -2), and the FE before this PR fails the select * case (it takes the first column).

…s apart

### Background

Nereids binds a name in two steps: it collects the slots of the scope whose names equal the name ignoring case, then a clause's precedence picks among them. For ORDER BY and GROUP BY, `ExpressionAnalyzer.bindExactSlotsByThisScope` prefers the slots whose qualifier has exactly as many parts as the name puts before the column, which for a bare name is an output alias over a relation's column: `select -t.a as A, t.a from t order by a` sorts by the alias. The first commit of this PR tells names such as `Σ` and `ς` apart (equal ignoring case, with different `Locale.ROOT` lower cases) by keeping only the slots of the same name between those two steps.

### What problem does this PR solve?

Issue Number: None
Related PR: apache#71211 (follow-up to its first commit)
PR Type: Bugfix

Problem Summary:

The same-name filter ran before that precedence, so it could drop the alias the precedence would pick. `select -t.Σ as ς, t.Σ from (select 1 as Σ union all select 2 as Σ) t order by Σ limit 1` returned `(-2, 2)` before this PR, sorting by the alias `ς`, and `(-1, 1)` with the first commit, sorting by `t.Σ`. With `t.Σ` not selected, the first commit still sorted by the alias, so selecting a column changed what ORDER BY sorted by. Turkish names behave alike: `select upper(t.isim) as İSİM, t.isim from (select 'a' as isim union all select 'B') t order by isim limit 1` returned `(A, a)` before this PR and `(B, B)` with the first commit. Names are now told apart only among the slots of one precedence: the same-name filter applies only when the slots the precedence prefers include one of the same name; otherwise every slot equal ignoring case is kept, as before this PR, and the precedence picks.

### Details

- **Frequency:** Always, with the first commit of this PR, for an output alias and a relation's column whose names are equal ignoring case but are not the same name (`ς` and `Σ`, `İSİM` and `isim`, `KIRMIZI` and `kırmızı`), referenced by a bare name in ORDER BY, or by any name that ORDER BY or GROUP BY binds through `bindExactSlotsByThisScope`. ASCII names never: for them the two comparisons agree. Found by the review: apache#71211 (comment)
- **Root cause:** `bindSlotsNamed` narrowed the candidates to the same name before `bindExactSlotsByThisScope` applied the qualifier precedence, and that method returns a single candidate without applying it.
- **Why existing tests missed it:** `order_by_bind_priority` and `bind_priority` test the ORDER BY and GROUP BY precedence with ASCII names only, and the first commit's `ExpressionAnalyzerTest` cases put every slot at one qualification depth.
- **Fix:** `bindSlotsNamed` takes the name's part count, finds the slots the precedence prefers (all of them when there are none), and keeps only the slots of the same name when those include one. The qualification test is one helper, shared with `bindExactSlotsByThisScope`. With this, a name binds otherwise than before this PR only where it took several slots of one precedence, which was an ambiguity error, the first of them (ORDER BY over `select *` took the first column), or GROUP BY moving on to an output alias; there it takes the one it names. The javadoc of `bindSlotsNamed` and `ColumnNames` says so.
- **Other paths and branches:** Binders without that precedence (a plain expression, HAVING) keep slots of two qualification depths as before this PR, ambiguous or the first, when the preferred depth has no slot of the same name. Only this PR has the bug.

### Testing

- `ExpressionAnalyzerTest.testSlotNamesAreToldApartAmongTheSlotsOfOnePrecedence` binds through `bindExactSlotsByThisScope`: an alias `ς` beside a column `t.Σ` takes `Σ`, with the column in scope or not; `t.Σ` takes the column; between the aliases `Σ` and `ς` each name takes its own. Without the fix it fails with `expected: <[ς#1]> but was: <[Σ#2]>`.
- `nereids_syntax_p0/order_by_bind_priority` gains three cases, `.out` from `-forceGenOut`: the review's query, `(-2, 2)`; the alias alone, `-2`; and `select * ... order by ς` over the columns `Σ` and `ς`, `(2, 10)`. On a local cluster they pass with this commit; with the FE of the first commit the first case fails (`-1` for `-2`), and with the FE before this PR the third case fails (`1` for `2`, the first column).
- FE unit tests, run locally with checkstyle on: 105 classes and 1102 tests pass, every `nereids/rules/analysis` test included.

### Release note

None

### Check List (For Author)

- Behavior changed: No
- Does this need documentation: No

### AI Disclosure

- Tool: Claude Code (Claude Opus 5.5)
- Generated: this change and this message
- Human review: not stated

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@morningman

Copy link
Copy Markdown
Contributor Author

run buildall

@morningman

Copy link
Copy Markdown
Contributor Author

/review

@hello-stephen hello-stephen left a comment

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.

No new actionable source defects found in fc29691e915071633edc081eb1ed87047aaec584. Both previously reported issues are fixed by source inspection:

  • P1, comment 4750618932: StatementContext.preloadFilteredScanPartitionViews() now resolves against the full schema before checking partition membership. A data column ς beside partition column σ no longer causes incorrect selective pruning. The new parameterized safety tests cover Greek and Turkish names through collection, preloading and partition pruning.
  • P2, comment 4764376726: ExpressionAnalyzer.bindSlotsNamed() considers name preference within the existing qualifier precedence. The reported ORDER BY query retains the output alias and yields (-2, 2), consistent with the added tests and expected output.

No previously reported P0/P1 remains verified on this head, and no duplicate inline comments are proposed.

Critical checkpoint conclusions

  • Goal and correctness: The shared catalog/ColumnNames.java rule distinguishes names such as Σ and ς, retains case-insensitive fallback, and uses Locale.ROOT. ColumnNamesTest and the new TVF/binding tests directly exercise these behaviors.
  • Scope and abstraction: The production changes are focused on naming, schema lookup/validation, file-schema spelling and preliminary partition binding. Table, ExternalTable, SchemaCacheValue and ExternalFileTableValuedFunction reuse ColumnNames.
  • Concurrency and locking: No new threads or shared mutable helper state are introduced. The changed partition binding remains in the preload pass before StatementContext.lock(); schema and partition columns use the same snapshot. Existing test fixtures explicitly check that metastore requests precede internal locks.
  • Lifecycle: No new owned resources or static initialization dependencies appear. ExternalTablePreloadInfo.clearPartitionViews() and StatementContext.resetMvccSnapshots() continue clearing execution-specific views; the change preserves snapshot and filtered-handle reuse.
  • Compatibility: The intended within-precedence Unicode disambiguation changes some bindings; alias precedence and fallback remain intact. Table.getColumn() preserves materialized-index define-name lookup. No persisted or wire format changes occur.
  • Parallel paths: Reviewed all four expression qualifier levels, narrow/wide scopes, table/external lookup, native/plugin TVFs and preliminary pruning. SlotReference.withName() retains the original Column, and PlanTranslatorContext.createSlotDesc() sends that identity to readers. Native Parquet/ORC matching agrees with ASCII folding; JSON and plugin spelling remain preserved.
  • Conditional checks and failure handling: Duplicate schema/path-column keys still raise errors. The full-schema partition-membership check has a concrete wrong-pruning trigger, documented locally and covered by StatementContextPartitionPredicateSafetyTest.
  • Test coverage: Added unit cases cover name distinctions, fallback, ambiguity, comparator-map collisions and alias precedence. Regression cases cover Lance/Parquet projection, filtering and ORDER BY. Negative duplicate-name cases remain covered in the inspected tests. Execution is unverified.
  • Changed expected results: Added ORDER BY outputs (-2, 2), (-2) and (2, 10) agree with the input rows and binding trace. TVF outputs agree with lance_build_column_case.py's declared rows. Binary payload values were not independently decoded.
  • Observability: This adds no new distributed operation requiring instrumentation. Existing duplicate-name exceptions, partition-policy failures and scan diagnostics remain available; no logging issue was identified.
  • Performance: Ordinary Table.getColumn() lookups retain the map fast path; colliding names scan the schema. Validation and candidate filtering remain linear in their inputs. No material regression was established by inspection; planning cost was not benchmarked.
  • Other invariants and integration: Traced predicate collection through selective/full-view reuse in PruneFileScanPartition, including the earlier missing-row trigger. No additional introduced correctness issue was established. There are no changes to transaction/write logic, visibility versions, configuration, Thrift/Protobuf definitions or FE–BE variables.

Paths above are within fe/fe-core/src/main/java/org/apache/doris/ unless identified as tests or fixture sources.

Requester focus

No additional focus was supplied.

Validation and coverage limits

Source coverage is complete for all 24 changed paths, including surrounding callers/consumers, test assertions and expected outputs. The main review and three delegated reviews converged in one round with no new actionable finding.

As requested, no build, FE/BE unit tests, regression suite, cluster SQL, fixture generator/checker or performance benchmark was run. Test pass status and automatic generation of .out files cannot be independently established from source. The committed Lance/Parquet artifacts received structural/reference inspection; their decoded values and reader-version compatibility remain unverified without runtime checks. Broader locale-sensitive and nested-field combinations were inspected in source but not executed. There are no remaining source-coverage gaps or unresolved introduced-defect candidates.

Review converged after 1 round(s).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants