Skip to content

[Bug]: TAE merge scheduler ignores denied memory reservations and releases another in-flight task's quota #32428

Done

Description

@LeftHandCold

Summary

On current main, one MergeScheduler.doSched can start multiple merge tasks against the same initial available-memory snapshot. It calls ExecuteFor before Acquire, ignores the returned grant boolean, and admits the completion observer even when Acquire refuses the reservation. Completing that unreserved task then subtracts a different, still-running task's reservation.

The confirmed defect is broken admission/accounting. This report does not claim that a physical OOM occurred, or that it caused the recent BigData Q7 latency change / 180-second merge-boundary timeout.

Environment

  • Branch: main
  • Commit: 6a2b29954749d5a47820ed429cfa8a6c4793682f
  • Validation: Linux/amd64, Go 1.27.1; matching native libraries built with the repository make cgo path.
  • Deterministic linked Go probe in pkg/vm/engine/tae/db/merge, without modifying production code. No service, wall-clock race, large physical allocation, or real memory pressure is required.

Production path and root cause

  1. The scheduler constructs the Merge throttler with WithSpecializedForMerge() and without an allow-over-limit policy (constructor).
  2. The main loop checks the 500 MiB global gate before entering doSched (gate). One Ln overlap gather can produce several disjoint tasks. controlTaskMemInPlace checks each task against the same available budget; it does not reserve their cumulative size (gather/admission, per-task control).
  3. The internal task loop starts work before asking for its reservation, discards both Acquire results, and unconditionally publishes admission on successful executor scheduling (doSched):
for _, task := range tasks {
    task.doneCB = a.taskObserverFactory(supp, task.eSize, rc)
    if a.executor.ExecuteFor(todo.table, task) {
        rc.Acquire(int64(task.eSize)) // returned grant can be false
        supp.AddTask()
        task.doneCB.Admit()
        // ...
    }
}
  1. A refused default Acquire leaves reserved unchanged (throttler). Every admitted observer nevertheless invokes Release(size) on completion (observer). Release subtracts a global scalar and clamps it at zero; it has no task ownership information (release).

Reproduced boundary

The fixture has six metadata-only objects with distinct identities: two disjoint key clusters, three overlapping objects per cluster. OriginSize=64 MiB is an ObjectStats scalar, not a payload allocation. Real EstimateMergeSize and real overlap gathering produce:

  • Per-task estimate E = 553,648,308 B (528 MiB + 180 B).
  • Initial budget B = 830,472,462 B (792 MiB + 270 B), above the production 500 MiB global gate.
  • Each task individually satisfies E <= 2/3 * B, so real gather retains both tasks without trimming.
  • First task: accepted; Acquire(E) succeeds, leaving 276,824,154 B.
  • Second task: accepted; Acquire(E) returns false. It is still admitted.
  • Complete the second task first: actual held reservation falls from E to 0, although the first task is still in flight (mergingTaskCnt=1). An independent per-task successful-grant ledger still holds E.

The probe asserts all relevant outer-loop preconditions: initial budget >=500 MiB, due todo, non-dropped/non-paused table and scheduler, no prior merging task, message queue below the early-return gate. It invokes the real handleTaskTrigger -> doSched -> gatherByTrigger -> taskObserver transitions directly; it does not run the main-loop goroutine. Both genuine Ln overlap gathering and an assigned-task trigger reproduce the defect. The strict controller implements the production grant/refusal/release contract with a stable budget; it does not force a refusal or change the production implementation.

Entry Tight budget Sufficient budget Executor rejects second task
Two Ln clusters, real overlap gather FAIL: unreserved task admitted; wrong reservation released PASS: both grants and releases balance PASS: only first grant/completion
Assigned tasks Same failure PASS PASS

Exact test selection is non-empty. Focused run exits 1 because the two tight-budget contract cells fail; all four neighboring controls pass. Package test body: 0.039 seconds.

Decisive output:

budget=830472462 task_estimate=553648308 executor_attempts=2 accepted=2
 decisions=[{ask:553648308 granted:true} {ask:553648308 granted:false}]
 held=553648308 independent_ledger=553648308
completed_accepted_task=2 held_before=553648308 held_after=0
 independent_ledger=553648308 pending=1

Expected behavior and impact

Only successfully reserved work may be admitted, and completion must release only the completing task's successful reservation. Reservation acquisition should precede publication/execution, with rollback if executor scheduling fails, or an equivalent ownership-safe admission protocol.

Current behavior both admits estimated work beyond the remaining budget and erases protection for another live task. This can weaken merge memory protection under pressure; the deterministic reproduction establishes the accounting violation, not a measured OOM or a particular production incident's cause.

Reproduction

Save the following diagnostic probe as pkg/vm/engine/tae/db/merge/reservation_accounting_probe_test.go at the commit above. It reuses package fixture helpers that exist at that commit. With matching native prerequisites, run:

GOMAXPROCS=1 GOMEMLIMIT=2GiB GOWORK=off \
  .agents/skills/mo-dev/scripts/mo-cgo-test \
  -p=1 -count=1 -timeout=120s -v \
  -run '^TestMergeReservationReachableBudgetProbe$' \
  ./pkg/vm/engine/tae/db/merge

The smaller TestMergeReservationAccountingProbe is an internal small-budget model only; use the explicitly named reachable-budget test above for the production 500 MiB gate. The pre-fix diagnostic includes assertions about current call order and is not a proposed final regression-test implementation.

Complete deterministic probe
package merge

import (
	"context"
	"fmt"
	"iter"
	"sort"
	"strings"
	"testing"
	"time"

	"github.com/matrixorigin/matrixone/pkg/container/types"
	"github.com/matrixorigin/matrixone/pkg/objectio"
	"github.com/matrixorigin/matrixone/pkg/vm/engine/tae/catalog"
	"github.com/matrixorigin/matrixone/pkg/vm/engine/tae/common"
	"github.com/matrixorigin/matrixone/pkg/vm/engine/tae/mergesort"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

// This deterministic controller implements the production default Acquire
// contract: a refusal leaves reservations unchanged. No host pressure or large
// allocations are needed to exercise scheduler admission.
type reservationProbeDecision struct {
	ask     int64
	granted bool
}

type reservationProbeRSC struct {
	limit     int64
	held      int64
	decisions []reservationProbeDecision
	releases  []int64
}

func (*reservationProbeRSC) Refresh()    {}
func (*reservationProbeRSC) PrintUsage() {}
func (r *reservationProbeRSC) Available() int64 {
	return max(int64(0), r.limit-r.held)
}
func (r *reservationProbeRSC) Acquire(ask int64) (int64, bool) {
	granted := ask <= r.Available()
	r.decisions = append(r.decisions, reservationProbeDecision{ask, granted})
	if granted {
		r.held += ask
	}
	return r.Available(), granted
}
func (r *reservationProbeRSC) Release(size int64) int64 {
	r.releases = append(r.releases, size)
	r.held = max(int64(0), r.held-size)
	return r.Available()
}

// A tiny MergeTable implementation delegates all identity/lifecycle behavior to
// the existing catalog fixture and supplies valid visible object metadata.
type reservationProbeTable struct {
	catalog.MergeTable
	stats []*objectio.ObjectStats
}

type reservationProbeItem struct{ stats *objectio.ObjectStats }

func (i reservationProbeItem) GetCreatedAt() types.TS                { return types.BuildTS(1, 0) }
func (i reservationProbeItem) GetObjectStats() *objectio.ObjectStats { return i.stats }
func (p *reservationProbeTable) IterDataItem() iter.Seq[catalog.MergeDataItem] {
	return func(yield func(catalog.MergeDataItem) bool) {
		for _, stat := range p.stats {
			if !yield(reservationProbeItem{stat}) {
				return
			}
		}
	}
}

type reservationProbeExecutor struct {
	delayed  *delayedCompletionExecutor
	rejectAt int
	attempts int
}

func (e *reservationProbeExecutor) ExecuteFor(table catalog.MergeTable, task mergeTask) bool {
	e.attempts++
	if e.attempts == e.rejectAt {
		return false // normal executor scheduling failure; no completion follows
	}
	return e.delayed.ExecuteFor(table, task)
}

func reservationProbeKey(task mergeTask) string {
	keys := make([]string, 0, len(task.objs))
	for _, obj := range task.objs {
		keys = append(keys, fmt.Sprintf("%x", obj.ObjectName()))
	}
	sort.Strings(keys)
	return strings.Join(keys, "/")
}

// This ledger owns individual successful grants. Unlike the implementation's
// scalar Release(size), completion can remove only that task's own grant.
type reservationProbeLedger map[string]int64

func (l reservationProbeLedger) total() int64 {
	var total int64
	for _, size := range l {
		total += size
	}
	return total
}

func TestMergeReservationAccountingProbe(t *testing.T) {
	runMergeReservationAccountingProbe(t, 64, false)
}

func TestMergeReservationReachableBudgetProbe(t *testing.T) {
	// OriginSize is a scalar in ObjectStats, not a payload allocation. With
	// three 64MiB logical objects per task the estimate exceeds 500MiB,
	// allowing the production handleMainLoop admission guard to pass first.
	runMergeReservationAccountingProbe(t, 64*common.Const1MBytes, true)
}

func runMergeReservationAccountingProbe(t *testing.T, originSize uint32, checkGlobalGuard bool) {
	for _, path := range []string{"assigned_tasks", "two_Ln_clusters"} {
		t.Run(path, func(t *testing.T) {
			for _, tc := range []struct {
				name     string
				ample    bool
				rejectAt int
			}{
				{name: "tight_budget"},
				{name: "sufficient_budget", ample: true},
				{name: "schedule_failure", rejectAt: 2},
			} {
				t.Run(tc.name, func(t *testing.T) {
					table := &reservationProbeTable{MergeTable: promotionTable(8901)}
					// Six metadata-only objects: two disjoint key clusters, each
					// containing the minimum default overlap depth of three.
					for cluster := range 2 {
						for range 3 {
							lo := int32(cluster*100 + 1)
							table.stats = append(table.stats,
								newTestObjectStats(t, lo, lo+1, originSize, 2, 1, nil, 0))
						}
					}
					clock := newFakeClock()
					trigger := NewMMsgTaskTrigger(table)
					if path == "assigned_tasks" {
						// Assigned triggers are used by ioVacuumCheck and are an
						// existing package seam. The tasks have disjoint objects.
						trigger.WithAssignedTasks([]mergeTask{
							{objs: table.stats[:3], level: 1, note: "cluster one"},
							{objs: table.stats[3:], level: 1, note: "cluster two"},
						})
					} else {
						trigger.WithLn(1, 1, DefaultOverlapOpts.Clone())
					}
					// Estimate uses metadata only; the size never allocates a
					// corresponding physical object or merge input payload.
					estimate := int64(mergesort.EstimateMergeSize(IterStats(table.stats[:3])))
					require.Positive(t, estimate)
					if !checkGlobalGuard {
						require.Less(t, estimate, int64(1024))
					}
					budget := estimate * 3 / 2
					if tc.ample {
						budget = estimate * 2
					}
					rc := &reservationProbeRSC{limit: budget}
					if checkGlobalGuard {
						require.GreaterOrEqual(t, rc.Available(), int64(500*common.Const1MBytes),
							"initial budget must pass handleMainLoop's global admission guard")
						if !tc.ample {
							require.Less(t, budget-estimate, int64(500*common.Const1MBytes),
								"the budget falls below the global guard after the first grant inside this doSched")
						}
					}
					gathered := newLaunchPad(clock).gatherByTrigger(
						context.Background(), trigger, clock.Now(), rc)
					require.Len(t, gathered, 2, "both independent tasks fit the same initial budget")
					seen := make(map[string]struct{})
					for _, task := range gathered {
						require.Len(t, task.objs, 3, "gather must not trim this fixture")
						require.Equal(t, estimate, int64(task.eSize))
						require.True(t, resourceAvailable(estimate, rc))
						for _, obj := range task.objs {
							key := fmt.Sprintf("%x", obj.ObjectName())
							_, duplicate := seen[key]
							require.False(t, duplicate, "executor scopes must be disjoint")
							seen[key] = struct{}{}
						}
					}
					require.Len(t, seen, 6)
					require.Zero(t, rc.held, "gather is only an availability check")
					delayed := &delayedCompletionExecutor{tasks: make(chan mergeTask, 2)}
					executor := &reservationProbeExecutor{delayed: delayed, rejectAt: tc.rejectAt}
					sched := NewMergeScheduler(time.Hour,
						&dummyCatalogSource{initTables: []catalog.MergeTable{table}}, executor, clock)
					sched.PatchTestRscController(rc)
					// Run the real single-threaded scheduler transition directly.
					// No service, worker goroutine, wall-clock sleep, or fake
					// operator state is involved.
					sched.handleTaskTrigger(nil, trigger)
					supp := sched.supps[table.ID()]
					require.False(t, sched.allPaused)
					require.False(t, supp.paused)
					require.False(t, table.HasDropCommitted())
					require.False(t, supp.todo.readyAt.After(clock.Now()))
					require.Zero(t, supp.mergingTaskCnt.Load())
					require.LessOrEqual(t, len(sched.msgChan), 50)
					sched.doSched(nil, supp.todo)
					accepted := make([]mergeTask, 0, len(delayed.tasks))
					for len(delayed.tasks) > 0 {
						accepted = append(accepted, <-delayed.tasks)
					}
					// Completion is immediate and deterministic, but register
					// cleanup before any assertion that can end the test.
					t.Cleanup(func() {
						for _, task := range accepted {
							task.doneCB.OnExecDone(nil)
						}
					})
					require.Equal(t, 2, executor.attempts)
					require.Len(t, rc.decisions, len(accepted))
					ledger := make(reservationProbeLedger)
					var acceptedBytes int64
					for i, task := range accepted {
						decision := rc.decisions[i]
						require.Equal(t, int64(task.eSize), decision.ask)
						acceptedBytes += int64(task.eSize)
						if decision.granted {
							ledger[reservationProbeKey(task)] = decision.ask
						}
						assert.True(t, decision.granted,
							"executor accepted task %d without a memory reservation", i+1)
					}
					t.Logf("budget=%d task_estimate=%d executor_attempts=%d accepted=%d decisions=%+v held=%d independent_ledger=%d",
						budget, estimate, executor.attempts, len(accepted), rc.decisions, rc.held, ledger.total())
					assert.LessOrEqual(t, acceptedBytes, budget,
						"total accepted work must fit the logical memory budget")
					assert.Equal(t, ledger.total(), rc.held)
					require.Equal(t, int64(len(accepted)), supp.mergingTaskCnt.Load())
					// Finish the second accepted task first. If its Acquire was
					// denied, it owns no grant and cannot release the first's.
					for i := len(accepted) - 1; i >= 0; i-- {
						task := accepted[i]
						before := rc.held
						delete(ledger, reservationProbeKey(task))
						task.doneCB.OnExecDone(nil)
						t.Logf("completed_accepted_task=%d held_before=%d held_after=%d independent_ledger=%d pending=%d",
							i+1, before, rc.held, ledger.total(), supp.mergingTaskCnt.Load())
						assert.Equal(t, ledger.total(), rc.held,
							"completion must release only the completing task's successful grant")
					}
					require.Zero(t, supp.mergingTaskCnt.Load())
					require.Zero(t, rc.held)
					require.Empty(t, ledger)
				})
			}
		})
	}
}

Existing tracking checked

Searched open and closed issues for merge Acquire, reservation, and merge memory, and inspected the closest reports. Closed #31656 fixed the default throttler's concurrent check/CAS race; its corrected refusal behavior is present here. This report concerns the merge caller ignoring that refusal and releasing an unowned grant, even in a serial scheduler transition. Closed #21585 / #22638 concern estimation or RSS/cache overhead; closed #26376 concerns an allocation-failure panic. None of those reports tracks this reproduced caller/observer accounting sequence.

Activity

  1. added
    kind/bug
    on Nov 9, 2026
  2. XuPeng-SH commented on Nov 18, 2026

    @XuPeng-SH
    Contributor

    Revalidated the same accounting break on main@87c44445f83e308ef12dd7ca0e570cec1e6690d9 with an independent ordered-completion probe. The merge/throttler files in the tested 517e1695388cbaf1135238d5ab0c19a4556fb551 checkout were verified identical to that main snapshot.

    The probe runs two identical tasks (each eSize=865103600) and holds A while completing B:

    granted_control:
      firstAsk=865103600 secondAsk=865103600 denied=0
      after B completes: reserved=865103600  PASS
    
    denied_second:
      firstAsk=865103600 secondAsk=865103600 denied=1
      executor attempts=2
      after B completes: reserved=0          FAIL
      expected 865103600 (A's live reservation), actual 0
    

    The denial is injected at the second Acquire, after both tasks have been gathered. B is nevertheless executed/admitted, and B's observer release subtracts A's reservation. The granted control shows that the harness preserves A's reservation when both acquisitions succeed.

    Command shape: controlled repository CGo wrapper, local diagnostic overlay in pkg/vm/engine/tae/db/merge, Go 1.27.1, darwin/arm64. No production source was modified. This is the same root cause already tracked here, so no duplicate issue was filed. It remains an admission/accounting reproduction, not a physical-OOM claim.

  3. added a commit that references this issue on Nov 21, 2026
    397ce07
  4. XuPeng-SH commented on Nov 21, 2026

    @XuPeng-SH
    Contributor

    QA 转测:#32911 已合入 main,合并提交 397ce074118889d402fc3f2319f2cb801e58fb05。本轮只覆盖 TAE merge 调度内存额度:取得额度后才提交、拒绝时不执行、执行器拒绝时归还、已接收任务完成后只释放一次。不把本修复视为解决物理 OOM 或 BigData Q7 延迟。

    独立评审在 ed2953a4ab 核对了上一头的测试证据:merge 包 47 项 race 通过,五个重点场景各重复 100 次,旧实现的紧额度及执行器拒绝场景失败。远端核对两份变更文件在评审头、最终 PR head 和合并提交一致,不代表整树同一。未在合并版重跑,也未验证生产 RSS 或末版全套 CI。

    请在合并后 main 核对跨任务额度归属、拒绝/完成时序、同轮较小任务及内存压力。转测不等于验收通过,工单保持开放。

  5. Ariznawlll commented on Nov 22, 2026

    @Ariznawlll
    Collaborator

    阶段性白盒测试结果

    在官方 main cc2c82dc4a6cb2cbcc046ef9caebde50c6004b15 上,pkg/vm/engine/tae/db/merge 的 TestMergeReservationReachableBudgetProbe、TestMergeReservationContinuesAfterDenial 和 TestMergeReservationInlineCompletion 已以 go test -race -count=30 执行通过。

    用例覆盖 assigned tasks / 两组重叠对象、紧张及充足额度、调度失败、拒绝大任务后继续尝试其他任务,以及同步完成时的额度归还;这些是受控调度与额度探针,逻辑对象大小由元数据模拟,不分配等量真实数据。

    尚未完成真实大对象多任务并发、实际 RSS/内存水位和生产压力下的验收;本结果不证明物理 OOM 或 BigData Q7 延迟已解决。Issue 暂保持开放。

  6. Ariznawlll commented on Nov 24, 2026

    @Ariznawlll
    Collaborator

    结论

    按原报告的 TAE merge admission/accounting 缺陷验收通过,关闭本 Issue。额度现在先取得再提交任务;拒绝时不再执行,执行器拒绝会归还额度,已完成任务只释放自己的一次成功 reservation,不再把另一个在途任务的额度错误清零。

    修复与验收版本

    • fix(merge): reserve memory before scheduling tasks #32911 已合入 main,merge commit:397ce074118889d402fc3f2319f2cb801e58fb05。
    • 合入后 QA 复测使用官方 main cc2c82dc4a6cb2cbcc046ef9caebde50c6004b15,包含上述修复。
    • 独立评审头 ed2953a4ab295a5cf045148a9c6be25a562f08a4 的 CI Required、UT、SCA、Coverage 和 BVT 成功;最终 head 2064d88187cb04f7981d30e5dff2322a661481b6 的快速合入运行被取消,不冒称最终 head 全套 CI 已执行。关闭依据是合入后 main 的定向 race 复测,而不是该取消状态。

    原确定性场景复测

    在合入后 main 上,以下生产调度探针以 go test -race -count=30 全部通过:

    • TestMergeReservationReachableBudgetProbe
    • TestMergeReservationContinuesAfterDenial
    • TestMergeReservationInlineCompletion

    覆盖:

    • assigned tasks 与真实两组 Ln overlap gather;
    • 紧张/充足额度、第二个任务 Acquire 被拒绝、executor scheduling failure;
    • 拒绝大任务后继续尝试较小任务;
    • 同步完成、逆序完成、拒绝后不发布 observer,以及额度最终归零和在途额度归属。

    独立评审另记录 merge 包 47 项 race通过、五个重点场景各 100 次通过;旧实现的紧额度和执行器拒绝对照按预期失败,证明测试可检出原问题。

    范围边界

    原 Issue 明确只报告确定性的调度器准入/记账破坏,并未声称物理 OOM、生产 RSS 或 BigData Q7 延迟,因此这里的生产路径白盒复测就是原场景验收,不是用白盒替代另一个部署事故。

    逻辑对象大小仍由元数据模拟,不分配等量真实数据;真实大对象、多任务生产并发和 RSS 水位属于额外压力验证,不纳入本次通过声明,也不能据此宣称 OOM 或 Q7 延迟已解决。

  7. added a commit that references this issue on Nov 25, 2026
    c46ba7e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

kind/bugneeds-triage

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions