Skip to content

test: bound race UT workloads and packet fixture allocations - #29157

Merged
XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/ut-cost-reduction
Sep 20, 2026
Merged

XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/ut-cost-reduction

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • Improvement
  • Test and CI

Which issue(s) this PR relates to

Related to #28419 (UT producer cost). This does not claim to resolve that whole-job timeout.

Systematic analysis and scope

The successful race job 35491083784 / 106026038604 spent 68m27s inside the UT script: light 16m38s, HNSW 38s, exclusive issues 11m04s, embedded 27m16s, engine 4m47s, and the overlapping heavy/plan tail about 7m36s, plus preparation. These are stage wall times, including build/link, not pure test-body times. Package/test elapsed values must not be summed: embedded cluster admission is runner-wide and wait time is included in test elapsed.

Local isolated race controls reinforce the need to separate attribution: TestHashBuildSharedBudgetRecoverySQL passed in 14.11s (11.90s service startup), and TestSpeedupAbortAllTxn in 15.37s (14.93s startup), versus CI elapsed 400.65s and 135.39s. This is a different platform/load and does not establish how much of the CI delta is queueing, startup, or resource contention. I did not shrink the spill fixture, remove restarts, raise concurrency, or reduce hang guards based on those totals.

This PR removes proven sources of repeated work and oversized packet-fixture allocations inside tests. It does not change production code, test selection, race flags, coverage configuration, cache seeding, or scheduling defaults, and does not duplicate #29113's package-serialization change. Existing fixture reductions in #29141 remain intact.

Changes and retained contracts

Case Previous work New functional work Retained/strengthened oracle
TestConcurrent 64 workers × 20,000 identical searches = 1,280,000 searches 64 × 2 same-query searches + 64 × 100 varying-query searches = 6,528 Same 100-vector native index, 64 search slots/workers; shared-query contention and context reuse; every worker visits all vectors; error, both result lengths, nearest key and zero distance checked
TestPartitionState_CollectObjectsBetweenInProgress 100,000 random draws from only 20 distinct timestamp windows All 21 ordered windows, including the previously unreachable (t6,t6] Original explicit boundary checks retained; expected complete inserted/deleted sets now detect missing/duplicate results, not only invalid returned objects

Native search workers start behind a readiness barrier and are all joined before index destruction. Worker failures use Errorf + return instead of FailNow from a worker. Cleanup is registered immediately after successful native allocation. The barrier establishes ready contenders, not a claim of deterministic simultaneous execution inside native code. Native C++ internals are not instrumented by Go's race detector.

The long same-query workload remains available as BenchmarkConcurrentSearch: one operation is 64 searches; -benchtime=20000x retains the original 1,280,000 searches. Result diagnostics are constructed only on failure, instead of reflection-based assertions on every successful search. The UT is not a soak test; long-run interleaving/throughput coverage is explicitly moved to the benchmark rather than claimed equivalent to fewer iterations.

Measured focused effect

Same local checkout/toolchain/native dependencies, Darwin arm64 (Apple M4), Go 1.26.4, -race -short -count=1; test elapsed excludes compilation/linking and the package-level race exit delay:

Test Base c2a1d63ee08 Candidate
TestConcurrent 8.02s 0.01s
TestPartitionState_CollectObjectsBetweenInProgress 0.95s 0.01s

Counts are deterministic: 99.49% fewer native searches in ordinary UT, and 99.979% fewer window queries with exhaustive rather than random coverage. Timings are single local observations, rounded by Go, not a statistical speedup guarantee. No whole-CI speedup or Linux runner before/after result is claimed for these two loop reductions. These two local reductions alone do not prove a large reduction in the 68-minute full suite.

The retained race benchmark also passed at 20,000 operations × 64 searches: 67,139 ns/batch and 1,049 ns/search locally. Benchmark timing is not directly substituted for test-body timing.

Validation

All commands use .agents/skills/mo-dev/scripts/mo-cgo-test so CGo links against this worktree's built native dependencies:

  • -race -short -count=1 -json -timeout=2m -run '^TestConcurrent$' ./pkg/vectorindex: PASS; both named subtests selected.
  • -race -short -count=100 -timeout=120s -run '^TestConcurrent$' ./pkg/vectorindex: PASS, 2.151s package elapsed. Adaptive repetition cap 100, based on the 0.01s focused duration.
  • -race -short -count=1 -timeout=3m -v -run '^TestPartitionState_CollectObjectsBetweenInProgress$' ./pkg/vm/engine/disttae/logtailreplay: PASS; all 21 named windows selected.
  • -race -run '^$' -bench '^BenchmarkConcurrentSearch$' -benchtime=20000x -count=1 -timeout=3m ./pkg/vectorindex: PASS.
  • -count=1 -timeout=8m ./pkg/vectorindex ./pkg/vm/engine/disttae/logtailreplay: both full owning packages PASS, without -short.
  • -race -count=1 -timeout=5m ./pkg/vectorindex ./pkg/vm/engine/disttae/logtailreplay: both full owning packages PASS, without -short.
  • gofmt, git diff --check: PASS. go test includes its default vet checks.

One initial replay timing command used a non-existent exact test name and selected zero tests; it is excluded from evidence and was replaced by the exact named run above.

Review and boundaries

Focused test-only maintenance: no production architecture/design gate triggered; no SQL/BVT change because neither production behavior nor a public SQL oracle changes. Resource review: one cleanup owner for the native index, release of the start barrier by the parent, worker joins before cleanup, fixed worker/fixture cardinalities; no new scheduler or long-lived global state.

Independent GPT-6 medium review of the original two-file diff: APPROVE, no concrete blockers. It explicitly verified the shared-query scenario, benchmark batch normalization, native cleanup ordering, and exhaustive timestamp-window oracles. CI is not being waited on as requested.

Follow-up: reduce frontend packet fixture memory traffic

A read-only sample of race job 35496528538 / 106040456596, head af8e0fe2a45009d4867db7e7456b4b9b2fdaa480, found frontend.test at 4,233,448 KiB RSS on an 8-CPU/16-GiB runner. This is a hotspot observation, not attribution of the entire process footprint to these tests.

Changes in pkg/frontend/mysql_buffer_test.go:

  • Read fixtures borrow immutable payloads through separate header/payload readers rather than repeatedly concatenating fake wire and expected output. ReadErr retains original payload sizes, both rounds, allocation-error/panic injection, and result/leak assertions.
  • Bad-network tests now fragment actual reads (1, 2, 3, 32-KiB limits). Previously fragmented writes were concatenated before reading and did not test short reads. Unfragmented reads still coalesce across packet boundaries.
  • Explicit matrix retains fixed-buffer boundaries, repeated logical packets, real 16-MiB continuation boundaries, short tails, and empty terminating packets. Five redundant 5-MiB packets become five fixed-buffer-plus-one packets; actual multi-16-MiB continuation cases remain.
  • Writer fixture wire is preallocated at its known size. Immutable row sources replace per-field/random/expected concatenation allocations; position markers distinguish aligned fields/blocks. Seven writer cases retain multirow batching, many-column and oversized-field paths, exact-max rows/fields, independent packet decoder, exact bytes, sequence and trailing-byte assertions.
  • Explicit per-test allocators and immediate Conn cleanup release owned buffers and assert allocator balance. No new parallelism, goroutine, production change, or protocol limit reduction.

Focused resource evidence

Same local Darwin arm64 / Go 1.26.4 native build, race binaries compiled through mo-cgo-test with -race -tags matrixone_test; baseline af8e0fe versus final frontend diff. Sequential runs, no other test/build running during measurement; five parents: TestMySQLProtocolRead, TestMySQLProtocolReadInBadNetwork, TestMySQLProtocolWriteRows, TestConn_ReadErr, TestConn_ReadOnePayload. Both PASS, -test.count=1 -test.timeout=5m, same memory-profile flags.

Metric Before After
Sampled cumulative allocation (MiB) 4,629.27 1,601.65 (-65.4%)
Process peak RSS (bytes) 1,604,616,192 1,372,192,768 (-14.5%)
Process user + system CPU 3.45s 1.87s (-45.8%)
Sum of five reported parent test durations 3.11s 1.55s
End-to-end binary wall time, including initialization/profile/exit 4.78s 5.03s

These are single local observations with sampling/runtime variance. Process wall time did not improve in this pair. The established gain is markedly less fixture allocation and CPU work, not a demonstrated whole-CI speedup or a guarantee of shorter Linux stage time. Lower memory traffic/headroom pressure may help shared-runner contention, but that remains an inference, not measured CI savings.

Follow-up validation and review

  • Full frontend normal package, without -short: PASS, 24.805s, via mo-cgo-test with -count=1 -tags matrixone_test -timeout=8m -json ./pkg/frontend.
  • Full frontend race package, without -short: PASS, terminal exit 0, using the wrapper-built final race binary with -test.v -test.count=1 -test.timeout=8m from pkg/frontend.
  • Incremental golangci-lint against af8e0fe for frontend: PASS, 0 issues; gofmt/diff-check PASS.
  • Focused changed frontend parents with race and count=2: PASS, terminal exit 0; fixture reentry/cleanup verified.
  • Independent GPT-6 medium follow-up: APPROVE, no remaining code blockers. Its P2 about periodic payloads hiding aligned field duplication was fixed with seed/absolute-position markers and re-reviewed. ReadErr error/panic/cleanup coverage was explicitly checked.
  • Design exemption: focused test-fixture maintenance only. No production SQL/BVT semantics change; no new concurrent lifecycle requiring stress scheduling. Original vector/replay validations above remain applicable to unchanged files. No merge or wait for CI.

@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 changed the title test: replace race UT soak loops with bounded coverage test: bound race UT workloads and packet fixture allocations Sep 20, 2026
@matrix-meow matrix-meow added size/L Denotes a PR that changes [500,999] lines and removed size/M Denotes a PR that changes [100,499] lines labels Sep 20, 2026

@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.

COMMENT — PASS at exact head 17cc565b231584e1bc92a278d4d2058ca74a498a; self-authored PR, so comment only. No actionable P0–P2 findings.

Reviewed all changed tests and production/fixture call chains. Functional oracles, protocol boundaries, worker joining, cleanup, packet continuation boundaries and deterministic replay-window coverage are retained or strengthened. Exact-head Linux UT and SCA succeeded.

Caveats: the native soak is now opt-in benchmark coverage; Go race detection does not instrument C++ internals; the readiness barrier does not guarantee simultaneous native execution; local validation was not independently rerun.

@XuPeng-SH
XuPeng-SH merged commit ac9d0aa into matrixorigin:main Sep 20, 2026
22 checks passed
@XuPeng-SH
XuPeng-SH deleted the codex/ut-cost-reduction branch September 20, 2026 10:02
XuPeng-SH added a commit that referenced this pull request Sep 20, 2026
## What type of PR is this?

- [x] Improvement
- [x] Test and CI

## Which issue(s) this PR relates to

Related to #28419 (UT producer cost). Follow-up to merged #29157.

## Why

Recent successful race jobs vary from about 34 minutes to 52–57 minutes.
The slowdown is broad across stages and correlates with roughly 2x CPU
work plus materially higher CPU/I/O pressure, rather than
cluster-admission waiting alone. In the latest #29157 run, embedded
packages still occupied about 17m54s of the serial critical path.

The embedded group currently contains nine race packages after the
exclusive `pkg/tests/issues` package is removed. Each package has a
large compile/link cost. The old optional prebuild only warmed the Go
cache, deleted the produced binaries, and then asked `go test` to
compile/link the complete scope again. A local cold `pkg/embed` race
binary build took multiple minutes under load and produced a 256 MiB
binary; this is directional evidence of material link work, not a CI
speedup measurement.

## Design

- While the already-running exclusive issues fixture owns the cluster
window, compile embedded race binaries with exactly one background
compiler.
- After issues exits, execute those exact binaries serially from each
package directory through `go tool test2json`.
- Keep one test process and one watchdog at execution time; no second
embedded cluster is admitted.
- Validate every binary and all `-race`/tag-aware package metadata
before executing any binary. Any build, artifact, metadata,
disk-headroom, or configuration failure falls back to the authoritative
complete-scope `go test` before partial execution.
- Once prebuilt execution starts, run every package and aggregate
failures without rerunning earlier packages.
- Preserve `-short`, race instrumentation, package identity, `TestMain`,
`-count=1`, panic-on-exit, package working directory, runtime library
path, and JSON output.
- Bound each package by `UT_TIMEOUT + 120s`, covering `TestMain` cleanup
and inherited-output drain beyond Go's internal test timer. TERM
escalates to KILL for the complete process group.
- Preserve single-writer ownership of `UT_REPORT`; scheduler diagnostics
go to stderr only.
- Require 6 GiB free workspace headroom before retaining the nine
binaries.
- Enable the path consistently in both `run_ut.sh` and the Makefile.
Stronger runners can still override the controls.

The theoretical critical-path saving is bounded by `min(issues duration,
embedded compile/link duration)`, minus any slowdown imposed on issues
by the single compiler and small per-package launch overhead. This PR
does not claim a measured whole-job speedup; CI stage checkpoints will
show the actual result.

## Failure and cancellation contracts

The scheduler tests cover:

- successful binary reuse;
- build failure and missing binary fallback;
- metadata failure fallback before any execution;
- package failure followed by execution of remaining packages;
- JSON-only report output on failure;
- compilation cancellation and join-window cancellation;
- execution cancellation while running;
- TERM in both active-process and watchdog spawn-to-PID publication
windows;
- hard timeout with a TERM-resistant descendant and complete PGID
cleanup;
- outer cancellation with a TERM-resistant test group;
- artifact, report, PID, and process-group cleanup.

The parent gives this two-group helper a 15-second cleanup budget,
longer than the helper's 5-second TERM-to-KILL window, so it cannot kill
the cleanup owner first.

## Validation

- `bash -n optools/run_ut.sh`: PASS
- `git diff --check origin/main...HEAD`: PASS
- `go test ./optools -run '^TestEmbeddedPrebuild' -count=1`: PASS
- `go test ./optools -count=1`: PASS, 44.873s after rebase onto
`cd5feff242`
- Post-test process scan: no embedded timeout/cancellation mock
processes remained.

One local direct-binary probe produced valid `test2json` failure JSON
but could not execute on Darwin because the CI runner's Linux
colon-separated rpath flags are not valid Mach-O rpaths. The
repository's existing engine/plan race paths already use the same `go
tool test2json` execution contract; no Darwin result is claimed here.

## Review

Independent GPT-6 medium performed four review rounds. It found and
drove fixes for external timeout/output drain, JSON pollution, preflight
metadata completeness, Makefile default propagation, leader/descendant
cleanup ordering, both PID publication races, outer/helper
cancellation-budget ordering, and one rebase residue. Final review of
commit `d5c0890e41`: **no remaining P1/P2; safe to push**.

CI is not being waited on, per request.

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/enhancement kind/test-ci 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