Skip to content

SQL: WHERE @rid IN [list] is planned as a full type scan, so resolving k RIDs costs O(n) #5824

Closed

Description

@tae898

Summary

SELECT ... FROM <Type> WHERE @rid IN [ ... ] is planned as a full bucket scan with a per-record filter. The cost is linear in the size of the type and independent of how many RIDs are in the list.

The address-based path already exists. SELECT ... FROM [ ... ] over the same RIDs plans as FETCH FROM RIDs and is flat in type size. So this looks like a missing planner rewrite rather than a missing capability.

Measured

Java against the released arcadedb-engine-26.8.1.jar (taken from the arcadedb-embedded==26.8.1 wheel), embedded database, k = 10 RIDs, 5 warmup + 20 timed iterations per point:

docs      form                            ms/query    ms per doc  plan step
100000    WHERE @rid IN [...]                21.25      0.000213  + FETCH FROM TYPE Doc WITH FILTER ()
100000    FROM [...]                          0.10      0.000001  + FETCH FROM RIDs
400000    WHERE @rid IN [...]                82.12      0.000205  + FETCH FROM TYPE Doc WITH FILTER ()
400000    FROM [...]                          0.07      0.000000  + FETCH FROM RIDs

4x the documents:
  WHERE @rid IN [...]  3.86x the time  -> LINEAR in type size (scan)
  FROM [...]           0.74x the time  -> flat (address-based)

At 400000 docs the target form is 1143x faster.

ms per doc stays flat for the IN form across a 4x change in type size. That is the signal: the query is reading the type, not the RIDs. Both forms return the same rows, and the repro checks that before it times anything.

At scale

At 8.84M documents (9.05 GB) the engine logs its own complaint about it:

WARNI [FetchFromTypeExecutionStep] Attempt to scan type 'Doc' in database 'l3_arcade'
of total size 9.05GB 901 times. This operation is very expensive, consider using an index

Measured there, one WHERE @rid IN [10 rids] query costs about 4.7 s, steady across 900 consecutive queries (7 min 52 s per 100-query batch, repeatable within 2 s).

Why it comes up

This is the natural way to resolve the output of anything that returns RIDs. vector.sparseNeighbors and vector.neighbors both return RIDs, so the second half of a two-step vector query lands on it: the ANN half is index-backed and fast, then the resolve half reads the whole corpus.

Not a regression

Same plan and the same order of magnitude on 26.8.1.dev22, so this is long-standing behaviour rather than something that changed recently.

Workaround

Rewrite the RID list as the query target, SELECT ... FROM [#1:0, #1:1, ...], which already uses FETCH FROM RIDs.

Related

#5756 is in the same execution step but is a different defect. There the column projection push-down inside ScanWithFilterStep is unreachable. This one is about the planner choosing that step at all for a RID list.

Repro (Java, self-contained)
import com.arcadedb.database.Database;
import com.arcadedb.database.DatabaseFactory;
import com.arcadedb.database.MutableDocument;
import com.arcadedb.query.sql.executor.Result;
import com.arcadedb.query.sql.executor.ResultSet;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Companion to RidInScanRepro: is there a SQL form that resolves a RID list in
 * O(k) instead of scanning the type?
 *
 * Two forms, same k RIDs, same result, two type sizes:
 *   A. SELECT id FROM Doc WHERE @rid IN [ ... ]   the natural form
 *   B. SELECT id FROM [ ... ]                      RIDs as the query TARGET
 *
 * The interesting column is ms/query as n grows. A form that is address-based
 * is FLAT in n. A form that scans is LINEAR in n. Reporting whether a
 * workaround exists is the difference between "this is slow" and "this is slow
 * and here is what to do until it is fixed", so it belongs in the issue.
 */
public class RidInWorkaroundRepro {

  private static final int[] SIZES = { 100_000, 400_000 };
  private static final int K = 10;
  private static final int WARMUP = 5;
  private static final int TIMED = 20;

  public static void main(String[] args) {
    final List<double[]> inTimes = new ArrayList<>(), targetTimes = new ArrayList<>();

    System.out.printf("%-9s %-28s %11s %13s  %s%n",
        "docs", "form", "ms/query", "ms per doc", "plan step");

    for (final int n : SIZES) {
      final String path = "/tmp/ridwa_" + n;
      deleteTree(new File(path));

      try (final Database db = new DatabaseFactory(path).create()) {
        db.command("sql", "CREATE DOCUMENT TYPE Doc");
        db.command("sql", "CREATE PROPERTY Doc.id LONG");
        db.transaction(() -> {
          for (int i = 0; i < n; i++) {
            final MutableDocument doc = db.newDocument("Doc");
            doc.set("id", i);
            doc.save();
          }
        });

        final List<String> rids = new ArrayList<>();
        try (final ResultSet rs = db.query("sql", "SELECT @rid AS r FROM Doc LIMIT " + K)) {
          while (rs.hasNext())
            rids.add(rs.next().getProperty("r").toString());
        }
        final String list = String.join(", ", rids);

        final String qIn     = "SELECT id FROM Doc WHERE @rid IN [" + list + "]";
        final String qTarget = "SELECT id FROM [" + list + "]";

        // Both forms must return the same rows, or the timing is meaningless.
        final int nIn = count(db, qIn), nTarget = count(db, qTarget);
        if (nIn != nTarget) {
          System.out.printf("  MISMATCH at n=%d: IN returned %d rows, target returned %d%n",
              n, nIn, nTarget);
          return;
        }

        final double tIn     = time(db, qIn);
        final double tTarget = time(db, qTarget);

        System.out.printf("%-9d %-28s %11.2f %13.6f  %s%n",
            n, "WHERE @rid IN [...]", tIn, tIn / n, step(db, qIn));
        System.out.printf("%-9d %-28s %11.2f %13.6f  %s%n",
            n, "FROM [...]", tTarget, tTarget / n, step(db, qTarget));

        inTimes.add(new double[] { n, tIn });
        targetTimes.add(new double[] { n, tTarget });
      }
      deleteTree(new File(path));
    }

    final double sizeRatio = SIZES[1] / (double) SIZES[0];
    final double inRatio     = inTimes.get(1)[1]     / inTimes.get(0)[1];
    final double targetRatio = targetTimes.get(1)[1] / targetTimes.get(0)[1];

    System.out.printf("%n%.0fx the documents:%n", sizeRatio);
    System.out.printf("  WHERE @rid IN [...]  %.2fx the time  -> %s%n", inRatio,
        inRatio > sizeRatio * 0.5 ? "LINEAR in type size (scan)" : "flat (address-based)");
    System.out.printf("  FROM [...]           %.2fx the time  -> %s%n", targetRatio,
        targetRatio > sizeRatio * 0.5 ? "LINEAR in type size (scan)" : "flat (address-based)");
    System.out.printf("%nAt %d docs the target form is %.0fx faster.%n",
        SIZES[1], inTimes.get(1)[1] / targetTimes.get(1)[1]);
  }

  private static int count(final Database db, final String q) {
    int c = 0;
    try (final ResultSet rs = db.query("sql", q)) {
      while (rs.hasNext()) { rs.next(); c++; }
    }
    return c;
  }

  private static double time(final Database db, final String q) {
    for (int i = 0; i < WARMUP; i++) count(db, q);
    final long t0 = System.nanoTime();
    for (int i = 0; i < TIMED; i++) count(db, q);
    return (System.nanoTime() - t0) / 1e6 / TIMED;
  }

  /** Take the plan as Object: Result.getProperty is generic, so assigning it
   *  straight into a String makes javac insert a cast that fails with a
   *  message-less ClassCastException. */
  private static String step(final Database db, final String q) {
    try (final ResultSet rs = db.query("sql", "EXPLAIN " + q)) {
      if (!rs.hasNext()) return "?";
      final Result r = rs.next();
      Object plan = r.getProperty("executionPlanAsString");
      if (plan == null) plan = r.getProperty("executionPlan");
      if (plan == null) plan = r.toJSON();
      for (final String line : String.valueOf(plan).split("\\n"))
        if (line.contains("SCAN") || line.contains("FETCH FROM"))
          return line.trim();
      final String flat = String.valueOf(plan).replaceAll("\\s+", " ");
      return flat.substring(0, Math.min(70, flat.length()));
    }
  }

  private static void deleteTree(final File f) {
    if (!f.exists()) return;
    final File[] kids = f.listFiles();
    if (kids != null) for (final File k : kids) deleteTree(k);
    f.delete();
  }
}

Built and run against the release jars with:

pip download --no-deps --only-binary=:all: --platform manylinux_2_34_x86_64 \
    --python-version 312 arcadedb-embedded==26.8.1 -d /tmp/whl
cd /tmp/whl && unzip -q -o *.whl -d /tmp/pkg
CP="/tmp/pkg/arcadedb_embedded/jars/*"
javac -cp "$CP" -d /tmp/out RidInWorkaroundRepro.java
java --add-modules jdk.incubator.vector -cp "/tmp/out:$CP" RidInWorkaroundRepro

Activity

  1. added this to the 26.9.1 milestone on Aug 5, 2026
  2. self-assigned this
    on Aug 6, 2026
  3. added theissue type on Aug 6, 2026
  4. added a commit that references this issue on Aug 6, 2026
    6f0303b
  5. lvca commented on Aug 6, 2026

    @lvca
    Member

    Fixed, let me know if it's fast now.

  6. tae898 commented on Aug 11, 2026

    @tae898
    ContributorAuthor

    Confirmed fast, and the plan is the thing that changed.

    Same RidInScanRepro as the issue, k = 10 RIDs, 5 warmup + 20 timed iterations
    per point, embedded, compiled and run against the jars from a 26.9.1-SNAPSHOT
    build rather than a source tree, so this is what actually ships:

    docs before (26.8.1) after plan step
    100,000 21.25 ms 0.20 ms + FETCH FROM RIDs
    400,000 82.12 ms 0.14 ms + FETCH FROM RIDs

    The plan step is now FETCH FROM RIDs instead of FETCH FROM TYPE Doc WITH FILTER (), which is exactly the rewrite the issue was asking for. The cost is
    flat in type size: 4x the documents cost 0.68x the time, so the remaining
    variation is noise rather than scan work. That also closes the gap with the
    SELECT ... FROM [ ... ] form, which was the address-based path all along.

    One scoping note so the number is not read as broader than it is: this
    measures literal RID lists. It says nothing about the parameterized form
    you flagged in #5855, and my harness would not have caught that, since it
    inlines the RIDs. Worth keeping the two apart when that one is looked at.

    Thanks for the quick turnaround on this.

  7. added 2 commits that reference this issue on Sep 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions