package statestore import ( "context" "errors" "slices" "time" "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/infrastructure/controlplanestore" "github.com/samcharles93/archie-core/internal/infrastructure/postgres" ) // auditRetentionSweepInterval is how often the stored retention is applied. const auditRetentionSweepInterval = time.Hour // auditEventPruner is the store's bounded, lock-guarded event delete. type auditEventPruner interface { PruneAuditEvents(ctx context.Context, kinds []string, cutoff time.Time) (int64, error) } // auditRetentionResources reads the instance's retention document. type auditRetentionResources interface { Resource(ctx context.Context, orgID, kind string) (storecontract.Resource, error) } // observabilityEventKinds is the hard-coded allowlist of high-volume event // kinds the sweep may delete. It is code, not a setting: no stored value can // widen it, and adding a kind here is the only way to make it prunable. Kinds // a product view reads are deliberately absent. func observabilityEventKinds() []string { return []string{ events.KindStageStart, events.KindAgentFinish, events.KindToolCall, events.KindLog, events.KindTurnCompleted, events.KindConfigCaptured, events.KindCuratorRun, events.KindCuratorAction, events.KindCuratorError, events.KindJobRun, events.KindJobError, } } // protectedEventKinds are the kinds the sweep must never delete: security // relevant records (approvals and rejections, retries, cancellation and // abandonment, pull-request actions, delivery records, binding and mapping // changes, alerts, update reports) and the two observability kinds a product // read depends on. stage_finish is the only source for StageStats' slowest // stages and most failures; changes_captured is what api_tasks_changes rebuilds // a task's captured-changes view from. Neither has a fallback, so pruning them // would silently change what the product shows. Keeping the list here, rather // than in a comment, is what lets the prunable predicate refuse a kind that // appears in both lists. func protectedEventKinds() []string { return []string{ events.KindStageFinish, events.KindChangesCaptured, events.KindTaskQueued, events.KindDeliveryRecorded, events.KindParked, events.KindOutcome, events.KindChatOutcome, events.KindPRMerged, events.KindPRRejected, events.KindPRClosed, events.KindPRMergeRequested, events.KindTaskDead, events.KindOperatorApproved, events.KindOperatorRejected, events.KindAgentApproved, events.KindAgentRejected, events.KindTaskApproved, events.KindTaskRejected, events.KindOperatorRereviewed, events.KindAgentRereviewed, events.KindTaskRereviewed, events.KindTaskRetried, events.KindTaskCancelled, events.KindTaskStopped, events.KindTaskAbandoned, events.KindRemediationRound, events.KindReviewApproved, events.KindStepRetried, events.KindTaskWithdrawn, events.KindTaskArchiveRequested, events.KindWorkRequestSubmitted, events.KindAlert, events.KindBindingChanged, events.KindMappingChanged, events.KindBindingStarted, events.KindWorkflowCallStarted, events.KindIdentityStarted, events.KindWorkflowCallFinished, events.KindUpdateReport, // Written by the daemon's binding dispatch as a bare literal. "binding_dispatch_failure", } } // prunableEventKinds is the allowlist with the protected set subtracted. The // two are disjoint; the subtraction is the fail-safe, so a kind accidentally // added to both is kept rather than deleted. func prunableEventKinds() []string { protected := protectedEventKinds() return slices.DeleteFunc(slices.Clone(observabilityEventKinds()), func(kind string) bool { return slices.Contains(protected, kind) }) } // prunableEventKind reports whether kind is on the sweep's allowlist. func prunableEventKind(kind string) bool { return slices.Contains(prunableEventKinds(), kind) } // sweepAuditRetention applies the audit-retention setting until ctx ends. It // reads the resource on every tick, so an edit reaches the next sweep without // a restart, and an unreadable or invalid document skips the tick rather than // falling back to a default that prunes. func (b *server) sweepAuditRetention(ctx context.Context) { ticker := time.NewTicker(auditRetentionSweepInterval) defer ticker.Stop() for { b.pruneAuditEvents(ctx) select { case <-ctx.Done(): return case <-ticker.C: } } } func (b *server) pruneAuditEvents(ctx context.Context) { resources, ok := b.st.(auditRetentionResources) if !ok { return } resource, err := resources.Resource(ctx, storecontract.DefaultOrgID, controlplanestore.AuditRetentionKind) if err != nil { if ctx.Err() == nil { b.log.WarnContext(ctx, "audit retention not applied: setting unreadable, sweep skipped", "err", err) } return } retention, err := controlplanestore.RuntimeEventRetention(resource.Value) if err != nil { if ctx.Err() == nil { b.log.WarnContext(ctx, "audit retention not applied: setting invalid, sweep skipped", "err", err) } return } if retention == 0 { // Keep forever: there is no cutoff to apply. return } pruner, ok := b.st.(auditEventPruner) if !ok { return } cutoff := time.Now().Add(-retention) rows, err := pruner.PruneAuditEvents(ctx, prunableEventKinds(), cutoff) switch { case errors.Is(err, postgres.ErrAuditPruneBusy): b.log.DebugContext(ctx, "audit retention sweep skipped: another sweep holds the lock") case err != nil: if ctx.Err() == nil { b.log.WarnContext(ctx, "prune audit events", "err", err) } default: b.log.InfoContext(ctx, "pruned audit observability events", "rows", rows, "cutoff", cutoff.UTC()) } }