Skip to content

[BUG] Inconsistent MAP path resolution across PPL commands #5152

Closed
2 of 2 issues completed
Closed

Description

@dai-chen

What is the bug?

When a PPL command produces a MAP-typed column (e.g., spath auto-extract), downstream commands that reference nested values via dotted paths like doc.user.name fail in many commands. See Technical Deep Dive for more details.

How can one reproduce the bug?

  1. Create an index with a JSON string field and enable Calcite:
PUT /test/_doc/1 {"doc": "{\"user\":{\"name\":\"John\",\"age\":30,\"city\":\"NYC\"}}"}
PUT /test/_doc/2 {"doc": "{\"user\":{\"name\":\"Alice\",\"age\":25,\"city\":\"LA\"}}"}
  1. Run any of these queries (see Impact Analysis):
# Field name matching failures (Category A):
source=test | spath input=doc | rename doc.user.name as username | fields username
source=test | spath input=doc | fillnull using doc.user.name = 'N/A'
source=test | spath input=doc | replace 'John' WITH 'Jonathan' IN doc.user.name
source=test | spath input=doc | top 1 doc.user.name by doc.user.city
source=test | spath input=doc | rare doc.user.name by doc.user.city
source=test | spath input=doc | fields - doc.user.name
source=test | spath input=doc | rename doc.user.* as extracted.*

# Projection naming failures (Category B):
source=test | spath input=doc | top 2 doc.user.name
source=test | spath input=doc | rare doc.user.name
source=test | spath input=doc
  | inner join left=a, right=b ON a.doc.user.name = b.name other_index

What is the expected behavior?

Path navigation expression, such as doc.user.name, should work uniformly across all PPL commands when root field type (doc) is a MAP/STRUCT column.

What is your host/environment?

  • PPL Calcite V3 engine

Do you have any screenshots?

N/A

Do you have any additional context?

Activity

  1. added
    bug
    on Feb 17, 2026
  2. added
    PPL
    and removed on Feb 17, 2026
  3. dai-chen commented on Feb 17, 2026

    @dai-chen
    CollaboratorAuthor

    Impact Analysis

    Impacted Commands (10 total)

    • Category A (6 commands) — command iterates getRowType().getFieldNames() or uses string-based relBuilder.field(name) lookup; MAP sub-paths like doc.user.name are invisible because only doc exists in the row type.
    • Category B (1 command) — command resolves field via rexVisitor.analyze() correctly, but output column gets wrong name because AST lacks Alias wrapping.
    • Category C (3 commands) — command bypasses visitChildren() or uses string-based relBuilder.field(name) in internal helpers that run after materialization, so centralized path resolution is never reached.

    Category A — Symbol-based commands (6 commands)

    Command Failure Fix Approach
    rename matchFieldNames() misses MAP paths. Wildcard doc.user.* unsolvable at plan time Non-wildcard: rexVisitor.analyze() fallback, project ITEM() with new alias. Wildcard: document as limitation
    fillnull equalsIgnoreCase() on field list skips doc.user.name silently Unmatched fields fall back to rexVisitor.analyze() + COALESCE on ITEM()
    replace relBuilder.field(name) throws and contains() misses MAP sub-paths Resolve target via rexVisitor.analyze(), apply replace on ITEM() result
    fields - Non-WC: projectExcept receives AS(ITEM()) which doesn't match any physical field by identity, so nothing gets excluded (silent no-op). WC: expandWildcardPattern misses MAP paths Non-WC: resolve via ITEM(), build manual exclusion projection. Wildcard: document as limitation
    addtotals Field list iteration and shouldAggregateField string match miss MAP sub-paths Resolve explicitly-named fields via rexVisitor.analyze()
    mvcombine isInputRef() check fails because ITEM() is not an InputRef MAP values are not multi-value. Document as unsupported

    Category B — Missing Alias wrapping (1 command)

    Command Failure Fix Approach
    top / rare getGroupByList() returns raw Fields without Alias wrapping, so output columns get auto-generated names Wrap in Alias in AstBuilder.getGroupByList(), matching getPartitionExprList() pattern

    Category C — Fragmented resolve API (3 commands)

    Command Failure Fix Approach
    lookup analyzeFieldsForLookUp() uses relBuilder.field(2, stackPos, fieldName) which is string-based. Source-side materialization via getOperands() works, but the string-based lookup in addJoinForLookUp still fails Replace analyzeFieldsForLookUp with rexVisitor.analyze() or QualifiedNameResolver for source-side fields
    streamstats (correlate path) extractGroupFieldName() gets raw string name, then relBuilder.field(groupName) fails. Affects buildGroupFilter() and buildRequiredLeft(). Default window-function path is safe Replace string-based relBuilder.field() with rexVisitor.analyze() in buildGroupFilter and buildRequiredLeft
    join (field-list) children.forEach(c -> analyze(c, context)) bypasses visitChildren() entirely. buildJoinConditionByFieldName → analyzeFieldsForLookUp uses string-based lookup. Both sides need materialization Change to use visitChildren() or add per-side materialization; replace string-based field lookup in join condition builder

    Separate Issues (not MAP path resolution)

    Command Issue Tracking
    eval (multiple dotted paths) shouldOverrideField incorrectly removes MAP root column doc when adding doc.user.name because "doc.user.name".startsWith("doc.") matches Filed as separate bug
    appendcol Subquery operates on raw source table (STRING doc), not the spath-transformed pipeline (MAP doc). INTERNAL_ITEM rejects STRING input Filed as separate bug

    Confirmed Safe Commands (19 total)

    All of these correctly resolve MAP sub-paths via rexVisitor.analyze() and QualifiedNameResolver:

    • where — condition resolved via rexVisitor.analyze()
    • eval (single path) — always Alias-wrapped by parser. Multiple dotted paths fail due to separate shouldOverrideField bug (see above)
    • stats — getPartitionExprList() wraps group-by in Alias
    • sort — sort keys resolved via rexVisitor.analyze()
    • dedup — dedup fields resolved via rexVisitor.analyze()
    • fields + (non-wildcard) — fixed in PR Fix path navigation on map columns for spath command #5149, ITEM aliased at projection
    • head — no field references
    • eventstats — getPartitionExprList() wraps in Alias; group-by uses rexVisitor.analyze() (not extractGroupFieldName)
    • chart — routes through visitAggregation with getPartitionExprList() (Alias-wrapped); tested and confirmed working
    • trendline — output alias from computation definition
    • parse — source field resolved via rexVisitor.analyze(), output names from regex groups
    • rex — field resolved via rexVisitor.analyze()
    • patterns — partition list Alias-wrapped, pattern field is flat
    • bin / bucket — field resolved via rexVisitor.analyze()
    • spath — rewrites as eval
    • search — filter resolved via rexVisitor.analyze()
    • reverse — no field references
    • flatten — flatten doc (MAP root) works correctly. Flatten on MAP sub-path is semantically invalid (value is VARCHAR, not struct)
    • transpose — works after fields projects MAP sub-paths as flat columns. Direct transpose on MAP column fails due to MAP-to-VARCHAR type incompatibility, not path resolution
    • expand — expand on MAP sub-path is semantically invalid (value is VARCHAR, not collection). (RexInputRef) cast error is a code quality issue but fixing it just changes the error message

    Note: fieldsummary does not exist in the Calcite engine (no visitor method).

  4. dai-chen commented on Feb 18, 2026

    @dai-chen
    CollaboratorAuthor

    Technical Deep Dive

    Summary

    The following table summarizes the root cause and potential solutions for each of the three failure categories identified in the Impact Analysis above:

    Category Root Cause Affected Commands Potential Solutions
    A — Symbol-based commands Symbol-based commands iterate field names as strings directly, and the schema only contains top-level fields (e.g., doc), so MAP sub-paths like doc.user.name are never matched. rename, replace, fillnull, fields -, addtotals, mvcombine 1. Rewrite commands to be expression-based (resolve paths as RexNode, write back via ITEM_SET)
    2. Central symbol-table API (QualifiedNameResolver) that resolves dotted paths against MAP roots
    3. Pre-materialize MAP paths as temporary columns before command logic
    4. Document as unsupported; users materialize with eval or per-field spath
    B — Missing alias wrapping Missing Alias wrapping causes wrong output column names; raw Field nodes returned without Alias wrapping, so output columns get auto-generated names instead of the user-visible dotted path. top, rare 1. Wrap group-by fields in Alias(name, field) in getGroupByList(), matching the pattern already used by getPartitionExprList()
    2. Pre-materialize MAP paths (A-3) also fixes this by making sub-paths available as top-level columns
    C — Fragmented resolve API Fragmented resolve API bypasses centralized path resolution by calling relBuilder.field(name) directly, so centralized path resolution never triggers. join (field-list), streamstats (correlate path), lookup 1. Route all field resolution through the centralized resolve API inside the bypassing helpers (buildJoinConditionByFieldName, buildGroupFilter, analyzeFieldsForLookUp)
    2. Pre-materialize MAP paths (A-3) also fixes this by ensuring sub-paths exist as top-level columns before any command runs

    Category A — Semantic mismatch in symbol-based commands

    • Some PPL commands such as rename, replace, and fillnull treat their field arguments as symbols that must already exist as top-level schema fields. After spath auto-extract, only the MAP root (for example, doc) exists in the row schema. This is why exposing element_at(...) / bracket access doesn't help.
    • This issue is more visible in PPL than in typical SQL because SQL is mostly expression-oriented (only DDL statement has L-value, e.g., ALTER ... column), while PPL has more pipeline commands that manipulate field-symbol lists directly.

    Failure example: replace command

    // Schema after spath: getFieldNames() = ["doc"]  (doc is MAP)
    // User query: replace 'John' WITH 'Jonathan' IN doc.user.name
    @Override
    public RelNode visitReplace(Replace node, CalcitePlanContext context) {
        List fieldNames = context.relBuilder.peek().getRowType().getFieldNames();
        // fieldNames = ["doc"]
    
        for (String fieldToReplace : fieldsToReplace) {
            context.relBuilder.field(fieldToReplace);  // throws: "doc.user.name" not in schema
        }
    
        // Even if validation passed, this loop also fails
        for (String fieldName : fieldNames) {           // iterates ["doc"]
            if (fieldsToReplace.contains(fieldName)) {  // "doc.user.name".contains("doc") → false
                RexNode fieldRef = context.relBuilder.field(fieldName);
                // ... apply replacement ...
                projectList.add(fieldRef);
            } else {
                projectList.add(context.relBuilder.field(fieldName));
            }
        }
        context.relBuilder.project(projectList, fieldNames);
    }
    

    Potential solutions

    • Solution 1 - Rewrite affected commands to be expression-based
      Idea: Refactor commands like rename / replace / fillnull to resolve field references as expressions (RexNode) instead of requiring field symbols, so MAP paths can be handled natively.
      Pros & Cons: Future-proof (aligns symbol-based commands with expression-capable behavior, but requires per-command refactoring and can be costly for commands deeply built around field-name lists or RexInputRef assumptions.
      if (fieldExpr.getKind() == SqlKind.ITEM) {
        // Write back into MAP: doc = ITEM_SET(doc, 'user.name', replaced)
        RexNode mapRoot = ((RexCall) fieldExpr).getOperands().get(0);  // doc
        RexNode path = ((RexCall) fieldExpr).getOperands().get(1);     // 'user.name'
        RexNode updated = rexBuilder.makeCall(ITEM_SET, mapRoot, path, replaced);
        // Project: override "doc" column with updated MAP
        projectPlusOverriding(context, updated, "doc");
      } else {
        // Flat field: project in-place as today
        projectList.add(replaced);
      }
    
    • Solution 2 - Introduce a central symbol-table API for symbol-based commands
      Idea: Keep command semantics symbol-oriented, but stop doing ad hoc field-name iteration/string lookup in each command; instead, use a shared API that can resolve top-level fields and path-backed “virtual fields” consistently.
      Pros & Cons: Improves consistency and maintainability across commands, but still requires each command migration to the shared API, and it does not prevent future commands that bypass it unintentionally.
    for (field in fieldList) {
        // BEFORE: string equality — fails when userField="doc.user.name", field.getName()="doc"
        // if (field.getName().equalsIgnoreCase(userField)) {
        // if (fieldsToReplace.contains(field.getName())) {
    
        // AFTER: resolve API — matches "doc.user.name" against "doc" via MAP path resolution
        Optional resolved = QualifiedNameResolver.resolve(userField, field.getName(), context);
        if (resolved.isPresent()) {
          RexNode target = resolved.get();  // ITEM(doc, 'user.name') or direct fieldRef
    }
    
    • Solution 3 - Pre-materialize required MAP paths before command logic [Preferred?]
      Idea: Internally resolve required paths (for example, doc.user.name), project them to temporary columns, then run the existing symbol-based logic on those temporary fields.
      Cons: Adds extra projections and temporary-column complexity, and can become a workaround-heavy design if overused.
    // In UnresolvedPlan:
    /**
     * Returns the input expressions this command operates on.
     * Each command returns its full operand expressions — the consumer
     * decides how to interpret them.
     */
    public abstract List<UnresolvedExpression> getOperands();
    
    // Rename — returns the Map (origin→target pairs):
    @Override
    public List getOperands() {
      return renameList.stream().map(m -> (UnresolvedExpression) m).collect(toList());
    }
    
    // In CalciteRelNodeVisitor:
    @Override
    public RelNode visitChildren(Node node, CalcitePlanContext context) {
      RelNode result = super.visitChildren(node, context);
      if (node instanceof UnresolvedPlan plan) {
        materializeMapPathsIfNeeded(plan, context);
      }
      return result;
    }
    
    • Solution 4 - Document MAP paths as unsupported in symbol-based commands (selectively)
      Idea: Document the limitation clearly and rely on user-side workarounds (eval materialization / chained spath).
      Pros & Cons: Fastest and lowest-risk option with clear boundaries, but preserves UX inconsistency and leaves users with command-specific behavior differences.
    # Document the limitation and workaround pattern below
    spath input=_source output=doc
    | eval username = doc.user.name
    | replace "John" with "Jonathan" in username
    
    # Or extract per-field with path mode
    spath input=doc path=user.name output=username
    | replace "John" with "Jonathan" in username
    

    Category B — Missing Alias wrapping causes wrong output column names

    Commands like top, rare, and chart resolve MAP sub-paths correctly via rexVisitor.analyze() during aggregation, but the output columns get auto-generated names instead of the user-visible dotted path. The root cause is in AstBuilder.getGroupByList() which returns raw Field nodes without Alias wrapping, unlike getPartitionExprList() used by stats/eventstats which wraps each field in Alias(name, field).

    Failure example: top command

    // User query: source=t | spath input=doc | top 2 doc.user.name
    
    // In AstBuilder — getGroupByList() returns raw Fields (no Alias):
    private List<UnresolvedExpression> getGroupByList(ByClauseContext ctx) {
        return ctx.fieldList().fieldExpression().stream()
            .map(this::internalVisitExpression)   // ← raw Field, no Alias wrapping
            .collect(Collectors.toList());
    }
    

    Potential solutions

    • Solution 1 — Wrap group-by fields in Alias (direct fix)
      Idea: In AstBuilder.getGroupByList(), wrap each field expression with Alias(name, field) before returning, matching the pattern already used by getPartitionExprList().
      Pros & Cons: Minimal, surgical one-line change using a proven pattern that already works for stats/eventstats. However, it only fixes column naming for this specific code path and doesn't prevent similar raw-field issues in future commands.

      private List<UnresolvedExpression> getGroupByList(ByClauseContext ctx) {
          return ctx.fieldList().fieldExpression().stream()
              // BEFORE: .map(this::internalVisitExpression)  // raw Field, no Alias
              .map(fe -> {
                  UnresolvedExpression expr = internalVisitExpression(fe);
                  return new Alias(fe.getText(), expr);
              })
              .collect(Collectors.toList());
      }
    • Solution 2 — Pre-materialize MAP paths (A-3)
      Idea: Temporary columns are projected with correct names before command logic runs, so even raw Field nodes resolve to properly named top-level columns.
      Pros & Cons: Fixes naming and resolution uniformly across all commands in one shot, but is a heavier approach for what is otherwise a one-line Alias fix and adds extra projection steps.


    Category C — Fragmented resolve API bypasses centralized path resolution

    Some commands bypass the standard visitChildren() → materializeMapPathsIfNeeded() flow by calling analyze(child, context) directly on their children, or by using string-based relBuilder.field(name) in internal helper methods that run after the materialization step. This means even if getOperands() is implemented, the materialization never triggers or the command's internal logic still uses raw string lookups.

    Affected commands:

    Command Bypass mechanism
    join (field-list) children.forEach(c -> analyze(c, context)) bypasses visitChildren() entirely; buildJoinConditionByFieldName → analyzeFieldsForLookUp uses string-based relBuilder.field(2, pos, name)
    streamstats (correlate path) extractGroupFieldName() extracts raw string name, then buildGroupFilter / buildRequiredLeft use relBuilder.field(name) string lookup against post-transformation schema
    lookup analyze(node.getLookupRelation(), context) bypasses visitChildren() for the lookup table side; analyzeFieldsForLookUp uses string-based relBuilder.field(2, pos, name) for both sides

    Failure example: streamstats command

    // User query: source=t | spath input=doc
    //   | streamstats window=2 global=true count() as cnt by doc.user.name
    
    // buildGroupFilter uses string-based lookup:
    private RexNode buildGroupFilter(...) {
        groupList.stream().map(expr -> {
            String groupName = extractGroupFieldName(expr);  // "doc.user.name"
            RexNode rightGroup = context.relBuilder.field(groupName);  // throws: not in schema
            RexNode outerGroup = context.relBuilder.field(correl, groupName);
            return context.relBuilder.equals(rightGroup, outerGroup);
        });
    }
    

    Potential solutions

    • Solution 1 — Route through centralized resolve API (direct fix)
      Idea: Replace direct relBuilder.field(name) calls in each bypassing helper with the centralized resolver, so MAP paths are resolved consistently.
      Pros & Cons: Fixes the root cause per-command and keeps resolution logic in one place. However, requires per-command refactoring since each helper has different call patterns (field(2, pos, name) in join/lookup vs field(name) in streamstats vs correlate variables).

      // In buildGroupFilter (streamstats):
      String groupName = extractGroupFieldName(expr);
      // BEFORE: RexNode rightGroup = context.relBuilder.field(groupName);  // throws
      Optional<RexNode> resolved = QualifiedNameResolver.resolve(
          groupName, context.relBuilder.peek().getRowType(), context);
      RexNode rightGroup = resolved.orElseThrow(
          () -> new SemanticCheckException("Cannot resolve field: " + groupName));
    • Solution 2 — Pre-materialize MAP paths (A-3)
      Idea: Because materialization happens before command logic, even direct relBuilder.field("doc.user.name") succeeds since the column now exists as a top-level field in the schema.
      Pros & Cons: Bypassing helpers work as-is without any per-command changes, but adds extra projection steps and leave the command as is (technical debt remains even if functional behavior is correct).

  5. self-assigned this
    on Feb 21, 2026
  6. dai-chen commented on Feb 27, 2026

    @dai-chen
    CollaboratorAuthor

    Proof of Concept: Pre-materializing MAP Paths

    Summary

    This proof of concept validates that pre-materializing referenced MAP sub-paths before command-specific planning (Solution A3 above). The PoC shows that this approach is technically viable and provides a uniform behavioral fix. However, it also reveals an architectural limitation: PPL V3 currently lacks a dedicated analysis phase.

    As a result, the PoC places a new operand-declaration contract on AST nodes as well as schema-enrichment inside the RelNode visitor. While this is effective as a practical workaround, it is not an ideal long-term design. Based on these findings, the current decision is to minimize code changes on existing command implementation and defer broader architectural follow-up to future design work:

    • Category A: Apply the PoC approach (with Option I: Centralized switch and Option A: Global traversal hook) to fix Category A field-name matching failures in symbol-based commands by materializing referenced MAP paths before command-specific planning.
    • Category B / C: Although the pre-materialization approach can also fix Category B and C indirectly, the current preference is to address these cases with direct localized fixes where possible.

    PoC Approach

    In this PoC, each AST node declares its input field operands through getOperands(). During CalciteRelNodeVisitor.visitChildren(), and before a command-specific visitXxx() method runs, a resolver performs the following steps:

    • Extract field references from the node's new getOperands API.
    • Resolve each field reference through the centralized QualifiedNameResolver and check whether it resolves to an ITEM() expression.
    • Project each resolved MAP path back into the input as an additional named column.
    // In UnresolvedPlan:
    /**
     * Returns the input expressions this command operates on.
     * Each command returns its full operand expressions — the consumer
     * decides how to interpret them.
     */
    public abstract List<UnresolvedExpression> getOperands();
    
    // Rename — returns the Map (origin→target pairs):
    @Override
    public List<UnresolvedExpression> getOperands() {
      return renameList.stream()
          .map(m -> (UnresolvedExpression) m)
          .collect(toList());
    }
    
    // In CalciteRelNodeVisitor:
    @Override
    public RelNode visitChildren(Node node, CalcitePlanContext context) {
      RelNode result = super.visitChildren(node, context);
    
      List<RexNode> toMaterialize = new ArrayList<>();
      List<UnresolvedExpression> fields = extractFields(node.getOperands());
      for (UnresolvedExpression field in fields) {
        RexNode resolved = rexVisitor.analyze(field, context);
        if (resolved.getKind() == SqlKind.ITEM) {
          toMaterialize.add(resolved)
        }
      }
      context.relBuilder.projectPlus(toMaterialize);
      return result;
    }

    PoC Results

    As a result, downstream command logic can continue to work against an enriched schema where referenced MAP sub-paths appear as ordinary fields. The PoC fixes all three failure categories in a consistent way below.

    Category A: Symbol-based command - replace

    # Before fix
    opensearchsql> source=t
    .............. | spath input=doc 
    .............. | replace 'John' WITH 'Jonathan' IN doc.user.name
    .............. | fields doc.user.name;
    {'reason': 'Invalid Query', 'details': 'field [doc.user.name] not found;
      input fields are: [_id, _index, _score, _maxscore, _sort, _routing, doc]',
      'type': 'IllegalArgumentException'}.
    
    # After fix
    opensearchsql> source=t
    .............. | spath input=doc
    .............. | replace 'John' WITH 'Jonathan' IN doc.user.name
    .............. | fields doc.user.name;
    fetched rows / total rows = 5/5
    +-----------------+
    | doc.user.name   |
    |-----------------|
    | Jonathan        |
    | Alice           |
    | Jonathan        |
    | Bob             |
    | null            |
    +-----------------+
    
    # Note: the materialization project and the fields project are merged by ProjectMergeRule.
    Logical:
      LogicalProject(doc.user.name=[REPLACE(ITEM(JSON_EXTRACT_ALL($0), 'user.name'), 'John', 'Jonathan')])
        CalciteLogicalIndexScan(table=[[OpenSearch, t]])
    
    

    Category B: Missing alias wrapping - top/rare

    # Before fix
    opensearchsql> source=t
    .............. | spath input=doc
    .............. | top 2 doc.user.name;
    fetched rows / total rows = 2/2
    +-------+---------+
    | $f1   | count   |    ← wrong column name
    |-------+---------|
    | John  | 2       |
    | Alice | 1       |
    +-------+---------+
    
    opensearchsql> source=t
    .............. | spath input=doc
    .............. | rare doc.user.name by doc.user.city;
    {'reason': 'Invalid Query', 'details': 'Field [doc.user.city] not found.', 'type': 'IllegalArgumentException'}
    
    # After fix
    opensearchsql> source=t
    .............. | spath input=doc
    .............. | top 2 doc.user.name;
    fetched rows / total rows = 2/2
    +-----------------+---------+
    | doc.user.name   | count   |    ← correct column name
    |-----------------+---------|
    | John            | 2       |
    | null            | 1       |
    +-----------------+---------+
    
    opensearchsql> source=t
    .............. | spath input=doc
    .............. | rare doc.user.name by doc.user.city;
    fetched rows / total rows = 5/5
    +-----------------+-----------------+---------+
    | doc.user.city   | doc.user.name   | count   |
    |-----------------+-----------------+---------|
    | SF              | John            | 1       |
    | LA              | Alice           | 1       |
    | NYC             | null            | 1       |
    | NYC             | Bob             | 1       |
    | NYC             | John            | 1       |
    +-----------------+-----------------+---------+
    
    Logical:
      LogicalProject(doc.user.name=[$0], count=[$1])
        LogicalFilter(condition=[<=($2, 2)])
          LogicalProject(doc.user.name=[$0], count=[$1],
                         _row_number_rare_top_=[ROW_NUMBER() OVER (ORDER BY $1 DESC)])
            LogicalAggregate(group=[{0}], count=[COUNT()])
              LogicalProject(doc.user.name=[ITEM(JSON_EXTRACT_ALL($0), 'user.name')])
                CalciteLogicalIndexScan(table=[[OpenSearch, t]])
    

    Category C: Fragmented resolve API - join

    # Before fix
    opensearchsql> source=t
    .............. | spath input=doc
    .............. | join type=inner left=l right=r on l.doc.user.name=r.name t_lookup;
    {'reason': 'Invalid Query',
     'details': 'field [doc.user.name] not found; input fields are: [name, dept]',
     'type': 'IllegalArgumentException'}
    
    # After fix
    opensearchsql> source=t
    .............. | spath input=doc
    .............. | join type=inner left=l right=r on l.doc.user.name=r.name t_lookup;
    fetched rows / total rows = 3/3
    +-------------------------------------------------------------+--------+-------------+
    | doc                                                         | name   | dept        |
    |-------------------------------------------------------------+--------+-------------|
    | {'user.age': '25', 'user.name': 'Alice', 'user.city': 'LA'}| Alice  | Marketing    |
    | {'user.age': '30', 'user.name': 'John', 'user.city': 'NYC'}| John   | Engineering  |
    | {'user.age': '35', 'user.name': 'John', 'user.city': 'SF'} | John   | Engineering  |
    +-------------------------------------------------------------+--------+-------------+
    
    Logical:
      LogicalJoin(condition=[=(ITEM($0, 'user.name'), $1)], joinType=[inner])
        LogicalProject(doc=[JSON_EXTRACT_ALL($0)])
          CalciteLogicalIndexScan(table=[[OpenSearch, t]])
        LogicalProject(name=[$0], dept=[$1])
          CalciteLogicalIndexScan(table=[[OpenSearch, t_lookup]])
    

    Implementation Options

    Part 1: How to Extract Field Operands from AST Nodes

    The materializer needs to know which Field references a command operates on.
    Two approaches:

    • Option I: Centralized switch — A single switch expression in the materializer maps each command type to its field extraction logic (current PR approach)
      • The extractFieldOperands method in MapPathPreMaterializer pattern-matches on the concrete UnresolvedPlan subclass and calls the appropriate getter
      • Pros: all extraction logic in one place; easy to audit which commands are covered; no changes to AST node classes; avoids polluting the AST API with materializer-specific concerns
      • Cons: violates open-closed principle — adding a new command requires modifying the switch.
      // MapPathPreMaterializer.java
      private List<Field> extractFieldOperands(UnresolvedPlan node) {
          return switch (node) {
              case Rename rename -> toFields(rename.getRenameList(), m -> m.getOrigin());
              case FillNull fillNull -> toFields(fillNull.getReplacementPairs(), Pair::getLeft);
              ...
              default -> List.of();
          };
      }
    • Option II: getFieldOperands() contract on AST nodes — Each command node exposes its referenced fields via a common interface method
      • Add a getFieldOperands() default method to UnresolvedPlan (returning List.of()) and override it in each command that references symbol-based fields
      • Similar in spirit to Calcite's SqlCall.getOperandList(), which provides a uniform way to access operands across all SQL call types
      • Pros: open-closed — new commands self-declare their operands; compile-time contract; materializer becomes a simple loop with no type-switching; each command owns its own field extraction logic
      • Cons: broader AST interface change; every UnresolvedPlan subclass inherits the method (even if irrelevant); extraction logic is scattered across AST classes instead of centralized; some commands have non-trivial extraction (e.g., Rename needs m.getOrigin(), Project only when excluded) which may not fit a simple List<Field> return type cleanly
      // UnresolvedPlan.java — base class
      public abstract class UnresolvedPlan extends Node {
          /** Fields referenced as symbol operands by this command. Default: none. */
          public List<Field> getFieldOperands() {
              return List.of();
          }
          // ... existing methods
      }
      
      // Rename.java — override
      @Override
      public List<Field> getFieldOperands() {
          return renameList.stream()
              .map(Map::getOrigin)
              .filter(Field.class::isInstance)
              .map(Field.class::cast)
              .toList();
      }

    Part 2: Where to Trigger Materialization

    • Option A: Global traversal hook — Override visitChildren to auto-materialize for every node
      • Override visitChildren in CalciteRelNodeVisitor; call materializePaths() after super.visitChildren() returns
      • Gated by instanceof UnresolvedPlan + per-command switch in extractFieldOperands
      • Pros: DRY — single hook point; new commands only need a switch case
      • Cons: fires for every AST node; couples MAP-specific side effects to the universal traversal contract; surprising to future developers who expect visitChildren to be pure traversal
      • Risk: low in practice — extractFieldOperands returns empty for unrecognized commands
      // CalciteRelNodeVisitor.java
      @Override
      public RelNode visitChildren(Node node, CalcitePlanContext context) {
          RelNode result = super.visitChildren(node, context);
          if (node instanceof UnresolvedPlan plan) {
              mapPathMaterializer.materializePaths(plan, context);
          }
          return result;
      }
    • Option B: Explicit per-command call — Each affected visit* method calls the materializer directly
      • Remove the visitChildren override; add mapPathMaterializer.materializePaths(node, context) after visitChildren(node, context) in each of the 6 affected methods (visitRename, visitFillNull, visitReplace, visitProject, visitAddTotals, visitMvCombine)
      • Pros: intent is explicit at each call site; visitChildren stays pure; no overhead for unrelated commands
      • Cons: 6 call sites to maintain; when adding a new symbol-based command, developer must remember to add the call; per-command knowledge is split between call sites and the extractFieldOperands switch
      // CalciteRelNodeVisitor.java — each affected method
      @Override
      public RelNode visitRename(Rename node, CalcitePlanContext context) {
          visitChildren(node, context);
          mapPathMaterializer.materializePaths(node, context);  // explicit
          // ... rest of rename logic
      }
    • Option C: Opt-in traversal helper — Wrapper method that composes traversal + materialization, called by affected commands
      • Extract a visitChildrenWithMaterialization(UnresolvedPlan, CalcitePlanContext) helper that calls visitChildren then materializePaths
      • Each affected visit* method calls this helper instead of visitChildren directly
      • Pros: visitChildren stays pure (no override); materialization is opt-in per command; logic centralized in one helper + MapPathPreMaterializer; easy to discover via grep
      • Cons: still requires each affected command to call the right method; slightly less automatic than Option A
      • Trade-off vs. Option B: reduces repetition (one helper vs. inline calls) while keeping the opt-in explicitness
      // CalciteRelNodeVisitor.java — helper method
      private RelNode visitChildrenWithMaterialization(
              UnresolvedPlan node, CalcitePlanContext context) {
          RelNode result = visitChildren(node, context);
          mapPathMaterializer.materializePaths(node, context);
          return result;
      }
      
      // Each affected method uses the helper
      @Override
      public RelNode visitRename(Rename node, CalcitePlanContext context) {
          visitChildrenWithMaterialization(node, context);
          // ... rest of rename logic
      }
  7. moved this from Not Started to Done in PPL Trackeron Mar 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

PPLbug

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions