Skip to content

MC 26.3 performance: block-state dictionary, integer time index, batched writes, faster rollback - #1

Merged
Pau1am merged 18 commits into
masterfrom
Ledger-Reoptimization
Oct 6, 2026
Merged

Pau1am merged 18 commits into
masterfrom
Ledger-Reoptimization

Conversation

@Pau1am

@Pau1am Pau1am commented Oct 5, 2026 •

Copy link
Copy Markdown
Owner

Optimisation branch for Ledger on MC 26.3, based on upstream master at 1.3.25.
Consolidates the changes that survived measurement; everything that did not was
dropped and is listed at the bottom.

Results

Measured by alternating the two builds inside a single time window (5 pairs, fresh
terrain each run). Interleaving matters here: this machine's throughput drifts by
several times over hours, so build A measured and then build B measured - the usual
pattern - would measure the drift as much as the change. As a control, one jar with
identical md5 measured 0.333 s of rollback at one point and 1.22 s later.

metric this branch upstream 1.3.25 delta win/loss
write drain window 3.163 s 4.217 s -25.0% 5-0
write drain rate 4,268 rows/s 3,202 rows/s +33.3% 5-0
write, full window 5.268 s 6.321 s -16.7% 5-0
query 0.044 s 0.123 s -64.2% 5-0
bytes per row 171.7 179.9 -4.6% 5-0
restore 0.190 s 0.200 s -5.0% 4-1
rollback 0.324 s 0.300 s +8.0% 2-3

Six of seven improve, five of them unanimously. Rollback is level, not a win.

What is in the branch

Storage

  • Block-state dictionary encoding - identical state strings stored once, referenced
    by integer id.
  • Integer time index - time is TEXT (~23 chars, ~35 bytes per index key); a new
    time_ms column carries the index at ~16 bytes. Migration is automatic, resumable,
    and queries fall back to the text column while a backfill is running, so a
    half-migrated database stays correct. /ledger compact reclaims the freed pages.

Performance

  • Real JDBC batch insert. batchInsert was emitting one statement per row - 13,500
    actions produced 13,500 individual INSERT statements. Writing through a prepared
    batch, with values still produced by Exposed column types so the stored
    representation is unchanged, cut the write window from 1.53 s to 0.62 s of real work.
  • Burst-aware queue scheduling. The writer paid the full batchDelay on every pass
    even with work already queued, which was 6.1 s of an 8.7 s ingest window. It now skips
    the wait only while the previous pass filled a complete batch.
  • Idle SQLite connection held open. SQLite checkpoints and deletes -wal whenever
    the last connection to a WAL database closes, and Ledger opens a connection per
    transaction, so every transaction paid for a full WAL teardown: 11 transactions cost
    642 ms that way versus 58 ms with one idle connection held open. One connection is now
    kept open for the process lifetime and released at shutdown. Transactions are acquired
    exactly as before; the anchor never runs a statement. Applied only when Ledger created
    the SQLite datasource itself.
  • Rolled-back flag written through one cached JDBC statement. The flag write cost
    36 us per row while the identical UPDATE run directly takes 2.9 us per row - the gap
    was Exposed building an IN list of thousands of elements. Same SQL, same rows;
    493 ms -> 37 ms.
  • Rollback batch raised to 50,000. 5,000 was slower than one batch (1.236 s vs
    0.326 s) because each transaction carries a large fixed cost beyond the SQL, so the
    transaction count dominates. Kept as a bound so a huge rollback cannot materialise
    millions of actions at once.

Tried and dropped

  • Reading the timestamp from the integer column instead of parsing TEXT: measured
    slower, reverted.
  • Raising the rollback batch to 5,000: 39% slower than upstream (fixed above).
  • Composite (time_ms, id) indexes: still force a temp B-tree sort, no query gain,
    +3% file size.
  • SQLite foreign keys off: 3% gain, not worth weakening referential integrity.
  • SQLite page_size: silently ignored once the database exists.
  • Dropping the legacy time column: ~13% smaller, but needs a table rebuild plus a
    branched read path for a non-reversible migration.
  • Moving storage to DuckDB: measured worse on every axis (bytes/row 97.5 vs 57.0 with
    no secondary indexes, queries 6-9x slower, flag updates 4-6x slower) and Exposed has
    no DuckDB dialect, so the whole data layer would have had to be rewritten.

Verification

Live MC 26.3 Fabric server: zero exceptions, zero tick warnings, rollback -> restore
round-trip preserves the exact block state, both migration paths pass their checks
(8/8 and 6/6), every benchmark run logs exactly 13,500 rows, and the world directory is
left with only ledger.sqlite after shutdown (no -wal/-shm, i.e. the anchor
connection is released). The single style: commit is detekt autocorrect.

Paul Lam added 18 commits October 5, 2026 22:37
…port

Reoptimization of the database layer:

- Add block_states dictionary table and nullable block_state_ref /
  old_block_state_ref columns on actions; new writes reference the
  dictionary instead of repeating full state strings (CoreProtect-style
  int encoding). Legacy text columns stay null-compatible for reads.
- Existing databases upgrade via instant ALTER TABLE ADD COLUMN
  (metadata-checked, idempotent).
- Replace single-column indexes with query-oriented composite indexes
  (player_id,time), (action_id,time), (object_id,time),
  (old_object_id,time), (world_id,x,z,time); superseded indexes are
  dropped under the existing updateSchema config flag.
- SQLite tuning: WAL journal + synchronous=NORMAL + 10s busy timeout.
- Streaming rollback/restore support: currentMaxActionId, countActionsFor,
  keyset-paginated selectRollbackBatch / selectRestoreBatch (manual
  LessOp/GreaterOp predicates since SqlExpressionBuilder is deprecated
  at ERROR level in Exposed 1.0.0).
- Search count cache (TTL 30s) so paging does not re-run full COUNTs.
- compactBlockStates(): batched legacy text -> dictionary migration with
  progress callback; vacuumDatabase(): VACUUM / OPTIMIZE TABLE.
- Shutdown drain: 4x larger batches and NonCancellable writes so a
  shutdown-time cancellation can never drop a half-flushed batch.

(cherry picked from commit dc14afb)
Reoptimization of the command layer:

- Rollback/restore no longer load the entire result set into memory and
  apply it in one monolithic main-thread loop. They now stream batches
  via keyset pagination (max 1000 rows in memory), commit the
  rolled_back flag per batch (crash-safe), yield one full tick whenever
  the main thread has worked for 25ms (adaptive tick budget,
  CoreProtect-style), and report progress every 5 batches.
- Rollback takes MAX(id)+1 as an exclusive upper bound before starting,
  so actions logged during the rollback itself can never be picked up
  by later batches of the same rollback.
- New /ledger compact command: migrates legacy text block states into
  the block_states dictionary (atomic per-row text->ref swap) and then
  reclaims disk space via VACUUM / OPTIMIZE TABLE. Safe on a live
  server; requires the purge permission level.
- Lang keys for progress messages (en_us, en_gb, zh_cn, zh_tw).

(cherry picked from commit eb7cf36)
(cherry picked from commit 005883e)
An earlier revision of this branch replaced upstream's single-column indexes
with four (dimension, time) composites and widened actions_by_location to
(world_id, x, z, time). Ledger stores timestamps as TEXT (~23 bytes), so every
extra time column in an index costs ~23 bytes per row.

Measured on a 13,500-row workload: index footprint 1.45 MB -> 3.29 MB, whole
file 2.39 MB -> 4.26 MB (+78%), with no measurable lookup improvement.

- Tables.kt: restore upstream index declarations
- DatabaseManager: re-assert the upstream index set and drop the four
  composites; rebuild actions_by_location as (x, y, z, world_id) when the wide
  form is detected. Metadata-driven and idempotent.
- Bytes per row: 315 -> 179 (upstream: 177)

Verified by bench/test_index_migration.py: a database carrying the intermediate
build's indexes is repaired on startup - composites dropped, single-column
indexes restored, actions_by_location rebuilt, 13,500 rows intact.

CHANGELOG: document the revert and the CoreProtect benchmark.
(cherry picked from commit c0f6410)
…budget

The time column is the one place where a wide index key was worth removing rather
than avoiding. actions.time stored TEXT ('2026-10-05 13:22:21.702') and an index
over it cost ~35 bytes per row - measured at 19.6% of the whole database, the
largest non-table object.

- Tables.kt: add time_ms (INTEGER, epoch millis) carrying the index; drop
  .index("actions_time") from the TEXT column.
- DatabaseManager: add the column, index it, backfill it in id-ordered batches,
  then drop the superseded TEXT index. Resumable; queries fall back to the TEXT
  column until the backfill completes so a partial migration stays correct. With
  updateSchema=false nothing runs and inserts skip the new column.
- DatabaseManager: SQLite pragmas via SQLiteConfig (temp_store=MEMORY, 16 MiB
  cache, 256 MiB mmap_size, 64 MiB journal_size_limit), reaching every pooled
  connection; verified applied through JDBC.
- Rollback/Restore: tick budget sized from the server's smoothed tick time instead
  of a fixed 25 ms. On an idle benchmark server this changes nothing measurable -
  a rollback completes with zero yields, so the budget was never its bottleneck.
  The benefit is backing off automatically under load. A previous comment claiming
  a large share of wall time went into delay(1) was wrong and is removed.

Measured, 13,500-block workload, medians of 3:
  time index   35.5 -> 14.6 B/row  (-59%)
  whole file  181.4 -> 159.3 B/row (-12.2%, after migration + VACUUM)
  ingest      1,959 -> 2,125 rows/s
Independent 500,000-row synthetic run: -11.5% file, -53% index.

Rollback and lookup show no measurable change and are not claimed as wins.
Composite (time_ms, id) indexes were measured at 500k rows and rejected: still
USE TEMP B-TREE FOR ORDER BY, and +3.0-3.7% file size.

Verified: migration 8/8 checks, fresh-database schema path, and a rollback/restore
state round-trip on a live MC 26.3 server, all with zero errors.

(cherry picked from commit d56252d)
Two figures overstated the change:

- the -12.2% database reduction compared a migrated+vacuumed database against an
  un-vacuumed one, crediting VACUUM (which any index drop would also produce) to
  the optimisation. Like-for-like the change is -7.9% (181.44 -> 167.2 B/row),
  with the index itself going 35.5 -> 16.4 B/row (-54%).
- ingest throughput does not reproduce: reopt.2 measured 2,125 rows/s in one
  campaign and 1,917 in the next, with reopt.1 at 1,959 and 1,957. It is noise,
  so ingest/lookup/rollback are now reported as no measurable change rather than
  as wins.

(cherry picked from commit cbdba32)
…heduling

Measured first, then fixed - two assumptions from the previous round turned out
to be wrong:

  * rollback's 14 reads and 14 rolled_back commits: bypassed, not the subject here
  * ingest: a 13,500-action burst logged 13,500 individual
    "INSERT INTO actions" statements. Exposed's batchInsert was issuing one
    statement per row. On the same schema and the same rows, a real JDBC batch
    costs 23 us/row and an individual statement 44 us/row - yet the live path
    measured 310-500 us/row, so statement machinery dominated.
  * the scheduler unconditionally `delay(batchDelay)` (500 ms) on every pass even
    with work already queued: 6.1 s of an 8.7 s ingest window was spent waiting,
    against 2.6 s of actual writes.

Changes:

- DatabaseManager.insertActions now writes through a prepared statement on the
  transaction's own JDBC connection with addBatch/executeBatch. Values still come
  from Exposed column types via valueToDB, so the stored representation
  ("yyyy-MM-dd HH:mm:ss.SSS" text) is unchanged - verified byte-for-byte against
  an archive written by the ORM path, 500/500 samples identical.
- ActionQueueService only skips the wait while the queue is being flooded (the
  previous pass filled a complete batch). Once a pass comes up short the
  configured batchDelay applies again, so trickle traffic still batches exactly as
  upstream did; an idle server does not become one transaction per action.

Measured over 3 runs each (medians, 13,500 actions, fresh terrain):

  drain window   4.534 s -> 3.622 s   (-0.91 s; the 3.0 s settle window is a
                                       constant, so actual write work went
                                       1.53 s -> 0.62 s)
  drain rate     2,977 -> 3,727 rows/s (+25%)
  ingest window  6.713 s -> 5.733 s
  rollback       unchanged (3.85 s -> 4.10 s, within run-to-run noise)

Also evaluated and REJECTED: turning off SQLite foreign keys. A controlled
transaction-cost test showed FK checks cost 5.9 -> 5.7 ms per 1,000-row
transaction (3%), which is not worth weakening referential integrity for.

Verified: fresh-database schema, zero errors on a live MC 26.3 server, rollback ->
restore state round-trip passes, dictionary references written correctly, and
time/time_ms remain mutually consistent in both the old and new paths.

(cherry picked from commit 0cb9653)
… rows

Rollback was the one metric with a large gap to CoreProtect (about 2 s vs 0.6 s
for the same 13,500 actions), so the batch size was measured rather than left at
its long-standing default. Hiding 1,000 rows behind each read and each
rolled_back commit means the per-statement overhead is paid fourteen times for a
13,500-row undo; 5,000 pays it three times.

Measured on a 13,500-block rollback, two fresh-terrain runs per setting:

  1,000 rows/batch : 3.857 s / 4.164 s
  5,000 rows/batch : 1.991 s / 2.030 s     (about 2x faster)

Safety was checked before adopting it, since a bigger batch means more work
between yields:

  * zero "can't keep up" warnings in every run at both settings, so the larger
    batch does not cost server responsiveness - the existing per-tick budget still
    splits a batch and yields mid-way through it
  * all four runs logged exactly 13,500 rows with zero errors

Worst-case memory is bounded by roughly 5,000 materialised actions.

Not changed, for the record: SQLite's page size cannot be altered on an existing
database (PRAGMA page_size is silently ignored once the file exists, confirmed by
measurement - every value collapsed back to 4,096), so it is not a lever this build
can pull. That same test did confirm that VACUUM alone reclaims about 4.7% of the
file, which /ledger compact already exposes to users.

(cherry picked from commit 4091b35)
Records this round's three changes (real JDBC batch insert, burst-aware queue
scheduling, 1,000 -> 5,000 rollback batch), the combined before/after numbers, and
the three options that were measured and rejected (foreign keys off, page_size,
dropping the legacy time column) with the reason in each case.

(cherry picked from commit 6fe0f56)
The publish helper reads a GitHub token from $GITHUB_TOKEN or from a .secrets/gh_token
file. Ignore both patterns so a token placed inside the working tree can never be
committed by accident.

(cherry picked from commit af6806d)
Purely mechanical - trailing whitespace, trailing commas, and `page-1` spacing.
Needed so the branch satisfies the project's own detekt configuration; safe to
skip when reviewing.

The same reformatting previously rode along inside the NBT commit. That commit was
dropped when this branch was rebased onto 1.3.25 (upstream fixed the NBT issue in
QuiltServerTools#402), so the formatting is restored here on its own.
Upstream moved while this branch was in flight:

  22705ac fix: update block state NBT format for 26.3 (QuiltServerTools#402)
  dd947aa Update modVersion from 1.3.24 to 1.3.25

QuiltServerTools#402 fixes exactly what this branch's own NBT commit fixed, so that commit has been
dropped in the rebase and the code is now upstream's - credit belongs there. The one
piece that was ours alone, a read-side fallback to the legacy "Properties" key, was
also dropped: on 26.3 writeBlockState emits "properties", so the fallback could never
fire and was dead code. That also removed the unrelated MessageUtils reformatting
from that commit, which is now its own change.

The CHANGELOG heading and comparison baseline move to 1.3.25, and the NBT entry now
records that the fix is upstream's rather than implying it is ours.

Verified after rebasing: builds clean, detekt passes, and a live MC 26.3 server
completes a rollback -> restore round-trip with the exact block state preserved
(oak_stairs[facing=west,half=top]) and zero exceptions.
…per transaction

Profiling a rollback showed its database time dominated by something outside the
SQL: measured with the statement's own timer, the rolled_back UPDATEs cost 339 ms
in total, while the surrounding DatabaseManager call measured 1061 ms. The missing
~720 ms was per-transaction connection setup.

The cause is not connection setup as such. SQLite checkpoints and deletes the -wal
file whenever the last connection to a WAL database closes, and Ledger opens a new
connection per transaction - so every transaction was paying for a full WAL
teardown and rebuild. Isolated measurement:

    connection open + query + close, no pragmas    :  1.4 ms
    same, with this project's 7 pragmas            : 55.9 ms
    11 transactions, fresh connection each         : 642 ms
    11 transactions, one idle connection held open :  58 ms   (11x)

Note the pragma count barely matters (0 vs 7 pragmas: 54 vs 88 ms), so the cost is
the WAL lifecycle, not the PRAGMAs themselves.

The fix keeps a single idle connection open for the process lifetime. It does not
change how transactions acquire connections - Exposed still gets a fresh connection
per transaction from the same DataSource, and the anchor never runs a statement of
its own. It only stops SQLite treating every close as the end of the world.

Scope and failure behaviour, deliberately conservative:

  * only when Ledger created the SQLite datasource itself; with a user-supplied
    DataSource we leave it alone, since holding one of its connections forever could
    starve a small pool
  * opened once at startup, released at shutdown before the world directory closes,
    so no handle is left behind (Windows cannot rename or delete an open file)
  * if the anchor cannot be opened we log and continue on the previous behaviour -
    the optimisation is never load-bearing for correctness

Measured over 3 runs each (medians, 13,500 actions, fresh terrain):

    rollback          4.25 s -> 1.26 s   (3.4x)
    drain window      4.52 s -> 3.17 s   (the 3.0 s settle detector is a constant, so
                                          real write work went 1.72 s -> 0.17 s)
    drain rate        2,860 -> 4,256 rows/s
    rollback read      876 ms -> 588 ms
    rollback flag write 1061 ms -> 493 ms

Rollback is now 6x away from CoreProtect rather than 20x, and ingest is 1.3x
faster than it.

Verified: three consecutive runs agreed to within 2 ms on the drain window, live
MC 26.3 server shows zero exceptions and zero tick warnings, rollback -> restore
preserves the exact block state, and the world directory is left with only
ledger.sqlite after shutdown (no -wal/-shm, i.e. the handle was released).
…atement

Answering "can rollback be sped up further by making parts of it asynchronous" led
somewhere more profitable than async I/O: half of what looked like database work was
statement construction.

Timing the flag write (13,500 rows, 5,000 per batch) through the statement's own timer
gave 36 us per row, while the identical UPDATE run directly against the same database
takes 2.9 us per row. The SQL was never the cost - Exposed's
`update { id inList actionIds }` builds an IN list of thousands of elements one at a
time. The text is now built once per size and cached; parameters are bound and
executed through JDBC.

The SQL and its meaning are unchanged: one UPDATE, the same predicate, the same rows
marked. Only statement building leaves the hot path. Chunk size is capped at 5,000,
well under this driver's 32,766 variable limit.

Measured segments of a 13,500-block rollback, before and after:

    flag write   493 ms -> 37 ms    (13x - the directly attributable part)
    read         588 ms -> 188 ms
    world writes 161 ms ->  43 ms

Only the flag write is claimed as this change's doing. The read and world-write
segments moved further than this patch can explain, and the read is a statement path
that was not touched, so that movement is probably incidental. Reported for
completeness, not presented as a win.

End to end, three runs each on fresh terrain:

    rollback   2.295 s -> 0.323 s   (7.1x against the build before the
                                     warm-connection work; 1.26 s -> 0.32 s, about
                                     3.9x, against the immediately preceding build)

Rollback is now within 1.5x of CoreProtect (0.21 s) instead of 11x.

Verified: the live server reports "Restoring 13500 actions" after the rollback, so
every row really was flagged; rollback -> restore preserves the exact block state;
zero exceptions and zero tick warnings; repeated runs agree to within 30 ms.
…fact

An attempt to optimise row materialisation failed, and investigating why exposed a
methodology problem that invalidates an earlier claim in this file.

The attempt: read a row's timestamp from the integer `time_ms` column instead of
letting Exposed parse the TEXT `time` column. Verified safe first (the two compare
equal on live rows, delta 0), but it measured slower, so it was reverted and never
committed.

Chasing that "slower" result is what found the real problem. The benchmark machine
drifts by several times over hours, so two builds measured hours apart are not
comparable. Concretely: an identical jar (same md5) measured 0.333 s of rollback at
one point and 1.22-1.32 s later; a class-by-class comparison of the two builds showed
every class the same size with only metadata differences, i.e. the code was not the
variable. Every cross-build number in this file that was taken sequentially rather
than interleaved is therefore suspect, including the previous claim of 2.295 s ->
0.323 s (~7x).

Re-measured by alternating the two builds within one window, 5 pairs:

  pair   this branch   upstream 1.3.24
     1        0.379 s          0.951 s
     2        0.293 s          0.339 s
     3        0.387 s          0.360 s
     4        0.319 s          0.308 s
     5        0.333 s          0.302 s

Medians 0.333 s vs 0.339 s. Rollback is at least as fast as upstream and markedly
less variable, but the large multiple was an artefact and is now withdrawn.

What still stands is everything measured within a single run, where both sides share
the same machine state: the flag write 493 -> 37 ms, and the write window going from
1.53 s to 0.62 s of real work with the drain rate rising 2,977 -> 4,270 rows/s.
Those reduce CPU work and tick pressure; they do not dominate the rollback wall clock.
…tch size itself

The rollback batch size had been raised to 5,000 on the reasoning that fewer round
trips must be better. Measuring it as a single variable shows that reasoning was
wrong, and expensively so.

On a 13,500-action rollback:

    5,000 per batch : 1.236 s   (three reads, three flag transactions)
    one batch       : 0.326 s   (3.8x faster)

Instrumenting the phase split shows why the gap is far larger than the SQL: inside a
rollback the reads, world writes and flag updates together accounted for 265 ms, yet
the command took about a second. Each transaction carries a large fixed cost beyond
the statement itself - dispatch through the single database context plus commit - so
the transaction count dominates, not the rows inside them.

Paired against upstream, which does no batching at all, on fresh terrain: 5,000 was
39% slower on rollback, a single batch is within 8%.

50,000 is kept as a bound rather than removed, so an enormous rollback on a large
server still cannot materialise millions of actions at once; at this size a typical
rollback fits in one round trip while pathological cases stay capped at roughly
50,000 actions (on the order of 15 MB).

Zero "can't keep up" warnings at every batch size tested.
@Pau1am
Pau1am merged commit d2cef97 into master Oct 6, 2026
@Pau1am
Pau1am deleted the Ledger-Reoptimization branch October 6, 2026 15:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant