Skip to content

perf(fileservice): re-land #32697 with fixes for remote column prefetch and the idle timeout - #32812

Closed
cpegeric wants to merge 240 commits into
matrixorigin:mainfrom
cpegeric:ivf_pin_entries
Closed

cpegeric wants to merge 240 commits into
matrixorigin:mainfrom
cpegeric:ivf_pin_entries

Conversation

@cpegeric

@cpegeric cpegeric commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #32811 #32792 #32796

What this PR does / why we need it:

Lands #32697 (with #32382) again, after its revert in #32809, with fixes for the regressions it caused. Against main this PR is #32697 plus the fix commits: d4d5221, 85d1d53, 1628d10, b4d7e52, 72499cc, 42e56c0, 16a7ceb, 832010e, 9e61768, 695fb9e, d884475, 95e6dee, 4b233a1, 8be6868, 11271e0, a1ad3d3, 2c3c3c9, 23b7e20, 8775af2, e0dda0a, 976676d and 6975ae0.

Nightly TN OOM: a finished download kept its source (pkg/fileservice, 11271e0)

  • The nightly regression of this PR (run 44220270906) OOM-killed the TN (32 Gi) during sysbench, after TPC-C; the IVF 10M LOAD DATA before it ran past its 1-hour timeout (main: ~28 min).
  • Cause: d4d5221 registered each fill's source reader with its objectDownload and never removed it, and the disk cache keeps the download of every cached file. For a TN write the source is the written object's bytes, so the TN kept every object it wrote while the object stayed cached.
  • A download now lists only the readers still reading. On TPC-C the TN's live heap after idle drops from 1,041 MB to main's level, and the writer buffers it held (306 MB WriteArena, 191 MB bytes.Buffer) are gone.

#32792: no idle timeout while a read waits (pkg/fileservice)

  • While a read waits for the bytes of a whole-object download or a prefetch range read, the download is bounded only by that read's context. Its wait for a connection, the response and each byte has no other timeout. This covers the read that started the download and any read that joined it.
  • Once no read waits, a download whose source sends nothing for 20 s stops silently. That frees its connection, prefetch memory and cache-write slot. A read that comes later reads its own bytes.
  • Before, the timer ran while reads waited and counted the wait for a free pooled connection, so reads failed under load.

#32796: remote scans prefetch column ranges (pkg/vm/engine/readutil, disttae)

  • A scan of some of a table's columns, and every index join-back scan (IVF-Flat, HNSW, CAGRA, fulltext, vector pre-filter), skips whole-object preloads and relies on column-range prefetch. Only LocalDisttaeDataSource did that prefetch. RemoteDataSource, on each other CN the scan is distributed to, prefetched nothing.
  • The column prefetch, its PrefetchScan handle and the scan pace move to readutil.ScanPrefetch, used by both data sources. The remote data source runs it whether or not it has a proc, and ends its scan on Close.

Asynchronous disk-cache writes wait instead of being dropped (pkg/fileservice, b4d7e52, 11271e0)

  • The disk cache wrote asynchronous updates on one goroutine, fsyncing each file in turn, with 64 slots.
  • Under TPC-C on two CNs, the column-range reads cache many small entries. They filled the slots, and thousands of entries were dropped every few minutes, so the same bytes kept being read from object storage.
  • Now:
    • The caller writes the entry to a cache file; only its publication (fsync, rename, index) is queued, so no copy of the bytes waits. The delete check runs at the publication's claim.
    • 4 workers publish, with 512 slots. A write, a whole-object fill included, waits for a slot instead of being dropped; it is dropped only when the cache closes or the caller's context ends. A download reserves its slot before its connections.
  • With the change, no updates were dropped in a TPC-C run.

Cache files stay open across reads (pkg/fileservice; a1ad3d3, 2c3c3c9, e0dda0a, 976676d)

  • Column prefetch caches an object's column ranges as separate files (4–5 per object on TPC-H SF10), and every read opened each file again and first tried entry paths with no file: warm TPC-H spent its extra time in open.
  • The disk cache and the index-file cache each keep up to disk-open-files-max files open (default 128; 0 keeps none), shared by later reads at their own offsets, least recently read closed first. A path found without a file is not opened again until it changes. Any change or eviction of a path closes its file once no read holds it.
  • 128 because a process's services share its open-file limit (3 CNs + 1 TN in one test process hold up to 8 such pools); warm TPC-H read as fast at 128 as at 512 or 1024.

IVF-Flat reads of index-file objects share their decode (pkg/fileservice, pkg/vectorindex/ivfflat; 23b7e20, 8775af2)

  • Concurrent reads of an entry shared its decode only when the disk cache held the object; entries objects in the index-file cache did not, so each concurrent search decoded each entry itself. They now share it the same way.
  • A search held its cached entries objects by opening, stat'ing and closing each one; it now holds them without opening (IndexFileCache.HoldCached).

IVF-Flat searches no longer wait for whole objects (pkg/fileservice, pkg/vectorindex; 72499cc, 16a7ceb, 832010e)

  • Before, a cold IVF-Flat scan loaded each entries object whole into the index-file cache before reading it. On 2 CNs, 88–92% of cold scan time was that wait.
  • Now an entries object enters the index-file cache through the disk cache's own whole-object download, on a read or prefetch carrying IndexFileObject. Only where the finished file is published differs (a fillTarget: the disk cache, or the index-file cache). Reads join the download and get their bytes as they arrive. The scan holds only the entries already cached.
  • The download takes no disk-cache room, and its file is written in the index-file cache's directory, so publishing is a rename. An object deleted during the download is not published.
  • Filtered searches (SkipFullFilePreloads) and the IO pipeline's prefetch also fill the index-file cache. A failed put is logged, not counted as a disk-cache write failure. A CN without a disk cache does not keep index objects.

Cold multi-run reads stay within the prefetch memory budget (pkg/fileservice, 42e56c0)

  • With no prefetch read under way, a read admitted every in-memory run of its window, up to the 256 MiB window, whatever the budget.
  • Now the runs that fit are read in memory and the others through disk-backed prefetch objects; each run is still read once.

Cold column prefetches stay within the prefetch memory budget; opening a source is idle-timed (pkg/fileservice, 9e61768)

  • With no prefetch under way, a column prefetch started every missing range at once, each charged at least 64 KiB: 1,024 ranges of 16 KiB charged 64 MiB against a 32 MiB budget. Now ranges start while they fit; with none under way one starts, and the others wait for flights to end.
  • The 20 s idle timeout of a download no read waits for timed only reads of its source, so one blocked opening its connection was never stopped. Opening is now timed the same way, for range prefetches, split-download parts and whole-object fills.

A read the caches hold does not wait for a queued prefetch (pkg/fileservice, 695fb9e, d884475)

  • A read joined a queued prefetch download of its object before looking in the caches, so a column read the disk cache held could wait for a download of other columns to start. A read now looks in the caches first, and a column read joins only a download of the whole object or of ranges holding bytes it reads.
  • A column prefetch reports itself started only once every range is under way, so a read that joined it finds the flight for its bytes.
  • A read that skips disk-cache reads (such as a SkipAllCache range lease) joins no queued download, since it cannot read what the download caches.

A full prefetch queue keeps a scan's column prefetches (pkg/fileservice, readutil, disttae; 95e6dee, 4b233a1, 8be6868)

  • The byte-limited prefetch queue dropped scans' column prefetches on SF100. Each dropped object was then read block by block: Q19 made 72 serial reads per lineitem object.
  • The queue is now bounded by half the disk cache. The scans' windows bound what is queued at once: on SF100 the queue held at most 1.8 GiB per CN.
  • An unordered scan asks again for an object's columns when it reaches the object, due now, so a request dropped at the bound costs lookahead, not per-block reads.

Review fixes (pkg/fileservice, readutil, sql/compile, proto; 6975ae0)

  • The disk cache keeps every object delete while it loads its files, so a burst of deletes does not make the load remove valid cache files.
  • A request for ranges the running download of its object does not download is queued once that download ends; before, it was counted as merged and lost.
  • A prefetch's object size is dropped only when that object was deleted, not when any object was.
  • A prefetch downloads at most 4 of its ranges to files at once, so it cannot take most of the download connections.
  • Table scans of an IVF-Flat entries table read whole objects into the index-file cache; an ordered remote scan prefetches no object's columns.
  • Plan node field 97 (narrow_scan, no longer read or set) is unused1.

docs/design/20261110-object-prefetcher.md v9 records the idle, async-write, prefetch-queue, download-source and open-file rules as decisions (prefetch memory: 5% of the memory available); docs/design/20261111-index-objects-in-index-file-cache.md records how index objects are loaded.

Validation

Two CNs, each reading object storage through an emulated link of 110 MiB/s (~0.9 Gbps, the TKE COS read speed) with 25 ms per request, from MinIO. Main 43addc1 vs this PR eb1f212, two interleaved runs each, every run a cold restart with empty caches.

TPC-H SF100 (66 GB stored), Q1–Q22 in order. Per CN: 4 GB memory, 200 GB disk and 100 GB index-file cache. Main 7fc45a2 vs this PR at 95e6dee, two runs each, and at 8be6868, one run.

main 95e6dee 8be6868
Q1–Q22, cold 491.2 / 492.8 s 355.9 / 359.3 s 341.6 s
Q1–Q22, warm 253.2 / 256.6 s 241.1 / 233.7 s 237.9 s
bytes over the links 55.5 GB 34.7 GB 34.7 GB
prefetches dropped 0 0 0
  • Q1–Q3 are the first queries to read each table; this PR reads the columns they use, main whole objects.
  • A manual cold run at 4b233a1 dropped no prefetch; Q19 took 17.1 s (main 16.5–17.0 s) with every lineitem object's column in one request and none read block by block.

Wiki 1M 768-D vectors, IVF-Flat 1000 lists, probe_limit 8, 8 sessions per CN, 1000 queries per round, after a TPC-H SF10 round. Per CN: 4 GB memory, 20 GB disk and 10 GB index-file cache.

main this PR
unfiltered, cold, QPS 55.5 / 55.7 57.2 / 55.5
unfiltered, cold, p95 564 / 568 ms 281 / 153 ms
filtered, after unfiltered, QPS 532 / 503 770 / 701
index-file cache after wiki, CN1 / CN2 0 1.3 / 2.0 GB

Local 2-CN cluster (no link emulation), main 517e169 vs this PR, warm = second and third round; one run each unless noted.

main this PR
TPC-H SF10 cold / warm 15.73 / 8.19, 7.99 s 12.97 / 7.56, 7.40 s
TPC-C, live heap of log+TN+CN1 after idle 426 MB 620 MB (~157 MB unflushed CN partition state; 1,041 MB before the leak fix)
TPC-C tpmC, 2 rounds, CN1 / CN2 6,948 / 5,963; 5,762 / 4,977 7,175 / 5,015; 6,478 / 4,412
wiki 1M warm unfiltered QPS, 2 interleaved runs 556–626 569–586 (equal within run-to-run variation)
wiki 1M filtered QPS 83–138 469–496

Connection-pool starvation against MinIO, idle timeout scaled down from 20 s to 100 ms: 8957 → 0 idle errors at 128 connections and 2048 readers; 7 → 0 at 13 connections.

Unit tests:

  • TestIdleReaderTimesOnlyDetached, TestDiskCacheWaitedDownloadIsNotTimed, TestPrefetchFlightWaitedIsNotTimed and TestRemoteDataSourcePrefetchesColumns, through the real NewRemoteDataSource. Each fails without its fix. The three idle tests and the existing stalled-download tests passed 100× under -race; so did TestRemoteDataSourcePrefetchesColumns.
  • TestIndexObjectReadFillsIndexFileCache, TestIndexObjectMissReadStreamsIntoIndexFileCache, TestIndexObjectPrefetchFillsIndexFileCache, TestIndexObjectAsyncFillPublishes, TestIndexObjectFillOfDeletedObjectIsNotPublished, TestIndexObjectFillWritesInIndexFileCache, TestNonIndexObjectFillUsesDiskCache, TestHoldIndexObjectsOfScan, TestMergePrefetchKeepsPolicy, TestPrefetchMemoryBoundForColdMultiRunRead, which fails without its fix (512 KiB in flight against a 128 KiB budget), TestColumnPrefetchMemoryBoundForColdRanges (without its fix all 8 ranges start against a budget for 2) TestPrefetchFlightFailsWhenOpenStalls (hangs without its fix), TestS3FSCachedColumnReadDoesNotWaitForQueuedColumns and TestS3FSColumnReadLeavesQueuedOtherColumns, TestS3FSCacheBypassReadLeavesQueuedObject (each waits without its fix), and TestPrefetchQueueLimit. Each new test passed 100× under -race.
  • TestDiskCacheDownloadKeepsNoSourceReader (fails without the leak fix), TestDiskCacheAsyncUpdateWritesBeforePublication, TestDiskCacheAsyncUpdateKeepsNoBytes, TestDiskCacheAsyncSetFileWaitsForFinalizeCapacity, TestDiskCacheReadKeepsFileOpen, TestDiskCacheKeptFileClosedOnDeleteAndClose, TestOpenFilePoolLimit, TestDiskCacheConcurrentReadsOfKeptFile, TestDiskCacheMissingPathForgottenOnWrite, TestDiskOpenFilesMaxConfig, TestDiskOpenFilesMaxZeroDisablesPool, TestIndexObjectReadKeepsFileOpen, TestIndexObjectSharedDecodeFillEligibility and TestIndexFileCacheHoldCached passed 76–100× under -race; so did the review fixes' TestObjectDeletesKeptWhileLoading, TestPrefetcherQueuesUncoveredRangesAfterRunningDownload, TestObjectPrefetchCovers, TestPrefetchFilesBoundsRangesAtOnce and TestPrefetchedSizeStoredOnlyWithoutDelete, each failing without its fix.
  • fileservice, objectio/ioutil, vectorindex/indexfile and vectorindex/ivfflat pass normally and under -race. readutil passes normally and under -race. disttae, sql/compile and sql/plan pass.

Limits

  • A read that waits for a stalled source now waits until its context ends or the one-minute I/O wait bound, then reads its own bytes. Before, it waited the 20 s idle timeout.
  • An entries object already whole in a CN's disk cache, as after that CN writes it, is served from there and moves into the index-file cache only after the disk cache evicts it.
  • When the index-file cache is smaller than the entries a search reads, objects are evicted before reuse and read again, as for any index file.
  • A Close whose context ends first can leave a pending put into the index-file cache running. It completes a valid entry or leaves a temp file that startup removes.
  • A disk-cache write waits for a publication slot when all 512 are taken, a TN object write's fill included; the 4 workers only fsync and rename.
  • Kept cache files count against the process's open-file limit: up to 2 × disk-open-files-max per service.
  • [Bug]: Main Wiki IVF 10M drops to ~2 QPS with S3 read amplification and RPC failures (suspected #32697 regression) #32760 is the documented capacity limit of the index-file cache: Wiki IVF 10M entries (~30 GB) need index-file-disk-capacity above the 8 GB default.

🤖 Generated with Claude Code

cpegeric and others added 5 commits November 16, 2026 09:45
…-file cache (matrixorigin#32697)"

This reverts commit b465f86, which also
carried the fileservice range-read and prefetch changes of matrixorigin#32382.

It regressed distributed SSB scans (matrixorigin#32796), Wiki IVF 10M under index-file
cache pressure (matrixorigin#32760), and fails reads with an idle-source timeout while
they wait for a connection (matrixorigin#32792).

Conflict resolution with later commits: policy.go keeps
ReplayDataForDiskCache from matrixorigin#32782 and drops ColumnPrefetch, ExactRead and
IndexFileObject; the replay write in S3FS.write calls fillFile without the
object-layout argument that matrixorigin#32697 added.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
While a read waits for the bytes of a whole-object download or a prefetch
range read, the download is bounded only by that read's context: its wait
for a connection, the response and each byte has no other timeout. Once no
read waits, a download whose source sends nothing for 20 s stops silently.

The timeout used to run while reads waited and counted the wait for a free
pooled connection, so reads failed under load (matrixorigin#32792).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A scan of some of a table's columns skips whole-object preloads and relies
on column-range prefetch, which only the local data source did. The remote
data source of each other CN a scan is distributed to prefetched nothing,
so it read each block's columns as separate serial range reads (matrixorigin#32796).

The column prefetch, its scan handle and the scan pace move to
readutil.ScanPrefetch, used by both data sources. The design doc records
both this rule and the idle-timeout rule (v6).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@mergify

mergify Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is closed, so it cannot be queued. Reopen it to get the box back.

cpegeric and others added 2 commits November 16, 2026 11:44
…refetch

- A whole-object fill counts the read that started it as waiting before
  the fill reads its source, not after the read receives the download, so
  the fill's wait for a connection is never timed while that read waits.
- A fill that still stops for the idle timeout leaves that read to read its
  own ranges instead of failing it.
- ScanPrefetch.End also resets the scan pace, so a data source reused after
  Close measures its pace afresh.
- RemoteDataSource keeps the existing preload check: ColumnPrefetch always
  comes with SkipFullFilePreloads, which it already skips.
- The waited-download tests leave 200 ms for the waiting read to attach.
- The design doc states which waiting reads give up after the I/O wait
  bound and which wait until their context ends.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
cpegeric and others added 30 commits November 25, 2026 14:17
… from the registry

The cache's postSet finds the download of the fill publishing a whole
object in the one registry, so the bytes readers took from it count
toward the cached file. No behavior change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…l's download

The read that starts a whole-object fill and streams its entries takes
the download of its own fill, from the fill's context, instead of looking
the object up in the whole-object download registry. No behavior change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Every place a read or a fill looks for a prefetch object to join (the
disk cache's read, readFromFlights, fetchRange, prefetchRead, a fill's
own join) applies one predicate: the object holds the bytes, is of the
reader's own cache, is live, is joinable, and ends cached when the reader
caches; a file fill is joined only when its bytes arrive no more than the
max extra wait after a range read could fetch them.

Behavior changes the range-fill design states: a read of an index object
joins only fills of the index-file cache, and a read of the disk cache
only fills of the disk cache; a stopped prefetch object is not joined. A
fill whose download wrote every byte stays live after its starter's
context ends, so a fill handed to an async finalize is joined until its
file is published (this also corrects the liveness check of the disk
cache's read from the earlier commit). White-box tests pass the cache to
the lookups they call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…he fill

The cache a download publishes into is the fill's (the download no longer
records it), the measurement of the download rate follows from the fill's
starter (a fill of bytes the write path holds is not measured), the split
into parts and the end of a whole object come from the fill, and a fill
of bytes the write path holds is made before its download and registered
with it. Preload credit stays the download's, set when it registers, and
the async finalize hand-off is the fill's. No behavior change.

White-box tests register hand-made downloads through the fill and check
the cache of a fill instead of the download's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Fills under way are registered only in the prefetch-object registry; the
whole-object download registry and its lookups are gone. What it still
provided, the count of downloads in flight that bounds splitting, is a
counter of that registry, taken in the same step as the split decision.
finishDownload takes effect once. Reads decide between waiting for a fill
and reading their own bytes through one rule; the duplicate-ratio rule for
fills of a whole object remains as a parameter of whole fills, which
TestDiskCacheReadWaitsWhenItWouldDuplicateTheDownload requires.

The test helper that finds a whole fill's download moves to the tests;
white-box tests count downloads in flight on the registry. No behavior
change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ithout cost model, publisher

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A whole-object fill publishes its file under the range name of the bytes it
holds and indexes it like any range; there is no separate whole-file name.
A fill of unknown size owns its range file once it finds the size. Reads
find cached bytes in the range index only; deletes and eviction remove a
whole object as one range. Startup removes cache files left under the old
whole-file name. A prefetch of an object of unknown size learns the size
from object storage when a range from the object's start is cached.

Fix-missing no longer restores objects from the disk cache: the setting is
accepted and ignored, and the flag and environment variable are removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each S3FS has one governor with room for min(max-conns-per-host,
storage concurrency) requests; it replaces the storage semaphore, the
metrics and HTTP-trace wrappers and the disk cache's download pool.
Waiting requests are admitted foreground first, then background, in
arrival order; background runs at most half the room; a running request
is never stopped; every wait ends with the waiter's context or close.

The governor offers typed requests and passes no functions: stat,
exists, delete, copy, identity stat, a listing entry by entry, a range
read into a caller buffer, a fill's file or a returned buffer with a
concrete progress record, a put of a buffer or a staged file, a disk
publish, and multipart create/part/complete/abort. A retry of a request
waits with no room held.

Caller code runs with no room held: a stream is a fill read in one
request into charged flight memory or an unlinked temporary file,
WriterForRead gets its range once read, a write's parts are read before
each part request (MinIO and Aliyun gain multipart), the disk object
storage stages the stream and publishes it in one request, and other
storage gets it from a temporary file. Fills take no room at admission;
each part of a split fill is its own request, and an unknown-size fill
stats in a request of its own. A waiting flight is not joinable and a
foreground flight's buffer is not held back by background flights.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… retry

The governor's room is min(max-conns-per-host, concurrency) and never
below 64: a smaller configured value is raised to 64 with one warning
naming the configured values, instead of being rejected. Background
requests hold at most half of it. setCapacity and the background floor
of 1 are gone; tests make contention by holding the rest of the room.

AWS calls wrapped in DoWithRetryContext make one SDK attempt and are
retried on the standard retryer's errors as often as it would retry
them; copies, multipart aborts and the bucket check keep the SDK
retryer. MinIO list, stat, put, delete and multipart calls go through a
client with MaxRetries 1 and are retried on the SDK's retryable
statuses and codes; copies, the bucket check and object reads, whose
request starts at the first read, keep a client with SDK retries. COS
already makes one attempt; the Aliyun SDK has no request retries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each request to object storage is a value of one of a closed set of
request types; governor.Do waits for room, makes the request on raw in
one switch and frees the room. writeParts makes its requests through the
same Do on the governor or on storageParts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A prefetch makes queued fills in the disk cache's one registry, next to
the prefetch objects under way, under its one lock. A queued fill is a
range, or the whole object, of one object into one cache. It waits as
data, holding no goroutine, buffer, file or room, ordered by class, then
share, then due time, then arrival. The first in order starts once it is
foreground, or once fewer background fills run than the governor's
background room and no foreground flight waits for a buffer, and, when
held in memory, once its buffer fits. A fill of ranges becomes, in the
step that starts it, the prefetch objects it registers; a fill of the
whole object stays registered until reads can join its download.

A prefetch for bytes a waiting fill of the same cache holds merges into
it (sooner due, larger share, both scans); bytes a fill under way holds
need nothing more, and a read-started download a fill relies on is kept;
the other bytes get fills of their own at once. Waiting background fills
are bounded by bytes, dropping ended-scan fills first, then the last in
order. A fill whose scans ended and no read joined never starts.

A read joins every waiting or running fill of its cache that holds bytes
it needs and promotes it: it orders first, its requests wait for room as
foreground ones (the governor moves a waiting background request whose
fill is promoted to the foreground waiters), and its buffer moves to the
foreground charge. A promoted whole fill splits at the read's block. A
part that has not begun is estimated as beginning now, so a read joins it.

One flight-memory budget is never exceeded: a fill or stream is
memory-backed only when its buffers fit its class's share (all for
foreground, half for background), a buffer is taken only when it fits,
and background takes none while a foreground flight waits for one.

Removed: the prefetcher (prefetch and live queues, workers, deferral,
joinQueued), readRanges and its slots, prefetchWorkers/prefetchShare,
governor.hasRoom and joinability by room, and foreground flights ignoring
background bytes.

Wait-for graph (an edge is "waits for"):

  read R      -> whole fill started (closed by its goroutine F at
                 registration or end)
  read R      -> fill bytes (written by F's requests Q; ended by F)
  read R      -> flight budget B (freed by the last release of a flight
                 or stream; flights end with their requests)
  read R      -> own request Q
  fill F      -> path owner P -> publisher U / other fill F'
  fill F, F'  -> request Q
  request Q   -> object storage (bytes, error, ctx, idle timeout)
  waiting fill-> nothing (data)

Q holds room and waits only for object storage. F takes its buffer,
registration and temp file before Q asks for room. P, U and F' wait only
for Q or other paths, never for R or a waiting fill. Nothing waits for R
or for a waiting fill, and every edge ends with the waiter's context, the
fill's end or object storage, so the graph has no cycle. The registry
lock is never held while waiting and is never taken under the governor's
lock.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ght budget

Record the contracts step Q needs: when the first waiting fill starts,
what a started fill is in the registry, a whole fill taking over waiting
range fills, deletes and close reaching waiting fills, a promoted running
fill's requests and buffer, and the one flight-memory budget.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Larger share first, an unknown share as the whole object, then the sooner
due time, then arrival, one fill at a time.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…etch

The read joins the whole-object fill it reads bytes of and is served by
it, so the fill no longer waits after the read; remove the opener the
removed range-prefetch tests used.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…budget

A memory-backed stream (ReadCloserForRead, a WriterForRead stream) frees
its buffer only when its caller closes it. Charged to the flight budget,
a caller holding open streams that filled the budget and then reading a
range whose flight needed a buffer waited on itself until its context
ended, and many such callers could all wait the same way.

Streams now charge a bound of their own, the size of the flight budget
(the same value: prefetchFlightBytes when set, else the measured share of
available memory). A stream takes a buffer only when its bytes fit that
bound at open, in a non-blocking check; otherwise it reads into its
temporary file, as when its size is unknown or too large. Nothing waits
for stream memory. Only flights charge the flight budget. Peak memory of
fills and streams is the flight budget plus the stream bound.

Wait-for graph (an edge is "waits for"):

  read R      -> whole fill started (closed by its goroutine F at
                 registration or end)
  read R      -> fill bytes (written by F's requests Q; ended by F)
  read R      -> flight budget B
  B           -> end of a memory flight M's download and the copies of
                 the reads holding M (a copy waits only for M's bytes)
  M           -> request Q
  read R      -> own request Q
  fill F      -> path owner P -> publisher U / other fill F'
  fill F, F'  -> request Q
  request Q   -> object storage (bytes, error, ctx, idle timeout)
  stream S    -> request Q (its memory is taken or refused at open)
  waiting fill-> nothing (data)

Every wait for memory is a wait for B, and B is held only by memory
flights: a flight frees its buffer once its download ends and the reads
holding it have copied, and a read holds a flight only while it copies,
releasing it before any caller code (WriterForRead, decode, the caller's
stream) runs. No edge reaches a caller, a stream, or code the caller runs,
and no node waits for R or for a waiting fill, so the graph has no cycle.

Probe TestStreamProbeOpenStreamsDoNotBlockFlights: a caller opens two
memory-backed streams that fill the old shared budget, keeps them open,
and reads a column range whose flight needs a buffer. Red on 718309c:
the read fails with context deadline exceeded after 2 s. Green: it returns
in under 1 s. Control: the same read with no stream open returns, and the
streams read their bytes. TestStreamProbeStreamBytesWithinBound: of six
streams only those fitting the bound take buffers, stream bytes never
exceed it, and no stream charges the flight budget.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Per the split policy, only a fill of a whole object splits into parts; a
fill of a smaller range is one part. A waiting range fill and a file run
of a read through prefetch ranges were still split by rangeParts. Each is
now one prefetch object of its range: memory-backed when the range is at
most the memory limit and its buffer fits its class's share, file-backed
otherwise. Whole-object splitting is unchanged, including starting at the
first joined read's block.

Removed: rangeParts, DiskCache.downloading (used only by it), withinShare
(folded into memoryBacked, its one caller), and the parts count and first
error of a queued fill (a range fill has one prefetch object, so it ends
with it; partEndedLocked is now rangeEndedLocked).

Test deleted: TestBlackBoxPrefetchRangeSplitIntoParts, which asserted that
a range prefetch of at least the split size is read as two parts cached as
two range files, the behavior removed here.

Probe TestRangeFillProbeOneRequestWholeObjectSplits, memory- and
file-backed: a 1 MiB range prefetch with a 512 KiB split size makes one
request for its range and caches one range, and a read across its middle
is served from the cache. Control, run first: a whole object of the same
size splits into its two parts. Red on 53c0ece: the range is read as
[65536 589824]. Green: [65536].

Co-Authored-By: Claude Opus 5.5 <[email protected]>
All memory-backed streams together hold at most disk-prefetch-memory-max
(32 MiB by default), apart from the flight budget.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Rename the type, its constructor, fields, files, tests and comments.
No behavior changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each file service has one object storage server, with a connection pool
and a memory budget of its own; nothing is shared across file services.

- Pool: every HTTP client gets a transport of its own, also when
  max-conns-per-host is unset; its connections and idle connections per
  host are the room. Room is min(max-conns-per-host or 128, concurrency
  or 1024), at least 64.
- One order for room: waiting requests are admitted foreground first,
  then background, each by a larger share, a sooner due time, then
  arrival. Fills wait with their share and due time; other requests
  have the whole share and are due when made.
- Memory: one budget per server, object-storage-memory (default 5% of
  the memory available, measured about every second, or 256 MiB).
  Memory is never waited for: fill buffers, stream buffers and write
  parts read from callers are taken only when they fit at once,
  foreground within the whole budget, background within half of it;
  what does not fit goes to a file. A fill is made memory-backed only
  when its buffer fits then, and takes it when its request is admitted,
  running file-backed if it no longer fits. A shrunk budget takes
  nothing back. The flight budget, its wait and order, the stream
  counter, the process-wide upload buffer budget and the process-wide
  upload semaphore are removed.
- A memory range fill waiting for room stays in the registry; a delete
  ends its wait.
- Writes of bytes in memory send the caller's bytes as they are (one put,
  or sections of them as parts), with no copy and no server memory. The
  SDKs send a section reader they are given without reading it into a
  copy. Parts read from callers use pooled buffers of the part size.
- Restored from main: the active-read operation count and the get-reader
  duration.
- disk-prefetch-memory-max is only the largest range held in memory.

Wait-for graph (an edge is "waits for"):

  read R        -> fill F started (closed at registration or end)
  read R        -> fill bytes (written by F's requests Q; ended by F)
  read R        -> own request Q
  fill F        -> path owner P -> publisher U / other fill F'
  fill F, F'    -> request Q
  request Q     -> room (held only by running requests Q')
  running Q'    -> object storage (bytes, error, ctx, idle timeout)
  retry of Q    -> room (holding only its own buffer)
  stream S      -> request Q (its memory taken or refused at open)
  write W       -> caller reader (holding no room and no wait)
  write W       -> its part requests Q (at most its concurrency)
  waiting fill  -> nothing (data)

No node waits for memory: every take is "fits now, otherwise a file".
Room is held only by running requests, which wait only for object
storage; a waiting request holds nothing a wait needs. No edge leaves a
request toward a read, a fill, a stream, a write or caller code, so the
graph has no cycle, whatever the caller holds or does.

Probes (object_storage_server_probe_test.go), red on f1d7381, green
here:
- OwnConnectionPools: with one client's 128 connections held, the
  other's request gets one at once. Red: context deadline exceeded.
- OneOrderForRoom: room and memory full; a foreground read and a
  background stat wait; one room frees; the read goes first. Red: stat.
- MemoryWithinBudget: memory held never passes the budget under reads,
  streams and prefetches; with the budget full a read returns at once.
  Red: peak 524288 over 262144.
- CallerMemoryBlocksNothing: streams fill the budget and writes from
  pipes block; a read and a caller-reader write complete at once.
  Red: write: context deadline exceeded. Control: same with none.
- InMemoryWriteCopiesNothing: 4 MiB and 32 MiB in-memory writes
  allocate under a quarter of their size. Red: 4197856 for 4 MiB.
- PartBuffersReused: 24 parts allocate under half a part each. Red:
  5704573 per part.
- MemoryBudgetConfig: set, default, shrink while in use. Red: invalid
  S3 argument: object-storage-memory.

Tests deleted: TestAwsParallelMultipartBufferBudgetBlocksBeforeRead and
TestParallelUploadBufferBudgetRejectsOversizedPartAndAcquiresAtomically
(the process-wide upload budget is removed),
TestFlightTransitionBudgetWaiterReturnsOnClose and
TestFlightTransitionBudgetWaiterContextEnds (nothing waits for memory).
Tests changed from "waits for a buffer" to "runs file-backed at once" or
"waits for room" where the old wait no longer exists.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…drops

Remove filePrefetchObject.fitsLocked and the probeJoined test helper,
which nothing calls since memory is never waited for.

TestServerProbePartBuffersReused allows less than one part of
allocation for each part with the race detector, which drops some
sync.Pool puts; without it, less than half a part. Under -race -count=50
-cpu 1,2,8 the half-part bound failed 3 of 150 runs (2.6-2.8 MiB per
5 MiB part). On f1d7381 a write allocates 5.7 MiB per part, past
both bounds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ports

An S3FS records the transports of the HTTP clients it makes, and Close
closes their idle connections, instead of leaving them for the 10 s idle
timeout. OwnsETLPath and CloseOwnedETL state which file services GetForETL
creates for a path (a local path or a service with arguments), so callers
close those and leave a named service open.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each user of GetForETL, GetForETLWithType, GetForBackup and NewOfflineFS
closes the file service it created when its last use ends: at function
exit, at the end of each listed directory or planned file, or in the
Close of the reader that holds it (S3 load readers, parquet and arrow
readers, iceberg delete files, hive partition listing, backup dirs,
object tool readers). deleteStageFile closed the file service
unconditionally, which closed a named shared service; it now closes only
one it owns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…cost model

A read that misses the cache joins every fill of its own cache holding any
of its bytes, waiting or running, each for the bytes it holds, and makes
fills of its own only for the bytes no fill holds. There is no estimate of
when bytes arrive, no extra-wait limit, no duplicate-bytes ratio and no
choice of the fastest fill. A read waits until its context ends or a joined
fill stops; for the bytes a stopped fill did not write it makes its own fill
(the existing stopped-fill path). A fill that ended holds only the bytes it
wrote. The two caches never join each other.

- fetchRange covers its range by the fills holding it, joins each, and
  fetches only the gaps (fetchPiece is the former single-range path).
- prefetchRead splits a block that fills hold only part of at their bounds
  and joins those pieces.
- joinableLocked returns the first registered fill holding the bytes.

Removed: prefetchObject.eta, fastestLocked, arrivesInTime, fastestPrefetch,
objectDownload.estimate, the download rate model (downloadRates,
downloadRateMinBytes, measured), rangeReadCost.cost/firstByte,
downloadDuplicateRatio, joinsFill, filePrefetchObject.declined and the
unpublished download path, fileDownload, memoryPrefetchObject.began, the
timeout of objectDownload.waitFor, the disk-download-max-extra-wait setting
(a .toml that still sets it loads: unknown keys are ignored), the
download_read_total{type="declined"} count and
disk_cache_download_declined_bytes_total; type="timed-out" is now
type="stopped". IOVector.downloadDeclined is now fillStopped.

Wait-for graph (no new edges; no cycle):
- read -> fill bytes (memory flight progress / download progress), until
  its ctx ends or the fill stops; holds no room, only buffer refs no one
  waits for.
- read -> server room, for a gap fill or a fill's request; holds nothing.
- read -> waiting fill started (joinFills), until its ctx ends.
- fill request holding room -> object storage only (bytes, error, ctx,
  idle timeout).
- fill -> path owner (paths.acquire) of its own range path, under ctx;
  owners are fills/publisher, which wait only for object storage or disk.
- nothing waits for memory: buffers are taken at once or the fill is
  file-backed.
Lock order is unchanged: prefetchObjects.mu before a fill's or a
download's own mutex.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…m is open

The probe sampled held memory only from a goroutine that need not run while
memory is held at GOMAXPROCS 1. Each stream now also records the held memory
after its open, when a stream or a read holds some.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch was successfully deployed

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

Labels

kind/bug Something isn't working kind/enhancement size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants