Repository navigation
HiLo: no thread-pool starvation on the first synchronous Store() burst (Fixes #5969) - #5972
Merged
Merged
Conversation
#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>
This was referenced Nov 15, 2026
Merged
Closed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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→resetSequencesbuiltmt_hilo/mt_get_next_hiby blocking on Weasel's asynchronous migration (generateOrUpdateFeature(...).AsTask().GetAwaiter().GetResult()) while holding theRuntimeSequenceslock. 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:ConfigureQueryCommand);CreateDeltaAsync), run over aBufferedSchemaReader, an in-memoryDbDataReaderthat holds every result set read synchronously. Its async members areDbDataReader'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, andInsufficientDatabasePrivilegeException/IMigrationLogger.OnFailurefailure handling, all as inMigrator.ApplyAllAsyncandPostgresqlMigrator.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 inNpgsqlCommand.WriteExecute: for a synchronous call, Npgsql writes the second and later statements of a multi-statement command or batch on the thread pool (ShouldSchedule→ aConcurrentExclusiveSchedulerPairoverTaskScheduler.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 blockedTask.Runwriters 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.AutoCreatemodes: withAutoCreate.Nonenothing is read or built. The old path read the catalog and then applied nothing.CreateOnlystill refuses to update an outdatedmt_get_next_hiwith Weasel's ownSchemaMigrationException, andCreateOrUpdate/Allcreate or update it. Parity tests compare the synchronous determine against Weasel'sSchemaMigration.DetermineAsyncfor 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.ApplyAllConfiguredChangesToDatabaseAsyncstill creates these objects as before. The concurrent first callers still wait on theRuntimeSequenceslock, 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
RuntimeSequenceslock. 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.AdvanceToNextHiSyncno longer waits on the in-flight prefetch, andSynchronousPrefetchWait(internal) is removed. If the prefetched block has already landed it's installed. OtherwiseStore()fetches a block synchronously straight away. #5938's atomicmt_get_next_himakes 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)
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.a_failed_prefetch_falls_back_and_never_poisons_the_sequencestill passes.NextLongAsyncpath is unchanged and still awaits the prefetch, which is fine because it doesn't block.Tests
hilo_thread_pool_starvation_tests(new, inHiloThreadPoolCollection,DisableParallelization): runsThreadPool.ThreadCount + 16Task.Runwriters, each calling synchronousStore()on two cold HiLo types (fresh schema, document storage resolved first), while aTask.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.csis 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,CreateOnlyandAutoCreate.None, plus the statement-splitter theory.hilo_prefetch_tests: droppedSynchronousPrefetchWaitfrom two tests and renamedfalls_back_…_when_the_prefetch_outlasts_the_wait→…_has_not_landed. Replacedthe_synchronous_path_waits_for_the_prefetch_instead_of_competing_with_itwiththe_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 asracing_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:DOTNET_PROCESSOR_COUNT=2(20 writers), 2 runsDOTNET_PROCESSOR_COUNT=2, 5 runsTimeout during reading attemptDOTNET_PROCESSOR_COUNT=2, 5 runs2-CPU Linux container (
docker run --cpus=2 mcr.microsoft.com/dotnet/sdk:10.0, test host run withdotnet DocumentDbTests.dll, PG on the host), 3 runs each. The "before" binary is master's Marten (verified by byte-searchingMarten.dll):hilo_prefetch_tests(10 tests)concurrent_sessions_storing_documents_get_unique_idshilo_tests(10 tests)hilo_tests.is_thread_safeSuites (net10.0, run directly against the test hosts)
On the head of this branch, rebased onto current master (which includes #5965), against
marten_10_ffon PG 17, with no retries: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 thatStore()no longer waits on the background fetch, that the first id builds the storage synchronously, and thatAutoCreate.Noneno longer reads the catalog. markdownlint and cspell report 0 issues.Found along the way (not fixed here)
NpgsqlBatchdepends 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 synchronousSaveChanges(), which batches its operations. Master has dropped most synchronous data access, so this is mostly a 9.x concern.HiloSequenceBase(Weasel) holds itsSemaphoreSlimgate across theawaitinNextLongAsync, and Marten's asyncAdvanceToNextHistill awaits the prefetch under it. A synchronousNextLong()on the same sequence then blocks a thread on that async work. Marten never callsNextLongAsyncin production, so it can't happen today, but it is the same pattern.🤖 Generated with Claude Code