Skip to content

[Bug]: FileService MemCache double-counts reservation handoff and stops synchronous reclamation early #29088

Closed

Description

@LeftHandCold

Is there an existing issue for the same bug?

  • I have checked the existing issues.

Related: #28627 (IVF read/decompression amplification), #28898 and #28918 (overlapping reads/allocations for the same key). This report isolates two independently reproduced MemCache accounting/reclamation defects. Reproducer A uses different keys and different backing allocations; reproducer B is serial and requires no duplicate read.

Recent open/closed searches since 2026-09-11 for reservedBytes, evictBatch, EvictToTargetWithWait, MemCache, and FIFO did not find a report covering these specific counterexamples. #28898 was read and compared, not excluded solely by its title.

Branch Name

main

Commit ID

  • Executed diagnostics: 6690f1af97977ad5671235e9204296cd2d504ad5.
  • Latest main rechecked on 2026-09-18: 480b91764a94cf9ab49d3f2b43a60cb63ce677c6.
  • git diff 6690f1af97977ad5671235e9204296cd2d504ad5 480b91764a94cf9ab49d3f2b43a60cb63ce677c6 -- pkg/fileservice pkg/common/malloc is empty. Thus the tested cache/allocation implementation remains unchanged on this main HEAD. This is code-equivalence verification, not a claim that a second complete MO image was deployed and tested.

Other Environment Information

  • Linux/amd64 test host, 20 CPUs and approximately 62 GiB RAM.
  • Go 1.26.4, repository mo-cgo-test wrapper, GOMAXPROCS=4, GOMEMLIMIT=1GiB.
  • Real pkg/fileservice MemCache, DataCache, FIFO and native allocator. Existing native build artifacts were reused; no full MO image rebuild or SQL-cluster test was performed.
  • Each data block is 1 MiB. Actual allocator backing size was checked to be exactly 1,048,576 bytes, larger than the 64 KiB idle-buffer-pool threshold.
  • Cache capacity: 4 MiB for A and 3 MiB for B. No production-source changes, remote object-store dependency, random sleep, OOM, external cache pressure, or cluster reconfiguration.
  • GOMEMLIMIT is only a Go runtime soft limit, not a hard bound on CGo/process RSS.

Actual Behavior

There are two separate defects in the capacity-accounting/reclamation path. They should not be conflated with normal FIFO policy decisions or assumed to share one root cause.

A. Reservation-to-FIFO handoff double-counts one allocation and evicts data that fits

The real MemCache can evict an existing entry even though all four distinct backing allocations fit its capacity. A deterministic channel barrier selects the interval after the real DataCache.Set has returned but before MemCache.Update commits that same buffer's reservation.

State/result Handoff paused Control: handoff completes before next allocation
Cache capacity 4 MiB 4 MiB
Used after C's real Set 3 MiB 3 MiB
Reserved after C's real Set 1 MiB 0
Used after inserting D 3 MiB 4 MiB
Resident keys B, C, D A, B, C, D
Eviction callback A, 1 MiB none
Used/reserved after final cleanup 0 / 0 0 / 0

Raw diagnostic output:

blocked=true unit=1048576 capacity=4194304
set_return_used=3145728 set_return_reserved=1048576
after_D_used=3145728 after_D_reserved=1048576
resident=map[A:false B:true C:true D:true]
postEvict=[fifo-validation/double-charge/1/1048576]
final_used=0 final_reserved=0

The remaining reservation in this snapshot belongs to paused C and is expected to remain pending until C resumes. The incorrect outcome is evicting A and retaining only 3 MiB of four otherwise fitting blocks, not merely the existence of a pending reservation.

Executed validation:

  • TestMemCacheReservationOverlapDoesNotEvictFitEntries: fails at the no-unnecessary-eviction oracle on the unmodified implementation.
  • TestMemCacheReservationOverlapNoBlockControl: passes with all four keys resident.
  • -count=20: 20/20 failing counterexamples and 20/20 passing controls.
  • -race: reproduces the same logical failure without a DATA RACE report.

The test gate delegates to the real Set first and then pauses only C. It does not override Used, reservation values, backing sizes, eviction results or allocator behavior. It enlarges a reachable scheduling interval; it does not measure that interval's duration or frequency in production.

B. Synchronous eviction mistakes a deleted main-queue record for no progress

After deletion has released an entry's value but left its lazy queue record, EvictToTarget(ctx, 0) can return while live entries remain, even with a live context and no concurrent insertions.

deleteHead=true unit=1048576 capacity=3145728
used_after_sync=2097152
resident_after_sync=map[A:false B:true C:true]
postEvict_after_sync=[]

Only A was deleted. B and C are separate file paths and remain valid cached allocations. The trace resets its eviction recorder after A's DeletePaths callback so the empty callback list refers to the subsequent synchronous eviction.

The control without DeletePaths reaches zero and evicts all three values. A second reclamation call after the counterexample clears B/C; final Used and reserved bytes are zero. This proves premature termination of one reclamation call, not an unconditional permanent hang.

  • TestMemCacheDeletedMainHeadDoesNotShortCircuitSynchronousEvict: fails at the zero-target oracle.
  • TestMemCacheDeletedMainNormalEvictControl: passes.

Normal-policy control

The production FIFO was also tested with 100 equal-sized capacity units initially occupied by 100 old hot entries, then a repeated 60-entry new working set:

Round New-working-set hits Old resident entries Used units
1 0/60 90 100
2 10/60 40 100
3 through 20 60/60 each round 40 100

TestFIFOValidationNormalWorkingSetFitsAfterOldHotPrefill passes. Old hot entries do not indefinitely prevent this fitting working set from warming. This control is not a claim that FIFO must behave as LRU or that every workload must fit after one scan.

Expected Behavior

  1. Transferring one backing allocation from pending reservation to FIFO ownership should not cause a competing allocation to count that same backing twice and unnecessarily evict otherwise fitting data. Avoiding double-counting must not introduce an under-accounted allocation interval.
  2. Synchronous eviction should continue when removing a lazy deleted queue record has made progress and additional reclaimable live entries remain above target. Whether a new value-release callback was produced is not equivalent to whether queue/accounting progress was made.

These expectations do not forbid normal capacity eviction, guarantee a minimum residency time, require a different replacement policy, or justify exceeding memory budgets.

Steps to Reproduce

The complete executed diagnostic source is supplied in a follow-up comment, so reproduction does not depend on access to the test host or private logs.

A: distinct-key handoff interleaving

  1. Create a 4 MiB MemCache; AllocateCacheData/Update A and B, each 1 MiB. Release caller references. Used=2 MiB, reserved=0.
  2. Allocate C, which creates a 1 MiB reservation.
  3. Run C's Update through a test-only DataCache wrapper that delegates the real Set, signals a channel, then pauses before returning to Update.
  4. At that boundary, verify Used=3 MiB and reserved=1 MiB, although only A/B/C have been allocated.
  5. Allocate and Update distinct key D, also 1 MiB. All four unique allocations would fit the 4 MiB capacity, but A is evicted.
  6. Release the gate, join C's Update, release vectors exactly once and flush. Verify final Used/reserved=0.
  7. Repeat without the pause. There is no eviction and all four values are present.

B: serial lazy-deletion trace

  1. Create a 3 MiB MemCache. Insert A/B/C, each 1 MiB and each at a different file path.
  2. Get each entry twice to make it eligible for promotion to the main queue.
  3. Delete only A via MemCache.DeletePaths. Its value is released, but its queue record still carries the access count and size.
  4. Call MemCache.EvictToTarget with a non-canceled context and target=0.
  5. The small-queue records are promoted. Main-queue eviction processes already-deleted A and returns early; B/C remain cached and Used=2 MiB.
  6. Compare the same trace without step 3: target=0 is reached in one call.

Commands after installing the diagnostic files and preparing the repository's Go/CGo dependencies:

GOMAXPROCS=4 GOMEMLIMIT=1GiB .agents/skills/mo-dev/scripts/mo-cgo-test \
  -v -count=20 -timeout=120s \
  -run '^TestMemCacheReservationOverlap' ./pkg/fileservice

GOMAXPROCS=4 GOMEMLIMIT=1GiB .agents/skills/mo-dev/scripts/mo-cgo-test \
  -v -race -count=1 -timeout=120s \
  -run '^TestMemCacheReservationOverlapDoesNotEvictFitEntries$' ./pkg/fileservice

GOMAXPROCS=4 GOMEMLIMIT=1GiB .agents/skills/mo-dev/scripts/mo-cgo-test \
  -v -count=1 -timeout=120s \
  -run '^TestMemCacheDeletedMain' ./pkg/fileservice

These commands intentionally exit nonzero on the affected code because the tests assert the desired invariant. They are bug reproductions, not passing fix-validation results.

Additional information

Proven root cause A: non-atomic accounting handoff

Exact code on the rechecked main commit:

  1. MemCache.reserveCacheData, lines 439-474 admits using capacity - Used - reservedBytes; its eviction target is capacity - reservedBytes - want.
  2. MemCache.Update, lines 790-803 calls Set first and CommitCacheReservation only after it returns.
  3. FIFO.Set, lines 271-281 charges the item to queue Used or pendingBytes before returning.

Therefore, the C allocation is simultaneously included in Used and reservedBytes during that interval. D's decision sees 4 - 3 - 1 = 0 MiB available instead of 1 MiB. Its requested eviction target becomes 4 - 1 - 1 = 2 MiB; the real FIFO removes A to reduce Used from 3 MiB to 2 MiB. This directly explains the observed callback, missing A and 3 MiB final residency. The unpaused control removes this exact precondition and preserves A.

This is synchronized operations composing into a logical accounting defect, not an unsynchronized-memory data race. The existing TestMemCacheCommitsReservationAfterFIFOUsageIsCharged protects against the opposite, under-counting window; it does not cover a concurrent allocation before reservation commit.

Proven root cause B: release-result is confused with progress

  1. DataCache.deletePath removes map membership and purges the value but intentionally leaves the queue record/accounting for lazy cleanup.
  2. FIFO.evict1 can promote this previously hot record to queue2.
  3. FIFO.evict2 dequeues the dead record and subtracts its size from used2, but returns evicted=false because the value was already purged.
  4. FIFO.evictBatch, lines 763-778 recognizes progress only through the recorded used1 change. It does not recognize this used2 decrease and returns a batch with evicted=false.
  5. FIFO.evictWithWait, lines 718-732 stops on !evicted, even though Used=2 MiB exceeds target=0 and B/C are still available to reclaim.

No queue fields were forged. The production S3FS.Delete -> MemCache.DeletePaths path can create these lazy records. MemCache.Flush uses the same synchronous zero-target primitive. Also, reserveCacheData rejects a reservation when this primitive returns above target; the caller then uses a non-cache-admitted transient buffer. Those are real consumers of the faulty progress decision.

Impact and evidence boundary

Confirmed: unnecessary eviction for otherwise fitting distinct allocations; incomplete synchronous reclamation with valid cached data remaining; controls and cleanup behavior described above.

Potential workload consequences: additional memory-cache misses, disk reads/decompression and transient non-cached allocations, or incomplete reclamation at a requested boundary. Their production frequency and scale have not been measured by these UTs.

Not established: data corruption, the entire cause of an IVF Daily's multi-fold slowdown, the fraction of production evictions caused by A, whether B was exercised by the affected read-only IVF objects, or a specific regression-introducing PR. Neither full IVF 10M nor a production-image A/B was executed for this report.

In particular, repeated reads of the same column every few seconds are insufficient by themselves to attribute each eviction to A or B: ordinary working-set turnover remains a valid alternative. No claim is made that fixing these two defects alone guarantees a particular QPS.

No production fix is included. The two root causes and their regression oracles are recorded separately to support a bounded repair without changing general FIFO policy, removing reservation safeguards, or expanding memory budgets.

Activity

  1. LeftHandCold commented on Sep 18, 2026

    @LeftHandCold
    CollaboratorAuthor

    Complete executed diagnostic sources

    These are temporary package-level diagnostics, not a production patch. They were executed on 6690f1af97977ad5671235e9204296cd2d504ad5; pkg/fileservice and pkg/common/malloc are unchanged at rechecked main 480b91764a94cf9ab49d3f2b43a60cb63ce677c6.

    A and B assert the intended invariants and fail on the affected code. Their corresponding controls pass. No FIFO counters/queues are modified by the harness. The handoff gate only pauses after the real Set for one chosen key and allows other Set calls to continue; cleanup joins the gated Update before releasing its caller reference.

    pkg/fileservice/mem_cache_reservation_overlap_test.go

    package fileservice
    
    import (
    	"context"
    	"fmt"
    	"sync"
    	"sync/atomic"
    	"testing"
    	"time"
    
    	"github.com/matrixorigin/matrixone/pkg/common/malloc"
    	"github.com/matrixorigin/matrixone/pkg/fileservice/fscache"
    )
    
    // setReturnGate pauses only after the delegated production DataCache.Set has
    // returned. The FIFO has therefore already charged Used before MemCache.Update
    // can commit the allocation reservation.
    type setReturnGate struct {
    	fscache.DataCache
    	entered chan struct{}
    	release chan struct{}
    	blocked atomic.Bool
    	key     fscache.CacheKey
    	open    sync.Once
    }
    
    func (g *setReturnGate) Set(ctx context.Context, key fscache.CacheKey, data fscache.Data) (bool, error) {
    	inserted, err := g.DataCache.Set(ctx, key, data)
    	if key == g.key && g.blocked.CompareAndSwap(false, true) {
    		close(g.entered)
    		<-g.release
    	}
    	return inserted, err
    }
    
    func (g *setReturnGate) unblock() {
    	g.open.Do(func() { close(g.release) })
    }
    
    type validationEvictions struct {
    	total atomic.Int64
    	mu    sync.Mutex
    	keys  []string
    }
    
    func (e *validationEvictions) record(key fscache.CacheKey) {
    	e.total.Add(1)
    	e.mu.Lock()
    	e.keys = append(e.keys, fmt.Sprintf("%s/%d/%d", key.Path, key.Offset, key.Sz))
    	e.mu.Unlock()
    }
    
    func (e *validationEvictions) snapshot() []string {
    	e.mu.Lock()
    	defer e.mu.Unlock()
    	return append([]string(nil), e.keys...)
    }
    
    type reservationOverlapResult struct {
    	unit             int64
    	capacity         int64
    	usedAtSetReturn  int64
    	reservedAtSetRet int64
    	usedAfterD       int64
    	reservedAfterD   int64
    	residentAfterD   map[string]bool
    	evictedKeys      []string
    	finalUsed        int64
    	finalReserved    int64
    }
    
    func validationReservedBytes(cache *MemCache) int64 {
    	cache.capacityMu.Lock()
    	defer cache.capacityMu.Unlock()
    	return cache.reservedBytes
    }
    
    func validationKey(offset int64, request int) fscache.CacheKey {
    	return validationKeyAtPath("fifo-validation/double-charge", offset, request)
    }
    
    func validationKeyAtPath(path string, offset int64, request int) fscache.CacheKey {
    	return fscache.CacheKey{
    		Path:   path,
    		Offset: offset,
    		Sz:     int64(request),
    	}
    }
    
    func validationVector(cache *MemCache, ctx context.Context, key fscache.CacheKey, request int, marker byte) *IOVector {
    	return validationVectorAtPath(cache, ctx, key, request, marker, "shared:/fifo-validation/double-charge")
    }
    
    func validationVectorAtPath(cache *MemCache, ctx context.Context, key fscache.CacheKey, request int, marker byte, filePath string) *IOVector {
    	data := cache.AllocateCacheDataWithHint(ctx, request, malloc.NoClear).(*Bytes)
    	data.Bytes()[0] = marker
    	return &IOVector{
    		FilePath: filePath,
    		Entries: []IOEntry{{
    			Offset:     key.Offset,
    			Size:       key.Sz,
    			CachedData: data,
    		}},
    	}
    }
    
    func validationResident(cache *MemCache, ctx context.Context, key fscache.CacheKey, marker byte) bool {
    	data, ok := cache.cache.Get(ctx, key)
    	if !ok {
    		return false
    	}
    	defer data.Release()
    	bytes := data.Bytes()
    	return len(bytes) > 0 && bytes[0] == marker
    }
    
    func waitValidationSignal(t *testing.T, ctx context.Context, ch <-chan struct{}, name string) {
    	t.Helper()
    	select {
    	case <-ch:
    	case <-ctx.Done():
    		t.Fatalf("timed out waiting for %s: %v", name, ctx.Err())
    	}
    }
    
    func runReservationOverlapScenario(t *testing.T, blocked bool) reservationOverlapResult {
    	t.Helper()
    
    	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
    	defer cancel()
    	const request = 1 << 20
    	unit := int64(DefaultCacheDataAllocator().BackingSize(request))
    	if unit <= 64<<10 {
    		t.Fatalf("validation request did not bypass idle pool: request=%d unit=%d", request, unit)
    	}
    	capacity := 4 * unit
    	evictions := new(validationEvictions)
    	cache := NewMemCache(
    		fscache.ConstCapacity(capacity),
    		&CacheCallbacks{PostEvict: []CacheCallbackFunc{
    			func(key fscache.CacheKey, _ fscache.Data) { evictions.record(key) },
    		}},
    		nil,
    		"",
    	)
    	defer cache.Close(context.Background())
    	if got := int64(cache.BackingSize(request)); got != unit {
    		t.Fatalf("cache allocator backing size differs from probe: probe=%d cache=%d", unit, got)
    	}
    
    	keys := []fscache.CacheKey{
    		validationKey(1, request),
    		validationKey(2, request),
    		validationKey(3, request),
    		validationKey(4, request),
    	}
    	markers := []byte{'A', 'B', 'C', 'D'}
    	for i := 0; i < 2; i++ {
    		vector := validationVector(cache, ctx, keys[i], request, markers[i])
    		if err := cache.Update(ctx, vector, false); err != nil {
    			vector.Release()
    			t.Fatalf("prefill %s: %v", markers[i:i+1], err)
    		}
    		vector.Release()
    	}
    	if got := cache.cache.Used(); got != 2*unit {
    		t.Fatalf("prefill used=%d want=%d", got, 2*unit)
    	}
    	if got := validationReservedBytes(cache); got != 0 {
    		t.Fatalf("prefill reserved=%d want=0", got)
    	}
    
    	cVector := validationVector(cache, ctx, keys[2], request, markers[2])
    	cReleased := false
    	defer func() {
    		if !cReleased {
    			cVector.Release()
    		}
    	}()
    	var gate *setReturnGate
    	var updateDone chan error
    	updateFinished := false
    	var finishGatedUpdate func()
    	if blocked {
    		gate = &setReturnGate{
    			DataCache: cache.cache,
    			entered:   make(chan struct{}),
    			release:   make(chan struct{}),
    			key:       keys[2],
    		}
    		cache.cache = gate
    		updateDone = make(chan error, 1)
    		go func() { updateDone <- cache.Update(ctx, cVector, false) }()
    		finishGatedUpdate = func() {
    			if updateFinished {
    				return
    			}
    			gate.unblock()
    			select {
    			case err := <-updateDone:
    				updateFinished = true
    				if err != nil {
    					t.Errorf("gated C update: %v", err)
    				}
    			case <-time.After(20 * time.Second):
    				t.Errorf("gated C update did not terminate")
    			}
    		}
    		defer finishGatedUpdate()
    		waitValidationSignal(t, ctx, gate.entered, "production FIFO Set return boundary")
    	} else if err := cache.Update(ctx, cVector, false); err != nil {
    		t.Fatalf("control C update: %v", err)
    	}
    
    	result := reservationOverlapResult{
    		unit:             unit,
    		capacity:         capacity,
    		usedAtSetReturn:  cache.cache.Used(),
    		reservedAtSetRet: validationReservedBytes(cache),
    		residentAfterD:   make(map[string]bool),
    	}
    	if blocked {
    		if result.usedAtSetReturn != 3*unit || result.reservedAtSetRet != unit {
    			t.Errorf("unexpected gated handoff accounting: used=%d reserved=%d want used=%d reserved=%d", result.usedAtSetReturn, result.reservedAtSetRet, 3*unit, unit)
    		}
    	}
    
    	dVector := validationVector(cache, ctx, keys[3], request, markers[3])
    	dReleased := false
    	defer func() {
    		if !dReleased {
    			dVector.Release()
    		}
    	}()
    	if err := cache.Update(ctx, dVector, false); err != nil {
    		t.Fatalf("D update: %v", err)
    	}
    	result.usedAfterD = cache.cache.Used()
    	result.reservedAfterD = validationReservedBytes(cache)
    	for i, key := range keys {
    		result.residentAfterD[string(markers[i])] = validationResident(cache, ctx, key, markers[i])
    	}
    	result.evictedKeys = evictions.snapshot()
    
    	if blocked {
    		finishGatedUpdate()
    	}
    
    	// C and D vectors own the foreground references. Drop them before Flush so
    	// the final allocator and reservation assertions cover both cache and caller
    	// ownership paths.
    	dVector.Release()
    	dReleased = true
    	cVector.Release()
    	cReleased = true
    	cache.Flush(ctx)
    	result.finalUsed = cache.cache.Used()
    	result.finalReserved = validationReservedBytes(cache)
    	t.Logf("scenario blocked=%t unit=%d capacity=%d set_return_used=%d set_return_reserved=%d after_D_used=%d after_D_reserved=%d resident=%v postEvict=%v final_used=%d final_reserved=%d", blocked, result.unit, result.capacity, result.usedAtSetReturn, result.reservedAtSetRet, result.usedAfterD, result.reservedAfterD, result.residentAfterD, result.evictedKeys, result.finalUsed, result.finalReserved)
    	return result
    }
    
    func TestMemCacheReservationOverlapDoesNotEvictFitEntries(t *testing.T) {
    	result := runReservationOverlapScenario(t, true)
    	if len(result.evictedKeys) != 0 || result.usedAfterD != result.capacity {
    		t.Errorf("DOUBLE_CHARGE_WINDOW: D did not fit without eviction: evicted=%v used_after_D=%d reserved_after_D=%d capacity=%d resident=%v", result.evictedKeys, result.usedAfterD, result.reservedAfterD, result.capacity, result.residentAfterD)
    	}
    }
    
    func TestMemCacheReservationOverlapNoBlockControl(t *testing.T) {
    	result := runReservationOverlapScenario(t, false)
    	if len(result.evictedKeys) != 0 {
    		t.Errorf("normal control evicted entries: %v", result.evictedKeys)
    	}
    	if result.usedAfterD != result.capacity || result.reservedAfterD != 0 {
    		t.Errorf("normal control accounting: used_after_D=%d reserved_after_D=%d capacity=%d", result.usedAfterD, result.reservedAfterD, result.capacity)
    	}
    	for _, marker := range []byte{'A', 'B', 'C', 'D'} {
    		if !result.residentAfterD[string(marker)] {
    			t.Errorf("normal control lost resident %c: %v", marker, result.residentAfterD)
    		}
    	}
    	if result.finalUsed != 0 || result.finalReserved != 0 {
    		t.Errorf("normal control did not release all backing: used=%d reserved=%d", result.finalUsed, result.finalReserved)
    	}
    }
    
    type deletedMainResult struct {
    	unit              int64
    	capacity          int64
    	usedAfterSync     int64
    	residentAfterSync map[string]bool
    	evictedAfterSync  []string
    	usedAfterFlush    int64
    	finalUsed         int64
    	finalReserved     int64
    }
    
    func warmValidationMain(t *testing.T, cache *MemCache, ctx context.Context, key fscache.CacheKey) {
    	t.Helper()
    	for range 2 {
    		data, ok := cache.cache.Get(ctx, key)
    		if !ok {
    			t.Fatalf("warm Get missed key=%v", key)
    		}
    		data.Release()
    	}
    }
    
    func runDeletedMainScenario(t *testing.T, deleteHead bool) deletedMainResult {
    	t.Helper()
    	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
    	defer cancel()
    	const request = 1 << 20
    	unit := int64(DefaultCacheDataAllocator().BackingSize(request))
    	if unit <= 64<<10 {
    		t.Fatalf("deleted-main request did not bypass idle pool: request=%d unit=%d", request, unit)
    	}
    	paths := []string{
    		"fifo-validation/deleted-main/A",
    		"fifo-validation/deleted-main/B",
    		"fifo-validation/deleted-main/C",
    	}
    	capacity := 3 * unit
    	evictions := new(validationEvictions)
    	cache := NewMemCache(
    		fscache.ConstCapacity(capacity),
    		&CacheCallbacks{PostEvict: []CacheCallbackFunc{
    			func(key fscache.CacheKey, _ fscache.Data) { evictions.record(key) },
    		}},
    		nil,
    		"",
    	)
    	defer cache.Close(context.Background())
    	if got := int64(cache.BackingSize(request)); got != unit {
    		t.Fatalf("deleted-main allocator backing size differs from probe: probe=%d cache=%d", unit, got)
    	}
    
    	keys := []fscache.CacheKey{
    		validationKeyAtPath(paths[0], 1, request),
    		validationKeyAtPath(paths[1], 2, request),
    		validationKeyAtPath(paths[2], 3, request),
    	}
    	markers := []byte{'A', 'B', 'C'}
    	for i, key := range keys {
    		vector := validationVectorAtPath(cache, ctx, key, request, markers[i], "shared:/"+paths[i])
    		if err := cache.Update(ctx, vector, false); err != nil {
    			vector.Release()
    			t.Fatalf("deleted-main Set %c: %v", markers[i], err)
    		}
    		vector.Release()
    	}
    	for _, key := range keys {
    		warmValidationMain(t, cache, ctx, key)
    	}
    
    	if deleteHead {
    		cache.DeletePaths(ctx, []string{paths[0]})
    		// DeletePaths releases A's value but intentionally leaves its queue item.
    		// Start the eviction oracle after that production callback, so the trace
    		// separates deletion from the stale-main cleanup under test.
    		evictions = new(validationEvictions)
    	}
    
    	result := deletedMainResult{
    		unit:              unit,
    		capacity:          capacity,
    		residentAfterSync: make(map[string]bool),
    	}
    	result.usedAfterSync = cache.EvictToTarget(ctx, 0)
    	for i, key := range keys {
    		result.residentAfterSync[string(markers[i])] = validationResident(cache, ctx, key, markers[i])
    	}
    	result.evictedAfterSync = evictions.snapshot()
    
    	// Flush is cleanup evidence only. The first synchronous target result above
    	// is the oracle; retrying here prevents a negative test from contaminating
    	// Close with live data left by the intentionally failing trace.
    	cache.Flush(ctx)
    	result.usedAfterFlush = cache.cache.Used()
    	if result.usedAfterFlush != 0 {
    		cache.Flush(ctx)
    	}
    	result.finalUsed = cache.cache.Used()
    	result.finalReserved = validationReservedBytes(cache)
    	t.Logf("deleted-main deleteHead=%t unit=%d capacity=%d used_after_sync=%d resident_after_sync=%v postEvict_after_sync=%v used_after_first_flush=%d final_used=%d final_reserved=%d", deleteHead, result.unit, result.capacity, result.usedAfterSync, result.residentAfterSync, result.evictedAfterSync, result.usedAfterFlush, result.finalUsed, result.finalReserved)
    	return result
    }
    
    func TestMemCacheDeletedMainHeadDoesNotShortCircuitSynchronousEvict(t *testing.T) {
    	result := runDeletedMainScenario(t, true)
    	if result.usedAfterSync != 0 || result.residentAfterSync["B"] || result.residentAfterSync["C"] {
    		t.Errorf("DELETED_MAIN_SHORT_CIRCUIT: synchronous eviction left live main entries: used=%d resident=%v postEvict=%v", result.usedAfterSync, result.residentAfterSync, result.evictedAfterSync)
    	}
    	if result.finalUsed != 0 || result.finalReserved != 0 {
    		t.Errorf("deleted-main cleanup did not converge: final_used=%d final_reserved=%d", result.finalUsed, result.finalReserved)
    	}
    }
    
    func TestMemCacheDeletedMainNormalEvictControl(t *testing.T) {
    	result := runDeletedMainScenario(t, false)
    	if result.usedAfterSync != 0 {
    		t.Errorf("normal deleted-main control left used=%d resident=%v", result.usedAfterSync, result.residentAfterSync)
    	}
    	if result.finalUsed != 0 || result.finalReserved != 0 {
    		t.Errorf("normal deleted-main control did not release all backing: used=%d reserved=%d", result.finalUsed, result.finalReserved)
    	}
    }

    pkg/fileservice/fifocache/fifo_normal_working_set_test.go

    This passing control uses capacity=100, a 60-entry new working set and repeated access. It does not incorrectly require one-pass LRU behavior or use a degenerate zero-sized probation target.

    package fifocache
    
    import (
    	"context"
    	"testing"
    
    	"github.com/matrixorigin/matrixone/pkg/fileservice/fscache"
    )
    
    // This is a bounded FIFO-policy control, not an LRU oracle: old hot entries
    // may survive some insertions, but a working set smaller than capacity must
    // eventually fit and old residents must be reclaimable.
    func TestFIFOValidationNormalWorkingSetFitsAfterOldHotPrefill(t *testing.T) {
    	ctx := context.Background()
    	const capacity = 100
    	const newWorkingSet = 60
    	const rounds = 20
    
    	cache := New[int, int](fscache.ConstCapacity(int64(capacity)), ShardInt[int], nil, nil, nil)
    	for key := 0; key < capacity; key++ {
    		inserted, rejected := cache.Set(ctx, key, key, 1)
    		if !inserted || rejected {
    			t.Fatalf("old prefill key=%d inserted=%t rejected=%t", key, inserted, rejected)
    		}
    	}
    
    	for key := 0; key < capacity; key++ {
    		for range 2 {
    			if _, ok := cache.Get(ctx, key); !ok {
    				t.Fatalf("hot prefill Get missed key=%d", key)
    			}
    		}
    	}
    
    	oldResident := func() int {
    		count := 0
    		for key := 0; key < int(capacity); key++ {
    			if cache.Contains(key) {
    				count++
    			}
    		}
    		return count
    	}
    
    	lastHits := 0
    	for round := 1; round <= rounds; round++ {
    		hits := 0
    		for i := 0; i < newWorkingSet; i++ {
    			key := capacity + i
    			if _, ok := cache.Get(ctx, key); ok {
    				hits++
    				continue
    			}
    			inserted, rejected := cache.Set(ctx, key, key, 1)
    			if !inserted || rejected {
    				t.Fatalf("round=%d new working-set key=%d inserted=%t rejected=%t", round, key, inserted, rejected)
    			}
    		}
    		if used := cache.Used(); used > capacity {
    			t.Fatalf("capacity exceeded after round=%d: used=%d capacity=%d", round, used, capacity)
    		}
    		lastHits = hits
    		t.Logf("round=%d hits=%d/%d old_resident=%d used=%d", round, hits, newWorkingSet, oldResident(), cache.Used())
    	}
    
    	for i := 0; i < newWorkingSet; i++ {
    		if !cache.Contains(capacity + i) {
    			t.Errorf("new working-set entry was not resident: key=%d", capacity+i)
    		}
    	}
    	if lastHits != newWorkingSet {
    		t.Fatalf("repeated working-set trace did not converge: last_hits=%d/%d", lastHits, newWorkingSet)
    	}
    	if old := oldResident(); old > capacity-newWorkingSet {
    		t.Fatalf("old hot entries exceed space left after working set converged: old_resident=%d limit=%d", old, capacity-newWorkingSet)
    	}
    	t.Logf("capacity=%d old_hot_prefill=%d new_working_set=%d rounds=%d final_hits=%d/%d old_resident_after=%d used=%d", capacity, capacity, newWorkingSet, rounds, lastHits, newWorkingSet, oldResident(), cache.Used())
    }

    Commands and expected results are in the issue body. The normal policy control is selected with -run '^TestFIFOValidationNormalWorkingSetFitsAfterOldHotPrefill$' ./pkg/fileservice/fifocache.

  2. self-assigned this
    on Sep 18, 2026
  3. added
    severity/s0
    and removed on Sep 18, 2026
  4. LeftHandCold commented on Sep 18, 2026

    @LeftHandCold
    CollaboratorAuthor

    Fix submitted to main: #29092, commit ce6176bb93f35b9248a5d4a3d8e890af471a9b07.

    Reproduction and fix verification

    The two implementation defects are confirmed independently of the Daily performance attribution. On server 50, the final patch passes the original production-path cache reproductions and controls:

    Scenario Unfixed baseline Final patch
    Four distinct 1 MiB buffers in a 4 MiB cache, pausing C after delegated DataCache.Set returns C is charged to both FIFO and reservation; allocating D evicts A and leaves only 3 MiB resident Reservation is already committed at the boundary; all A/B/C/D remain resident, 4 MiB used, no eviction
    Same allocations without the pause All four fit All four fit
    Warm A/B/C, DeletePaths(A), then synchronous target-zero eviction Stops with B/C still resident and 2 MiB reported used Reaches zero in that call; B/C are reclaimed
    Eviction control without deleting A Reaches zero Reaches zero

    All final scenarios finish with both usage and reservation equal to zero. The harness uses the actual MemCache/native backing and Set/Get/DeletePaths/eviction paths, not fabricated production counters. Adapting the original harness required the private counter's new .Load() accessor and changing the old diagnostic expectation for C's reservation from 1 MiB to zero; the residency, no-unnecessary-eviction, target, and cleanup oracles are unchanged.

    The fix makes reservation handoff atomic with capacity admission and recognizes progress in both FIFO queues. It does not change the FIFO replacement policy, cache sizes, SQL semantics, or S3/DiskCache read policy. External callbacks remain outside the accounting guard. Values without the reservation protocol do not acquire that guard; a dedicated UT protects this fast path.

    Validation on the final sources:

    • Full FileService and FIFO package tests, normal and race modes: pass.
    • Focused FIFO, MemCache/original-repro, and six ObjectIO consumer cases with -race -count=100: pass.
    • ObjectIO tests exercise real validated-vector wrappers and memory/remote cache admission.
    • Relevant go vet, formatting, and diff checks: pass.
    • SHA-256 matches all 11 changed files between the submitted worktree and the 50 validation checkout.

    Same-host/same-command five-run microbenchmark medians (baseline -> final patch): Update 3150 -> 3191 ns/op; Read 248.2 -> 240.6; sequential Set 874.8 -> 878.4; parallel Set 244.3 -> 247.6. Allocs/op are unchanged. An earlier local prototype unnecessarily serialized non-reservation Set and regressed that microbenchmark by about 2.2x; it was rejected and is not the submitted patch. These measurements are not a blanket zero-overhead guarantee.

    Introduction history

    These are not defects present since the original FIFO introduction (#14019, January 2024):

    This attribution is based on the introducing commits and their parent code, not just PR titles. It is not a complete old-version deployment bisect.

    Live telemetry: evidence boundary

    Read-only Grafana/Loki checks of ONLY/PRE round 2 showed:

    Metric Full Daily 35243665787 Isolated 35204196542
    AP MemCache hit ratio 79.5% 98.1%
    AP DiskCache hit ratio 99.94% 99.85%
    Per-AP cache capacity 16 GiB 16 GiB
    RSS-pressure trigger / memory pressure eviction / admission-skip counter increments 0 0

    Loki also confirms the same approximately 25 MB physical key being read from disk and set into memory repeatedly on one AP, at 04:12:01, 04:12:17, and 04:12:31 CST. However, telemetry does not export the reservation handoff, per-key FIFO eviction reasons, or deleted queue records. The above ratios aggregate AP traffic in the selected windows, not an exclusive per-query counter; the isolated round also has only four 30-second samples.

    Therefore: poor reuse is observed, and the two code defects are reproduced and fixed, but their contribution to the complete Daily slowdown is not yet proven. Zero RSS-pressure counters do not mean zero ordinary capacity eviction. No full SQL/IVF production-image A/B was performed, and this PR must not be presented as a guarantee of restoring a particular IVF QPS.

  5. added a commit that references this issue on Sep 18, 2026
    d972519
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

kind/bugseverity/s0

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions