mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-05 16:02:12 +00:00
perf: harden billing ledger recovery and bound quota refresh memory
This commit is contained in:
1 parent
87f58a231e
commit
a4d2111692
11 files changed
+164
-31
No files matched your search
@@ -15,6 +15,7 @@ Thumbs.db
|
||||
/config.local.yaml
|
||||
/config.*.local.yaml
|
||||
/docs/*
|
||||
/docs/rules/*
|
||||
/backend/docs/goal/
|
||||
*.har
|
||||
*.pcap
|
||||
|
||||
@@ -292,6 +292,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat
|
||||
auditService.UpdateWriterConfig(cfg.Audit.BatchSize, cfg.Audit.FlushInterval.Value(), cfg.Audit.CommitDelay.Value())
|
||||
auditService.UpdateLedgerConfig(auditLedgerConfig(cfg.Audit))
|
||||
auditService.SetCommitObserver(clientKeyService.CompleteBillingBatch)
|
||||
auditService.SetDropObserver(clientKeyService.ReleaseBillingProtectionBatch)
|
||||
dashboardService := dashboardapp.NewService(dashboardRepo)
|
||||
selector := gateway.NewSelector(accountRepo, concurrency, sticky, providers, cfg.Routing.StickyTTL.Value(), cfg.Routing.CooldownBase.Value(), cfg.Routing.CooldownMax.Value(), cfg.Routing.CapacityWait.Value())
|
||||
selector.UpdatePreferFreeBuild(cfg.Routing.PreferFreeBuild)
|
||||
|
||||
@@ -148,9 +148,9 @@ func readinessSnapshot(
|
||||
if ledgerState.Ready {
|
||||
snapshot.Components["billing_ledger"] = httpserver.ReadinessComponent{State: "ready"}
|
||||
} else {
|
||||
detail := fmt.Sprintf("审计账本不可用;连续失败 %d 次,队列 %d/%d", ledgerState.ConsecutiveFailures, ledgerState.QueueDepth, ledgerState.QueueCapacity)
|
||||
detail := fmt.Sprintf("审计账本不可用;连续失败 %d 次,丢失 %d 条,队列 %d/%d", ledgerState.ConsecutiveFailures, ledgerState.Dropped, ledgerState.QueueDepth, ledgerState.QueueCapacity)
|
||||
snapshot.Components["billing_ledger"] = httpserver.ReadinessComponent{State: "degraded", Detail: detail}
|
||||
if ledgerState.Mode == auditapp.LedgerModeEnforce {
|
||||
if ledgerState.Irrecoverable || ledgerState.Mode == auditapp.LedgerModeEnforce {
|
||||
snapshot.State = "not_ready"
|
||||
return snapshot
|
||||
}
|
||||
|
||||
@@ -46,6 +46,7 @@ type LedgerConfig struct {
|
||||
type LedgerSnapshot struct {
|
||||
Mode LedgerMode
|
||||
Ready bool
|
||||
Irrecoverable bool
|
||||
QueueDepth int
|
||||
QueueCapacity int
|
||||
ConsecutiveFailures int
|
||||
@@ -68,6 +69,8 @@ const (
|
||||
auditEnqueueWait = 25 * time.Millisecond
|
||||
auditWriteTimeout = 2 * time.Second
|
||||
auditWriteAttempts = 3
|
||||
auditWriteRetryBase = 250 * time.Millisecond
|
||||
auditWriteRetryMax = 5 * time.Second
|
||||
auditDefaultCommitDelay = 5 * time.Millisecond
|
||||
auditSummaryTTL = 10 * time.Second
|
||||
)
|
||||
@@ -109,6 +112,7 @@ type Service struct {
|
||||
ledgerLastWarning time.Time
|
||||
observerMu sync.RWMutex
|
||||
commitObserver func([]string)
|
||||
dropObserver func([]string)
|
||||
}
|
||||
|
||||
func NewService(audits repository.AuditRepository, logger *slog.Logger, bufferSize, batchSize int, flushInterval time.Duration) *Service {
|
||||
@@ -127,8 +131,8 @@ func NewService(audits repository.AuditRepository, logger *slog.Logger, bufferSi
|
||||
|
||||
func defaultLedgerConfig() LedgerConfig {
|
||||
return LedgerConfig{
|
||||
Mode: LedgerModeObserve,
|
||||
FailureThreshold: 3,
|
||||
Mode: LedgerModeEnforce,
|
||||
FailureThreshold: 1,
|
||||
UnhealthyGrace: 10 * time.Second,
|
||||
QueueHighWatermarkPercent: 90,
|
||||
}
|
||||
@@ -161,6 +165,14 @@ func (s *Service) SetCommitObserver(observer func([]string)) {
|
||||
s.observerMu.Unlock()
|
||||
}
|
||||
|
||||
// SetDropObserver registers a callback for records that can no longer enter
|
||||
// the writer. It must not release the durable billing reservation itself.
|
||||
func (s *Service) SetDropObserver(observer func([]string)) {
|
||||
s.observerMu.Lock()
|
||||
s.dropObserver = observer
|
||||
s.observerMu.Unlock()
|
||||
}
|
||||
|
||||
// LedgerSnapshot returns a bounded, identity-free view of the durable ledger state.
|
||||
func (s *Service) LedgerSnapshot() LedgerSnapshot {
|
||||
now := s.now().UTC()
|
||||
@@ -169,14 +181,16 @@ func (s *Service) LedgerSnapshot() LedgerSnapshot {
|
||||
|
||||
s.ledgerMu.Lock()
|
||||
s.updateQueuePressureLocked(now, queueDepth, queueCapacity)
|
||||
ready := s.ledgerReadyLocked(now)
|
||||
dropped := s.dropped.Load()
|
||||
ready := dropped == 0 && s.ledgerReadyLocked(now)
|
||||
snapshot := LedgerSnapshot{
|
||||
Mode: s.ledgerConfig.Mode,
|
||||
Ready: ready,
|
||||
Irrecoverable: dropped > 0,
|
||||
QueueDepth: queueDepth,
|
||||
QueueCapacity: queueCapacity,
|
||||
ConsecutiveFailures: s.ledgerFailures,
|
||||
Dropped: s.dropped.Load(),
|
||||
Dropped: dropped,
|
||||
LastSuccessAt: s.ledgerLastSuccess,
|
||||
LastFailureAt: s.ledgerLastFailure,
|
||||
UnhealthySince: s.ledgerUnhealthySince,
|
||||
@@ -188,10 +202,14 @@ func (s *Service) LedgerSnapshot() LedgerSnapshot {
|
||||
return snapshot
|
||||
}
|
||||
|
||||
// CheckLedgerReady fails only in enforce mode; observe mode still records and reports degradation.
|
||||
// CheckLedgerReady always blocks after confirmed data loss. Observe mode only
|
||||
// permits traffic while a recoverable writer or queue degradation is active.
|
||||
func (s *Service) CheckLedgerReady() error {
|
||||
snapshot := s.LedgerSnapshot()
|
||||
if snapshot.Ready || snapshot.Mode != LedgerModeEnforce {
|
||||
if snapshot.Ready && !snapshot.Irrecoverable {
|
||||
return nil
|
||||
}
|
||||
if !snapshot.Irrecoverable && snapshot.Mode != LedgerModeEnforce {
|
||||
return nil
|
||||
}
|
||||
return ErrLedgerUnavailable
|
||||
@@ -352,6 +370,7 @@ func (s *Service) recordEnqueueDrop(request auditWriteRequest, reason string) {
|
||||
if dropped == 1 || dropped%1000 == 0 {
|
||||
s.logger.Warn("audit_queue_full", "reason", reason, "dropped", dropped)
|
||||
}
|
||||
s.notifyDropped(request.record.EventID)
|
||||
}
|
||||
|
||||
// Close 停止接收新审计并尽力排空队列。
|
||||
@@ -736,6 +755,8 @@ func (s *Service) run() {
|
||||
func (s *Service) persistBatch(requests []auditWriteRequest) {
|
||||
startedAt := time.Now()
|
||||
pending := append([]auditWriteRequest(nil), requests...)
|
||||
retryDelay := auditWriteRetryBase
|
||||
retryRound := 0
|
||||
for len(pending) > 0 {
|
||||
lastErr := s.persistAuditRequests(pending)
|
||||
var invalid *repository.InvalidBatchRecordError
|
||||
@@ -756,20 +777,19 @@ func (s *Service) persistBatch(requests []auditWriteRequest) {
|
||||
completeAuditWrites(pending, nil)
|
||||
return
|
||||
}
|
||||
completeAuditWrites(pending, lastErr)
|
||||
s.recordLedgerFailure()
|
||||
dropped := s.dropped.Add(uint64(len(pending)))
|
||||
s.recordLedgerDrop()
|
||||
perfmetrics.Default.Add("audit_records_total", perfmetrics.Labels{Subsystem: "audit", Stage: "batch", Outcome: "dropped"}, int64(len(pending)))
|
||||
perfmetrics.Default.Add("audit_batch_size", perfmetrics.Labels{Subsystem: "audit", Stage: "batch", Outcome: "failed"}, int64(len(pending)))
|
||||
perfmetrics.Default.ObserveDuration("audit_batch_commit_duration_us", perfmetrics.Labels{Subsystem: "audit", Stage: "batch", Outcome: "failed"}, time.Since(startedAt))
|
||||
perfmetrics.Default.Add("audit_batch_size", perfmetrics.Labels{Subsystem: "audit", Stage: "batch", Outcome: "retry"}, int64(len(pending)))
|
||||
retryRound++
|
||||
var panicErr *batch.PanicError
|
||||
if errors.As(lastErr, &panicErr) {
|
||||
s.logger.Error("audit_batch_write_failed", "count", len(pending), "attempts", auditWriteAttempts, "dropped", dropped, "error", panicErr, "stack", string(panicErr.Stack))
|
||||
s.logger.Error("audit_batch_write_retrying", "count", len(pending), "attempts", auditWriteAttempts, "retry_in", retryDelay, "error", panicErr, "stack", string(panicErr.Stack))
|
||||
} else if retryRound == 1 {
|
||||
s.logger.Warn("audit_batch_write_retrying", "count", len(pending), "attempts", auditWriteAttempts, "retry_in", retryDelay, "error", lastErr)
|
||||
} else {
|
||||
s.logger.Error("audit_batch_write_failed", "count", len(pending), "attempts", auditWriteAttempts, "dropped", dropped, "error", lastErr)
|
||||
s.logger.Debug("audit_batch_write_retrying", "count", len(pending), "attempts", auditWriteAttempts, "retry_in", retryDelay, "error", lastErr)
|
||||
}
|
||||
return
|
||||
timer := time.NewTimer(retryDelay)
|
||||
<-timer.C
|
||||
retryDelay = min(retryDelay*2, auditWriteRetryMax)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -786,6 +806,7 @@ func (s *Service) persistAuditRequests(requests []auditWriteRequest) error {
|
||||
if errors.Is(lastErr, repository.ErrInvalidRecord) {
|
||||
return lastErr
|
||||
}
|
||||
s.recordLedgerFailure()
|
||||
if attempt < auditWriteAttempts {
|
||||
timer := time.NewTimer(time.Duration(attempt) * 100 * time.Millisecond)
|
||||
select {
|
||||
@@ -811,6 +832,7 @@ func (s *Service) recordRejectedAudit(request auditWriteRequest, err error) {
|
||||
s.recordLedgerDrop()
|
||||
perfmetrics.Default.Inc("audit_records_total", perfmetrics.Labels{Subsystem: "audit", Operation: string(request.record.Operation), Stage: "batch", Outcome: "rejected"})
|
||||
s.logger.Error("audit_record_rejected", "event_id", request.record.EventID, "dropped", dropped, "error", err)
|
||||
s.notifyDropped(request.record.EventID)
|
||||
}
|
||||
|
||||
func completeAuditWrites(requests []auditWriteRequest, err error) {
|
||||
@@ -829,8 +851,10 @@ func (s *Service) recordLedgerSuccess() {
|
||||
now := s.now().UTC()
|
||||
s.ledgerMu.Lock()
|
||||
s.ledgerFailures = 0
|
||||
s.ledgerUnhealthySince = time.Time{}
|
||||
s.ledgerLastSuccess = now
|
||||
if s.dropped.Load() == 0 && s.ledgerQueueHighSince.IsZero() {
|
||||
s.ledgerUnhealthySince = time.Time{}
|
||||
}
|
||||
s.ledgerMu.Unlock()
|
||||
}
|
||||
|
||||
@@ -859,7 +883,11 @@ func (s *Service) recordLedgerDrop() {
|
||||
|
||||
func (s *Service) updateQueuePressureLocked(now time.Time, depth, capacity int) {
|
||||
if capacity <= 0 || depth*100 < capacity*s.ledgerConfig.QueueHighWatermarkPercent {
|
||||
wasHigh := !s.ledgerQueueHighSince.IsZero()
|
||||
s.ledgerQueueHighSince = time.Time{}
|
||||
if wasHigh && s.ledgerFailures == 0 && s.dropped.Load() == 0 {
|
||||
s.ledgerUnhealthySince = time.Time{}
|
||||
}
|
||||
return
|
||||
}
|
||||
if s.ledgerQueueHighSince.IsZero() {
|
||||
@@ -913,3 +941,21 @@ func (s *Service) notifyCommitted(records []auditdomain.Record) {
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) notifyDropped(eventID string) {
|
||||
if eventID == "" {
|
||||
return
|
||||
}
|
||||
s.observerMu.RLock()
|
||||
observer := s.dropObserver
|
||||
s.observerMu.RUnlock()
|
||||
if observer == nil {
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
s.logger.Error("audit_drop_observer_panicked", "error", recovered)
|
||||
}
|
||||
}()
|
||||
observer([]string{eventID})
|
||||
}
|
||||
@@ -49,7 +49,7 @@ func TestServiceCloseFlushesQueuedAudits(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestAuditBatchRetriesTransientDatabaseFailure(t *testing.T) {
|
||||
repo := &flakyAuditRepository{failures: 2}
|
||||
repo := &flakyAuditRepository{failures: 5}
|
||||
service := NewService(repo, slog.Default(), 8, 4, time.Hour)
|
||||
service.Start()
|
||||
if !service.Record(auditdomain.Record{RequestID: "retry", StatusCode: 200}) {
|
||||
@@ -60,7 +60,7 @@ func TestAuditBatchRetriesTransientDatabaseFailure(t *testing.T) {
|
||||
if err := service.Close(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if attempts := repo.attempts.Load(); attempts != 3 {
|
||||
if attempts := repo.attempts.Load(); attempts != 6 {
|
||||
t.Fatalf("attempts = %d", attempts)
|
||||
}
|
||||
}
|
||||
@@ -279,6 +279,13 @@ func TestWriterIsolatesInvalidAuditRecordFromValidBatch(t *testing.T) {
|
||||
repo := &observedBatchAuditRepository{AuditRepository: baseRepo, sizes: make(chan int, 4)}
|
||||
service := NewService(repo, slog.Default(), 8, 8, time.Second)
|
||||
service.UpdateWriterConfig(8, time.Second, 100*time.Millisecond)
|
||||
service.UpdateLedgerConfig(LedgerConfig{Mode: LedgerModeObserve, FailureThreshold: 1, UnhealthyGrace: time.Hour, QueueHighWatermarkPercent: 90})
|
||||
droppedEvents := make(chan string, 1)
|
||||
service.SetDropObserver(func(eventIDs []string) {
|
||||
if len(eventIDs) > 0 {
|
||||
droppedEvents <- eventIDs[0]
|
||||
}
|
||||
})
|
||||
service.Start()
|
||||
t.Cleanup(func() { closeAuditService(t, service) })
|
||||
|
||||
@@ -328,6 +335,20 @@ func TestWriterIsolatesInvalidAuditRecordFromValidBatch(t *testing.T) {
|
||||
if total != 1 {
|
||||
t.Fatalf("persisted audits = %d, want 1", total)
|
||||
}
|
||||
select {
|
||||
case eventID := <-droppedEvents:
|
||||
if eventID != "evt_isolated_invalid_record_02" {
|
||||
t.Fatalf("dropped event = %q", eventID)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("drop observer was not notified")
|
||||
}
|
||||
if snapshot := service.LedgerSnapshot(); snapshot.Ready || !snapshot.Irrecoverable || snapshot.Dropped != 1 {
|
||||
t.Fatalf("ledger snapshot after rejected record = %#v", snapshot)
|
||||
}
|
||||
if err := service.CheckLedgerReady(); !errors.Is(err, ErrLedgerUnavailable) {
|
||||
t.Fatalf("irrecoverable drop did not block observe mode: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallerTimeoutDoesNotCancelQueuedSettlement(t *testing.T) {
|
||||
@@ -369,14 +390,19 @@ func TestLedgerReadinessObserveAndEnforceModes(t *testing.T) {
|
||||
repo := &toggleAuditRepository{err: errors.New("database unavailable")}
|
||||
service := NewService(repo, slog.Default(), 8, 4, time.Second)
|
||||
service.Start()
|
||||
t.Cleanup(func() { closeAuditService(t, service) })
|
||||
t.Cleanup(func() {
|
||||
repo.setError(nil)
|
||||
closeAuditService(t, service)
|
||||
})
|
||||
service.now = func() time.Time { return time.Unix(0, nowNanos.Load()).UTC() }
|
||||
service.UpdateLedgerConfig(LedgerConfig{Mode: LedgerModeObserve, FailureThreshold: 1, UnhealthyGrace: time.Second, QueueHighWatermarkPercent: 90})
|
||||
if err := service.CreateDurable(context.Background(), auditdomain.Record{EventID: "observe"}); err == nil {
|
||||
t.Fatal("expected durable write failure")
|
||||
writeCtx, writeCancel := context.WithTimeout(context.Background(), 150*time.Millisecond)
|
||||
defer writeCancel()
|
||||
if err := service.CreateDurable(writeCtx, auditdomain.Record{EventID: "observe"}); !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("write error = %v", err)
|
||||
}
|
||||
nowNanos.Add(int64(2 * time.Second))
|
||||
if snapshot := service.LedgerSnapshot(); snapshot.Ready || snapshot.ConsecutiveFailures != 1 {
|
||||
if snapshot := service.LedgerSnapshot(); snapshot.Ready || snapshot.ConsecutiveFailures < 1 {
|
||||
t.Fatalf("snapshot = %#v", snapshot)
|
||||
}
|
||||
if err := service.CheckLedgerReady(); err != nil {
|
||||
@@ -388,7 +414,9 @@ func TestLedgerReadinessObserveAndEnforceModes(t *testing.T) {
|
||||
t.Fatalf("enforce readiness error = %v", err)
|
||||
}
|
||||
repo.setError(nil)
|
||||
if err := service.CreateDurable(context.Background(), auditdomain.Record{EventID: "recovered"}); err != nil {
|
||||
recoveryCtx, recoveryCancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer recoveryCancel()
|
||||
if err := service.CreateDurable(recoveryCtx, auditdomain.Record{EventID: "recovered"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if snapshot := service.LedgerSnapshot(); !snapshot.Ready || snapshot.ConsecutiveFailures != 0 {
|
||||
@@ -411,6 +439,11 @@ func TestLedgerReadinessDetectsSustainedQueuePressure(t *testing.T) {
|
||||
if err := service.CheckLedgerReady(); !errors.Is(err, ErrLedgerUnavailable) {
|
||||
t.Fatalf("queue pressure readiness error = %v", err)
|
||||
}
|
||||
<-service.queue
|
||||
service.recordLedgerSuccess()
|
||||
if snapshot := service.LedgerSnapshot(); !snapshot.Ready {
|
||||
t.Fatalf("drained queue did not restore readiness: %#v", snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommitObserverRunsOnlyAfterDurableCommit(t *testing.T) {
|
||||
|
||||
@@ -393,6 +393,12 @@ func (s *Service) CompleteBilling(eventID string) {
|
||||
}
|
||||
|
||||
func (s *Service) CompleteBillingBatch(eventIDs []string) {
|
||||
s.ReleaseBillingProtectionBatch(eventIDs)
|
||||
}
|
||||
|
||||
// ReleaseBillingProtectionBatch removes process-local activity markers. The
|
||||
// durable reservation remains authoritative until commit, cancel, or expiry.
|
||||
func (s *Service) ReleaseBillingProtectionBatch(eventIDs []string) {
|
||||
if len(eventIDs) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -655,7 +655,7 @@ func defaultConfig() Config {
|
||||
},
|
||||
Audit: AuditConfig{
|
||||
BufferSize: 16384, BatchSize: 256, FlushInterval: Duration(250 * time.Millisecond), CommitDelay: Duration(5 * time.Millisecond),
|
||||
LedgerMode: "observe", LedgerFailureThreshold: 3,
|
||||
LedgerMode: "enforce", LedgerFailureThreshold: 1,
|
||||
LedgerUnhealthyGrace: Duration(10 * time.Second), LedgerQueueHighWatermarkPct: 90,
|
||||
},
|
||||
ClientKeyDefaults: ClientKeyDefaultsConfig{RPMLimit: clientkeydomain.DefaultRPMLimit, MaxConcurrent: clientkeydomain.DefaultMaxConcurrent},
|
||||
|
||||
@@ -66,6 +66,9 @@ bootstrapAdmin:
|
||||
if cfg.Audit.CommitDelay.Value() != 5*time.Millisecond {
|
||||
t.Fatalf("audit commit delay = %s", cfg.Audit.CommitDelay.Value())
|
||||
}
|
||||
if cfg.Audit.LedgerMode != "enforce" || cfg.Audit.LedgerFailureThreshold != 1 {
|
||||
t.Fatalf("audit ledger defaults = %#v", cfg.Audit)
|
||||
}
|
||||
expectedDatabasePath := filepath.Join(dir, "data", "backend.db")
|
||||
if cfg.Database.SQLite.Path != expectedDatabasePath {
|
||||
t.Fatalf("database path = %q, want %q", cfg.Database.SQLite.Path, expectedDatabasePath)
|
||||
|
||||
@@ -12,7 +12,10 @@ import (
|
||||
"github.com/chenyme/grok2api/backend/internal/repository"
|
||||
)
|
||||
|
||||
const maxQuotaRefreshDirty = 100000
|
||||
const (
|
||||
maxQuotaRefreshDirty = 100000
|
||||
quotaRefreshExpiryCompactionMinStale = 1024
|
||||
)
|
||||
|
||||
type quotaRefreshDirtyState struct {
|
||||
accountID uint64
|
||||
@@ -74,6 +77,7 @@ func (c *QuotaRefreshCoordinator) MarkQuotaRefreshDirty(_ context.Context, accou
|
||||
c.values[key] = state
|
||||
c.dirty[key] = struct{}{}
|
||||
heap.Push(&c.expires, quotaRefreshExpiry{key: key, generation: state.generation, expiresAt: state.expiresAt})
|
||||
c.compactExpiryHeapLocked()
|
||||
return state.generation, nil
|
||||
}
|
||||
|
||||
@@ -86,6 +90,7 @@ func (c *QuotaRefreshCoordinator) QuotaRefreshGeneration(_ context.Context, acco
|
||||
if !ok || !now.Before(state.expiresAt) {
|
||||
delete(c.values, key)
|
||||
delete(c.dirty, key)
|
||||
c.compactExpiryHeapLocked()
|
||||
return 0, false, nil
|
||||
}
|
||||
return state.generation, state.dirty, nil
|
||||
@@ -100,6 +105,7 @@ func (c *QuotaRefreshCoordinator) ClearQuotaRefreshDirty(_ context.Context, acco
|
||||
if !ok || !now.Before(state.expiresAt) {
|
||||
delete(c.values, key)
|
||||
delete(c.dirty, key)
|
||||
c.compactExpiryHeapLocked()
|
||||
return false, nil
|
||||
}
|
||||
if state.generation != generation {
|
||||
@@ -139,6 +145,7 @@ func (c *QuotaRefreshCoordinator) ListQuotaRefreshDirty(_ context.Context, now t
|
||||
if len(values) > limit {
|
||||
values = values[:limit]
|
||||
}
|
||||
c.compactExpiryHeapLocked()
|
||||
return values, nil
|
||||
}
|
||||
|
||||
@@ -154,6 +161,20 @@ func (c *QuotaRefreshCoordinator) pruneLocked(now time.Time) {
|
||||
}
|
||||
}
|
||||
|
||||
// compactExpiryHeapLocked bounds stale generation entries without adding a
|
||||
// second index. Rebuilding is amortized and retains exactly one expiry per key.
|
||||
func (c *QuotaRefreshCoordinator) compactExpiryHeapLocked() {
|
||||
if len(c.expires) <= len(c.values)*2+quotaRefreshExpiryCompactionMinStale {
|
||||
return
|
||||
}
|
||||
values := make(quotaRefreshExpiryHeap, 0, len(c.values))
|
||||
for key, state := range c.values {
|
||||
values = append(values, quotaRefreshExpiry{key: key, generation: state.generation, expiresAt: state.expiresAt})
|
||||
}
|
||||
heap.Init(&values)
|
||||
c.expires = values
|
||||
}
|
||||
|
||||
func quotaRefreshKey(accountID uint64, mode string) string {
|
||||
return fmt.Sprintf("%d:%s", accountID, mode)
|
||||
}
|
||||
@@ -77,3 +77,25 @@ func TestQuotaRefreshCoordinatorListExcludesClearedAndExpiredState(t *testing.T)
|
||||
t.Fatalf("listed cleared or expired states: %+v", states)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuotaRefreshCoordinatorCompactsStaleExpiryGenerations(t *testing.T) {
|
||||
coordinator := NewQuotaRefreshCoordinator()
|
||||
ctx := context.Background()
|
||||
const updates = 10000
|
||||
|
||||
for range updates {
|
||||
if _, err := coordinator.MarkQuotaRefreshDirty(ctx, 42, "fast", 24*time.Hour); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
if len(coordinator.values) != 1 || len(coordinator.dirty) != 1 {
|
||||
t.Fatalf("coordinator state = values:%d dirty:%d", len(coordinator.values), len(coordinator.dirty))
|
||||
}
|
||||
if got, maxExpected := len(coordinator.expires), quotaRefreshExpiryCompactionMinStale+2; got > maxExpected {
|
||||
t.Fatalf("expiry heap retained %d stale generations, want at most %d", got, maxExpected)
|
||||
}
|
||||
if generation, dirty, err := coordinator.QuotaRefreshGeneration(ctx, 42, "fast"); err != nil || !dirty || generation != updates {
|
||||
t.Fatalf("generation = %d, dirty = %v, err = %v", generation, dirty, err)
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -100,8 +100,8 @@ audit:
|
||||
flushInterval: 250ms
|
||||
# [通常不要修改] 需要调用方确认提交的审计最多聚合等待该时长;建议保持 1ms–50ms。
|
||||
commitDelay: 5ms
|
||||
# [按需修改] observe 仅报告账本异常;enforce 在异常持续超过宽限期后拒绝新的推理任务。
|
||||
ledgerMode: observe # observe | enforce
|
||||
ledgerFailureThreshold: 3
|
||||
# [通常不要修改] enforce 会在异常持续超过宽限期后暂停新的推理请求;确认发生数据丢失时会立即暂停。
|
||||
ledgerMode: enforce # observe | enforce
|
||||
ledgerFailureThreshold: 1
|
||||
ledgerUnhealthyGrace: 10s
|
||||
ledgerQueueHighWatermarkPercent: 90
|
||||
Reference in new issue
Block a user