You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@asterixdb.apache.org by mh...@apache.org on 2026/08/10 18:13:18 UTC

(asterixdb) branch master updated: [ASTERIXDB-3771][COMP] Fix ANN top-k projection collision with meta()

This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/asterixdb.git


The following commit(s) were added to refs/heads/master by this push:
     new f5d90d5649 [ASTERIXDB-3771][COMP] Fix ANN top-k projection collision with meta()
f5d90d5649 is described below

commit f5d90d564944b93f938f23a9adaf3809daa8cb00
Author: Murtadha Hubail <mu...@couchbase.com>
AuthorDate: Mon Aug 10 17:18:19 2026 +0300

    [ASTERIXDB-3771][COMP] Fix ANN top-k projection collision with meta()
    
    - user model changes: no
    - storage format changes: no
    - interface changes: no
    
    The vector-index-only fast path for ORDER BY ann_distance(...) LIMIT k
    queries decided whether a projected field-access was PK-safe (and
    could therefore be substituted with the vector index's PK variable)
    by field NAME alone, never checking whether that PK is sourced from
    the data record or from meta(). When a dataset declared PRIMARY KEY
    (id) ON META() and the record itself also had its own unrelated field
    named "id", a query projecting the record's own "id" got it silently
    rewritten to the vector index's PK variable, so it returned meta().id
    instead of the record's own field.
    
    IntroduceTopKAccessMethodRule.isProjectionPkOnly() and
    VectorIndexAccessMethod.createIndexSearchPlan() now consult
    DatasetUtil.getKeySourceIndicators() and match a field-access target
    only against the record it is actually sourced from (data record vs.
    meta record), the same way AbstractIntroduceAccessMethodRule already
    does for BTree/RTree secondary indexes.
    
    Added create-index-vtree-meta-pk, a regression covering a meta()-
    sourced PK colliding in name with an undeclared (open) record field.
    
    Ex-ref: MB-73218
    Co-Authored-By: Claude Opus 5 <no...@anthropic.com>
    Change-Id: I3e8dcfdb87863674e4325dc7707ff410297919de
    Reviewed-on: https://asterix-gerrit.ics.uci.edu/c/asterixdb/+/21532
    Reviewed-by: Ali Alsuliman <al...@gmail.com>
    Integration-Tests: Jenkins <je...@fulliautomatix.ics.uci.edu>
    Tested-by: Jenkins <je...@fulliautomatix.ics.uci.edu>
---
 .../rules/am/IntroduceTopKAccessMethodRule.java    | 91 ++++++++++++++++------
 .../rules/am/VectorIndexAccessMethod.java          | 62 +++++++++------
 asterixdb/asterix-app/data/csv/vector-meta-pk.csv  | 12 +++
 .../queries_sqlpp/vector/VectorQueries.xml         |  5 ++
 .../create-index-vtree-meta-pk.1.ddl.sqlpp         | 59 ++++++++++++++
 .../create-index-vtree-meta-pk.2.update.sqlpp      | 24 ++++++
 .../create-index-vtree-meta-pk.3.ddl.sqlpp         | 22 ++++++
 .../create-index-vtree-meta-pk.4.ddl.sqlpp         | 29 +++++++
 .../create-index-vtree-meta-pk.5.query.sqlpp       | 29 +++++++
 .../create-index-vtree-meta-pk.6.query.sqlpp       | 29 +++++++
 .../create-index-vtree-meta-pk.7.plans.sqlpp       | 30 +++++++
 .../create-index-vtree-meta-pk.99.ddl.sqlpp        | 20 +++++
 .../create-index-vtree-meta-pk.5.adm               |  3 +
 .../create-index-vtree-meta-pk.6.adm               |  3 +
 .../create-index-vtree-meta-pk.7.regex             |  1 +
 15 files changed, 373 insertions(+), 46 deletions(-)

diff --git a/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/am/IntroduceTopKAccessMethodRule.java b/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/am/IntroduceTopKAccessMethodRule.java
index e455772f70..93f8c12c1b 100644
--- a/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/am/IntroduceTopKAccessMethodRule.java
+++ b/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/am/IntroduceTopKAccessMethodRule.java
@@ -32,6 +32,7 @@ import org.apache.asterix.common.config.DatasetConfig.IndexType;
 import org.apache.asterix.metadata.declared.IIndexProvider;
 import org.apache.asterix.metadata.declared.MetadataProvider;
 import org.apache.asterix.metadata.entities.Index;
+import org.apache.asterix.metadata.utils.DatasetUtil;
 import org.apache.asterix.om.base.AString;
 import org.apache.asterix.om.base.IAObject;
 import org.apache.asterix.om.constants.AsterixConstantValue;
@@ -791,12 +792,13 @@ public class IntroduceTopKAccessMethodRule extends AbstractIntroduceAccessMethod
      *       in {@link #aboveLimitOps}.</li>
      *   <li>For each live-out variable, trace through the bindings: it is PK-safe iff it resolves to a
      *       PK variable, a constant, or a {@code field-access-by-name($$rec, f)} where {@code f} is the
-     *       (top-level, single-segment) name of a PK column. If any live-out variable fails the trace,
-     *       the optimization cannot be safely applied.</li>
+     *       (top-level, single-segment) name of a PK column sourced from the SAME record ($$rec being the
+     *       dataset record or the meta record) that the PK column is actually declared on. If any live-out
+     *       variable fails the trace, the optimization cannot be safely applied.</li>
      * </ol>
      *
-     * <p>Conservatively returns {@code false} for any dataset with a meta record (currently out of
-     * scope), composite PK paths, external data sources, or unfamiliar plan shapes.
+     * <p>Conservatively returns {@code false} for composite or nested PK paths, external data sources, or
+     * unfamiliar plan shapes.
      */
     protected boolean isProjectionPkOnly() {
         // Index-only skips the primary BTree lookup and emits (pk, dist) straight from the secondary VTree.
@@ -818,14 +820,20 @@ public class IntroduceTopKAccessMethodRule extends AbstractIntroduceAccessMethod
         List<LogicalVariable> dsVars = dataSourceOp.getVariables();
 
         // PK fields: only support top-level single-segment paths (e.g. ["id"]); composite or nested PK
-        // paths are out of scope for the initial activation.
+        // paths are out of scope for the initial activation. Split PK field names by their key source
+        // (data record vs. meta record) so a PK sourced from meta() named "id" is never confused with an
+        // unrelated data-record field that happens to share the same name.
         List<List<String>> pkPaths = subTree.getDataset().getPrimaryKeys();
-        Set<String> pkFieldNames = new HashSet<>();
-        for (List<String> p : pkPaths) {
+        List<Integer> keySourceIndicators = DatasetUtil.getKeySourceIndicators(subTree.getDataset());
+        Set<String> recordPkFieldNames = new HashSet<>();
+        Set<String> metaPkFieldNames = new HashSet<>();
+        for (int i = 0; i < pkPaths.size(); i++) {
+            List<String> p = pkPaths.get(i);
             if (p == null || p.size() != 1) {
                 return false;
             }
-            pkFieldNames.add(p.get(0));
+            boolean fromMeta = keySourceIndicators != null && keySourceIndicators.get(i) == 1;
+            (fromMeta ? metaPkFieldNames : recordPkFieldNames).add(p.get(0));
         }
         int numPK = pkPaths.size();
         if (dsVars.size() < numPK + 1) {
@@ -833,8 +841,13 @@ public class IntroduceTopKAccessMethodRule extends AbstractIntroduceAccessMethod
         }
         Set<LogicalVariable> pkVars = new HashSet<>(dsVars.subList(0, numPK));
         // Anything after PKs is the dataset record (+ optional meta record). Direct references to these
-        // mean we need the assembled record; only field-access for PK names is OK.
+        // mean we need the assembled record; only field-access for PK names is OK, and only against the
+        // record that field's PK is actually sourced from.
         Set<LogicalVariable> recordVars = new HashSet<>(dsVars.subList(numPK, dsVars.size()));
+        LogicalVariable dataRecordVar = dsVars.get(numPK);
+        LogicalVariable metaRecordVar = dsVars.size() > numPK + 1 ? dsVars.get(numPK + 1) : null;
+        PkFieldContext pkCtx = new PkFieldContext(pkVars, recordVars, dataRecordVar, metaRecordVar, recordPkFieldNames,
+                metaPkFieldNames);
 
         // Collect ASSIGN bindings throughout the entire subtree.
         Map<LogicalVariable, ILogicalExpression> bindings = new HashMap<>();
@@ -853,7 +866,7 @@ public class IntroduceTopKAccessMethodRule extends AbstractIntroduceAccessMethod
         // Trace each live-out variable; fail on the first non-PK-derived one.
         Set<LogicalVariable> visiting = new HashSet<>();
         for (LogicalVariable v : liveOut) {
-            if (!isVarPkSafe(v, bindings, pkVars, recordVars, pkFieldNames, visiting)) {
+            if (!isVarPkSafe(v, bindings, pkCtx, visiting)) {
                 LOGGER.trace("isProjectionPkOnly: live-out variable {} is not PK-derived; bailing", v);
                 return false;
             }
@@ -869,7 +882,7 @@ public class IntroduceTopKAccessMethodRule extends AbstractIntroduceAccessMethod
         Set<LogicalVariable> filterVars = new HashSet<>();
         collectSelectConditionVars(subTree.getRoot(), filterVars);
         for (LogicalVariable v : filterVars) {
-            if (!isVarPkSafe(v, bindings, pkVars, recordVars, pkFieldNames, visiting)) {
+            if (!isVarPkSafe(v, bindings, pkCtx, visiting)) {
                 LOGGER.trace("isProjectionPkOnly: WHERE condition var {} is not PK-safe; not index-only", v);
                 return false;
             }
@@ -877,6 +890,33 @@ public class IntroduceTopKAccessMethodRule extends AbstractIntroduceAccessMethod
         return true;
     }
 
+    /**
+     * Groups the pieces {@link #isVarPkSafe} and {@link #isExprPkSafe} need to decide whether a
+     * {@code field-access-by-name} target is PK-safe: the data-source PK variables, the combined
+     * record/meta "direct use" variables, the data-record and meta-record variables individually, and the
+     * PK field names declared on each of those two records (kept separate so a same-named field on the
+     * "wrong" record — e.g. a data-record field called "id" next to a {@code meta().id} PK — is never
+     * treated as PK-safe).
+     */
+    private static final class PkFieldContext {
+        final Set<LogicalVariable> pkVars;
+        final Set<LogicalVariable> recordVars;
+        final LogicalVariable dataRecordVar;
+        final LogicalVariable metaRecordVar;
+        final Set<String> recordPkFieldNames;
+        final Set<String> metaPkFieldNames;
+
+        PkFieldContext(Set<LogicalVariable> pkVars, Set<LogicalVariable> recordVars, LogicalVariable dataRecordVar,
+                LogicalVariable metaRecordVar, Set<String> recordPkFieldNames, Set<String> metaPkFieldNames) {
+            this.pkVars = pkVars;
+            this.recordVars = recordVars;
+            this.dataRecordVar = dataRecordVar;
+            this.metaRecordVar = metaRecordVar;
+            this.recordPkFieldNames = recordPkFieldNames;
+            this.metaPkFieldNames = metaPkFieldNames;
+        }
+    }
+
     /**
      * Collect the variables used in every {@code SELECT} condition in the subtree (below the LIMIT). Used by
      * {@link #isProjectionPkOnly} to reject the index-only plan when a {@code WHERE} needs a non-PK record
@@ -921,12 +961,11 @@ public class IntroduceTopKAccessMethodRule extends AbstractIntroduceAccessMethod
     }
 
     private boolean isVarPkSafe(LogicalVariable v, Map<LogicalVariable, ILogicalExpression> bindings,
-            Set<LogicalVariable> pkVars, Set<LogicalVariable> recordVars, Set<String> pkFieldNames,
-            Set<LogicalVariable> visiting) {
-        if (pkVars.contains(v)) {
+            PkFieldContext pkCtx, Set<LogicalVariable> visiting) {
+        if (pkCtx.pkVars.contains(v)) {
             return true;
         }
-        if (recordVars.contains(v)) {
+        if (pkCtx.recordVars.contains(v)) {
             // Direct use of the dataset record — requires the assembled record. Not safe.
             return false;
         }
@@ -941,40 +980,44 @@ public class IntroduceTopKAccessMethodRule extends AbstractIntroduceAccessMethod
                 // don't track). Be conservative.
                 return false;
             }
-            return isExprPkSafe(e, bindings, pkVars, recordVars, pkFieldNames, visiting);
+            return isExprPkSafe(e, bindings, pkCtx, visiting);
         } finally {
             visiting.remove(v);
         }
     }
 
     private boolean isExprPkSafe(ILogicalExpression e, Map<LogicalVariable, ILogicalExpression> bindings,
-            Set<LogicalVariable> pkVars, Set<LogicalVariable> recordVars, Set<String> pkFieldNames,
-            Set<LogicalVariable> visiting) {
+            PkFieldContext pkCtx, Set<LogicalVariable> visiting) {
         switch (e.getExpressionTag()) {
             case CONSTANT:
                 return true;
             case VARIABLE:
-                return isVarPkSafe(((VariableReferenceExpression) e).getVariableReference(), bindings, pkVars,
-                        recordVars, pkFieldNames, visiting);
+                return isVarPkSafe(((VariableReferenceExpression) e).getVariableReference(), bindings, pkCtx, visiting);
             case FUNCTION_CALL: {
                 AbstractFunctionCallExpression fce = (AbstractFunctionCallExpression) e;
                 FunctionIdentifier fid = fce.getFunctionIdentifier();
-                // Special-case field access on the record variable: PK fields only.
+                // Special-case field access on the record/meta variable: PK fields sourced from that SAME
+                // record only. A PK field name that collides with an unrelated field on the OTHER record
+                // (e.g. a data-record field "id" next to a meta()-sourced PK also named "id") must not be
+                // treated as PK-safe here — only field-access on the record the PK is actually declared on
+                // is a safe substitute.
                 if (BuiltinFunctions.FIELD_ACCESS_BY_NAME.equals(fid) && fce.getArguments().size() == 2) {
                     ILogicalExpression a0 = fce.getArguments().get(0).getValue();
                     ILogicalExpression a1 = fce.getArguments().get(1).getValue();
                     if (a0.getExpressionTag() == LogicalExpressionTag.VARIABLE
                             && a1.getExpressionTag() == LogicalExpressionTag.CONSTANT) {
                         LogicalVariable target = ((VariableReferenceExpression) a0).getVariableReference();
-                        if (recordVars.contains(target)) {
+                        if (target.equals(pkCtx.dataRecordVar) || target.equals(pkCtx.metaRecordVar)) {
                             String fieldName = extractStringConstant(a1);
-                            return fieldName != null && pkFieldNames.contains(fieldName);
+                            Set<String> allowedNames = target.equals(pkCtx.dataRecordVar) ? pkCtx.recordPkFieldNames
+                                    : pkCtx.metaPkFieldNames;
+                            return fieldName != null && allowedNames.contains(fieldName);
                         }
                     }
                 }
                 // For any other function call: all argument expressions must be PK-safe.
                 for (Mutable<ILogicalExpression> arg : fce.getArguments()) {
-                    if (!isExprPkSafe(arg.getValue(), bindings, pkVars, recordVars, pkFieldNames, visiting)) {
+                    if (!isExprPkSafe(arg.getValue(), bindings, pkCtx, visiting)) {
                         return false;
                     }
                 }
diff --git a/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/am/VectorIndexAccessMethod.java b/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/am/VectorIndexAccessMethod.java
index 503c74c334..961ebe8037 100644
--- a/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/am/VectorIndexAccessMethod.java
+++ b/asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/am/VectorIndexAccessMethod.java
@@ -33,6 +33,7 @@ import org.apache.asterix.common.config.DatasetConfig.IndexType;
 import org.apache.asterix.common.vector.VectorSimilarityMetric;
 import org.apache.asterix.metadata.entities.Dataset;
 import org.apache.asterix.metadata.entities.Index;
+import org.apache.asterix.metadata.utils.DatasetUtil;
 import org.apache.asterix.object.base.AdmObjectNode;
 import org.apache.asterix.om.base.ADouble;
 import org.apache.asterix.om.base.AInt32;
@@ -370,17 +371,25 @@ public class VectorIndexAccessMethod implements IAccessMethod {
                 for (int i = 0; i < numPK; i++) {
                     pkSubstitution.put(oldVars.get(i), newPkVars.get(i));
                 }
-                // The record variable (and meta record var, if present) — we rewrite
-                // field-access($$rec, "<pk_field>") to VarRef($$pk_new) below.
+                // The record variable and, if present, the meta record variable — we rewrite
+                // field-access($$rec, "<pk_field>") / field-access($$meta, "<pk_field>") to
+                // VarRef($$pk_new) below, keeping the two separate so a PK field name that collides
+                // with an unrelated field on the OTHER record (e.g. a data-record field "id" next to a
+                // meta()-sourced PK also named "id") is never substituted on the wrong record.
                 LogicalVariable oldRecVar = numPK < oldVars.size() ? oldVars.get(numPK) : null;
+                LogicalVariable oldMetaVar = numPK + 1 < oldVars.size() ? oldVars.get(numPK + 1) : null;
 
-                // Map PK field name -> new PK variable.
-                Map<String, LogicalVariable> pkFieldToNewVar = new java.util.HashMap<>();
+                // Map PK field name -> new PK variable, split by the record the PK field is actually
+                // sourced from (0 = data record, 1 = meta record).
+                List<Integer> keySourceIndicators = DatasetUtil.getKeySourceIndicators(dataset);
+                Map<String, LogicalVariable> recordPkFieldToNewVar = new java.util.HashMap<>();
+                Map<String, LogicalVariable> metaPkFieldToNewVar = new java.util.HashMap<>();
                 List<List<String>> pkPaths = dataset.getPrimaryKeys();
                 for (int i = 0; i < numPK; i++) {
                     List<String> p = pkPaths.get(i);
                     if (p != null && p.size() == 1) {
-                        pkFieldToNewVar.put(p.get(0), newPkVars.get(i));
+                        boolean fromMeta = keySourceIndicators != null && keySourceIndicators.get(i) == 1;
+                        (fromMeta ? metaPkFieldToNewVar : recordPkFieldToNewVar).put(p.get(0), newPkVars.get(i));
                     }
                 }
 
@@ -397,20 +406,30 @@ public class VectorIndexAccessMethod implements IAccessMethod {
                 org.apache.hyracks.algebricks.core.algebra.operators.logical.visitors.VariableUtilities
                         .substituteVariablesInDescendantsAndSelf(rewriteRoot, pkSubstitution, context);
 
-                // 2. Rewrite field-access on the old record var to direct PK VarRefs (e.g. the
-                //    SELECT VALUE m.idx projection above LIMIT).
+                // 2. Rewrite field-access on the old record/meta vars to direct PK VarRefs (e.g. the
+                //    SELECT VALUE m.idx projection above LIMIT), each against only its own PK fields.
                 if (oldRecVar != null) {
-                    rewriteRecordFieldAccessToPk(rewriteRoot, oldRecVar, pkFieldToNewVar);
+                    rewriteRecordFieldAccessToPk(rewriteRoot, oldRecVar, recordPkFieldToNewVar);
+                }
+                if (oldMetaVar != null) {
+                    rewriteRecordFieldAccessToPk(rewriteRoot, oldMetaVar, metaPkFieldToNewVar);
                 }
 
-                // 3. Any remaining ASSIGN expression that still references oldRecVar (transitively) —
-                // for example $$x := $$m.getField("embedding") hoisted by the SQL++ compiler out of
-                // ann_distance(m.embedding, ...) — is now structurally orphaned: no operator above
-                // LIMIT consumes it (we wouldn't have entered the index-only branch otherwise) but the
-                // type system still walks it. Replace each such expression with MISSING so it types
-                // cleanly. None of these values is ever read at runtime.
+                // 3. Any remaining ASSIGN expression that still references oldRecVar/oldMetaVar
+                // (transitively) — for example $$x := $$m.getField("embedding") hoisted by the SQL++
+                // compiler out of ann_distance(m.embedding, ...) — is now structurally orphaned: no
+                // operator above LIMIT consumes it (we wouldn't have entered the index-only branch
+                // otherwise) but the type system still walks it. Replace each such expression with
+                // MISSING so it types cleanly. None of these values is ever read at runtime.
+                List<LogicalVariable> deadRecordVars = new ArrayList<>();
                 if (oldRecVar != null) {
-                    neutralizeDanglingExpressions(rewriteRoot, oldRecVar);
+                    deadRecordVars.add(oldRecVar);
+                }
+                if (oldMetaVar != null) {
+                    deadRecordVars.add(oldMetaVar);
+                }
+                if (!deadRecordVars.isEmpty()) {
+                    neutralizeDanglingExpressions(rewriteRoot, deadRecordVars);
                 }
 
                 // Recompute type env bottom-up over every operator whose schema/expressions changed:
@@ -695,16 +714,15 @@ public class VectorIndexAccessMethod implements IAccessMethod {
 
     /**
      * Replace any ASSIGN expression whose subtree (transitively) mentions a dead variable with a MISSING
-     * constant. Seeded with the now-gone dataset record variable; the closure grows to include every
-     * variable whose defining ASSIGN we neutralize, so chains such as
-     * {@code $$237 := field-access($$rec, "embedding")} → {@code $$dist := ann_distance($$237, ...)} are
-     * fully repaired (the second ASSIGN references {@code $$237}, not {@code $$rec} directly, and would
+     * constant. Seeded with the now-gone dataset record variable(s) (data record and, if present, meta
+     * record); the closure grows to include every variable whose defining ASSIGN we neutralize, so chains
+     * such as {@code $$237 := field-access($$rec, "embedding")} → {@code $$dist := ann_distance($$237, ...)}
+     * are fully repaired (the second ASSIGN references {@code $$237}, not {@code $$rec} directly, and would
      * otherwise dangle and fail type inference). The live-out check guarantees nothing above LIMIT depends
      * on these values, but the type system still walks them.
      */
-    private static void neutralizeDanglingExpressions(ILogicalOperator root, LogicalVariable oldRecVar) {
-        Set<LogicalVariable> dead = new java.util.HashSet<>();
-        dead.add(oldRecVar);
+    private static void neutralizeDanglingExpressions(ILogicalOperator root, List<LogicalVariable> oldRecordVars) {
+        Set<LogicalVariable> dead = new java.util.HashSet<>(oldRecordVars);
         // Iterate to a fixpoint: each pass may neutralize an ASSIGN whose variable then feeds the next.
         while (neutralizeDeadPass(root, dead)) {
             // keep going until no new variable becomes dead
diff --git a/asterixdb/asterix-app/data/csv/vector-meta-pk.csv b/asterixdb/asterix-app/data/csv/vector-meta-pk.csv
new file mode 100644
index 0000000000..c110b16b1f
--- /dev/null
+++ b/asterixdb/asterix-app/data/csv/vector-meta-pk.csv
@@ -0,0 +1,12 @@
+901,"{""id"":1, ""embedding"":[0.0, 0.0, 0.0, 0.1]}"
+902,"{""id"":2, ""embedding"":[0.0, 0.0, 0.0, 0.2]}"
+903,"{""id"":3, ""embedding"":[0.0, 0.0, 0.0, 0.3]}"
+904,"{""id"":4, ""embedding"":[0.0, 0.0, 0.0, 0.4]}"
+905,"{""id"":5, ""embedding"":[0.0, 0.0, 0.0, 0.5]}"
+906,"{""id"":6, ""embedding"":[0.0, 0.0, 0.0, 0.6]}"
+907,"{""id"":7, ""embedding"":[10.0, 10.0, 10.0, 0.1]}"
+908,"{""id"":8, ""embedding"":[10.0, 10.0, 10.0, 0.2]}"
+909,"{""id"":9, ""embedding"":[10.0, 10.0, 10.0, 0.3]}"
+910,"{""id"":10, ""embedding"":[10.0, 10.0, 10.0, 0.4]}"
+911,"{""id"":11, ""embedding"":[10.0, 10.0, 10.0, 0.5]}"
+912,"{""id"":12, ""embedding"":[10.0, 10.0, 10.0, 0.6]}"
\ No newline at end of file
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/VectorQueries.xml b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/VectorQueries.xml
index 5cfb9f8b73..e9bb00fe5e 100644
--- a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/VectorQueries.xml
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/VectorQueries.xml
@@ -27,6 +27,11 @@
             <output-dir compare="Clean-JSON">create-index-vtree</output-dir>
         </compilation-unit>
     </test-case>
+    <test-case FilePath="vector">
+        <compilation-unit name="create-index-vtree-meta-pk">
+            <output-dir compare="Clean-JSON">create-index-vtree-meta-pk</output-dir>
+        </compilation-unit>
+    </test-case>
     <test-case FilePath="vector">
         <compilation-unit name="create-index-vtree-nested">
             <output-dir compare="Clean-JSON">create-index-vtree-nested</output-dir>
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.1.ddl.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.1.ddl.sqlpp
new file mode 100644
index 0000000000..95328b10d1
--- /dev/null
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.1.ddl.sqlpp
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+// Regression for a VTREE index-only plan bug: the dataset's primary key is sourced from META()
+// and named "id", while the data record ALSO has its own unrelated field named "id". The two must
+// never be confused when the vector-index-only optimization decides which projections are PK-safe.
+
+DROP DATAVERSE test IF EXISTS;
+CREATE DATAVERSE test;
+USE test;
+
+// 'id' is deliberately left UNDECLARED (the type is OPEN): a declared field would get devirtualized
+// to positional field-access-by-index by an earlier rewrite rule, which would never reach the
+// field-access-by-name check this regression targets. Leaving it open keeps m.id as a genuine
+// field-access-by-name all the way to IntroduceTopKAccessMethodRule.
+CREATE TYPE VecType AS OPEN {
+  embedding: [double]
+};
+
+CREATE TYPE VecMetaType AS {
+  id: int
+};
+
+CREATE DATASET VecMeta(VecType) WITH META(VecMetaType)
+PRIMARY KEY META().id;
+
+// Datasets with a meta part cannot be populated via INSERT/LOAD/COPY; a feed is required to set a
+// literal meta id per record. Column 0 of the CSV is the meta id, column 1 is the escaped record.
+CREATE FEED VecMetaStream WITH {
+ "adapter-name" : "localfs",
+ "reader" : "localfs",
+ "parser" : "record-with-metadata",
+ "type-name" : "VecType",
+ "meta-type-name" : "VecMetaType",
+ "path" : "asterix_nc1://data/csv/vector-meta-pk.csv",
+ "format" : "csv",
+ "delimiter" : ",",
+ "record-format" : "adm",
+ "record-index" : "1",
+ "key-indexes" : "0",
+ "key-indicators" : "1",
+ "header" : "false"
+};
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.2.update.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.2.update.sqlpp
new file mode 100644
index 0000000000..c12a399eaa
--- /dev/null
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.2.update.sqlpp
@@ -0,0 +1,24 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+USE test;
+
+SET `wait-for-completion-feed` "true";
+CONNECT FEED VecMetaStream TO DATASET VecMeta;
+START FEED VecMetaStream;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.3.ddl.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.3.ddl.sqlpp
new file mode 100644
index 0000000000..9305266828
--- /dev/null
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.3.ddl.sqlpp
@@ -0,0 +1,22 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+// A sample index is required before creating a vector index (quantization training
+// scans it in Job 1). Fixed sample-seed keeps the sample deterministic.
+ANALYZE DATASET test.VecMeta WITH {"sample-seed": 1000};
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.4.ddl.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.4.ddl.sqlpp
new file mode 100644
index 0000000000..e2300f29c9
--- /dev/null
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.4.ddl.sqlpp
@@ -0,0 +1,29 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+USE test;
+
+// Pin the k-means training RNG so index creation is reproducible run-to-run.
+SET `compiler.vector.trainseed` "42";
+
+CREATE INDEX idx_emb
+  ON VecMeta(embedding VECTOR)
+  TYPE VTREE
+  WITH { "dimension": 4, "similarity": "euclidean", "num_clusters": 2, "train_list_fraction": 1.0 }
+  EXCLUDE UNKNOWN KEY;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.5.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.5.query.sqlpp
new file mode 100644
index 0000000000..fa92fbfeef
--- /dev/null
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.5.query.sqlpp
@@ -0,0 +1,29 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/*
+ * Description: the dataset's primary key is meta().id, but the record ALSO has its own unrelated
+ * field named "id". This must return the RECORD's "id" (1, 2, 3), not the meta id (901, 902, 903).
+ */
+
+USE test;
+
+SELECT VALUE m.id
+FROM VecMeta m
+ORDER BY ann_distance(m.embedding, [0.0, 0.0, 0.0, 0.0], "euclidean", 1.0)
+LIMIT 3;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.6.query.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.6.query.sqlpp
new file mode 100644
index 0000000000..e08bab2d95
--- /dev/null
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.6.query.sqlpp
@@ -0,0 +1,29 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/*
+ * Description: sanity check that meta().id (the actual PK) still resolves correctly (901, 902, 903)
+ * and is unaffected by the fix to the "id" collision case in step 5.
+ */
+
+USE test;
+
+SELECT VALUE meta(m).id
+FROM VecMeta m
+ORDER BY ann_distance(m.embedding, [0.0, 0.0, 0.0, 0.0], "euclidean", 1.0)
+LIMIT 3;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.7.plans.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.7.plans.sqlpp
new file mode 100644
index 0000000000..7ee3229821
--- /dev/null
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.7.plans.sqlpp
@@ -0,0 +1,30 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+-- param compile-only:string=true
+-- param optimized-logical-plan:string=true
+
+// Even though "id" collides in name with the meta()-sourced PK, the plan must still use the vector
+// index (idx_emb); it just cannot safely take the index-only shortcut for this projection, so it
+// falls back to lookup-and-rerank instead. Either way idx_emb must appear, confirming step 5's
+// correctness check actually exercises the vector-index code path rather than a full scan.
+SELECT VALUE m.id
+FROM test.VecMeta m
+ORDER BY ann_distance(m.embedding, [0.0, 0.0, 0.0, 0.0], "euclidean", 1.0)
+LIMIT 3;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.99.ddl.sqlpp b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.99.ddl.sqlpp
new file mode 100644
index 0000000000..20dc6fde5e
--- /dev/null
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.99.ddl.sqlpp
@@ -0,0 +1,20 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+DROP DATAVERSE test IF EXISTS;
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.5.adm b/asterixdb/asterix-app/src/test/resources/runtimets/results/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.5.adm
new file mode 100644
index 0000000000..01e79c32a8
--- /dev/null
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.5.adm
@@ -0,0 +1,3 @@
+1
+2
+3
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.6.adm b/asterixdb/asterix-app/src/test/resources/runtimets/results/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.6.adm
new file mode 100644
index 0000000000..97c87f0a3c
--- /dev/null
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.6.adm
@@ -0,0 +1,3 @@
+901
+902
+903
diff --git a/asterixdb/asterix-app/src/test/resources/runtimets/results/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.7.regex b/asterixdb/asterix-app/src/test/resources/runtimets/results/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.7.regex
new file mode 100644
index 0000000000..2641d57116
--- /dev/null
+++ b/asterixdb/asterix-app/src/test/resources/runtimets/results/vector/create-index-vtree-meta-pk/create-index-vtree-meta-pk.7.regex
@@ -0,0 +1 @@
+/(?s).*idx_emb.*/
\ No newline at end of file