Skip to content

Full-scan GROUP BY spends most of its time on per-record overhead: BucketIterator looks each record up two more times, and aggregate() rebuilds the default alias per record #8260

Closed

Description

@tae898

Summary

A full-scan GROUP BY over 6M documents takes about 4 s on ArcadeDB where SQLite and MongoDB answer the same query in 1.3 to 1.6 s. All three scan on one thread here. Profiling points at per-record overhead rather than data volume: a type with one property scans as slowly as a type with nine. I found three sources on the scan path and prototyped fixes for two of them. Together they took 16% to 25% off the GROUP BY on Java 21 and 19% to 24% on Java 25. Details, measurements, and the lines involved are below. I have not run your test suite against either prototype.

Where it shows up

In my benchmark (TPC-H SF1, lineitem as 6,001,215 documents, one type with the default single bucket), this query is identical text on ArcadeDB and SQLite:

SELECT l_shipmode, count(*) AS n FROM LineItem GROUP BY l_shipmode ORDER BY l_shipmode
engine median of 5 runs
ArcadeDB embedded, 417314c18 (26.10.1-SNAPSHOT), Corretto 25 + COH 4,041 ms (3,997 to 4,064)
ArcadeDB server, same build 4,261 ms
SQLite 3.46.1 1,574 ms
MongoDB 8.2.12 ($group) 1,310 ms

Each engine ran alone on the same host with the same 12 CPUs. The result is 7 rows, so result handling costs nothing, and no index is involved. The benchmark drives the embedded engine from Python, but with 7 result rows the wrapper has nothing to do, and the Java repro below shows the same shape with no Python at all. On all five of the benchmark's analytical queries ArcadeDB is behind SQLite, by 2.0x to 3.8x, and this is the simplest of them.

Reproduction

One file, engine jars only: GroupByScanRepro.java, in the details block at the end. It loads 3,000,000 TPC-H-shaped LineItem documents with the nine properties above, and a second Narrow type with only l_shipmode, then times the same count five ways after one warm-up, median of 5. Every answer is checked against the Java-API count.

Laptop, Intel Core Ultra X9 388H pinned to its 4 P-cores, -Xmx8g, database on NVMe (ext4). 26.8.1 is 727aa4568c, main is cbd0947c18. Temurin 21.0.12, and Temurin 25.0.4 with -XX:+UseCompactObjectHeaders (COH), which is what I run in production:

path (3,000,000 records) 26.8.1, Java 21 main, Java 21 26.8.1, Java 25 + COH main, Java 25 + COH
iterateType only, no property read 1,367 ms 1,380 ms 1,291 ms 1,421 ms
iterateType + getString("l_shipmode") + HashMap, 9 properties 3,428 ms 3,249 ms 3,266 ms 3,513 ms
same, 1 property 3,399 ms 3,328 ms 3,167 ms 3,442 ms
SQL GROUP BY l_shipmode, count(*), 9 properties 5,987 ms 5,456 ms 5,135 ms 5,427 ms
SQL same, 1 property 5,677 ms 5,313 ms 4,983 ms 5,501 ms
SQL count(*) WHERE l_quantity >= 0 (forces a scan) 4,462 ms 4,107 ms 3,977 ms 4,259 ms

Two things stand out. The 1-property type costs the same as the 9-property one, so the time is per record, not per byte. And the SQL GROUP BY takes 1.5x to 1.8x the plain Java loop over the same records.

1. BucketIterator.fetchNext() looks each record up two more times

fetchNext() already holds currentPage and has read the record's slot position and size marker from it. Then, per record:

  • BucketIterator.java:205 calls bucket.existsRecord(rid), which calls readRecordSizeMarker(rid): a new PageId, a page-manager lookup (ConcurrentHashMap.get), and the size marker read again, from the page the iterator already holds. It also runs checkPermissionsOnFile, which looks up the DatabaseContext by path.
  • BucketIterator.java:209 calls lookupByRID(rid, false). Under the default READ_COMMITTED that returns a record without content (LocalDatabase.java:1008).
  • The first property read then calls ImmutableDocument.checkForLazyLoading(), which fetches the record by RID a third time (ImmutableDocument.java:286: getBucketById(...).getRecord(rid), with the same permission check and page lookup again) and copies the bytes.

In a JFR profile of the Java loop, PageManager.getCachedPage is 21% of samples, ConcurrentHashMap.get 25% (self), checkForLazyLoading 15%, and DatabaseContext.getContextIfExists 17%.

Two prototypes, each a patched copy of BucketIterator put ahead of the engine jar on the classpath:

  • A: skip existsRecord(rid) when recordSize[0] > 0. The marker read from currentPage a few lines above already says the record is live and in-page. It keeps the call for FIRST_CHUNK.
  • B: A, plus lookupByRID(rid, true), so the content is read in the same pass.

Temurin 21, run order original, A, B, B, A, original; each cell is both runs' medians:

path original A B
iterateType only, 1 property 1,741 / 1,727 ms 488 / 474 ms (-72%) 2,240 / 2,259 ms (+30%)
Java loop + getString, 1 property 2,868 / 2,933 ms 2,430 / 2,338 ms (-18%) 2,180 / 2,228 ms (-24%)
Java loop + getString, 9 properties 2,907 / 2,979 ms 2,534 / 2,377 ms (-17%) 2,274 / 2,262 ms (-23%)
SQL GROUP BY, 1 property 4,667 / 4,822 ms 4,426 / 4,325 ms (-8%) 4,049 / 4,128 ms (-14%)
SQL GROUP BY, 9 properties 4,791 / 5,104 ms 4,552 / 4,399 ms (-10%) 4,204 / 4,310 ms (-14%)
SQL count(*) scan, 9 properties 3,625 / 3,673 ms 3,227 / 3,082 ms (-14%) 2,949 / 2,945 ms (-19%)

A removes most of a bare scan's cost. B helps whenever a property is read, but makes a bare scan slower, since it loads content nobody reads. The fix I would suggest, if you agree with the diagnosis, is to build the immutable record straight from currentPage's bytes when the record fits in its page. That is one lookup instead of three, and no lazy reload. I have not prototyped it. One thing a real fix has to keep: existsRecord is where the scan checks READ_RECORD today, and prototype A skips that check for in-page records until the lazy load. Since the check is per file, once per bucket per scan should be enough.

2. aggregate() rebuilds the default alias on every record

AggregateProjectionCalculationStep.java:195 runs proj.getProjectionAlias().getStringValue() for every projection on every record, before the isAggregate() check. For an item without AS, ProjectionItem.getProjectionAlias() (ProjectionItem.java:159) returns expression.getDefaultAlias(), which builds a new Identifier(...) and escapes it (Expression.java:226). For a non-identifier expression it also calls this.toString() (Expression.java:228). So the group key l_shipmode gets a fresh Identifier built and discarded 3,000,000 times. Identifier.escape is 11% of the SQL GROUP BY samples.

  • C: cache the default alias in a field of ProjectionItem. No caller modifies the returned Identifier; a real fix should also reset the cache in setExpression, or compute the aliases once in the step's constructor.

Temurin 21, run order original, C, A+C, B+C, then reversed. The laptop ran about 10% slower in the second half, on every variant alike, so each variant is compared with the original from its own half:

path original C A+C B+C
SQL GROUP BY, 1 property 4,770 / 5,336 ms 4,323 (-9%) / 4,960 (-7%) 3,905 (-18%) / 4,362 (-18%) 3,978 (-17%) / 4,315 (-19%)
SQL GROUP BY, 9 properties 4,911 / 5,892 ms 4,480 (-9%) / 5,360 (-9%) 4,137 (-16%) / 4,433 (-25%) 3,889 (-21%) / 4,526 (-23%)
SQL count(*) scan, 9 properties 3,557 / 4,295 ms 3,513 (-1%) / 4,471 (+4%) 3,063 (-14%) / 3,409 (-21%) 2,938 (-17%) / 3,472 (-19%)

Temurin 25.0.4 + COH, all three together, run order original, A+C, B+C, B+C, A+C, original:

path original A+C B+C
iterateType only, 1 property 1,541 / 1,516 ms 482 / 517 ms (-67%) 2,443 / 2,304 ms (+55%)
Java loop + getString, 1 property 3,629 / 3,222 ms 2,882 / 2,877 ms (-16%) 2,488 / 2,508 ms (-27%)
Java loop + getString, 9 properties 3,567 / 3,489 ms 2,368 / 2,472 ms (-31%) 2,446 / 2,581 ms (-29%)
SQL GROUP BY, 1 property 4,963 / 5,220 ms 4,164 / 4,070 ms (-19%) 3,905 / 3,844 ms (-24%)
SQL GROUP BY, 9 properties 5,312 / 5,344 ms 4,080 / 4,068 ms (-24%) 4,328 / 4,030 ms (-22%)
SQL count(*) scan, 9 properties 3,815 / 3,926 ms 3,062 / 3,175 ms (-19%) 3,278 / 3,022 ms (-19%)

3. Not prototyped: SuffixIdentifier.execute reads each property twice

SuffixIdentifier.java:161 calls currentRecord.hasProperty(varName) and then getProperty(varName). On an ImmutableDocument the first scans the record header through serializer.hasProperty (after checkForLazyLoading), and the second deserializes. ImmutableDocument.has is 12.8% of the GROUP BY samples. A single lookup that tells "absent" from "null" would need a change to Result, so I stopped at the profile. BasicCommandContext.setVariable("current", ...), called per record at FetchFromTypeExecutionStep.java:290, is another 7%.

Not a defect, but it multiplies all of the above

arcadedb.queryParallelScan is on by default but needs at least arcadedb.queryParallelScanMinBuckets (2) buckets, and arcadedb.typeDefaultBuckets is 1. So a type created with plain CREATE DOCUMENT TYPE always scans on one thread, as all the numbers here do. Everything above is per-record cost, so it applies per thread either way.

Environment

Laptop numbers: Intel Core Ultra X9 388H, 4 P-cores (--cpuset-cpus 0-3), -Xms8g -Xmx8g, G1, database on NVMe (ext4). Temurin 21.0.12 (eclipse-temurin:21-jdk) and Temurin 25.0.4 with -XX:+UseCompactObjectHeaders (eclipse-temurin:25-jdk). Absolute times on this laptop drift by up to 15% between sessions, so every comparison above is between runs from the same session, with the variants alternated.

GroupByScanRepro.java
import com.arcadedb.database.Database;
import com.arcadedb.database.DatabaseFactory;
import com.arcadedb.database.Document;
import com.arcadedb.database.MutableDocument;
import com.arcadedb.database.Record;
import com.arcadedb.query.sql.executor.Result;
import com.arcadedb.query.sql.executor.ResultSet;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * Where does a GROUP BY over a full scan spend its time? TPC-H-shaped LineItem documents (nine
 * properties, the types the benchmark's ArcadeDB arm declares), then the same count-per-ship-mode
 * answered five ways. Every answer is checked against the Java-API count.
 *
 *   java -cp 'lib/*:cls' GroupByScanRepro <dbPath> <rows>
 */
public class GroupByScanRepro {
  static final String[] MODES = { "AIR", "FOB", "MAIL", "RAIL", "REG AIR", "SHIP", "TRUCK" };
  static final int REPS = 5;

  public static void main(String[] a) throws Exception {
    final String path = a[0];
    final int n = Integer.parseInt(a[1]);
    try (DatabaseFactory f = new DatabaseFactory(path)) {
      if (f.exists()) f.open().drop();
      final Database db = f.create();
      db.command("sql", "CREATE DOCUMENT TYPE LineItem");
      for (String c : new String[] { "l_orderkey", "l_partkey" }) db.command("sql", "CREATE PROPERTY LineItem." + c + " LONG");
      for (String c : new String[] { "l_quantity", "l_extendedprice", "l_discount" }) db.command("sql", "CREATE PROPERTY LineItem." + c + " DOUBLE");
      for (String c : new String[] { "l_returnflag", "l_linestatus", "l_shipdate", "l_shipmode" }) db.command("sql", "CREATE PROPERTY LineItem." + c + " STRING");
      db.command("sql", "CREATE DOCUMENT TYPE Narrow");
      db.command("sql", "CREATE PROPERTY Narrow.l_shipmode STRING");

      final Random r = new Random(1);
      final long t0 = System.nanoTime();
      db.begin();
      for (int i = 0; i < n; i++) {
        final String mode = MODES[r.nextInt(MODES.length)];
        final MutableDocument d = db.newDocument("LineItem");
        d.set("l_orderkey", (long) (i / 4));
        d.set("l_partkey", (long) r.nextInt(200_000));
        d.set("l_quantity", (double) (1 + r.nextInt(50)));
        d.set("l_extendedprice", 900 + r.nextDouble() * 100_000);
        d.set("l_discount", r.nextInt(11) / 100.0);
        d.set("l_returnflag", new String[] { "A", "N", "R" }[r.nextInt(3)]);
        d.set("l_linestatus", new String[] { "F", "O" }[r.nextInt(2)]);
        d.set("l_shipdate", String.format("199%d-%02d-%02d", 2 + r.nextInt(7), 1 + r.nextInt(12), 1 + r.nextInt(28)));
        d.set("l_shipmode", mode);
        d.save();
        db.newDocument("Narrow").set("l_shipmode", mode).save();
        if ((i + 1) % 50_000 == 0) { db.commit(); db.begin(); }
      }
      db.commit();
      System.out.printf("loaded %,d LineItem + %,d Narrow in %.1f s; engine %s%n", n, n, (System.nanoTime() - t0) / 1e9,
          com.arcadedb.Constants.getVersion());

      final Map<String, Long> truth = javaCount(db, "LineItem");
      System.out.println("truth " + truth);

      time("Java iterateType only, no property read   [LineItem, 9 props]", () -> iterateOnly(db, "LineItem"), null);
      time("SQL  GROUP BY l_shipmode, count(*)        [LineItem, 9 props]", () -> sqlGroup(db, "LineItem"), truth);
      time("SQL  GROUP BY l_shipmode, count(*)        [Narrow,   1 prop ]", () -> sqlGroup(db, "Narrow"), truth);
      time("SQL  count(*) WHERE l_quantity >= 0 (scan) [LineItem]         ", () -> sqlScanCount(db), null);
      time("Java iterateType + getString + HashMap    [LineItem, 9 props]", () -> javaCount(db, "LineItem"), truth);
      time("Java iterateType + getString + HashMap    [Narrow,   1 prop ]", () -> javaCount(db, "Narrow"), truth);
      db.close();
    }
  }

  interface Q { Object run(); }

  static void time(String label, Q q, Map<String, Long> truth) {
    q.run(); // warm-up, not timed
    final List<Double> ms = new ArrayList<>();
    Object ans = null;
    for (int i = 0; i < REPS; i++) {
      final long s = System.nanoTime();
      ans = q.run();
      ms.add((System.nanoTime() - s) / 1e6);
    }
    Collections.sort(ms);
    final String ok = truth == null ? "" : (truth.equals(ans) ? "  answer=ok" : "  ANSWER DIFFERS " + ans);
    System.out.printf("RESULT %-64s median %8.1f ms  [%.1f-%.1f]%s%n", label, ms.get(REPS / 2), ms.get(0), ms.get(REPS - 1), ok);
  }

  static Map<String, Long> sqlGroup(Database db, String type) {
    final Map<String, Long> m = new HashMap<>();
    try (ResultSet rs = db.query("sql", "SELECT l_shipmode, count(*) AS n FROM " + type + " GROUP BY l_shipmode ORDER BY l_shipmode")) {
      while (rs.hasNext()) { final Result x = rs.next(); m.put(x.getProperty("l_shipmode"), ((Number) x.getProperty("n")).longValue()); }
    }
    return m;
  }

  static Long sqlScanCount(Database db) {
    try (ResultSet rs = db.query("sql", "SELECT count(*) AS n FROM LineItem WHERE l_quantity >= 0")) {
      return ((Number) rs.next().getProperty("n")).longValue();
    }
  }

  static Long iterateOnly(Database db, String type) {
    long n = 0;
    final Iterator<Record> it = db.iterateType(type, false);
    while (it.hasNext()) { it.next(); n++; }
    return n;
  }

  static Map<String, Long> javaCount(Database db, String type) {
    final Map<String, Long> m = new HashMap<>();
    final Iterator<Record> it = db.iterateType(type, false);
    while (it.hasNext()) m.merge(((Document) it.next().asDocument()).getString("l_shipmode"), 1L, Long::sum);
    return m;
  }
}

Activity

  1. added
    engine
    severity:minor
    on Sep 23, 2026
  2. added this to the 26.10.1 milestone on Sep 23, 2026
  3. added
    in progress
    on Sep 23, 2026
  4. self-assigned this
    on Sep 23, 2026
  5. lvca commented on Sep 23, 2026

    @lvca
    Member

    Working this. Three independent sources of per-record scan overhead were identified; splitting them up since they carry different risk:

    Leaving this issue open until #8265 and #8266 are resolved too.

  6. added 4 commits that reference this issue on Sep 23, 2026
  7. removed
    in progress
    on Sep 23, 2026
  8. lvca commented on Sep 23, 2026

    @lvca
    Member

    Fixed in PR #8267 (merged): a GROUP BY without an explicit column alias (e.g. count(*) instead of count(*) AS n) was rebuilding that default name from scratch on every single row of the scan, for nothing - it's the same name every time. Now it's computed once per query instead of once per row.

    The other two things this report found need a bit more care and are tracked separately, since fixing them safely means changing some sensitive lower-level code (not urgent to read, just for the record):

    Closing this one since the piece it's fixing is done; the other two stay open under their own numbers.

    ❤️ Thanks for helping make ArcadeDB better! ArcadeDB is free and open source, sustained by its community. If it's useful to you or your company, please consider becoming a sponsor to keep development going.

  9. added a commit that references this issue on Sep 23, 2026
  10. added theissue type on Sep 23, 2026
  11. tae898 commented on Sep 23, 2026

    @tae898
    ContributorAuthor

    Verified with the repro from the issue on main at 33d274af81 (the published 26.10.1-SNAPSHOT image, which contains #8267), against cbd0947c18, the build it was filed on. One 3M-record database, runs alternated before, after, after, before, on the same 4 laptop cores:

    path Temurin 21 Temurin 25 + COH
    SQL GROUP BY l_shipmode, count(*), 9 properties -4% -6% / -6%
    same, 1 property -5% -3% / -6%
    SQL count(*) AS n WHERE l_quantity >= 0, every column aliased, so the fix does not reach it -1% +0% / +1%
    Java iterateType + getString loops, no SQL (1 and 9 properties) -1%, +0% between -1% and +2%

    Answers are identical before and after. The first Java 21 run was about 12% slow on every path, the pure Java loops included (a cold start), so that column is the second pair only; the Java 25 column is both pairs. The bare iterateType loop without a property read spread by about 20% within a run on both JDKs, so I left it out rather than read anything into it.

    So the merged piece is worth about 5% on this query shape, a little under the 7-9% the prototype measured in an earlier session, and the larger share stays with #8265 and #8266 as you split them. The Python bindings' test suite passes on a wheel built from 5b040a438e (467 passed, 2 skipped), and the repros of the earlier fixes still hold on 33d274af81: #8232, #8129, #8179, and #8132.

  12. lvca commented on Sep 23, 2026

    @lvca
    Member

    I'm working to the issues:

    They should bring some extra speed. It should be done for tomorrow night.

  13. lvca commented on Sep 24, 2026

    @lvca
    Member

    @tae898 Done

  14. tae898 commented on Sep 25, 2026

    @tae898
    ContributorAuthor

    Measured, as promised, for #8265 and #8266 together (they landed in one PR, #8311). Before is the published snapshot at 5b040a438e, after is the published snapshot at 0b800cfe1c (it contains #8311), each run on its own image's jars, on Temurin 25 with compact object headers / Temurin 21, 4 cores, with the repros from #8260 and every answer checked:

    3M rows before after
    bare scan, no property read 1,226 / 1,114 ms 551 / 484 ms (2.2x to 2.3x)
    GROUP BY l_shipmode, count(*) 4,424 / 4,619 ms 3,258 / 3,455 ms (1.34x to 1.36x)
    count(*) WHERE l_quantity >= 0 3,776 / 3,476 ms 2,599 / 2,728 ms (1.27x to 1.45x)

    And the parallel scan now pays off (2M rows loaded into a one-bucket type and a four-bucket type, GROUP BY, two rounds each):

    1 bucket 4 buckets
    before 2.90 to 3.04 s 3.92 to 4.12 s, 35% slower
    after 2.18 to 2.31 s 1.57 to 1.61 s, about 1.4x faster

    The filtered count(*) does not gain from four buckets (1.71 to 1.86 s either way), in case that path is worth a look.

    One question it raises. My benchmark (https://humem.ai/projects/arcadedb/next, whose tables are measured at 417314c18, before this fix) runs every engine at its defaults, and the type default is still one bucket, so a default install never sees the parallel scan. Is a higher default planned, or is there a setting you would recommend? I would follow the default rather than tune ArcadeDB alone.

  15. tae898 commented on Sep 25, 2026

    @tae898
    ContributorAuthor

    Measured #8312 (step 2 of the plan in #8265) with the same repros. Before is the published snapshot at 3440a871a9 (it has #8311, not #8312), after is the published snapshot at 5f8b817097 (it has #8312), each run on its own image's jars, on Temurin 25 with compact object headers / Temurin 21, 4 cores, with every answer checked:

    3M rows before after
    bare scan, no property read 494 / 487 ms 459 / 453 ms (unchanged, as expected)
    GROUP BY l_shipmode, count(*) 3,338 / 3,410 ms 1,891 / 1,957 ms (1.74x to 1.77x)
    count(*) WHERE l_quantity >= 0 2,653 / 2,665 ms 1,309 / 1,356 ms (1.97x to 2.03x)
    Java iterateType plus one getString per record 2,379 / 2,306 ms 972 / 1,009 ms (2.29x to 2.45x)

    Together with #8311, the GROUP BY went from 4,424 / 4,619 ms at 5b040a438e to 1,891 / 1,957 ms on the same laptop and repro, 2.3x.

    It also mostly answers my bucket question above. With the per-record cost gone, one bucket caught up (2M rows, GROUP BY, two rounds each):

    1 bucket 4 buckets 4 against 1
    before 2.11 to 2.38 s 1.53 to 1.64 s 1.36x to 1.47x
    after 1.27 to 1.34 s 1.20 to 1.27 s 1.01x to 1.09x

    So a higher default bucket count would now buy little on this repro, and the question is low priority from my side. I will measure it again at my next pin.

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

Metadata

Metadata

Assignees

Labels

engineperformanceseverity:minorsql

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions