Skip to content

fix(rscthrottler): account for cgroup memory usage - #29294

Closed
daviszhen wants to merge 56 commits into
matrixorigin:mainfrom
daviszhen:codex/fix-29270-cgroup-memory
Closed

daviszhen wants to merge 56 commits into
matrixorigin:mainfrom
daviszhen:codex/fix-29270-cgroup-memory

Conversation

@daviszhen

@daviszhen daviszhen commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Related to #29270

Problem and change

The current implementation completes the shared-domain and shared-admission mechanisms in schemes 1 and 2. Execution, write throttlers, public memory readers, remote compile sizing, vector-cache sizing and lock-retry pressure classification consume the published MemoryDomain snapshot. The reader supports cgroup v1/v2 and host layouts, inherited hard/soft limits, and last-good-sample retention on read failure. Hierarchy sizing/cache bounds remain separate from the binding usage/limit pair.

Production throttlers and execution allocations use one process-wide physical ledger by default, with component/CN/query quotas layered below it. The former independent RSS admission vetoes are retained only by explicit isolated test fixtures. Clean-cache working-set credit cannot bypass the charged cgroup hard/soft boundary.

Statement entry now uses a bounded, cancellable FIFO queue before transaction side effects. Healthy work is not concurrency-throttled; below one calibrated reserve of remaining physical headroom, new ordinary statements are limited by the scheduler capacity (configurable). Entry does not reserve a query cap or impose the removed fixed 256 MiB floor. Nested SQL borrows a live same-owner admission. Authentication, task control, bootstrap readiness and COMMIT/ROLLBACK retain bounded, physically accounted progress; nested execution does not close its parent's control allowance.

Defaults: MO_MEMORY_STATEMENT_MAX_QUEUED=1024, MO_MEMORY_STATEMENT_WAIT_TIMEOUT=250ms; MO_MEMORY_STATEMENT_PRESSURE_CONCURRENCY=0 derives the pressure-only limit from GoMaxProcs.

All outstanding reservations remain charged against hard-pressure headroom until Release. Acquire precedes allocation, and the existing interface has no allocation-complete ownership handoff; a reservation surviving a refresh is not evidence that its bytes are included in memory.current. For example, with usage 95/100, A reserves 4 and pauses before allocation. B's request for 4 is rejected both before and after a refresh reading 95. If A's allocation fails and A releases its reservation, B can proceed. Read failures retain the previous cgroup sample rather than erase the pending budget.

This deliberately conservative treatment can count already-resident reservations twice at hard pressure. It also declines to use RSS/reusable-page estimates as proof of cgroup coverage. The separate RSS reuse accounting is retained, but it cannot bypass the cgroup budget. Avoiding this conservative backpressure would require a valid allocation/ownership handoff; it cannot be inferred from reservation timing.

Validation

For the schemes 1/2 implementation:

  • Nine relevant owning/consumer packages passed local race tests; all 67 colexec packages passed.
  • Queue, cancellation, timeout, same-owner nesting, physical ownership and control-lifetime regressions passed 50 race repetitions.
  • Static analysis reported zero issues.
  • Linux/arm64 Docker verification uses a 16 GiB/no-swap container. The production SQL lifecycle regression covers multi-statement requests, prepared execution, nested SET queries, COMMIT/ROLLBACK, an execution error followed by a successful query, and admission cleanup after cluster shutdown.
  • Exact-head remote CI and controlled TPCC performance acceptance remain pending.

Historical validation from earlier revisions (not relabeled as exact-head benchmark evidence):

  • go test -race -tags matrixone_test ./pkg/common/rscthrottler passed locally with repository CGO include/library paths after merging main at 27ea64ab038c80cfc94ad4368315ab30d21e6d56.
  • New refresh/accounting regressions passed 100 repetitions under -race.
  • The reader/publication barrier regression retains the old snapshot across refresh for admission and physical-available calculations; actual default/S3 policies also reject the competing request against the new sample.
  • A blocked-owner regression covers default/S3/DataBranch reserve, denied acquire, the cgroup sampling stage used by ForceRefresh, denied retry, allocation-failure rollback and successful reacquire.
  • Concurrent refreshes and acquirers cannot renew a five-unit pending budget. A failed cgroup read preserves that budget.
  • git diff --check passed. New-head CI results remain pending.

Outstanding performance and root-cause acceptance

This PR is not yet demonstrated to satisfy controlled memory AND no throughput/tail-latency regression. The reported f8 three-run 100W/1000T mean tpmC of about 13,291 versus d7's 15,304 is about 13.2% lower. Fewer pauses and no observed OOM support improved pressure control only. They do not prove admission correctness, performance neutrality, or a fix for the original TPCC memory-growth cause. Those runs also do not validate this newer conservative admission policy.

Before acceptance, build base and candidate from the same base revision; use an exclusive host and fixed slot, 84 GiB/no swap, identical data reset/warm-up and repeated A/B plus B/A runs. Compare accounting-only with accounting plus reclamation and retain pressure-time heap/CPU profiles, Go/native/mpool and FileService ownership metrics, cgroup memory.stat/events/pressure, cache/refault and I/O/commit-latency data. Report per-run throughput, tail latency, errors, peaks and post-cycle live memory together.

Historical or non-exclusive runs are not substitutes for the current-revision matched controls. No new matched A/B result or pressure-time memory attribution is claimed here. Performance and memory-source acceptance remain open for review.

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

@daviszhen

Copy link
Copy Markdown
Contributor Author

Benchmark validation

Run 35859101708 tested PR head 3f95935ab0419fc9c759096dc764e79dc90572fe with the same host, slot, dataset, configuration, and TPCC case list as baseline Run 35854624310.

Result

  • The workflow completed successfully; all selected TPCC cases and consistency checks passed.
  • No MatrixOne restart occurred, and the host oom_kill counter stayed unchanged at 34.
  • The PR correctly detected cgroup pressure: cgroup usage reached 79.47 GiB while process RSS was only 56.76 GiB, and hard pressure was entered. The PR run's maximum RSS was 60.89 GiB, versus 79.34 GiB in the baseline.
  • However, the 100W/1000T throughput decreased materially:
    • tpmC: 18,614 -> 10,369 (-44.3%)
    • tpmTOTAL: 41,465 -> 23,065 (-44.4%)
  • The lower-scale TPCC cases were nearly unchanged; the regression is concentrated in the high-memory-pressure case.

Interpretation

The PR improves OOM safety, but max(RSS, cgroup_usage) is currently used not only for pressure detection and cache scavenging, but also for Merge/Flush/DataBranch admission. At high pressure this causes more backpressure and Merge pauses, which explains the throughput loss.

The current result supports keeping cgroup-aware hard-pressure protection, but suggests separating or tuning the cgroup-based safety backstop from normal admission so reclaimable cgroup cache is not treated as full non-reclaimable RSS. The current run only covers the same 10W/100W TPCC set as the baseline; the 500W/1000W stages still need validation after any adjustment.

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

Findings\n\n1. [P1] Account for cumulative reservations against the sampled cgroup headroom — \n\n The cgroup cap is compared with each request's , but is not reduced by reservations granted since the cgroup usage sample. For example, with total=100 MiB, sampled usage=95 MiB, RSS=70 MiB, and zero reservations, two successive 4 MiB requests can each pass the unchanged 5 MiB cgroup headroom check. The normal refresh is rate-limited, so both can be granted before another sample and exceed the remaining headroom. The generic/data-branch path has the same issue because clamps to the same sampled headroom without accounting for reservation growth against that sample. Please make the cgroup budget account atomically for cumulative growth since the sample, and cover sequential and concurrent acquisitions.\n\n2. **[P2] Apply the cgroup guard to projected additional S3 growth, not raw ** — \n\n This rejects an S3 reservation whenever , even if the requested memory is already represented by resident/reusable S3 pages covered by / . For example, at total=100 MiB and cgroup/RSS usage=95 MiB, a 6 MiB request is rejected against 5 MiB headroom even when the existing coverage means it adds no projected physical usage. That can surface as a spurious “CN S3 write memory is exhausted” on reuse/retry. Please base this guard on projected incremental physical growth while preserving the existing reuse accounting, and add a regression case with nonzero cgroup usage.\n\nThe exact-head CI is green, but current tests exercise only single-request headroom rejection and do not cover these cases.

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

Correction to my previous review: shell quoting stripped the inline code identifiers from its body. Please use the complete findings below; these supersede the malformed formatting above.

Findings

  1. [P1] Account for cumulative reservations against the sampled cgroup headroom — pkg/common/rscthrottler/resource_throttler.go:300-317,850-854

    The cgroup cap is compared with each request's ask, but is not reduced by reservations granted since the cgroup usage sample. For example, with total=100 MiB, sampled usage=95 MiB, RSS=70 MiB, and zero reservations, two successive 4 MiB requests can each pass the unchanged 5 MiB cgroup headroom check. The normal refresh is rate-limited, so both can be granted before another sample and exceed the remaining headroom. The generic/data-branch path has the same issue because capAdmissionAvailable clamps to the same sampled headroom without accounting for reservation growth against that sample. Please make the cgroup budget account atomically for cumulative growth since the sample, and cover sequential and concurrent acquisitions.

  2. [P2] Apply the cgroup guard to projected additional S3 growth, not raw ask — pkg/common/rscthrottler/resource_throttler.go:850-854

    This rejects an S3 reservation whenever ask > headroom, even if the requested memory is already represented by resident/reusable S3 pages covered by rssReservedBase / rssMpoolLiveBase. For example, at total=100 MiB and cgroup/RSS usage=95 MiB, a 6 MiB request is rejected against 5 MiB headroom even when the existing coverage means it adds no projected physical usage. That can surface as a spurious “CN S3 write memory is exhausted” on reuse/retry. Please base this guard on projected incremental physical growth while preserving the existing reuse accounting, and add a regression case with nonzero cgroup usage.

The exact-head CI is green, but current tests exercise only single-request headroom rejection and do not cover these cases.

@daviszhen

Copy link
Copy Markdown
Contributor Author

CI 失败诊断:共享物理内存准入导致 SQL/认证饥饿

分析对象为 exact head ae6de31ccabe8f8d76a0567b53e99b29e3805565,对照 base aa4b6eddfdad54d11be6fd75a5675eb9801f6690。本次下载并核对了两个 job 的日志及 6 份相关 artifacts,包括服务日志、mo-tester 最终报告、执行日志和覆盖率产物;没有修改代码或重跑 workflow。

1. 两个 job 的最终结果

Job TOTAL SUCCESS FAILED IGNORED ABNORMAL
PROXY — 117283991406 46,467 29,755 406 633 15,673
PESSIMISTIC — 117283991463 85,575 50,124 1,363 455 33,633

服务日志与报告可从本轮 PROXY artifact 和 PESSIMISTIC artifact 下载。

2. 已确认的主要失败链路

大面积失败不是普通 golden 差异,而是新增的共享物理内存门禁拒绝 SQL,进一步扩散到后台任务和登录认证:

共享物理内存余量低于入口要求
→ 普通 SQL/DDL/任务轮询/心跳被拒绝
→ 部分 DDL 未完成,后续出现 table-not-found 等连带错误
→ 认证内部 SQL 同样被拒绝
→ Proxy 返回 Auth failed,mo-tester 无法重连
→ 大量 ABNORMAL

关键日志时间均为 UTC:

  • PROXY CN0 在 02:27:36 已拒绝后台任务 SQL:requested=268435456 used=0 cap=11207887,随后出现 cap=0。
  • PESSIMISTIC 首批用户可见拒绝发生于 02:34:16,在 load_data/string_to_datetime_conversion.sql 中返回:requested=268435456 used=0 cap=267404085。
  • PROXY 在 02:48:23 的观测为:total=15.61GiB、domain usage 13.82GiB、CN RSS 1.306GiB、shared-reserve=1.811GiB、shared-reserved=0B、shared-available=0B。
  • PROXY CN0 在 02:48:29 明确记录 authenticate user failed ... execution resource admission rejected: requested=268435456 used=0 cap=0,随后 Proxy 记录 Auth failed: internal error: access error。
  • PESSIMISTIC CN0 在 02:40:09 也记录了同类认证拒绝。

因此,“没有有效连接”不代表 CN 已经崩溃。下载的服务日志中未发现 panic/fatal/OOM-kill 证据;CN 在认证失败期间仍运行,直到 CI 清理阶段才记录 TERM 触发的正常关闭(PROXY 约 02:51:50,PESSIMISTIC 约 02:43:37)。

3. 为什么该 PR 会触发这些失败

A. 新门禁改变了原有语义,而不只是增加 cgroup 用量统计。

base 的 openProcessGeneration() 没有物理账本入口等待。PR 在 execution_resource_budget.go:1166–1184 新增 physicalLedger.WaitFor(entryFloor, ...)。

默认 RuntimeBytes=256MiB;当执行预算上限大于这个 floor 时,入口要求额外具备 256MiB 可用余量。默认最多等待 250ms,不足即返回 admission error。

这里 requested=268435456 是入口余量要求,不是该 SQL 已经实际申请了 256MiB。该拒绝路径主动把 used 填为 0;它不代表机器或 CN 的实际内存用量为零。

B. 本轮落在 host 内存域,新共享账本没有抵扣可回收缓存。

两个 job 均记录 memory-domain-source=host、cgroup=0B。诊断字段 cgroup-usage 此时实际上是所选 host domain 的 usage,不应解释为某个有限额容器的实际 cgroup 用量。

宿主机采样 保存 gosigar.Mem.Used;所固定的 Linux gosigar 实现以 MemTotal-MemFree 计算 Used,以 MemAvailable 计算 ActualFree。虽然 snapshot 另行记录了 Reclaimable,但 共享账本 计算为:

Available = max(0, AdmissionLimit - Used - Reserve - Reserved)

它没有使用 Reclaimable。对于本轮没有 soft limit 的 host domain,等价于:

Available = max(0, MemFree - Reserve - Reserved)

原来的执行 headroom 路径仍可以把可回收缓存计为可用,但随后增加的共享账本会独立拒绝它。因此,即使前一道检查允许,新增检查仍能拒绝;两者口径不一致。

按日志中的保护区估算,常规入口要求约为 MemFree >= 1.811GiB + 256MiB + Reserved。这可以在未达到原 throttler 的 92% hard-pressure 阈值时触发,因而当前实现并不满足 PR 描述中“仅在硬压力下限制,其余保持原行为”的范围承诺。

C. 内部控制操作也受同一门禁限制,缺少有界进展保障。

生产进程只要具备 FileService,就会 接入共享账本。当前入口没有区分普通数据查询和认证/任务心跳等控制操作。日志已直接证明这两类内部 SQL 会被一起拒绝。

WaitFor() 只做有界重试,不保证主动触发并完成回收。FileService cache eviction/Go scavenging 也不能保证及时降低整个宿主机、尤其是内核文件缓存和其他进程带来的占用。

此外,shared-reserved=0B 时仍然出现 shared-available=0B,所以本轮不能简单归因于 reservation 泄漏或此前 reviewer 指出的 accounting 竞态。

4. 独立保留的 wrong-result 问题

PROXY 还有两处真实少行:

SQL 用例 EXPECT ACTUAL
fulltext/fulltext.sql:394,MATCH 后 COUNT 3,840,001 1,051,826
fulltext/fulltext_bm25.sql:391,MATCH 后 COUNT 3,840,001 120,311

对应索引回填 SQL 日志均报告 AffectedRows=23040006。因此不能直接把这两处解释为“异步索引尚未完成”,也不能更新 golden 接受少行。它们发生于同一内存压力/拒绝区间,但当前证据尚未证明其完整代码因果链;仍需验证压力下 MATCH 的查询完整性、spill 和错误传播。

5. 修复方向与验证缺口

  1. 区分 host 可用内存政策和有限 cgroup 的 hard-OOM 保护,避免把可回收缓存一律当成不可用执行内存;不能简单移除真实物理分配上限。
  2. 重新审查固定 256MiB 入口 floor;为认证、心跳和必要清理提供有界且受计费的进展能力,不能无限豁免全部内部 SQL。
  3. 覆盖 host 的低 MemFree/高可回收内存场景、cgroup 真正耗尽场景,以及压力下登录/后台任务仍可推进的回归。
  4. 在相同 base/配置上复验本轮两组完整多 CN BVT,并单独验证上述两处全文检索结果。

当前单测不能代替这些验证:代码明确让无 FileService 的裸进程夹具不接入生产共享账本,因而很多隔离单测不会经过新增入口门禁。

证据边界: 新入口直接造成 SQL 和认证拒绝已确认;host cache-sensitive accounting 与统一入口 floor 的机制也已由差异确认。但 artifacts 没有事故时完整 /proc/meminfo 或 heap/native profiles,不能断言 13.8GiB 占用全部是可回收缓存,也不能据此宣称内存泄漏,或将两处 MATCH 少行完全归因为该门禁。

@daviszhen

Copy link
Copy Markdown
Contributor Author

Re-reviewed unchanged head ae6de31ccabe8f8d76a0567b53e99b29e3805565 against base aa4b6eddfdad54d11be6fd75a5675eb9801f6690, incorporating the completed CI and the new failure diagnosis.

Recommendation: request changes. This supersedes the "no new blocking code findings; CI pending" assessment in my previous comment. The code has not changed, but the completed integration evidence exposes an availability regression that the earlier owning-package tests did not cover.

[P1] Prevent the new physical entry gate from starving SQL and authentication

At execution_resource_budget.go:1179–1184, every generation whose cap exceeds the default 256 MiB entry floor must pass the shared ledger's check. This also applies to authentication and background SQL; the requested 256 MiB is an entry threshold, not the statement's actual allocation.

The shared ledger subtracts raw Used, reserve and outstanding claims without using Reclaimable. For a Linux host domain without a soft limit, the pinned gosigar implementation makes this MemFree - reserve - claims, even though the execution headroom provider credits reclaimable memory. This can reject entry below the old hard-pressure threshold.

Independent exact-head witness, using the actual MemoryAvailableIncludingCache, MemoryAdmissionBudget.WaitFor and TryReserve APIs with an injected immutable sample and the default reserve values:

  • Host total=16 GiB, used=14 GiB, reclaimable=8 GiB, no outstanding claims: execution headroom=10 GiB, reserve=1.85 GiB, shared available=0.15 GiB. Entry for 256 MiB fails after the default-length 250 ms wait, although a real 1 MiB reservation succeeds.
  • Control with the same non-reclaimable footprint but cache already reclaimed (used=6 GiB, reclaimable=0): execution headroom remains 10 GiB and entry succeeds.
  • Truly exhausted host control correctly rejects both entry and allocation.

The cached-host expectation fails in all three -race repetitions; both controls pass. There is no race-detector report. This is an admission-policy counterexample, not a live kernel-reclaim experiment.

The production impact is independently present in the raw CI evidence:

  • PROXY CN0 at 02:48:29 UTC and PESSIMISTIC CN0 at 02:40:09 UTC record authenticate user failed ... execution resource admission rejected: requested=268435456 used=0 cap=0. The preceding PROXY sample reports memory-domain-source=host, shared-reserved=0B, and shared-available=0B. See the PROXY artifact and PESSIMISTIC artifact.
  • The Ubuntu UT log additionally shows TestIssue29399TableRestoreRetainsDatabaseOwnership failing on drop account if exists issue_29399_owner_scope with requested=268435456 used=0 cap=168579072; background task queries are rejected alongside it. This is not merely a coverage threshold failure.

Please reconcile host admission with reclaimable-memory availability while retaining finite-cgroup protection and cumulative pending claims. Rework the fixed entry floor so authentication, heartbeats and necessary cleanup have bounded, charged progress under pressure; do not simply exempt all internal SQL. Add production-path tests with FileService/shared-ledger participation, including low-free/high-reclaimable host memory and true exhaustion, then validate both multi-CN BVT configurations.

Other evidence and limits

  • Both BVTs, Ubuntu UT and UT Coverage have now failed; aggregate Coverage and CI Required also fail. Shared Build, arm64 SCA and Connector/J passed. I have not attributed every failing test to the finding above.
  • The PROXY report separately confirms MATCH counts of 1,051,826 and 120,311 where 3,840,001 is expected (fulltext.sql:394, fulltext_bm25.sql:391). These need independent correctness investigation; this review does not establish their causal link to admission, justify changing golden results, or infer that all observed host usage was reclaimable.
  • Previous controller-boundary, soft-only and pending-reservation probes still pass three -race repetitions on this head. Their closure does not cover this entry/host-policy regression.
  • The already-agreed current-revision performance acceptance remains open. No benchmark or CI rerun was launched, and no product changes were pushed. This is an ordinary review comment, not a formal GitHub review event.

Separate clean-cache working-set reserve from raw hard/soft charged limits, retain bounded runtime credit for control work, and tag only bootstrap readiness probes. Give pure operator fixtures lazy finite private budgets while retaining live-domain coverage. Cover the failing CI memory sample, allocation ownership, soft-limit exhaustion, and fixture cleanup; fix the control test preallocation lint.
Keep the one-second blocked-work watchdog without charging CI scheduling, race instrumentation, or logging delay. Both mock-only work and peer cursor tests pass 20 repeated race runs.
@daviszhen

Copy link
Copy Markdown
Contributor Author

Re-reviewed exact head 820ca8cf790490eabbcac2aedc429dfaa5f2d7bb against base aa4b6eddfdad54d11be6fd75a5675eb9801f6690, including all four commits since ae6de31cca and their interactions with the shared ledger, process allocation ownership, authentication/task classification, bootstrap and test fixtures.

Recommendation: request changes — one newly identified P2 remains. The previous cached-host/fixed-entry-floor counterexample is closed in the tested paths; the finding below is a different recovery failure in the PR's shared ledger, not an assertion that the latest four commits introduced it.

[P2] Let ordinary admission recover after a transient non-Go memory peak

At memory_admission.go:204–209, nonGoHighWater only increases and is substituted for the current sample when calculating the reserve. When 2 * historicalNonGo + RuntimeBytes >= AdmissionLimit, headroomLocked returns zero forever at that limit, even after pressure has completely subsided. NonGo includes transient dirty/writeback/shmem/kernel charges; it is not a count of still-owned reservations. Neither releasing claims nor receiving healthy observations reduces this watermark.

Independent exact-head witness, using the default policy values and the actual FileService-backed Process.GetExecutionResourceBudget → allocation account → MPool.AllocAccounted path:

  1. Observe a 16 GiB domain with Used=12 GiB and NonGo=8 GiB; there are no outstanding reservations.
  2. Recover the same domain to Used=1 GiB, NonGo=64 MiB, Reclaimable=0 and provide ten further healthy observations.
  3. The retained ledger still reports Reserve=16.25 GiB, Available=0, Reserved=0. A 4 KiB accounted allocation fails with requested=4096 used=0 cap=0.
  4. A fresh ledger with exactly the same current sample and policy admits that allocation. A smaller historical peak of 1 GiB also recovers successfully with the retained ledger.

The high-peak cases fail for host, cgroup v1 and cgroup v2 in all three -race repetitions; every small-peak/fresh-ledger control passes, and no race is reported. This is a deterministic recovery-policy counterexample with injected domain observations, not a live kernel-pressure reproduction or an explanation of an observed CI failure.

The new bounded control allowance does not restore ordinary SQL/write-path admission. Please bound or safely recalibrate the historical reserve so recovered domains can resume ordinary work, while retaining the raw charged hard/soft boundary and cumulative outstanding claims. Add a pressure → recovery regression through the production allocation path; do not fix this by discarding live reservations or exempting ordinary queries from accounting.

Previous finding and validation

The previous P1's fixed 256 MiB entry check is removed. Host cache credit is aligned between the shared ledger and component backstops. The new control leases have bounded concurrency/bytes and retain their charge and slot until physical frees complete. These corrections pass the tested boundaries; this is not yet a claim that the prior full multi-CN incidents are resolved.

Exact-head validation in an isolated macOS/arm64 worktree:

  • Full existing system, rscthrottler and process suites passed with -race -tags matrixone_test before adding review probes.
  • Focused committed host/cgroup/control/production-MPool and earlier boundary regressions passed 20 race repetitions.
  • Previous independent controller/soft-only/pending-claim probes and a new 32-contender mixed ordinary/control accounting probe passed three race repetitions. The separate high-water recovery counterexample above intentionally fails.
  • Focused frontend authentication/task classification passed; bootstrap readiness, fixture ownership and both modified lock-keeper watchdog tests passed three repetitions.
  • The previously failing TestIssue29399TableRestoreRetainsDatabaseOwnership passed locally through the authenticated embedded cluster. This healthy-host result does not reproduce the old Linux CI pressure conditions.
  • make err-check and PR git diff --check passed. No tracked product files were changed.

At the latest check, Connector/J passed; Shared Build, Ubuntu UT, arm64 SCA and UT Coverage were still running. Do not carry the old head's failures forward as results for this head. The earlier MATCH wrong-result evidence remains an independent validation item, and the PR body's agreed current-revision performance acceptance is still open.

No benchmark, CI rerun or code push was performed. This is an ordinary comment, not a formal GitHub review event.

Route public memory readers, component sizing and remote execution through the shared domain. Preserve independent hierarchy capacity/cache bounds while retaining paired usage and admission limits; use host accounting when a cgroup quota is not binding.

Install the shared physical ledger by default and keep component/query quotas as child ceilings instead of retaining independent RSS admission vetoes. Add cancellable, bounded FIFO statement entry before transaction side effects, with pressure-only concurrency control and no fixed byte precharge. Reuse live context admissions for nested SQL and retain one bounded control lease across nested generations.

Cover hierarchy sizing, FIFO/cancel/timeout/queue bounds, physical ownership, nested control lifetime, and real protocol multi-statement/prepared/transaction/error cleanup paths. Current-revision TPCC performance acceptance remains separate.
@daviszhen

Copy link
Copy Markdown
Contributor Author

Re-reviewed exact head a3a1f8e15e025ef92be52f63162c63aca9a73a13 against base aa4b6eddfdad54d11be6fd75a5675eb9801f6690, focusing on the new statement queue/shared-domain changes since 820ca8cf79 and rechecking the previous recovery finding.

Recommendation: request changes — two new P2 findings, and the previous P2 remains reproducible.

[P2, new] Keep query cancellation usable when pressure admission is saturated

At memory_statement_admission.go:32–38, only COMMIT/ROLLBACK are classified as control statements. KILL QUERY therefore passes through ordinary admission before reaching its cancellation handler. Once Available < Reserve and StatementActive >= PressureConcurrency, the ordinary queue waits and times out instead of canceling the active query. This prevents a user/operator from releasing query resources precisely when the queue is saturated.

I reproduced this through real authenticated MySQL connections to an embedded single-CN cluster, not just by directly calling the queue:

  1. Start the test process with MO_MEMORY_STATEMENT_PRESSURE_CONCURRENCY=1 and MO_MEMORY_HOST_RESERVE_PERCENT=1. The latter keeps the healthy control out of incidental host pressure on this machine. Prewarm the cancellation connection's SQL/catalog path.
  2. Hold one worker query in a fault-point WAIT barrier, verifying that it has actually reached the barrier.
  3. Use a pending shared-ledger reservation to leave 1 MiB available, without making a large physical allocation. The observed reserve is 612,032,840 bytes and StatementActive=1.
  4. Issue KILL QUERY <worker-id> from the second connection. It returns Error 20101 (HY000): ... execution resource admission rejected: statement entry: memory statement admission wait timed out after the default admission wait.
  5. Release only the injected reservation. The same identity, connection, target and KILL statement now succeed; release the test barrier and verify that the worker returns ER_QUERY_INTERRUPTED.

All three repetitions fail only the expectation that cancellation should remain available under pressure; all three healthy controls and worker-interruption checks pass. This is a controlled admission-pressure reproduction, not a live OOM experiment. It does not rely on a full queue: one occupied configured pressure slot is sufficient.

Please route authorized cancellation through an appropriately bounded control/cancellation path, retain authorization and physical accounting, and add a client-protocol regression with saturated pressure concurrency. This should not become an unrestricted internal-SQL exemption.

[P2, still open] Ordinary admission remains poisoned by a transient non-Go peak

The previous finding is unchanged at memory_admission.go:216–222: nonGoHighWater never decreases and is substituted for the current observation when calculating the reserve. The new statement queue also uses this calculation; bounded waiting does not restore ordinary admission after recovery.

I reran the unchanged production-allocation-path counterexample on this head: a 16 GiB domain first observes NonGo=8 GiB, then recovers to Used=1 GiB/NonGo=64 MiB with ten additional healthy observations and no outstanding claims. Reserve remains 16.25 GiB, Available=0, and a FileService-backed process's 4 KiB accounted allocation fails. A fresh ledger with the same current sample, and the retained-ledger smaller-peak control, both succeed. Host/cgroup-v1/cgroup-v2 high-peak cases fail in all three -race repetitions; the controls pass without race reports. These are injected domain observations, not live cgroup experiments.

Please safely bound/recalibrate the historical reserve so recovered domains can resume ordinary work, without dropping live claims or weakening hard/soft physical boundaries.

[P2, new] New error constructors fail the repository's required static-check entry point

The new errors.New calls and fmt.Errorf wrapper violate the repository's existing err-check rule. On this exact head, make err-check exits 2:

'fmt.Errorf()' is found.
pkg/vm/process/control_memory.go:117:fmt.Errorf
'errors.New()' is found.
pkg/common/system/memory_statement.go:26:errors.New
*** Use moerr instead.. Stop.

Both static-check and static-check-analysis depend on this target, so package tests or a standalone analyzer pass do not satisfy this gate. Please use the project's supported error construction/wrapping while preserving cause/errors.Is behavior. This is a locally reproduced gate failure, not a claim that the still-running remote SCA job has already failed.

Validation and limits

Exact-head validation in an isolated macOS/arm64 worktree:

  • Full committed system, rscthrottler and process suites passed with -race -tags matrixone_test, before adding the temporary review probes.
  • Focused committed statement queue, nesting/control borrowing and hierarchy/public-reader regressions passed 20 race repetitions. Earlier independent boundary/pending-claim probes and mixed ordinary/control accounting passed three race repetitions.
  • Focused frontend authentication/task/statement tests, remote-compile/lock-pressure consumers, and vector-cache limit tests passed. The vector-cache test needed the existing arm64 static jemalloc archive explicitly linked because this host also has an incompatible x86 dylib.
  • The committed TestStatementMemoryAdmissionSQLLifecycle passed through the real MySQL path under the default policy, including multi-statement/prepared/nested SQL and COMMIT/ROLLBACK cleanup. It does not cover the cancellation-under-pressure case above.
  • PR git diff --check passed; make err-check failed as described above. No tracked product files were changed.

At the latest check, Connector/J and Iceberg checks passed; Shared Build, Ubuntu UT, arm64 SCA and UT Coverage were still running. Prior-head BVT/MATCH failures are not asserted as current-head results. The already-agreed current-revision performance acceptance remains open; these local tests do not replace full Linux multi-CN validation or that acceptance.

No benchmark, CI rerun or code push was performed. This is an ordinary comment, not a formal GitHub review event.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Follow-up review of unchanged head a3a1f8e15e025ef92be52f63162c63aca9a73a13 (base aa4b6eddfdad54d11be6fd75a5675eb9801f6690). There are no new commits or subsequent review responses since my previous review.

Recommendation remains request changes. I rechecked the relevant source and reran each of the three outstanding P2 witnesses in this review; these are confirmations of the existing findings, not three additional findings:

  • KILL QUERY under admission pressure: another real authenticated MySQL reproduction fails with Error 20101 ... statement entry: memory statement admission wait timed out, with Available=1 MiB, Reserve=612,032,840 bytes and StatementActive=1. After releasing only the injected reservation, the same connection/identity/target succeeds and the worker returns ER_QUERY_INTERRUPTED. As previously documented, this probe uses pressure concurrency=1 and host reserve percent=1, with a fault barrier and a pending ledger claim rather than a large physical allocation. KILL still needs bounded cancellation/control progress instead of waiting behind the query it should cancel.
  • Recovery after a transient non-Go peak: another -race -count=1 run fails for all three injected domain sources (host, cgroup v1/v2). After recovery, Reserve remains 16.25 GiB against a 16 GiB limit, Available=0 and Reserved=0; the production-path 4 KiB allocation is rejected. Fresh-ledger and smaller-peak controls pass, with no race report. The historical reserve still needs safe recalibration without dropping outstanding claims.
  • Static-check entry point: make err-check again exits 2 for fmt.Errorf at pkg/vm/process/control_memory.go:117 and errors.New at pkg/common/system/memory_statement.go:26–27. These must use supported project error construction/wrapping while retaining cause matching.

git diff --check still passes. I did not rerun the full package suites in this follow-up; their earlier exact-head results are documented in the linked review.

CI update: Shared Build has now passed, alongside Connector/J and Iceberg checks. In run 39014641388, Ubuntu UT, arm64 SCA, UT Coverage, PROXY BVT and PESSIMISTIC BVT are still in progress at this check. The local err-check result is not being presented as a completed remote SCA failure. Prior-head BVT/MATCH failures are not relabeled as current-head results, and the PR's agreed current-revision performance acceptance remains open.

No product edits, code pushes, benchmark runs or CI reruns were performed. This is an ordinary comment, not a formal GitHub review event.

@daviszhen

daviszhen commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Addressed the three P2 findings from the latest re-review in commit 31d1330f24f18eea2c6edca8eb463417756719a4.

  1. Cancellation under saturated statement admission. KILL QUERY / KILL CONNECTION use the existing bounded control path, without bypassing authentication, physical accounting, or the normal handler. The real-client regression also exposed a pre-AST blocker: an invalidated rewrite-policy cache could queue its catalog reads before KILL was classified. Only that scoped mandatory-policy lookup now uses control memory; policy errors still fail closed and the caller's ordinary SQL does not inherit the marker. The regression holds a real authenticated worker query at a fault barrier, saturates admission, and injects a pending ledger claim (not a large physical allocation). Ordinary SELECT remains rejected, KILL succeeds, the worker returns ER_QUERY_INTERRUPTED, and queue/control ownership drains.

  2. Recovery after a transient non-Go peak. Historical calibration can be reset only when it alone blocks admission and the current observation has a full current reserve of spare headroom AFTER all outstanding claims and physical gates. A low NonGo reading alone is insufficient. Delayed/undated observations cannot undo a newer dated peak. Live claims, charged hard/soft boundaries, and the normal reserve floor remain intact. Tests cover host/cgroup-v1/cgroup-v2 recovery, real FileService-backed MPool allocation, retained claims, continued pressure, soft-limit exhaustion, and out-of-order observations. The original 16 GiB / 8 GiB NonGo witness failed before the fix and now recovers without recreating the ledger.

  3. Required static-check entry point. Statement-admission sentinels now use moerr; supported wrapping plus errors.Join preserves both the execution-admission classification and queue-full/timeout/cancellation causes. make err-check passes. Tests assert cause matching before any allocation.

Validation of this revision:

  • macOS/arm64: all nine affected/consumer package suites passed with -race -tags matrixone_test (system, rscthrottler, process, frontend, compile, lockop, vector cache, bootstrap, testutil).
  • Fifty race repetitions of focused admission/recovery/statement/control and production-MPool tests passed.
  • make err-check and affected-package static-check-selected (molint plus golangci-lint) passed, with zero lint issues. git diff --check passed.
  • Linux/arm64 Docker, 16 GiB / no swap / six CPUs: full system, rscthrottler, process, frontend and compile suites passed with race detection.
  • Linux real-MySQL statement lifecycle and cancellation-under-pressure integration tests passed three repetitions with race detection.
  • Additional Linux race regressions (TestIssue29399* and TestArrowLoadBVT) passed. The verification container exited 0 with OOMKilled=false; its final memory.events counters (including max/oom/oom_kill) were all zero.

These are deterministic admission-pressure and SQL lifecycle checks, not live OOM/TPCC experiments. The already-agreed matched current-revision base/candidate and accounting-only/reclamation performance acceptance remains open; this does not claim to close #29270's original memory-growth root cause. No 129 benchmark workflow was dispatched.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Re-reviewed exact head 31d1330f24f18eea2c6edca8eb463417756719a4 against base aa4b6eddfdad54d11be6fd75a5675eb9801f6690, including all ten files changed since a3a1f8e15e and the author's response.

Assessment: the three P2 findings from my previous review are resolved in the tested paths. I found no new blocking code issue in this revision. This is not yet merge approval: current-head CI and the already-agreed performance acceptance remain pending.

Previous findings

  1. KILL under pressure — closed. Statement classification now sends KILL through the bounded control path. The mandatory rewrite-policy lookup is also scoped to control memory before the client AST is classified; its marker is not installed on the caller and lookup errors still propagate. I copied the original independent MySQL witness unchanged into an isolated new-head worktree: all three race repetitions now pass, with Available=1 MiB, Reserve=612,032,840 bytes, StatementActive=1 and kill under pressure: <nil>. The worker returns ER_QUERY_INTERRUPTED. This independent probe retains its documented concurrency=1 / host-reserve-percent=1 configuration. Separately, the committed pressure test passes three race repetitions under the default policy (GOMAXPROCS=3), with ordinary SELECT still rejected, KILL succeeding, and control/queue ownership draining. Live protocol verification here covers KILL QUERY; both KILL forms are covered by classification tests.

  2. Latched non-Go peak — closed. The recalibration requires a sufficiently recent observation and a full current reserve of spare headroom after outstanding claims and physical gates; it does not erase reservations. The original independent 16 GiB-domain / 8 GiB-peak / recovered-4 KiB-allocation witness now passes for host, cgroup v1 and cgroup v2 in all three race repetitions. Fresh-ledger and smaller-peak controls pass as well. Committed retained-claim, continued-pressure, soft-boundary and out-of-order/undated-observation cases also pass.

  3. Required error-policy gate — closed. make err-check now exits 0. The sentinels use moerr, and the supported wrapper/join preserves execution-admission and underlying timeout/queue-full/cancellation causes in the tested cases.

Validation performed for this review

  • Full committed system, rscthrottler and process suites passed with -race -tags matrixone_test before adding temporary review probes.
  • Focused recovery, production-MPool, statement queue/nesting/control borrowing and error-cause regressions passed 20 race repetitions.
  • Earlier independent controller-boundary, soft-only, pending-claim and mixed ordinary/control accounting probes passed three race repetitions, alongside the recovery witness above.
  • Focused frontend statement classification/lifetime, rewrite-policy scope/failure propagation, task control and authentication tests passed three race repetitions.
  • The committed real-MySQL SQL lifecycle and pressure-cancellation tests each passed three race repetitions. The unchanged independent KILL witness also passed three race repetitions. No race reports were observed.
  • TestDaemonClaimSQLRoundTrip passed once locally with race detection. git diff --check passed. This was macOS/arm64 validation, not a new Linux/OOM/TPCC experiment or a rerun of all nine consumer package suites.

CI evidence that still needs current-head closure

I also inspected two completed failures from the previous head's CI. These belong to a3a1f8e15e, not 31d1330f24:

  • arm64 SCA failed exactly at the now-fixed fmt.Errorf / errors.New gate, exit 2.
  • UT Coverage failed because tests failed, not because of a coverage percentage threshold. Its diagnostic artifact contains 18 failed test/package events, all in pkg/embed. At 07:58:45 UTC, authentication returns execution resource admission rejected: statement entry: memory statement admission wait timed out; task-service readiness then fails and 15 shared-cluster tests report that setup error. TestCrossTargetUpgradeRecovery/4.0.12 separately times out starting CNs, with repeated handleGetProtocolVersion deadline errors. I have not established a common root cause for that separate upgrade failure, nor proved that the authentication incident was caused by the historical watermark. The successful local daemon test above does not reproduce the full Linux CI pressure conditions.

The new head's CI run 39017009767 is still running. Please use its completed UT/Coverage/SCA and multi-CN BVT results to close the integration gap; do not carry the old failures forward as current-head findings or treat healthy-host tests as full incident resolution. The PR's existing matched current-revision memory/throughput/tail-latency acceptance remains open.

No product code was edited or pushed, and no CI rerun or benchmark was launched. This is an ordinary comment, not a formal GitHub approval/review event.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Run 39017009767:UT / UT Coverage 失败分析与修改建议

分析提交:31d1330f24f18eea2c6edca8eb463417756719a4。

已下载两个 job 的完整日志,以及 ut-diagnostics-39017009767-1-all、ut-coverage-diagnostics-attempt-1、ut-coverage-report-attempt-1 三份 artifacts。本评论是诊断与建议,不代表以下修改已实施或验证通过。

1. 已确认的失败

普通 UT job 有三个失败测试:

测试 日志证据 判断
TestStatementMemoryAdmissionKillQueryUnderPressure 普通 SELECT 1 按预期 admission 超时,但随后的 KILL QUERY 1 也报 memory statement admission wait timed out 控制操作未在本次压力场景下取得进展;具体限制项尚未确认
TestCDCTargetSetupTransientDiagnosticOnMO CREATE CDC 在 statement entry 被 admission 拒绝 尚未进入该测试的目标 CDC 故障/恢复验证,便被入口门禁阻断
TestScoreTraversalWorkspaceExact 实际 121 次分配,上限为 8 次 分配次数超标,不是全文检索结果错误

UT Coverage job 的关键首发错误发生于 TestCDCEndTsWildcardLateTableOnMO 启动共享集群时:

hash build memory budget exceeded (requested=16, used=0, limit=0)

同一时段的快照为:

指标 值
memory domain cgroup-v1
cgroup limit 14 GiB
cgroup usage 13.75 GiB
当前测试进程 RSS 633.6 MiB
shared reserve 2.618 GiB
shared reserved 0 B
shared available 0 B

当前 availableWithReserveLocked() 同时约束工作集余量和原始 cgroup charged headroom;后者扣除默认 256 MiB runtime reserve 后,在此快照附近已无可用额度。因此极小的 hash-build 分配也会被拒绝。后续多 CN 启动还出现了同类 hash-build/排序零预算错误。

这里的 cgroup usage 是共享内存域的总计数,不能等同于该 CN 的 RSS。现有日志不足以确定其他进程、文件缓存和内核内存各占多少,也不能据此判定 CN 内存泄漏。

共享测试夹具随后缓存了初始化错误,多个测试以 0s 连带失败。报告中的 36 条 fail 事件包含子测试和 package 事件,不是 36 个独立缺陷。UT Coverage 退出码为 1,导致覆盖率 profile 未上传,继而阻塞 Coverage 合并;本次不是覆盖率低于阈值。

ArrowLoad 和升级测试另有 CN bootstrap 超时,当前证据不足以将这两个超时完全归因于 admission,需要保留单独排查。

2. 建议优先修改:拒绝诊断与确定性压力测试

  • 在拒绝位置记录本次判定使用的同一个快照及账本状态:usage/limit、reserve、pending reservations、普通/control 可用额度、活跃数、排队数和具体拒绝原因,避免事后重新采样混淆归因。
  • KILL 已经被分类为 control,不应重复加白名单。其 allowance 仍受实时 cgroup usage 和 pending reservations 约束;当前日志缺少拒绝瞬间的 control 快照,不能确定是物理余量耗尽、control 槽/额度耗尽,还是控制路径有误。
  • 单元测试使用可控的内存域快照,分别验证“普通槽已满但 control 仍有额度”和“物理余量确实耗尽”,包含取消、失败清理和无额度泄漏断言。
  • 当前集成测试用 reservation 只留下 1 MiB 普通余量,随后还要等待一次普通 SQL 超时;真实 CI 内存变化会影响假设。应明确建立并验证 control 余量,避免把宿主机波动当作确定性前提。该 KILL 测试在 Coverage job 中通过,也说明需要排查环境/时序敏感性。

先确定拒绝原因,再决定是否修改生产 admission 行为。真实物理内存耗尽时不能无界放行 control SQL。

3. 建议验证并约束 CI 重型测试的共享 cgroup 竞争

  • 先在同样的 runner 配置和同一提交上,将重型测试包串行运行作对照,检查零预算启动失败是否消失。这是建议实验,尚未完成。
  • 若确认是跨测试进程竞争,对 embedded/multi-CN 测试建立跨进程并发限制,并覆盖集群整个生命周期,而不只是进程内启动锁。
  • 对可恢复的资源不足,评估在初始化前有界等待并重新检查条件;部分启动后的失败必须先完整清理,再考虑重试。
  • 共享夹具缓存错误放大了失败数量,但不是首发原因,不宜先靠重置夹具缓存掩盖资源不足。

不建议通过降低 runtime reserve、给内部 SQL 无条件放行,或全局延长 250 ms statement admission 超时来消除这些失败。

4. 分离全文索引结构分配与系统内存采样开销

代码调用链为:

partitionOrderedKeys → CheckBudget → MemoryTotal → CurrentMemoryDomain

PR 将 MemoryTotal() 从原子缓存读取改为可能同步刷新内存域采样。采样分配进入被测区间,是 121 次分配的较强嫌疑,但尚未完成 Linux 上的隔离归因;本机单独运行该测试 3 次通过,不能据此视为稳定复现。

建议容量查询优先读取已发布的缓存,由统一采样机制刷新;admission 仍须保持 usage/limit 成对快照,不能重新拆开读取。结构性分配测试注入固定容量来源,另行测试采样刷新成本,并在 Linux CI 参数下对照验证。

不建议直接把分配次数上限从 8 放宽到 121。

推荐顺序:先补拒绝快照和确定性测试,同时执行重型包串行对照;有归因证据后再调整 admission 行为和容量查询热路径。

… state

Scope deterministic SQL pressure to a test CN instead of exhausting the process-wide real-domain ledger. Keep CN sizing and execution on the same physical owner. Preserve the failed admission snapshot and reason without allocating diagnostics on healthy requests. Isolate score-traversal allocation measurements from capacity sampling while retaining production live quotas and the original allocation bound.
@daviszhen

Copy link
Copy Markdown
Contributor Author

Re-reviewed head 9f3552a866e6c6f4bed0a9a5909d650dda2596ca, focusing on the 10-file delta since 31d1330f24 and the affected admission/allocator consumers.

No new blocking code finding in this delta. This is not merge approval; exact-head integration and the existing performance/memory-source acceptance remain open.

What I checked:

  • Rejection diagnostics retain the failed decision's snapshot and ledger state under the same lock. Formatting/unwrapping does not resample the domain or acquire a control slot; timeout/queue-full classification remains available through errors.Is. Healthy entry still avoids constructing rejection diagnostics.
  • The new pressure fixture is scoped to the embedded test's service. Statement entry, allocation ownership and live CN-cap sampling use that service's same ledger; services without an explicit fixture still use the process-wide production ledger. The real-MySQL regression still rejects ordinary SQL, allows bounded KILL progress, observes the interrupted worker, and checks cleanup.
  • The fulltext fixture isolates structural allocation counting from live memory sampling without raising the existing allocation bound of 8. Production pools still use the live capacity provider. This test change is not evidence that production sampling overhead has been removed or measured.

Validation on this exact head, macOS/arm64, -race -tags matrixone_test:

  • Full suites: pkg/common/system, pkg/common/rscthrottler, pkg/vm/process, and pkg/fulltext passed.
  • The full pkg/fulltext/plugin/search suite passed 3 repetitions. Its first local build hit an arm64/x86 jemalloc linker mismatch; the rerun explicitly linked the repository's matching arm64 static archive, without source changes.
  • Rejection snapshots, healthy-entry allocation bound, queue behavior, service-fixture ownership and fixed-pool/live-provider separation passed 20 repetitions.
  • Committed MySQL SQL-lifecycle and deterministic pressure/KILL tests passed 3 repetitions. Focused frontend control/catalog, remote compile sizing, bootstrap-control and lock-retry pressure tests also passed 3 repetitions.
  • An independent real-MySQL pressure/KILL probe using the default global ledger, not the new service fixture, passed 3 repetitions. It uses a pending claim rather than a large allocation (MO_MEMORY_STATEMENT_PRESSURE_CONCURRENCY=1, MO_MEMORY_HOST_RESERVE_PERCENT=1); this is a controlled local witness, not a default-policy Linux CI reproduction.
  • The independent recovered-non-Go-peak/4-KiB allocation probe passed 3 repetitions across modeled host, cgroup-v1 and cgroup-v2 domains. make err-check on the committed tree and git diff --check passed.

At the final check, the head was unchanged: ALL CI run 39024341564 still had Ubuntu UT, Coverage, arm64 SCA and multi-CN BVT jobs in progress; Connector/J Pool Reset E2E had passed. These are not completed-green integration results.

The previous run's CDC/startup zero-budget failures under shared cgroup pressure are not closed by these local successes. This delta improves attribution and isolates two test premises; it does not demonstrate that the other integration failures are fixed. Use completed checks on this head rather than relabeling failures from 31d1330f24 as current-head failures.

The PR's stated current-revision matched base/candidate TPCC acceptance also remains necessary: controlled memory, throughput/tail latency and pressure-time memory attribution together. Neither fixture isolation nor fewer OOM/pauses establishes that acceptance.

No product code was edited or pushed, and no CI rerun or benchmark was launched. This is an ordinary comment, not a formal approval/request-changes event.

Cover post-password system-variable initialization and tenant catch-up without persisting control classification on the session. Add real-protocol pressure regressions for fresh dump/root connections, wrong-password rejection, ordinary-query throttling, and KILL. The new fresh-connection tests fail on the previous head with control=false and pass after the fix.
Do not infer that eight or more CPUs can fit four race-instrumented embedded clusters in a 14-16 GiB domain. Preserve explicit three/four-worker opt-ins and serial rollback, with scheduler contract coverage for both defaults and overrides.
@daviszhen

Copy link
Copy Markdown
Contributor Author

Re-reviewed exact head 2a73fed2eaeff94a4a668fb2bcc42a3aecba3db4, focusing on the four-file delta since 9f3552a866e6c6f4bed0a9a5909d650dda2596ca and its handshake/admission and CI scheduling consumers.

No new blocking code finding in this delta. This is not merge approval: completed exact-head integration and the PR's stated performance/memory-source acceptance are still needed.

Handshake fix verified with a before/after control

The local control marker in Session.AuthenticateUser did not reach the subsequent tenant/system-variable initialization in MysqlProtocolImpl.authenticateUser. Extending the marker to the outer handshake call covers that work without writing it back to the user's session/request context. The existing control-slot, allocation-accounting and physical-domain limits remain in force.

I copied the new cold-connection regression into the previous-head worktree under review-only test names. On 9f3552a866, both dump and sys#root#moadmin fail at the correct-password cold connection: handshake admission times out with ordinary_reason=pressure-concurrency, control=false, and control_reason=not-requested. On this head, the committed regression passes three race-enabled repetitions for both identities. It also verifies wrong-password rejection, ordinary SELECT 1 remaining subject to ordinary admission after login, successful KILL QUERY, the interrupted worker, and control/queue cleanup. This is a deterministic service-ledger pressure fixture, not a live Linux OOM reproduction.

Scheduling change is scoped to ordinary UT, not Coverage

The two-worker defaults preserve the eight issues batches/four audited embedded batches and explicit larger-pool overrides. The complete optools suite passes, including Make configuration, bounded pools, inventory/report handling and failure propagation.

However, the current run resolves matrixorigin/CI to b0f959479893a3ab54ff3d9422e135ae2e9c67b2. Its Coverage workflow sets COVERAGE_UT_PACKAGE_PARALLELISM=8 and invokes go test -p directly through its own wrapper. It does not consume these Makefile pool defaults. Please do not treat this pool reduction as closure of the Coverage pressure incident; that path needs its own completed result and, if it fails again, a same-runner bounded-concurrency comparison.

For attribution, the previous head's UT failure includes CDC setup being rejected by statement admission. Its Coverage failure includes TestRewritePolicySavedResult/round_1/revoked receiving a hash-build zero-budget error (requested=8, used=0, limit=0) and CDC-related failures. These are 9f3552a866 results, not failures established on 2a73fed2ea, and local handshake success does not close those separate integration cases.

Exact-head local validation

macOS/arm64, -race -tags matrixone_test:

  • Full optools, frontend, system, rscthrottler and process suites passed.
  • Committed real-MySQL SQL lifecycle, warm-connection pressure/KILL, and cold-connection pressure/KILL tests passed three repetitions.
  • Focused statement/control admission, bounded physical allowance, context lifetime and catalog/task-control regressions passed 20 repetitions.
  • make err-check and git diff --check passed. No race-detector report occurred.

At the final check, the head is unchanged. Current CI run 39032010323 still has UT, Coverage and arm64 SCA in progress; the shared build, Connector/J Pool Reset E2E and native checks have passed. This is not a completed-green integration run. The already-agreed matched current-revision base/candidate memory, throughput/tail-latency and pressure-time attribution acceptance remains open; reducing test concurrency is not performance evidence.

No product code was edited or pushed, and no CI rerun or benchmark was launched. This is an ordinary comment, not a formal GitHub review event.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Remediation plan for the four design defects (head 2db8e3622f)

Following the defect analysis (D1–D4) and the TPCC counterexample in run 39216607157, here is a concrete, code-anchored fix plan. Guiding principle: keep the hard-safety gate cache-blind forever (never trust kernel reclaim), and split "pressure scheduling" from "hard admission" into two consistent views. Total delta ≈ 250–350 LOC including tests.

Fix Defect Location Size Priority
F1 Split pressure vs hard views D1: tripwire mixes views pkg/common/system/memory_statement.go:185 + memory_admission.go ~30 LOC + UT P0
F2 Graded slope + desynced timeout D2: 719→28 cliff + synchronized 250 ms timeout memory_statement.go (EnterStatement) ~60 LOC + UT P0
F3 Share pressure state to write path D3: entry gate closed while write gate keeps admitting rscthrottler + budget exposes pressure ~50 LOC P1
F4 Minimal Solution-4 landing D4: reserve-absorption premise broken under the blind gate 4b in-PR; 4a charge control as follow-up PR ~20 LOC / separate P1/P2
F5 Observability Diagnosis required reverse-engineering a 47 MB docker log rejection diagnostics + metrics ~25 LOC P0

F1 — split the views (root cause of the incident)

At memory_statement.go:177–185, available := b.availableLocked(snapshot) is min(working-set view, raw-charge view) — dominated by the raw view under load — but the tripwire compares it against the full calibrated reserve (max(floor, 2×nonGoHW, 5%/10% capacity) + runtime). In the incident: used 79.3/84 GiB with ~30 GiB clean cache → raw view ≈ 4.3 GiB < reserve → false pressure, while the real working set was only 59%.

The min-of-two-gates is correct for hard admission (the raw gate must not assume kernel reclaim succeeds). Pressure scheduling asks a different question — how much working-set headroom remains? — and needs the matching view:

// memory_admission.go — pressure scheduling only; hard admission untouched
func (b *MemoryAdmissionBudget) availableForPressureLocked(s MemoryDomainSnapshot) uint64 {
    used := s.Used
    if s.Source == MemoryDomainSourceHost || s.IsCgroup() {
        used -= min(used, s.Reclaimable)
    }
    rs := s; rs.NonGo = b.nonGoHighWater
    return b.headroomLocked(s, used, b.policy.Reserve(rs))
}
// memory_statement.go EnterStatement
hardAvailable     := b.availableLocked(snapshot)             // two-gate, unchanged
pressureAvailable := b.availableForPressureLocked(snapshot)  // single consistent view
underPressure     := pressureAvailable < b.policy.Reserve(reserveSample)
if snapshot.Measured && hardAvailable > 0 && atHead && (!underPressure || ...) { ... }

Under the incident's shape, WS headroom ≈ 84−(79.3−30)−4.3 ≈ 30 GiB ≥ reserve → no false pressure. With genuinely dirty cache, Reclaimable≈0, the two views coincide → no false negatives either. The change only relaxes the throttle switch; the raw hard gate is byte-identical, so it is monotonically safe (it can only reduce false positives, never admit past the charged boundary).

UT: three cgroup fixtures — large clean cache must not trip / dirty cache must trip / raw crossing still rejects hard.

F2 — graded slope + desynchronized timeout

Replace the binary !underPressure || active < GOMAXPROCS cliff with a linear ramp and jitter the waiter expiry:

// limit = 1 for avail→0 (liveness floor), up to base at avail=reserve
func pressureLimit(base, avail, reserve uint64) uint64 {
    if reserve == 0 || avail >= reserve { return math.MaxUint64 }
    return max(uint64(1), 1+(base-1)*avail/reserve)
}
// waiter expiry: jitter to break the synchronized mass timeout
expires = now + timeout/2 + rand.N(timeout)   // [0.5T, 1.5T]

Backpressure then manifests as queueing latency instead of 26,326 client-fatal errors in 43 s (9.6% of measured tpmC window). F2 is the shape insurance once F1 removes the false trips.

F3 — propagate pressure to the write path

While the entry gate was closed, internal writes (flush-to-S3 etc.) still saw ~4.3 GiB raw headroom and kept admitting, feeding the pollution loop. Export a hysteresis-backed state:

func (b *MemoryAdmissionBudget) UnderPressure() bool
// enters when pressureAvailable < reserve; exits when > 1.25×reserve for 4 samples
  • rscthrottler: when under pressure, halve write/flush in-flight allowance (floor = existing minimum); restore on release;
  • add mo_system_memory_pressure gauge.

F4 — Solution-4 minimal landing

  • 4b (this PR, ~20 LOC): document/encode the contract "scheduling decisions use the working-set view; hard safety uses the raw view" (F1 + existing hardAvailable>0), so the reserve-absorption claim holds exactly in the view where it is made;
  • 4a (follow-up PR): true charge control — bind clean-cache growth (pkg/fileservice/cache.go, already touched here) to a budget share and proactively evict clean pages when raw headroom falls below threshold, instead of waiting for admission failures. This is also the one component whose policy must invert between container (cache is the enemy) and bare-metal (cache is a friend) deployments.

F5 — observability (P0, mechanical)

Add reclaimable=, raw_available=, ws_available=, pressure= to MemoryStatementAdmissionError fields, and a statement_rejected{reason} counter. This incident was only diagnosable by reverse-engineering a 47 MB docker log because these four values were missing.

Acceptance / verification

  1. Incident replay: embed fixture reproducing run 39216607157's memory shape (84 Gi cap, ~30 GiB clean cache, TPCC 1000W) → criteria: zero client-fatal errors, no pressure flap, post-load recovery ≤ the current 8 s;
  2. A/B performance: base vs candidate, same slot, ≥ 2 steady windows each — this still stands as the open performance acceptance;
  3. No false negatives: pin dirty cache, confirm pressure still trips;
  4. Existing UT/BVT green plus the new table-driven UTs.

F1+F2+F5 alone would have prevented this counterexample; F3+4a make the class structurally impossible.

This branch was previously deployed

1 inactive deployment
ci — 855523b2 Deployed Oct 20, 2026 by daviszhen
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants