Skip to content

HiLo: no thread-pool starvation on the first synchronous Store() burst (Fixes #5969) - #5972

Merged
jeremydmiller merged 1 commit into
masterfrom
fix/5969-hilo-thread-pool-starvation
Nov 15, 2026
Merged

jeremydmiller merged 1 commit into
masterfrom
fix/5969-hilo-thread-pool-starvation

Conversation

@jeremydmiller

Copy link
Copy Markdown
Member

Fixes #5969.

The first burst of synchronous Store() calls on a HiLo-identified type could stall the whole process through thread-pool starvation. This PR fixes both causes named in the issue, and a third one that only showed up once the first was fixed.

Design

1. Build the sequence storage synchronously, one statement per command

MartenDatabase.Sequences → resetSequences built mt_hilo / mt_get_next_hi by blocking on Weasel's asynchronous migration (generateOrUpdateFeature(...).AsTask().GetAwaiter().GetResult()) while holding the RuntimeSequences lock. Every other storing thread blocked on the lock, and the migration needed a free pool thread to finish.

The lazy build is now genuinely synchronous (SynchronousFeatureMigration). It is a synchronous port of the path Weasel takes for one feature, and it reuses Weasel for everything that decides what to do:

  • each object's own introspection query (ConfigureQueryCommand);
  • each object's own delta reader (CreateDeltaAsync), run over a BufferedSchemaReader, an in-memory DbDataReader that holds every result set read synchronously. Its async members are DbDataReader's defaults, which call the sync ones, so the delta readers complete on the calling thread with no I/O. A counter (AsynchronousDeltaReads) records any read that didn't complete synchronously, and a test holds it at zero;
  • SchemaMigration, AssertPatchingIsValid(AutoCreate), WriteSchemaCreationSql / WriteAllUpdates, the destructive-change and withheld-drop warnings, the catalog-concurrency retry, and InsufficientDatabasePrivilegeException / IMigrationLogger.OnFailure failure handling, all as in Migrator.ApplyAllAsync and PostgresqlMigrator.executeDelta.

Every command holds exactly one SQL statement. This turned out to be essential, not a style choice. My first version did the same work synchronously with Weasel's multi-statement commands, and it still starved: the heartbeat was ~990 ms late every run, and one run hit a 5 s Timeout during reading attempt. The reason is in NpgsqlCommand.WriteExecute: for a synchronous call, Npgsql writes the second and later statements of a multi-statement command or batch on the thread pool (ShouldSchedule → a ConcurrentExclusiveSchedulerPair over TaskScheduler.Default), to keep large batches from deadlocking against the server's results. So a synchronous multi-statement command waits on a pool thread just as sync-over-async does. A standalone console repro confirmed it: under a lock with 20 blocked Task.Run writers on 2 CPUs, a sync single-statement query takes about 25–100 ms, and the same work as one multi-statement command times out after 5 s.

So the introspection SQL is split into its statements (a small splitter that respects '…', E'…', "…", $tag$…$tag$ and nested comments, with theory tests), and each statement runs as its own command with only the parameters it references. DDL that Weasel writes as several statements runs inside one explicit transaction. That keeps the all-or-nothing behaviour of the implicit transaction a multi-statement command gets.

AutoCreate modes: with AutoCreate.None nothing is read or built. The old path read the catalog and then applied nothing. CreateOnly still refuses to update an outdated mt_get_next_hi with Weasel's own SchemaMigrationException, and CreateOrUpdate / All create or update it. Parity tests compare the synchronous determine against Weasel's SchemaMigration.DetermineAsync for a cold schema, a built schema and an outdated function.

Why not warm up asynchronously at startup instead? A bare DocumentStore.For(...) has no startup hook, and the lazy path still has to be safe for whoever reaches it first, so the lazy path had to be fixed regardless. With it fixed, an async warm-up would only save a few round trips once per database, so I left it out. ApplyAllConfiguredChangesToDatabaseAsync still creates these objects as before. The concurrent first callers still wait on the RuntimeSequences lock, but only for a few sequential single-statement round trips, which need no other thread to finish.

Left out on purpose: the database initializers (the tenant-partition registry, which only concerns document tables) and Weasel's private, asynchronous in-process migration lock. These objects are only ever built lazily by this path, under the RuntimeSequences lock. What can still race is another process or an explicit apply, as before. The schema statement guards itself and the statements get Weasel's retry.

2. Remove #5947's synchronous wait on the prefetch

HiloSequence.AdvanceToNextHiSync no longer waits on the in-flight prefetch, and SynchronousPrefetchWait (internal) is removed. If the prefetched block has already landed it's installed. Otherwise Store() fetches a block synchronously straight away. #5938's atomic mt_get_next_hi makes the overlap safe: both callers get a block, never -1. If the prefetch reserved the lower block, it's discarded when it's next looked at (a gap, never a duplicate or an out-of-order id).

Guarantees kept (#5862 / #5938)

  • Ids are unique and increasing within a process. The existing concurrency tests still pass (concurrent_sync_and_async_callers_never_get_the_same_id, concurrent_sessions_storing_documents_get_unique_ids, is_thread_safe), and the repro asserts unique ids.
  • Store() stays synchronous, and the synchronous fallback stays.
  • No unobserved task exceptions. The prefetch still never faults, and a_failed_prefetch_falls_back_and_never_poisons_the_sequence still passes.
  • The async NextLongAsync path is unchanged and still awaits the prefetch, which is fine because it doesn't block.

Tests

  • hilo_thread_pool_starvation_tests (new, in HiloThreadPoolCollection, DisableParallelization): runs ThreadPool.ThreadCount + 16 Task.Run writers, each calling synchronous Store() on two cold HiLo types (fresh schema, document storage resolved first), while a Task.Delay(10) heartbeat in the same test measures the worst delay. It asserts the delay is under 500 ms, all ids are > 0 and unique, and there are no failures. HiloThreadPoolCollection.cs is byte-identical to HiLo concurrency tests froze the test process's thread pool; run them alone (Fixes #5935) #5965's, which has since merged.
  • synchronous_sequence_storage_tests (new): parity with Weasel for a cold schema, a built schema, an outdated function, CreateOnly and AutoCreate.None, plus the statement-splitter theory.
  • hilo_prefetch_tests: dropped SynchronousPrefetchWait from two tests and renamed falls_back_…_when_the_prefetch_outlasts_the_wait → …_has_not_landed. Replaced the_synchronous_path_waits_for_the_prefetch_instead_of_competing_with_it with the_synchronous_path_never_waits_on_a_prefetch_in_flight. Rewrote Flaky: HiLo AdvanceToNextHi retry limit exceeded under concurrent load (Bug_1404); suspected interaction with #5862's prefetch #5938's row-holding test as racing_a_prefetch_for_the_hilo_row_costs_the_synchronous_path_no_attempts: the sync fetch now really does queue behind the prefetch's row lock (the test asserts it saw that), succeeds with a budget of one attempt because the increment is atomic, and the overtaken prefetch is discarded.

Red / green

The repro, the_first_burst_of_synchronous_stores_does_not_starve_the_thread_pool:

Build Where Result
master macOS, 18 cores (34 writers), 3 runs red: heartbeat 978 / 978 / 980 ms late, burst 3.6 s
master DOTNET_PROCESSOR_COUNT=2 (20 writers), 2 runs red: heartbeat 977 / 977 ms, burst 3.6 s
sync build but multi-statement commands (my first attempt) DOTNET_PROCESSOR_COUNT=2, 5 runs red: heartbeat ~992 ms every run, burst 1.6–11.7 s, one run with a 5 s Timeout during reading attempt
this PR macOS and DOTNET_PROCESSOR_COUNT=2, 5 runs green, ~320 ms per test

2-CPU Linux container (docker run --cpus=2 mcr.microsoft.com/dotnet/sdk:10.0, test host run with dotnet DocumentDbTests.dll, PG on the host), 3 runs each. The "before" binary is master's Marten (verified by byte-searching Marten.dll):

master this PR
starvation repro: worst heartbeat delay 982 ms / 991 ms / 9,621 ms (red ×3) 102 / 102 / 111 ms (green ×3)
starvation repro: burst of 20 writers 4.6 s / 5.6 s / 9.7 s 108–113 ms
hilo_prefetch_tests (10 tests) 8.2 s / 8.6 s / 4.3 s 3.0 s / 3.3 s / 3.3 s
concurrent_sessions_storing_documents_get_unique_ids 4.6 s / 0.7 s / 5.0 s 0.67 / 0.80 / 0.90 s
hilo_tests (10 tests) 2.2 s / 2.7 s / 2.2 s 0.72 / 0.71 / 0.65 s
hilo_tests.is_thread_safe 1.5 s / 2.0 s / 1.5 s 36–45 ms

Suites (net10.0, run directly against the test hosts)

On the head of this branch, rebased onto current master (which includes #5965), against marten_10_ff on PG 17, with no retries:

  • DocumentDbTests: 1294 total, 1293 passed, 1 skipped, 0 failed
  • CoreTests: 919 total, 910 passed, 9 skipped, 0 failed
  • DaemonTests: 394 total, 394 passed, 0 failed

The same three suites were also green before the rebase.

Docs

docs/documents/identity.md ("How HiLo Blocks Are Fetched") and the migration guide's HiLo section now say that Store() no longer waits on the background fetch, that the first id builds the storage synchronously, and that AutoCreate.None no longer reads the catalog. markdownlint and cspell report 0 issues.

Found along the way (not fixed here)

  • Npgsql: a synchronous multi-statement command or NpgsqlBatch depends on the thread pool. It writes statements 2..n on the pool (NpgsqlCommand.ShouldSchedule). Anything in Marten that runs a multi-statement command synchronously is open to this same starvation. On 9.0 that includes synchronous SaveChanges(), which batches its operations. Master has dropped most synchronous data access, so this is mostly a 9.x concern.
  • HiloSequenceBase (Weasel) holds its SemaphoreSlim gate across the await in NextLongAsync, and Marten's async AdvanceToNextHi still awaits the prefetch under it. A synchronous NextLong() on the same sequence then blocks a thread on that async work. Marten never calls NextLongAsync in production, so it can't happen today, but it is the same pattern.
  • After a synchronous fallback overtakes an in-flight prefetch, no new prefetch starts until the stale one is discarded at the next exhaustion, so the block after a discard is always fetched synchronously. This is a small inefficiency, not a correctness problem.

🤖 Generated with Claude Code

#5969)

The first burst of synchronous Store() calls on a HiLo-identified type could
stall the whole process. Two causes, both fixed:

1. MartenDatabase built the HiLo sequence storage by blocking on Weasel's
   asynchronous migration (sync-over-async) under the RuntimeSequences lock.
   Every other storing thread blocked on that lock, the migration needed a
   free pool thread to finish, and there was none until the pool injected
   more. The build is now genuinely synchronous (SynchronousFeatureMigration):
   Weasel's own introspection queries, delta readers (over an in-memory
   BufferedSchemaReader, so they complete without I/O), SchemaMigration and
   DDL writers, with synchronous I/O around them. Every command holds one
   statement: for a synchronous call Npgsql writes the 2nd+ statements of a
   multi-statement command on the thread pool, so a synchronous
   multi-statement command depends on the pool just as sync-over-async does.
   Multi-statement DDL runs in one explicit transaction, matching the
   implicit transaction it got before. With AutoCreate.None nothing is read
   or built.

2. #5938's synchronous wait on the in-flight prefetch is gone. If the
   prefetched block has not landed, Store() fetches one synchronously at
   once; #5938's atomic mt_get_next_hi makes the overlap safe (at worst a
   gap in ids, never a duplicate). SynchronousPrefetchWait is removed.

Adds a starvation repro (Task.Run writers on a cold HiLo type with a
Task.Delay(10) heartbeat), red on master, and parity tests holding the
synchronous build to Weasel's answers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.

HiLo: first burst of synchronous Store() can starve the thread pool (sync-over-async sequence build under lock; #5947's prefetch wait)

1 participant