Skip to content

Native select applies limit to the index candidate scan: skip/limit paging and IS NOT NULL silently lose rows #6565

Closed

Description

@ivan-velikanov

Version: reproduced on 26.7.3 and on 26.8.1 (latest release); root cause still present on main at 86c4338
Environment: JDK 25 (Temurin), Windows 11 x64, embedded DatabaseFactory, no server
Component: com.arcadedb.query.select — native select builder

Tagging: @robfrank @lvca

Summary

SelectExecutor.lookForIndexes() hands the query's result limit to MultiIndexCursor, which applies it to candidates read from the index. Those candidates are then reduced twice more downstream — by evaluateWhere(), and by skip — so the cap is spent before the filtering it was supposed to survive. The query returns fewer rows than match, with no error and no warning.

Two query shapes are affected, and the second one is ordinary paging.

A. A null check combined with another condition. The index covers only the other condition, so the null check runs on whatever candidates survived the cap.

db.select().fromType("T").where()
  .property("a").eq().value("x")
  .and().property("b").isNotNull()
  .limit(500).documents();           // 200 documents match; returns 101

B. skip + limit on a plain indexed equality — no null check anywhere. The candidate cap is limit, but reaching row skip+1 needs at least skip + limit candidates, so the result is short by skip, and empty whenever skip >= limit.

db.select().fromType("T").where()
  .property("a").eq().value("x")
  .skip(100).limit(50).documents();  // 1000 documents match; returns 0

.count() on that same query returns 0 as well.

The same queries through the SQL engine are all correct, so this is an inconsistency between two of ArcadeDB's own APIs rather than a limitation of the data or the schema.

Reproducer

A single self-contained jbang file — no build, no server, embedded database in a temp directory, pulls arcadedb-engine itself. Save as ArcadeDbLimitBug.java and run jbang ArcadeDbLimitBug.java. It exits 1 while the bug is present.

ArcadeDbLimitBug.java
///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS com.arcadedb:arcadedb-engine:26.8.1
//JAVA 21+

import com.arcadedb.database.Database;
import com.arcadedb.database.DatabaseFactory;
import com.arcadedb.schema.Schema;
import com.arcadedb.schema.Type;

import java.nio.file.Files;
import java.util.Iterator;

class ArcadeDbLimitBug {

    static final int ROWS = 1000, MATCHES = 200;
    static boolean reproduced = false;

    public static void main(String[] args) throws Exception {
        var dir = Files.createTempDirectory("arcadedb-limit-bug");
        try (var db = new DatabaseFactory(dir.resolve("db").toString()).create()) {
            seed(db);

            System.out.println("\nArcadeDB native select vs SQL - " + ROWS + " rows, all with a='x', exactly "
                    + MATCHES + " with b set\n");
            System.out.println("A. a null check combined with another condition, with a limit");
            System.out.printf("%-46s %-10s %-10s %s%n", "query", "native", "sql", "expected");

            for (var limit : new int[]{50, 100, 200, 500, 1000}) {
                var expected = Math.min(limit, MATCHES);
                check("a='x' AND b IS NOT NULL   limit " + limit,
                        nativeEqNotNull(db, limit),
                        sql(db, "select from T where a = 'x' and b is not null limit " + limit),
                        expected);
            }
            check("a='x' AND b IS NOT NULL   no limit",
                    nativeEqNotNull(db, -1), sql(db, "select from T where a = 'x' and b is not null"), MATCHES);

            System.out.println("\nB. skip + limit on a plain indexed equality - no null check anywhere");
            System.out.printf("%-46s %-10s %-10s %s%n", "query", "native", "sql", "expected");
            page(db, 0, 50, 50);
            page(db, 10, 50, 50);
            page(db, 100, 50, 50);
            page(db, 500, 50, 50);
            page(db, 0, 1000, 1000);
            page(db, 100, 1000, 900);
            checkCount(db);

            System.out.println("\nC. controls - every other shape pages correctly");
            System.out.printf("%-46s %-10s %-10s %s%n", "query", "native", "sql", "expected");
            check("b IS NOT NULL alone        limit 500",
                    count(db.select().fromType("T").where().property("b").isNotNull().limit(500).documents()),
                    sql(db, "select from T where b is not null limit 500"), MATCHES);
            check("a='x' AND n<200            limit 500",
                    count(db.select().fromType("T").where().property("a").eq().value("x")
                            .and().property("n").lt().value(200).limit(500).documents()),
                    sql(db, "select from T where a = 'x' and n < 200 limit 500"), MATCHES);
            check("b='set' alone              limit 500",
                    count(db.select().fromType("T").where().property("b").eq().value("set").limit(500).documents()),
                    sql(db, "select from T where b = 'set' limit 500"), MATCHES);

            System.out.println(reproduced
                    ? "\nBUG REPRODUCED: the limit is spent on index candidates, before the where clause and the skip."
                    : "\nNot reproduced on this build.");
        }
        if (reproduced) System.exit(1);
    }

    static void seed(Database db) {
        db.transaction(() -> {
            var t = db.getSchema().createDocumentType("T");
            t.createProperty("a", Type.STRING);
            t.createProperty("b", Type.STRING);
            t.createProperty("n", Type.INTEGER);
            t.createTypeIndex(Schema.INDEX_TYPE.LSM_TREE, false, "a");
            t.createTypeIndex(Schema.INDEX_TYPE.LSM_TREE, false, "b");
            t.createTypeIndex(Schema.INDEX_TYPE.LSM_TREE, false, "n");
        });
        db.transaction(() -> {
            for (var i = 0; i < ROWS; i++) {
                var d = db.newDocument("T");
                d.set("a", "x");
                d.set("n", i);
                if (i % (ROWS / MATCHES) == 0) d.set("b", "set");
                d.save();
            }
        });
    }

    static int nativeEqNotNull(Database db, int limit) {
        var after = db.select().fromType("T").where()
                .property("a").eq().value("x").and().property("b").isNotNull();
        return count(limit < 0 ? after.documents() : after.limit(limit).documents());
    }

    static void page(Database db, int skip, int limit, int expected) {
        check("a='x'   skip " + skip + " limit " + limit,
                count(db.select().fromType("T").where().property("a").eq().value("x")
                        .skip(skip).limit(limit).documents()),
                sql(db, "select from T where a = 'x' skip " + skip + " limit " + limit),
                expected);
    }

    static void checkCount(Database db) {
        var nativeCount = db.select().fromType("T").where().property("a").eq().value("x").skip(100).limit(50).count();
        if (nativeCount != 50) reproduced = true;
        System.out.printf("%-46s %-10s %-10s %-6d %s%n", "a='x'   skip 100 limit 50   .count()",
                nativeCount, 50, 50, nativeCount != 50 ? "  <-- WRONG" : "");
    }

    static int sql(Database db, String query) {
        var n = 0;
        try (var rs = db.query("sql", query)) {
            while (rs.hasNext()) { rs.next(); n++; }
        }
        return n;
    }

    static int count(Iterator<?> it) {
        var n = 0;
        while (it.hasNext()) { it.next(); n++; }
        return n;
    }

    static void check(String label, int nativeCount, int sqlCount, int expected) {
        var bad = nativeCount != expected;
        if (bad) reproduced = true;
        System.out.printf("%-46s %-10s %-10s %-6d %s%n", label, nativeCount, sqlCount, expected,
                bad ? "  <-- WRONG" : "");
    }
}

Actual vs expected

1000 documents, all with a='x', exactly 200 with b set; non-unique LSM_TREE indexes on a, b and n.

A. a null check combined with another condition, with a limit
query                                          native     sql        expected
a='x' AND b IS NOT NULL   limit 50             11         50         50       <-- WRONG
a='x' AND b IS NOT NULL   limit 100            21         100        100      <-- WRONG
a='x' AND b IS NOT NULL   limit 200            41         200        200      <-- WRONG
a='x' AND b IS NOT NULL   limit 500            101        200        200      <-- WRONG
a='x' AND b IS NOT NULL   limit 1000           200        200        200
a='x' AND b IS NOT NULL   no limit             200        200        200

B. skip + limit on a plain indexed equality - no null check anywhere
query                                          native     sql        expected
a='x'   skip 0 limit 50                        50         50         50
a='x'   skip 10 limit 50                       41         50         50       <-- WRONG
a='x'   skip 100 limit 50                      0          50         50       <-- WRONG
a='x'   skip 500 limit 50                      0          50         50       <-- WRONG
a='x'   skip 0 limit 1000                      1000       1000       1000
a='x'   skip 100 limit 1000                    900        900        900
a='x'   skip 100 limit 50   .count()           0          50         50       <-- WRONG

C. controls - every other shape pages correctly
query                                          native     sql        expected
b IS NOT NULL alone        limit 500           200        200        200
a='x' AND n<200            limit 500           200        200        200
b='set' alone              limit 500           200        200        200

Every wrong number falls out of the arithmetic below, which is what makes us think this is one defect rather than two: in A the candidate cap is limit + 1 and one candidate in five carries b, giving limit/5 + 1; in B the cap is limit + 1 candidates of which skip are consumed, giving max(0, limit + 1 - skip).

Root cause

SelectExecutor.lookForIndexes() passes select.limit straight into the cursor:

private MultiIndexCursor lookForIndexes() {
  if (select.fromType != null && select.rootTreeElement != null) {
    final List<IndexCursor> cursors = new ArrayList<>();

    // FIND AVAILABLE INDEXES
    boolean canUseIndexes = isTheNodeFullyIndexed(select.rootTreeElement);   // <-- computed, never read

    filterWithIndexes(select.rootTreeElement, cursors);
    if (!cursors.isEmpty())
      return new MultiIndexCursor(cursors, select.limit, true);              // <-- a RESULT limit used as a CANDIDATE limit
  }
  return null;
}

MultiIndexCursor.hasNext() then stops the scan after limit + 1 candidates:

if (limit > -1 && browsed > limit)
  return false;

Downstream, SelectIterator is correct on its own terms — its constructor consumes the first skip records, its hasNext() caps at skip + limit, and fetchNext() drops anything failing evaluateWhere(). That is exactly why the candidate cap is unsound: a candidate cap of select.limit is only correct when the index cursors match the predicate exactly and skip == 0, and neither condition is tested.

The unused canUseIndexes local looks like the intended guard, but as written it would not be sufficient either — isTheNodeFullyIndexed() returns true for a='x' AND b IS NOT NULL, because for an and node it returns leftIsIndexed || rightIsIndexed, i.e. "an index is usable here" rather than "the predicate is fully covered".

Suggested fix

Cap the candidate scan only where it is provably safe, and account for skip:

  • pass -1 (unbounded) whenever the index cursors do not cover the whole where-tree, i.e. whenever any conjunct will still be re-checked by evaluateWhere() — which includes every is_null / is_not_null node;
  • otherwise pass select.skip + select.limit rather than select.limit;
  • separately, browsed > limit in MultiIndexCursor.hasNext() admits one candidate more than asked for, which is where the +1 in the numbers above comes from.

We would be glad to open a PR along those lines if that is welcome — tell us which shape you would prefer for the "fully covered" test and we will follow it.

Why it matters

The failure is silent and both shapes are common. A caller gets a plausible row count and a green build. In our case a listing built as eq(...) + isNotNull(...) + limit(n) reported 111 attachments where 767 existed, and zero for a container holding thirty; the numbers were wrong but believable, so the write path got suspected first. Shape B is worse in one respect: a paged listing over an indexed equality returns nothing at all from page two onward once skip >= limit, and the same query shape driving a delete would remove the wrong subset.

Workaround

Use db.query("sql", ...) for these shapes, or drop skip/limit from the native query and bound the result in the caller.

Activity

  1. self-assigned this
    on Aug 22, 2026
  2. added theissue type on Aug 22, 2026
  3. added
    in progress
    on Aug 22, 2026
  4. added this to the 26.9.1 milestone on Aug 22, 2026
  5. removed
    in progress
    on Aug 22, 2026
  6. ivan-velikanov commented on Aug 22, 2026

    @ivan-velikanov
    Author

    That was very fast thank you. There are a few more like this, I will properly check and get back with helpful examples. Thank you.

  7. lvca commented on Aug 22, 2026

    @lvca
    Member

    Thanks @ivan-velikanov for the very detailed issue. If you have more, send them here :-D

  8. added a commit that references this issue on Aug 22, 2026
    03a8f8d
  9. added
    engine
    on Sep 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugengine

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions