Skip to content

perf(fileservice): avoid buffering S3 uploads for disk cache - #32782

Merged
XuPeng-SH merged 2 commits into
mainfrom
codex/32751-s3-cache-replay-main-20261116
Nov 15, 2026
Merged

XuPeng-SH merged 2 commits into
mainfrom
codex/32751-s3-cache-replay-main-20261116

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Problem

When an object writer uses S3FS with disk-cache writes enabled, the upload is currently teed into a growing bytes.Buffer, which is then copied into the disk cache. The entire object is retained in a second Go heap buffer during the write. Buffer growth can allocate more than the object's size cumulatively.

Change

  • Object writers opt in through a cache policy that promises their prepared Data entries and owners remain stable until the synchronous Write returns. Ordinary FileService.Write calls and wrapper side effects are preserved.
  • For known-size, contiguous, exact-sized in-memory entries, S3FS reads the entries with a cursor for both upload and disk-cache fill. It replays only the prefix actually consumed by the upload. Streams, gaps, invalid sizes, disabled cache writes and callers without the policy retain the existing path.
  • Main's disk-cache copy reads the data synchronously; only file finalization can be asynchronous. A test blocks the finalizer, changes the caller's buffer after Write returns, and verifies the published cache. This checks for later reads of that buffer; it does not measure GC reachability or immediate heap reclamation.

This adds a policy bit visible to custom file-service implementations. In-tree consumers use policy masks, and tests exercise forwarding wrappers; downstream implementations that compare the complete policy value should review the new bit. No SQL type or object format change is intended.

Evidence and limits

  • On a local disk-backed S3FS with synchronous cache publication, a 4 MiB, two-entry write allocated 8,397,512 B → 41,128 B in Go TotalAlloc during Write. A 160 KiB write split into 10,000 entries allocated 2,932,688 B → 40,648 B. Cache contents and disk-cache hits were verified. In this run, both versions issued 256 write syscalls and wrote 8,388,608 bytes for the 4 MiB object plus its cache copy. These are cumulative allocations and process syscall counts, not peak RSS or physical-disk traffic.
  • A single-thread in-memory benchmark draining the actual reader/capture components to a discard sink measured 160 KiB / 10,000 entries at a median 642 µs → 182 µs over three repetitions. It excludes disk, network and most file-service overhead. Four paired no-op Sync benchmarks were approximately 24.45 ns on both versions with no allocations; the isolated buffer-constructor median was 30.94 → 31.88 ns, also with unchanged allocations. These microbenchmarks do not establish end-to-end latency.
  • Two opposite-order local 1-CN/1-TN/1-log comparisons used a disk-backed S3FS, a 64 MiB memory cache, a 128 MiB disk cache, and a test-only 512 KiB CN spill threshold. Each loaded 32 rows totaling 5.94 MiB, then altered a column; all row hashes matched after both phases and each phase performed six S3 writes. Sampled LOAD RSS rises from phase start were 72.89 / 73.03 MiB on base and 63.94 / 66.38 MiB on head; shared-memory-cache maxima were approximately 5.97 MiB on both sides. These are observations in a small local setup and include other CN/GC activity. In one sampled cumulative heap profile, bytes.growSlice under S3FS.write accounted for 41.19 MB on base and was not sampled on head.
  • LOAD timings changed direction across those two pairs: base/head 2.50/3.81 s and 2.61/1.90 s. A separate local-disk fragmentation test also varied from milliseconds to hundreds of milliseconds on both versions. The evidence does not establish an end-to-end latency improvement or rule out a regression.

This optimization applies only when S3FS disk-cache writes are enabled. The production incident's cache configuration is not established here, a real S3 service and production network conditions were not exercised, and this change alone does not establish that a 251 MiB row can be processed safely.

Validation

  • Focused fileservice replay, stream, cancellation, partial-upload, cache-failure, wrapper, parallel-upload and async-finalizer tests: -race -count=10.
  • AWS SDK multipart upload to a local mock HTTP server, with two parts crossing entry boundaries and a cancellation that must not publish a cache entry: -race -count=3.
  • Complete pkg/objectio tests, normal and -race; includes object readback after arena release and a file-exists retry.
  • make static-check-selected STATIC_CHECK_PACKAGES='./pkg/fileservice ./pkg/objectio'.
  • Local S3FS/cache content checks and the two small CN comparisons described above.

Part of #32751. Counterpart: #32783.

@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 15, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is merged.

@XuPeng-SH

XuPeng-SH commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor Author

mo-bot review · mo-bot-local · done

Commit: 9c9ed5f70487da936742cbea06a5dcddbc4027a7

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mo-bot review · mo-bot-local · review

Commit: 9c9ed5f70487da936742cbea06a5dcddbc4027a7

Assessment: approve

Reviewed all 10 changed files and the main-branch upload/cache/object-writer ownership closure. The opt-in cursor removes full-object capture and entry cloning while reusing fillFile/contentFill and its existing buffered copy. Source consumption completes synchronously; async finalizers retain only file and cache bookkeeping. Fallbacks, cancellation, retry and cache-failure behavior remain aligned with the baseline. The added mechanism is proportionate to the allocation benefit and introduces no new worker or queue. No actionable finding remains; all discussion entries are informational and the broader #32751 integration tracker stays open.

Model: gpt-6.1-sol / max

Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0

Validation:

  • Private /tmp and loopback preflight passed; preflight.stdout and checks/1794777260637519252-2.json. Initial Go 1.26.6 selection failed the declared minimum; Go 1.27.1 was then recovered into the assigned task cache and selection passed (go127-selection.stdout; receipt 1794777505028799033-2).

  • Built fresh CPU prerequisites using current repository thirdparty/CGo Make owners in the diagnostic directory, including jemalloc; all 195 frozen native inputs and 69 produced library/header hashes verified. native-build.stdout, native-inputs.json, native-artifacts.json; receipts 1794777463065520502-2 and 1794778154654845732-2.

  • All 18 added test roots passed focused normal and race runs using the supplied test-exec, including real AWS SDK multipart on local HTTP, blocked finalization, stream/fallback, cancellation, consumed-prefix, wrapper, retry and arena-release readback cases. focused-normal.jsonl and focused-race-once.jsonl; receipts 1794777720784751535-2 and 1794777985759302595-2.

  • Complete owning-package short-mode runs passed normal and race: ./pkg/fileservice ./pkg/objectio, 921 root test passes in each run with six explicitly recorded skips. owning-normal.jsonl and owning-race.jsonl; receipts 1794777967661240295-2 and 1794778219588818666-2.

  • Six individually selected lifecycle/concurrency tests passed adaptive race repetition: concurrent inputs 50, blocked finalizer 58, multipart cancellation 100, multipart success 21, upload cancellation 100 and arena-release readback 19. race-plan.json, stress-Test*.jsonl and matching per-command receipts listed in validation-summary.json.

  • Owning-package build and incremental static checks passed: repository-pinned molint and golangci-lint reported zero issues; Go 1.27.1 gofmt clean. static-selected.stdout, owning-build.stdout, format-native-audit.stdout; receipts 1794777832561942838-2, 1794778295192445563-2 and 1794778154654845732-2.

  • Final source/discussion/execution audit passed: patch matches frozen head/base, source clean, all discussion keys covered exactly once, all added tests selected, native provenance verified, and logs reconciled with terminal source/command/exit receipts. review-audit.stdout, validation-summary.json and checks/1794778363039985778-2.json.

Limitations:

  • Frozen CI contains pending checks. Local validation used disk-backed S3FS, MinIO and mock HTTP rather than a real S3 service or production network. Six existing optional/short-mode tests were skipped and are not claimed as passes.

  • Author-reported allocation, syscall, local-CN RSS and timing measurements have no retained raw artifacts in local_validation. Source confirms removal of the capture buffer, but this review does not establish end-to-end latency, immediate heap reclamation, production peak-RSS benefit or safe processing of a 251 MiB row.

@XuPeng-SH
XuPeng-SH merged commit e1a0b7d into main Nov 15, 2026
@XuPeng-SH
XuPeng-SH deleted the codex/32751-s3-cache-replay-main-20261116 branch November 15, 2026 23:39
XuPeng-SH added a commit that referenced this pull request Nov 15, 2026
…32783)

## Problem

When an object writer uses S3FS with disk-cache writes enabled, the
upload is teed into a growing `bytes.Buffer`, which is then copied into
the disk cache. The entire object is retained in a second Go heap buffer
during the write. Buffer growth can allocate more than the object's size
cumulatively.

## Change

- Object writers opt in through a cache policy that promises their
prepared `Data` entries and owners remain stable until the synchronous
`Write` returns. Ordinary `FileService.Write` calls and wrapper side
effects are preserved.
- For known-size, contiguous, exact-sized in-memory entries, S3FS reads
the entries with a cursor for both upload and disk-cache fill. It
replays only the prefix actually consumed by the upload. Streams, gaps,
invalid sizes, disabled cache writes and callers without the policy
retain the existing path.
- On 4.2 the cache-copy reader implements `WriterTo`: it writes large
spans directly and batches small entries using the existing 32 KiB I/O
buffer pool. DiskCache avoids taking an unused second buffer when the
source already implements `WriterTo`. This preserves the prior `io.Copy`
source dispatch while avoiding extra small disk writes.

This adds a policy bit visible to custom file-service implementations.
In-tree consumers use policy masks, and tests exercise forwarding
wrappers; downstream implementations that compare the complete policy
value should review the new bit. No SQL type or object format change is
intended.

## Evidence and limits

- On a local disk-backed S3FS, a 4 MiB, two-entry write allocated
**8,395,368 B → 39,096 B** in Go `TotalAlloc` during `Write`. A 160 KiB
write split into 10,000 entries allocated **2,455,504 B → 38,816 B**.
Cache contents and disk-cache hits were verified. Across earlier
repeated runs, the 4 MiB object plus its cache copy used 129 write
syscalls and 8,388,608 bytes on both versions; the final run saw one
additional 8-byte background write on base. These are cumulative
allocations and process syscall counts, not peak RSS or physical-disk
traffic.
- A single-thread in-memory benchmark draining the actual reader/capture
components to a discard sink measured 160 KiB / 10,000 entries at a
median **472 µs → 141 µs** over three repetitions. It excludes disk,
network and most file-service overhead. Four paired no-op `Sync`
benchmarks were approximately 20.5 ns on both versions with no
allocations; the isolated buffer-constructor median was 4.247 → 4.369
µs, with unchanged allocations. These microbenchmarks do not establish
end-to-end latency.
- A local 1-CN/1-TN/1-log comparison used a disk-backed S3FS, a 64 MiB
memory cache, a 128 MiB disk cache, and a test-only 512 KiB CN spill
threshold. Each side loaded 32 rows totaling 5.94 MiB, then altered a
column; all row hashes matched after both phases and each phase
performed six S3 writes. Sampled LOAD RSS rise from phase start was
**80.94 MiB → 68.76 MiB**, but shared-memory-cache maxima differed (5.95
MiB on base and 11.89 MiB on head), so the RSS difference cannot be
attributed solely to this change. In one sampled cumulative heap
profile, `bytes.growSlice` under `S3FS.write` accounted for 37.40 MB on
base and was not sampled on head.
- Local-disk fragmentation measurements varied from milliseconds to
hundreds of milliseconds on both versions. The evidence does **not**
establish an end-to-end latency improvement or rule out a regression.

This optimization applies only when S3FS disk-cache writes are enabled.
The production incident's cache configuration is not established here, a
real S3 service and production network conditions were not exercised,
and this change alone does not establish that a 251 MiB row can be
processed safely.

## Validation

- Focused fileservice replay, stream, cancellation, partial-upload,
cache-failure, wrapper and parallel-upload tests: `-race -count=10`.
- AWS SDK multipart upload to a local mock HTTP server, with two parts
crossing entry boundaries and a cancellation that must not publish a
cache entry: `-race -count=3`.
- `WriterTo` tests cover large and fragmented vectors, exact prefixes,
partial/short writes, errors and cancellation.
- Existing `TestDiskCache*`, `TestS3FS` and subpath tests under `-race`.
- Complete `pkg/objectio` tests, normal and `-race`; includes object
readback after arena release and a file-exists retry. The legacy test's
hard-coded temporary root was redirected to a task-owned directory for
these local runs; this fixture adjustment is not part of the patch.
- `make static-check-selected STATIC_CHECK_PACKAGES='./pkg/fileservice
./pkg/objectio'`.
- Local S3FS/cache content checks and the small CN comparison described
above.

Part of #32751. Counterpart: #32782.
XuPeng-SH added a commit that referenced this pull request Nov 16, 2026
## What type of PR is this?

- [ ] API-change
- [ ] BUG
- [x] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

Related to #32751

## What this PR does / why we need it:

The object writer currently compresses into a separate scratch buffer
and then copies the compressed bytes into the writer arena. When the
unused arena tail already fits the LZ4 compression bound, that creates
an avoidable live allocation and copy.

Compress directly into the unused tail when it is large enough and does
not overlap the input. Commit only the actual compressed length to the
arena after success. Inputs overlapping the tail, insufficient space,
and writers without an arena keep the existing scratch path. The LZ4
format, extent metadata, ownership of completed output, and arena
accounting remain unchanged.

Validation on a CPU-only 57 host:

- Exact compressed bytes, offsets, NULLs, multiple sequential writes,
alias and insufficient-capacity fallback, and an in-memory object
write/read after arena reuse were checked. The full objectio package
passed normally and under race; the independent concurrent-arena test
passed 100 race repetitions. Incremental lint and formatting passed.
- In two isolated 1-CN LOAD/ALTER cases (one 8 MiB field and 31 64 KiB
fields, large field first or last), all row hashes and strict/non-strict
diagnostics matched. The load-idle native profile dropped the 16 MiB
compression scratch while retaining the 32 MiB arena. Sampled LOAD RSS
deltas changed 115.13→105.11 MiB and 106.39→95.11 MiB; one run per order
with 5 ms sampling is not an exact peak or a production-scale estimate.
- Combined with merged #32771, an additional 1-CN case preserved all
hashes and diagnostics. Its sampled LOAD/ALTER RSS deltas were
96.68/34.46 MiB versus 115.13/50.46 MiB in the separate base run;
profile attribution confirms both allocation reductions, but individual
runs are not directly additive.
- Three alternating microbenchmark rounds showed little change for 64
B–4 KiB serial inputs and about 52% lower time for 8 MiB varied input in
the direct path. A four-producer 4 KiB case was 1.3% slower. The initial
8 MiB fallback samples were 4–6% slower; eight additional alternating
pairs had a +0.39% median with several-percent variation. These
shared-host samples do not prove a universal no-regression result.

Rows whose compression bound exceeds the unused arena capacity retain
the existing path; this alone does not resolve the original
very-large-row OOM.

## Overlap guard and SCA follow-up

- `unsafe` is confined to `compression_overlap.go`, which compares
addresses without dereferencing or reconstructing pointers. The caller
must keep both buffers and their owners valid and must not release the
arena concurrently. `writer.go` remains subject to the unsafe-import
check. Empty, same-start, containment, both partial-overlap directions,
adjacent and separate slices are tested; real compression tests verify
that overlapping input falls back and adjacent input uses the direct
path.
- The pinned molint is the official master commit `147a3f213653` merged
in [linter PR 57](matrixorigin/linter#57); it no
longer depends on the unmerged compatibility branch. Compared with the
previous MatrixOne main pin, this version also includes three
function-scoped `recover` approvals already merged in [linter PR
56](matrixorigin/linter#56).
- The complete `pkg/objectio` suite passed normally and under race on
the earlier PR head. After merging the latest main including #32782,
compression and S3 writer/cache interaction tests passed under race, and
the official merged molint plus golangci passed `make
static-check-selected STATIC_CHECK_PACKAGES=./pkg/objectio` on commit
`11e75981aa3ce38812484cb533c093be89bf9260`. Full CI is running on that
head. The linter itself passed `go test ./...` before merge.
- Comparing the guard extraction against the earlier PR head on the
shared 57 host, the first three-pair 64-byte sample had a +3.35% median;
six additional alternating pairs had a -0.23% paired median. The 4 KiB
follow-up paired median was +0.09%. These short samples are noisy and do
not establish a universal performance result.
XuPeng-SH pushed a commit that referenced this pull request Nov 16, 2026
…-file cache (#32697)" (#32809)

## What type of PR is this?

- [ ] API-change
- [x] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue #32796 #32760 #32792

## What this PR does / why we need it:

Reverts #32697 (squash commit b465f86). That commit also carried the
fileservice range-read and prefetch changes of #32382, so both are
reverted.

It caused three regressions on main:

- **#32796**: distributed SSB scans are 8–11x slower. A scan of some of
a table's columns skips whole-object preloads and relies on column-range
prefetch. Only the local data source has that prefetch;
`RemoteDataSource` has none, so remote CNs read each block's columns one
range at a time.
- **#32760**: Wiki IVF 10M falls to ~2 QPS. Its entries objects (about
30 GB) do not fit the 8 GiB index-file cache, so searches keep
downloading whole objects again.
- **#32792**: reads fail with `fileservice: no bytes from the source
within the idle timeout`. The new 20 s idle timer also counts the wait
for a free pooled connection. A whole-object cache fill that waits that
long fails the query.

Root causes and the planned fixes are in the issue comments. The changes
will be re-landed with those fixes.

Conflict resolution with later commits, both from #32782:

- `pkg/fileservice/policy.go` keeps `ReplayDataForDiskCache` and drops
`ColumnPrefetch`, `ExactRead` and `IndexFileObject`.
- The replay write in `S3FS.write` calls `fillFile` without the
object-layout argument that #32697 added.

Validation: the build and `go vet` pass, and the tests pass in every
package the revert touches (`fileservice/...`, `objectio`,
`objectio/ioutil`, `vm/engine/readutil`, `vm/engine/disttae`,
`disttae/logtailreplay`, `tae/tables`, `tae/txn/txnimpl`, `sql/plan`,
`sql/compile`, `vectorindex/indexfile/...`, `vectorindex/ivfflat/...`,
`util/metric/v2`).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

This branch was previously deployed

1 inactive deployment
ci — 477ab890 Deployed Nov 16, 2026 by XuPeng-SH
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants