Skip to content

fix(objectio): age out idle write arenas instead of a global drain timer - #29303

Merged
fengttt merged 5 commits into
matrixorigin:mainfrom
fengttt:fix-write-arena-retention
Sep 25, 2026
Merged

fengttt merged 5 commits into
matrixorigin:mainfrom
fengttt:fix-write-arena-retention

Conversation

@fengttt

@fengttt fengttt commented Sep 24, 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:

No tracked issue. This was found while investigating memory use of parallel multi-file LOAD (the glob fan-out from #29242 / #29245).

What this PR does / why we need it:

After a wide parallel LOAD, about 1.6 GB of off-heap memory stayed resident indefinitely.

select mo_memory_usage('') pins it to the write-arena mpool: the WriteArena free lists in pkg/objectio/arena_pool.go.

  • Each concurrent S3 writer (the sinker) takes a large-tier arena.
  • Reset grows it to the next power of two of its biggest cycle, up to arenaMaxSize (128 MB).
  • PutArena parks it: up to 2 × GOMAXPROCS arenas.
  • The only release was drainArenaPools, run 10 minutes after the last ScheduleArenaDrain(). Every TAE checkpoint and every sinker Close called it, so on a live server the timer was pushed back indefinitely.

The memory is off-heap, so Go heap profiles don't show it.

Fix

Arenas now age out individually.

  • The free list is a stack of {arena, parkedAt}. GetArena takes the most recently parked arena, so the arenas a steady workload cycles stay on top and warm, while the surplus of a burst sinks to the bottom.
  • A one-shot timer frees idle arenas. It's armed only while arenas are parked, frees those parked longer than arenaIdleTTL (one minute), and re-arms for the oldest remaining one. The excess is released while other work continues, and an idle server releases too, with no permanent goroutine.
  • The old debounce is removed. ScheduleArenaDrain / drainArenaPools and their two call sites (checkpoint runner, sinker) are gone.
  • The count cap is unchanged.

Trade-off: an arena left unused for more than a minute is reallocated on its next use. That's at most one allocation per object write cycle, which is negligible next to the write.

Verification

Same machine (24 cores, single node), one glob LOAD of 40 lz4 CSV files (300 M rows) with parallel 'true':

after the load before after
write-arena at load end 1,598 MB 1,548 MB
write-arena 60–80 s later 1,598 MB 64 MB → 0 MB
write-arena 13 min later 1,598 MB —
process RSS, settled ~2,420 MB 1,172 MB

Two minutes after the load, TAE flush and merge of the new data use a few arenas again (~80 MB). Those are live work and age out the same way.

  • New pkg/objectio/arena_pool_test.go:

    • reuse within the TTL;
    • freed after the TTL with pool memory back to baseline;
    • a burst's surplus released while one arena stays in use;
    • the count cap.

    Passes with -race (-count=3).

  • go test: pkg/objectio, pkg/objectio/ioutil, pkg/vm/engine/tae/db/checkpoint and pkg/vm/engine/tae/mergesort pass.

  • make static-check: 0 issues.

Also in this PR: an unrelated CI fix

Since about 19:00 UTC on 2026-09-24, the SCA job has failed on every PR against main with a govet lostcancel warning in pkg/proxy/heartbeat_test.go (lines 153 and 179). TestServerHeartbeatSendsImmediately skipped cancel() on its t.Fatal timeout path. Commit b6615ed3db adds defer cancel() right after the context is created. It changes only the test, and it can be merged separately if preferred.

🤖 Generated with Claude Code

After a wide parallel LOAD the "write-arena" mpool kept ~1.6 GB of
off-heap memory indefinitely. Each concurrent S3 writer takes a large-tier
WriteArena, Reset grows it to the next power of two of its biggest cycle
(up to 128 MB), and PutArena parks it: up to 2x GOMAXPROCS arenas. The
only release was drainArenaPools, run 10 minutes after the last
ScheduleArenaDrain; every checkpoint and every sinker Close called it,
so on a live server the timer was pushed back forever. Measured on a
24-core single node: 1,598 MB parked after the load and still 1,598 MB
13 minutes later, invisible to Go profiles.

Arenas now age out individually. The free list is a stack of parked
arenas with the time each was parked: GetArena takes the most recent, so
the arenas a steady workload cycles stay on top and warm, and the surplus
of a burst sinks to the bottom. A one-shot timer, armed only while
arenas are parked, frees those parked for longer than arenaIdleTTL (one
minute) and re-arms for the oldest remaining one, so an idle server
releases too. ScheduleArenaDrain and its two callers are removed. The
count cap is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[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 →

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed head 06437c4. Static ownership/timer inspection found no demonstrated production double-free or use-after-free in Get/Put/reaper transitions. The exact-head CI run 35948805390 completed successfully. I did not run local tests; reported race-test logs could not be independently verified.

Comment thread pkg/objectio/arena_pool_test.go Resolved
XuPeng-SH pushed a commit that referenced this pull request Sep 24, 2026
…#29316)

## 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 #29315

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

`load_data/load_data_parquet.sql` fails intermittently in multi-CN CI at
`pq_file_fanout_rollback`. It failed on #29303, whose change is
unrelated.

```
[EXPECT RESULT]: invalid input: column name not found
[ACTUAL RESULT]: internal error: convert go error to mo error reading magic footer of parquet file: context canceled (read: 0)
```

### Root cause

- When one shard of a parallel load fails, it cancels its siblings.
- The scope scheduler reports the failing shard's error by recognising
each sibling's error as that cancellation (`normalizeScopeRunError` /
`preferPrimaryScopeResult`, via `errors.Is`).
- `moerr.ConvertGoError` formatted every Go error into an internal
error. So a context cancellation or deadline, often wrapped by a
library, stopped matching `errors.Is(err,
context.Canceled/DeadlineExceeded)`, and whichever shard's result was
collected first won.

It's not only the parquet reader:
- The planner's parquet footer read (`compile.go`) flattens the same
way.
- The four RPC error encoders (`pkg/pb/{pipeline,shard,lock,query}`) go
through `ConvertGoError` too, so a remote scope's cancellation reached
the coordinator as an internal error.
- About 88 call sites check `errors.Is` against the context sentinels,
including the frontend, CDC and RPC clients.

### Fix, in `moerr`

- **Conversion:** `ConvertGoError` converts a context error, wrapped or
not, to one of two new codes. The message is the original text.
- `ErrContextCanceled` (20109), sent to clients as MySQL
`ER_QUERY_INTERRUPTED`.
- `ErrDeadlineExceeded` (20110). A deadline joined with a cancellation
keeps the deadline.
- **`Error.Is`:** it matches only those two codes to `context.Canceled`
/ `context.DeadlineExceeded`. `errors.Is` then behaves after conversion
as it did before, and also after an RPC round trip, because the code is
what's serialized.
- **Unaffected errors:** errors built directly, such as a killed query
(`ErrQueryInterrupted`) or a statement timeout (`ErrQueryTimeout`),
don't gain new `errors.Is` matches.
- **RPC contract:** the result is still a `*moerr.Error`, as the RPC
encoders require. Returning raw context errors panicked those paths.
- **Mixed versions:** older nodes decode the new codes with their
message and MySQL code intact, because unmarshalling doesn't validate
codes.

This replaces the parquet-only `convertReaderError` from the first
commit of this PR. The parquet reader uses `moerr.ConvertGoError` again.

## Tests

Each of these fails without the change:

- **`TestConvertGoErrorKeepsContextIdentity`:** the mapping, MySQL
codes, kept message, marshal/unmarshal round trip,
deadline-over-cancellation for joined errors, and that directly built
`ErrQueryInterrupted` / `ErrQueryTimeout` / internal errors are
unaffected.
- **`TestPreferPrimaryScopeResult`:** a sibling's parquet cancellation,
both converted locally and decoded from `pipeline.EncodedMessageError`,
resolves to the failing shard's error.
- **`TestParquetOpenFileCanceledBySibling`:** opening a real parquet
file with a context canceled by a sibling reports `ErrContextCanceled`,
which matches `context.Canceled`.

Other checks:

- **`go test`:** `common/moerr`, `sql/compile`, `sql/colexec/external`,
`pb/...`, `cdc`, `txn/service`, `util/export/etl`,
`sql/plan/function/ctl`, `frontend`, `lockservice`, `shardservice` and
`queryservice` all pass.
- **BVT:** no expected result contains the old flattened cancellation
text.
- **`make static-check`:** 0 issues.

The CI race itself doesn't reproduce locally (60/60 single-node runs
gave the expected error), so the tests cover the mechanism
deterministically.

### Not covered

Code that flattens errors itself, e.g. `moerr.NewInternalErrorf("...%v",
err)` or `err.Error()`, still loses the identity. Those sites need
routing through `ConvertGoError` wherever a cancellation can reach them;
that's a separate follow-up.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
The large write-arena pool parks at most max(4, 2*GOMAXPROCS) arenas, so at
GOMAXPROCS <= 2 it has four slots. TestArenaFreedAfterIdleTTL returned five
arenas and asserted all five parked; the fifth is freed on Put, so the
assertion failed even though TTL expiry works. TestArenaBurstReleasedWhileStillActive
had the same shape: it returned eight and derived per-arena memory from what
stayed parked, which halves the estimate at four slots.

Size both fixtures by min(n, maxCount). Overflow past the cap stays covered by
TestArenaPoolCountCap. Passes with -race at GOMAXPROCS 1, 2, 3, 4 and 24.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
TestServerHeartbeatSendsImmediately only called cancel() when the first
heartbeat arrived, so a t.Fatal on the timeout path left the context
uncancelled. golangci-lint's govet/lostcancel now reports this in the SCA job
(heartbeat_test.go:153 and :179), failing SCA for every PR against main.
Defer cancel() right after creating the context; the explicit cancel() that
stops the heartbeat loop is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

This branch was previously deployed

1 inactive deployment
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 size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants