Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(entitlement): observe mode and per-workspace over-limit records (MUL-9481) (#10811)

Multica Eve505026479d93
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index 55166b7134..3bd92d5320 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -143,6 +143,7 @@ var concurrentIndexCleanups = map[string]string{
"676_chat_wakeup_due_idx": "idx_chat_wakeup_due",
"677_chat_wakeup_session_idx": "idx_chat_wakeup_session",
"678_chat_wakeup_requester_idx": "idx_chat_wakeup_requester",
+ "680_entitlement_limit_overage_scope_idx": "uq_entitlement_limit_overage_scope",
"671_weixin_account_state_unique_index": "weixin_account_state_pkey",
"669_weixin_login_session_unique_index": "weixin_login_session_pkey",
"666_weixin_login_expiry_idx": "weixin_login_expiry_idx",
diff --git a/server/internal/entitlement/README.md b/server/internal/entitlement/README.md
index 41fb9a5dc8..870bda852e 100644
--- a/server/internal/entitlement/README.md
+++ b/server/internal/entitlement/README.md
@@ -17,7 +17,7 @@ The client reads:
- `schema_version`: only version 1 is accepted.
- `policy_revision`: the effective-instruction generation, currently fixed at
- `2` by Cloud and not deployment configuration. Cloud advances it when the
+ `3` by Cloud and not deployment configuration. Cloud advances it when the
meaning or set of actionable instructions changes, including additive
instructions; `schema_version` changes only for incompatible wire parsing.
- `subscription_version`: the workspace's monotonic subscription revision. A
@@ -30,9 +30,10 @@ The client reads:
for enforcement expiry.
- `valid_until`: diagnostic Cloud wall-clock time only; it is never used to
extend enforcement.
-- `gates`: effective `off` or `enforce` instructions and parameters. Cloud does
- not expose an `observe` rollout mode; `observe` exists only as Multica's local
- downgrade of an expired cached `enforce` instruction.
+- `gates`: effective `off`, `observe`, or `enforce` instructions and
+ parameters. Cloud chooses the action per gate; `observe` carries the same
+ limit and period parameters as `enforce`. Multica also downgrades an expired
+ cached `enforce` instruction to `observe` locally (see below).
- `gates.*.notifications`: an optional, additive delivery policy. The autopilot
quota consumer recognizes `first_rejection_per_period` and delivers one
workspace notice for the first rejected execution in the Cloud-defined quota
@@ -43,10 +44,36 @@ No deployment order is required for the optional notification policy. The
consumer treats a missing policy as notices-disabled while continuing to
enforce the quota.
+Deploy this consumer before Cloud policy revision 3, which is the first to send
+`observe`. A consumer released before revision 3 rejects `observe` as an
+unknown action and fails the whole policy open to `off`.
+
Responses tolerate unknown JSON fields and gates for additive compatibility.
Unknown schema/action, malformed fields, a missing `autopilot_runs` gate, HTTP
failures, and timeouts fail open.
+## Actions
+
+Every consumer handles the three actions the same way:
+
+| Action | Admits the operation | Records an over-limit attempt |
+| --- | --- | --- |
+| `off` | yes, without reading quota tables | no |
+| `observe` | yes, even past the limit | yes, `observed_count` |
+| `enforce` | only within the limit | yes, `enforced_count` |
+
+Over-limit attempts are stored per workspace, gate, and Cloud-defined period
+in `entitlement_limit_overage` (`service.EntitlementOverages`). Each row keeps
+the latest limit, the peak usage an attempt would have reached, the observed
+and enforced counts, and the first and last attempt times, so
+`peak_usage - limit_value` is how far a workspace went over. A later admission
+inside the limit also syncs a changed limit onto an existing row, so an upgrade
+mid-period clears the overage without erasing the history. Rollout reach,
+over-limit notices, and grace periods read this table; metrics stay
+low-cardinality and never carry workspace IDs. Recording runs after the
+admission transaction commits and is best-effort: a failed write is logged and
+never changes the admission decision.
+
## Cache and degradation
The cache is workspace-keyed, LRU-bounded, and collapses concurrent refreshes
diff --git a/server/internal/entitlement/client.go b/server/internal/entitlement/client.go
index 9c245671fb..cbeffdd07c 100644
--- a/server/internal/entitlement/client.go
+++ b/server/internal/entitlement/client.go
@@ -309,7 +309,9 @@ func normalizeGate(name GateName, wire wireGate) (Gate, error) {
switch action {
case ActionOff:
return Gate{Action: ActionOff}, nil
- case ActionEnforce:
+ case ActionObserve, ActionEnforce:
+ // observe carries the same parameters as enforce so consumers can tell
+ // what would have been blocked without rejecting anything.
default:
return Gate{}, ErrInvalidPolicy
}
diff --git a/server/internal/entitlement/client_test.go b/server/internal/entitlement/client_test.go
index 2b16cc26ec..ba7063e240 100644
--- a/server/internal/entitlement/client_test.go
+++ b/server/internal/entitlement/client_test.go
@@ -286,11 +286,16 @@ func TestColdFailuresFailOpen(t *testing.T) {
gate.Action = "future"
p.Gates[string(GateAutopilotRuns)] = gate
}), ReasonInvalidPolicy},
- {"cloud observe action", policyHandler(func(p *wirePolicy) {
+ {"observe without limit", policyHandler(func(p *wirePolicy) {
gate := p.Gates[string(GateAutopilotRuns)]
gate.Action = string(ActionObserve)
+ gate.Limit = nil
p.Gates[string(GateAutopilotRuns)] = gate
}), ReasonInvalidPolicy},
+ {"observe without autopilot period", policyHandler(func(p *wirePolicy) {
+ limit := testAutopilotLimit
+ p.Gates[string(GateAutopilotRuns)] = wireGate{Action: string(ActionObserve), Limit: &limit}
+ }), ReasonInvalidPolicy},
{"missing gate", policyHandler(func(p *wirePolicy) { delete(p.Gates, string(GateAutopilotRuns)) }), ReasonInvalidPolicy},
{"excessive TTL", policyHandler(func(p *wirePolicy) { p.ValidForSeconds = 301 }), ReasonInvalidPolicy},
{"missing autopilot period", policyHandler(func(p *wirePolicy) {
@@ -317,6 +322,63 @@ func TestColdFailuresFailOpen(t *testing.T) {
}
}
+// Cloud chooses off, observe, or enforce per gate. Each must reach consumers
+// unchanged; observe keeps the enforce parameters so consumers can measure
+// what would have been blocked.
+func TestCloudGateActionsAreDeliveredUnchanged(t *testing.T) {
+ for _, action := range []Action{ActionOff, ActionObserve, ActionEnforce} {
+ t.Run(string(action), func(t *testing.T) {
+ server := httptest.NewServer(policyHandler(func(p *wirePolicy) {
+ *p = samplePolicy(3, 1, 60, action)
+ }))
+ defer server.Close()
+ client := newTestClient(t, server.URL, nil)
+
+ decision := client.Gate(context.Background(), uuid.New(), GateAutopilotRuns)
+ if decision.Gate.Action != action || decision.Reason != ReasonRefreshed || decision.PolicyRevision != 3 {
+ t.Fatalf("decision = %+v", decision)
+ }
+ if action == ActionOff {
+ if decision.Gate.Limit != nil || decision.Gate.PeriodStart != nil {
+ t.Fatalf("off gate carries parameters: %+v", decision.Gate)
+ }
+ return
+ }
+ gate := decision.Gate
+ if gate.Limit == nil || *gate.Limit != testAutopilotLimit || gate.PeriodStart == nil ||
+ gate.PeriodEnd == nil || gate.ResetAt == nil {
+ t.Fatalf("%s gate lost its parameters: %+v", action, gate)
+ }
+ })
+ }
+}
+
+func TestStaleCloudObserveStaysObserve(t *testing.T) {
+ clock := time.Date(2026, 8, 18, 9, 0, 0, 0, time.UTC)
+ var fail atomic.Bool
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ if fail.Load() {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ }
+ writePolicy(t, w, samplePolicy(3, 0, 5, ActionObserve))
+ }))
+ defer server.Close()
+ client := newTestClient(t, server.URL, nil)
+ client.now = func() time.Time { return clock }
+ workspaceID := uuid.New()
+
+ if fresh := client.Gate(context.Background(), workspaceID, GateAutopilotRuns); fresh.Gate.Action != ActionObserve {
+ t.Fatalf("fresh = %+v", fresh)
+ }
+ fail.Store(true)
+ clock = clock.Add(6 * time.Second)
+ stale := client.Gate(context.Background(), workspaceID, GateAutopilotRuns)
+ if stale.Gate.Action != ActionObserve || stale.Reason != ReasonStale {
+ t.Fatalf("stale = %+v", stale)
+ }
+}
+
func TestAutopilotResetMayFollowPeriodEnd(t *testing.T) {
policy := samplePolicy(1, 0, 60, ActionEnforce)
gate := policy.Gates[string(GateAutopilotRuns)]
diff --git a/server/internal/entitlement/types.go b/server/internal/entitlement/types.go
index 9c9d2501fe..92302c1d99 100644
--- a/server/internal/entitlement/types.go
+++ b/server/internal/entitlement/types.go
@@ -26,6 +26,8 @@ func (n GateName) valid() bool {
type Action string
+// Cloud chooses one of these per gate. ActionObserve is also Multica's local
+// downgrade of a stale cached ActionEnforce.
const (
ActionOff Action = "off"
ActionObserve Action = "observe"
@@ -78,6 +80,10 @@ type Decision struct {
// needs. It deliberately has no error return: every failure is represented by a
// fail-open Decision with ActionOff (or ActionObserve for a bounded stale
// snapshot that can no longer enforce).
+//
+// Consumers handle the three actions the same way for every gate: off skips
+// the gate entirely, observe admits the operation and records an over-limit
+// attempt, enforce rejects it.
type Provider interface {
Gate(ctx context.Context, workspaceID uuid.UUID, name GateName) Decision
}
diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.go
index affc6752da..0e23e236b0 100644
--- a/server/internal/handler/workspace.go
+++ b/server/internal/handler/workspace.go
@@ -1331,6 +1331,10 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {
name: "delete autopilot quota periods",
run: func() error { return qtx.DeleteWorkspaceAutopilotQuotaPeriods(ctx, requester.WorkspaceID) },
},
+ {
+ name: "delete entitlement limit overages",
+ run: func() error { return qtx.DeleteWorkspaceEntitlementLimitOverages(ctx, requester.WorkspaceID) },
+ },
{
name: "delete chat messages",
run: func() error { return qtx.DeleteWorkspaceChatMessages(ctx, requester.WorkspaceID) },
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index c975767b36..c44d9a3e82 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -65,6 +65,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"dingtalk_group_presence": workspaceDelete,
"dingtalk_bot_identity": workspaceDelete,
"dingtalk_group_route": workspaceDelete,
+ "entitlement_limit_overage": workspaceDelete,
"feedback": workspaceDeleteDetach,
"github_installation": workspaceDelete,
"github_pending_check_suite": workspaceDelete,
diff --git a/server/internal/service/autopilot_quota.go b/server/internal/service/autopilot_quota.go
index e3310574ec..36d08e5c63 100644
--- a/server/internal/service/autopilot_quota.go
+++ b/server/internal/service/autopilot_quota.go
@@ -182,9 +182,10 @@ func (s *AutopilotService) createAutopilotRunWithQuota(
if err := tx.Commit(ctx); err != nil {
return db.AutopilotRun{}, false, fmt.Errorf("commit blocked quota admission: %w", err)
}
- // Inbox delivery is presentation-only. It runs after the admission
- // transaction commits so a malformed notification marker or failed insert
- // can never turn the quota response into a 500 or roll back blocked counts.
+ // Overage recording and Inbox delivery are presentation-only. They run
+ // after the admission transaction commits so a failed write can never turn
+ // the quota response into a 500 or roll back blocked counts.
+ s.recordAutopilotQuotaExceeded(ctx, policy, workspaceID, period)
s.deliverAutopilotQuotaRejectionNotice(ctx, policy, workspaceID, source, params)
s.recordAutopilotQuotaDecision(policy.action, source, "blocked")
return db.AutopilotRun{}, false, &AutopilotQuotaExceededError{
@@ -192,8 +193,8 @@ func (s *AutopilotService) createAutopilotRunWithQuota(
Limit: policy.limit, ResetAt: policy.resetAt,
}
}
- // Observe-only would-blocks stay in the bounded decision metric. Durable
- // blocked counts back the usage API only for decisions that reject work.
+ // Observe admits the run. The would-block is recorded per workspace after
+ // commit; blocked_counts stay reserved for decisions that reject work.
reservation, err := qtx.CreateAutopilotQuotaReservation(ctx, db.CreateAutopilotQuotaReservationParams{
WorkspaceID: workspaceID, PeriodStart: periodArgs.PeriodStart, PeriodEnd: periodArgs.PeriodEnd,
PolicyRevision: policy.policyRevision, SubscriptionVersion: policy.subscriptionVersion,
@@ -218,11 +219,35 @@ func (s *AutopilotService) createAutopilotRunWithQuota(
result := "admitted"
if wouldBlock {
result = "would_block"
+ s.recordAutopilotQuotaExceeded(ctx, policy, workspaceID, period)
+ } else {
+ EntitlementOverages{Queries: s.Queries}.SyncLimit(
+ ctx, workspaceID, entitlement.GateAutopilotRuns, policy.periodStart, policy.periodEnd, policy.limit,
+ )
}
s.recordAutopilotQuotaDecision(policy.action, source, result)
return run, false, nil
}
+// recordAutopilotQuotaExceeded stores an over-limit attempt. period holds the
+// counts seen before the attempt, so the attempt itself is the +1.
+func (s *AutopilotService) recordAutopilotQuotaExceeded(
+ ctx context.Context,
+ policy autopilotQuotaPolicy,
+ workspaceID pgtype.UUID,
+ period db.AutopilotQuotaPeriod,
+) {
+ EntitlementOverages{Queries: s.Queries}.Record(ctx, LimitExceededAttempt{
+ WorkspaceID: workspaceID,
+ Gate: entitlement.GateAutopilotRuns,
+ Action: policy.action,
+ PeriodStart: policy.periodStart,
+ PeriodEnd: policy.periodEnd,
+ Limit: policy.limit,
+ AttemptedUsage: period.UsedCount + period.ReservedCount + 1,
+ })
+}
+
func (s *AutopilotService) recordAutopilotQuotaDecision(action entitlement.Action, source, result string) {
if s.QuotaMetrics != nil {
s.QuotaMetrics.RecordAutopilotQuotaDecision(string(action), source, result)
diff --git a/server/internal/service/autopilot_quota_test.go b/server/internal/service/autopilot_quota_test.go
index ed647da6c1..82cab33442 100644
--- a/server/internal/service/autopilot_quota_test.go
+++ b/server/internal/service/autopilot_quota_test.go
@@ -88,6 +88,7 @@ func newAutopilotQuotaFixture(t *testing.T, action entitlement.Action, limit int
t.Cleanup(func() {
pool.Exec(context.Background(), `DELETE FROM autopilot_quota_reservation WHERE workspace_id = $1`, workspaceID)
pool.Exec(context.Background(), `DELETE FROM autopilot_quota_period WHERE workspace_id = $1`, workspaceID)
+ pool.Exec(context.Background(), `DELETE FROM entitlement_limit_overage WHERE workspace_id = $1`, workspaceID)
})
return fixture
}
@@ -725,6 +726,124 @@ func TestAutopilotQuotaObserveToEnforceAndOffFinalization(t *testing.T) {
}
}
+// The same limit under off, observe and enforce: off neither blocks nor
+// records, observe admits every run but records each would-block for the
+// workspace, enforce rejects and records.
+func TestAutopilotQuotaRecordsOverLimitAttemptsPerWorkspace(t *testing.T) {
+ fixture := newAutopilotQuotaFixture(t, entitlement.ActionOff, 1)
+ ctx := context.Background()
+ overages := EntitlementOverages{Queries: fixture.queries}
+ create := func(key string) error {
+ _, _, err := fixture.service.createAutopilotRunWithQuota(ctx, fixture.workspaceID, "schedule", key, fixture.createRunArgs)
+ return err
+ }
+ workspaceOverages := func() []LimitOverage {
+ t.Helper()
+ rows, err := overages.ForWorkspace(ctx, fixture.workspaceID)
+ if err != nil {
+ t.Fatalf("ForWorkspace: %v", err)
+ }
+ return rows
+ }
+
+ for i := 0; i < 3; i++ {
+ if err := create(fmt.Sprintf("off-%d", i)); err != nil {
+ t.Fatalf("off admission %d: %v", i, err)
+ }
+ }
+ if rows := workspaceOverages(); len(rows) != 0 {
+ t.Fatalf("off recorded overages: %+v", rows)
+ }
+
+ fixture.setPolicy(entitlement.ActionObserve, fixture.periodStart, fixture.periodEnd, 1)
+ for i := 0; i < 3; i++ {
+ if err := create(fmt.Sprintf("observe-%d", i)); err != nil {
+ t.Fatalf("observe admission %d must not be blocked: %v", i, err)
+ }
+ }
+ rows := workspaceOverages()
+ if len(rows) != 1 {
+ t.Fatalf("observe overages = %+v, want one period row", rows)
+ }
+ got := rows[0]
+ if got.Gate != entitlement.GateAutopilotRuns || got.Limit != 1 || got.PeakUsage != 3 || got.Over != 2 ||
+ got.ObservedCount != 2 || got.EnforcedCount != 0 ||
+ !got.PeriodStart.Equal(fixture.periodStart) || !got.PeriodEnd.Equal(fixture.periodEnd) ||
+ got.FirstExceededAt.IsZero() || got.LastExceededAt.Before(got.FirstExceededAt) {
+ t.Fatalf("observe overage = %+v", got)
+ }
+ usage, err := fixture.service.AutopilotQuotaUsage(ctx, fixture.workspaceID)
+ if err != nil || len(usage.BlockedCounts) != 0 || usage.Reached != nil {
+ t.Fatalf("observe usage = %+v, %v; observe must not count as blocked", usage, err)
+ }
+
+ fixture.setPolicy(entitlement.ActionEnforce, fixture.periodStart, fixture.periodEnd, 1)
+ var quotaErr *AutopilotQuotaExceededError
+ if err := create("enforce-0"); !errors.As(err, &quotaErr) {
+ t.Fatalf("enforce admission error = %v, want quota exceeded", err)
+ }
+ got = workspaceOverages()[0]
+ if got.ObservedCount != 2 || got.EnforcedCount != 1 || got.PeakUsage != 4 || got.Over != 3 {
+ t.Fatalf("enforce overage = %+v", got)
+ }
+
+ byPeriod, err := overages.ForPeriod(ctx, entitlement.GateAutopilotRuns, fixture.periodStart, fixture.periodEnd)
+ if err != nil {
+ t.Fatalf("ForPeriod: %v", err)
+ }
+ found := false
+ for _, row := range byPeriod {
+ if row.WorkspaceID == fixture.workspace {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatalf("ForPeriod = %+v, missing workspace %s", byPeriod, fixture.workspace)
+ }
+
+ // A mid-period upgrade that raises the limit above the peak clears Over
+ // while keeping the history of attempts.
+ fixture.setPolicy(entitlement.ActionObserve, fixture.periodStart, fixture.periodEnd, 3)
+ if err := create("observe-after-upgrade"); err != nil {
+ t.Fatalf("observe after upgrade: %v", err)
+ }
+ got = workspaceOverages()[0]
+ if got.Limit != 3 || got.PeakUsage != 4 || got.Over != 1 || got.ObservedCount != 3 {
+ t.Fatalf("overage after upgrade = %+v", got)
+ }
+
+ // An upgrade above the peak followed by a run inside the new limit must
+ // clear Over even though that run is not itself over the limit. History
+ // (counts, peak, times) stays.
+ before := got
+ fixture.setPolicy(entitlement.ActionObserve, fixture.periodStart, fixture.periodEnd, 10)
+ if err := create("observe-within-raised-limit"); err != nil {
+ t.Fatalf("observe within raised limit: %v", err)
+ }
+ got = workspaceOverages()[0]
+ if got.Limit != 10 || got.Over != 0 || got.PeakUsage != before.PeakUsage ||
+ got.ObservedCount != before.ObservedCount || got.EnforcedCount != before.EnforcedCount ||
+ !got.LastExceededAt.Equal(before.LastExceededAt) {
+ t.Fatalf("overage after upgrade above peak = %+v, before = %+v", got, before)
+ }
+ byPeriod, err = overages.ForPeriod(ctx, entitlement.GateAutopilotRuns, fixture.periodStart, fixture.periodEnd)
+ if err != nil {
+ t.Fatalf("ForPeriod after upgrade: %v", err)
+ }
+ for _, row := range byPeriod {
+ if row.WorkspaceID == fixture.workspace && (row.Limit != 10 || row.Over != 0) {
+ t.Fatalf("ForPeriod after upgrade = %+v", row)
+ }
+ }
+}
+
+func TestLimitOverageNeverReportsNegativeOver(t *testing.T) {
+ rows := limitOveragesFromRows([]db.EntitlementLimitOverage{{LimitValue: 10, PeakUsage: 4}})
+ if len(rows) != 1 || rows[0].Over != 0 {
+ t.Fatalf("rows = %+v, want Over clamped to zero", rows)
+ }
+}
+
func TestAutopilotQuotaConsumedCreateIssueCannotBeRefunded(t *testing.T) {
fixture := newAutopilotQuotaFixture(t, entitlement.ActionEnforce, 2)
ctx := context.Background()
diff --git a/server/internal/service/entitlement_overage.go b/server/internal/service/entitlement_overage.go
new file mode 100644
index 0000000000..59d1558d43
--- /dev/null
+++ b/server/internal/service/entitlement_overage.go
@@ -0,0 +1,160 @@
+package service
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/entitlement"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// LimitExceededAttempt is one operation that went over a gate's limit. Under
+// observe it was admitted anyway; under enforce it was rejected.
+type LimitExceededAttempt struct {
+ WorkspaceID pgtype.UUID
+ Gate entitlement.GateName
+ Action entitlement.Action
+ PeriodStart time.Time
+ PeriodEnd time.Time
+ Limit int64
+ // AttemptedUsage is the usage the operation would reach if admitted,
+ // counting itself.
+ AttemptedUsage int64
+}
+
+// LimitOverage is how far one workspace went over one gate's limit in one
+// period. Observe-mode rollouts, over-limit notices and grace periods read it
+// per workspace; metrics deliberately carry no workspace label.
+type LimitOverage struct {
+ WorkspaceID uuid.UUID
+ Gate entitlement.GateName
+ PeriodStart time.Time
+ PeriodEnd time.Time
+ // Limit is the latest limit seen in the period.
+ Limit int64
+ PeakUsage int64
+ // Over is PeakUsage beyond Limit. It is zero when a later, higher limit
+ // (an upgrade mid-period) covers the peak.
+ Over int64
+ ObservedCount int64
+ EnforcedCount int64
+ FirstExceededAt time.Time
+ LastExceededAt time.Time
+}
+
+// EntitlementOverages records and reads over-limit attempts for every
+// entitlement gate. Only gates that are observing or enforcing reach it, so a
+// self-hosted deployment without Cloud never touches the table.
+type EntitlementOverages struct {
+ Queries *db.Queries
+}
+
+// Record stores one over-limit attempt. It is a best-effort side effect that
+// runs after the caller's admission decision has committed: a failure is
+// logged and never changes whether the operation was admitted.
+func (o EntitlementOverages) Record(ctx context.Context, attempt LimitExceededAttempt) {
+ if attempt.Action != entitlement.ActionObserve && attempt.Action != entitlement.ActionEnforce {
+ return
+ }
+ _, err := o.Queries.RecordEntitlementLimitExceeded(ctx, db.RecordEntitlementLimitExceededParams{
+ WorkspaceID: attempt.WorkspaceID,
+ Gate: string(attempt.Gate),
+ PeriodStart: pgtype.Timestamptz{Time: attempt.PeriodStart.UTC(), Valid: true},
+ PeriodEnd: pgtype.Timestamptz{Time: attempt.PeriodEnd.UTC(), Valid: true},
+ LimitValue: attempt.Limit,
+ AttemptedUsage: attempt.AttemptedUsage,
+ Observed: attempt.Action == entitlement.ActionObserve,
+ })
+ if err != nil {
+ slog.Warn("entitlement over-limit attempt was not recorded; admission decision is unchanged",
+ "workspace_id", util.UUIDToString(attempt.WorkspaceID),
+ "gate", string(attempt.Gate),
+ "action", string(attempt.Action),
+ "error", err,
+ )
+ }
+}
+
+// SyncLimit updates the limit on an existing over-limit record when an
+// admission inside the limit sees a different one, e.g. after an upgrade
+// mid-period. Without it Over would keep being measured against the old
+// limit. Best-effort like Record; a workspace with no record is a no-op.
+func (o EntitlementOverages) SyncLimit(
+ ctx context.Context,
+ workspaceID pgtype.UUID,
+ gate entitlement.GateName,
+ periodStart, periodEnd time.Time,
+ limit int64,
+) {
+ err := o.Queries.SyncEntitlementLimitOverageLimit(ctx, db.SyncEntitlementLimitOverageLimitParams{
+ WorkspaceID: workspaceID,
+ Gate: string(gate),
+ PeriodStart: pgtype.Timestamptz{Time: periodStart.UTC(), Valid: true},
+ PeriodEnd: pgtype.Timestamptz{Time: periodEnd.UTC(), Valid: true},
+ LimitValue: limit,
+ })
+ if err != nil {
+ slog.Warn("entitlement over-limit record limit was not synced; admission decision is unchanged",
+ "workspace_id", util.UUIDToString(workspaceID),
+ "gate", string(gate),
+ "error", err,
+ )
+ }
+}
+
+// ForWorkspace lists every period in which a workspace went over a limit,
+// newest period first.
+func (o EntitlementOverages) ForWorkspace(ctx context.Context, workspaceID pgtype.UUID) ([]LimitOverage, error) {
+ rows, err := o.Queries.ListWorkspaceEntitlementLimitOverages(ctx, workspaceID)
+ if err != nil {
+ return nil, fmt.Errorf("list workspace limit overages: %w", err)
+ }
+ return limitOveragesFromRows(rows), nil
+}
+
+// ForPeriod lists the workspaces that went over one gate's limit in a
+// period, furthest over first.
+func (o EntitlementOverages) ForPeriod(
+ ctx context.Context,
+ gate entitlement.GateName,
+ periodStart, periodEnd time.Time,
+) ([]LimitOverage, error) {
+ rows, err := o.Queries.ListEntitlementLimitOveragesForPeriod(ctx, db.ListEntitlementLimitOveragesForPeriodParams{
+ Gate: string(gate),
+ PeriodStart: pgtype.Timestamptz{Time: periodStart.UTC(), Valid: true},
+ PeriodEnd: pgtype.Timestamptz{Time: periodEnd.UTC(), Valid: true},
+ })
+ if err != nil {
+ return nil, fmt.Errorf("list limit overages for period: %w", err)
+ }
+ return limitOveragesFromRows(rows), nil
+}
+
+func limitOveragesFromRows(rows []db.EntitlementLimitOverage) []LimitOverage {
+ out := make([]LimitOverage, 0, len(rows))
+ for _, row := range rows {
+ over := row.PeakUsage - row.LimitValue
+ if over < 0 {
+ over = 0
+ }
+ out = append(out, LimitOverage{
+ WorkspaceID: uuid.UUID(row.WorkspaceID.Bytes),
+ Gate: entitlement.GateName(row.Gate),
+ PeriodStart: row.PeriodStart.Time.UTC(),
+ PeriodEnd: row.PeriodEnd.Time.UTC(),
+ Limit: row.LimitValue,
+ PeakUsage: row.PeakUsage,
+ Over: over,
+ ObservedCount: row.ObservedCount,
+ EnforcedCount: row.EnforcedCount,
+ FirstExceededAt: row.FirstExceededAt.Time.UTC(),
+ LastExceededAt: row.LastExceededAt.Time.UTC(),
+ })
+ }
+ return out
+}
diff --git a/server/migrations/679_entitlement_limit_overage.down.sql b/server/migrations/679_entitlement_limit_overage.down.sql
new file mode 100644
index 0000000000..114cf2f15f
--- /dev/null
+++ b/server/migrations/679_entitlement_limit_overage.down.sql
@@ -0,0 +1 @@
+DROP TABLE IF EXISTS entitlement_limit_overage;
diff --git a/server/migrations/679_entitlement_limit_overage.up.sql b/server/migrations/679_entitlement_limit_overage.up.sql
new file mode 100644
index 0000000000..dbe4e54d9d
--- /dev/null
+++ b/server/migrations/679_entitlement_limit_overage.up.sql
@@ -0,0 +1,28 @@
+-- Per-workspace record of attempts that went over an entitlement limit, for
+-- every gate and both acting modes. Under observe the attempt was admitted and
+-- only recorded here; under enforce it was rejected. Rollout dashboards, over-
+-- limit notices and grace periods read this table instead of metrics, which
+-- carry no workspace label.
+--
+-- One row per workspace, gate and Cloud-defined period. limit_value is the
+-- latest limit seen in the period and peak_usage the highest usage an attempt
+-- would have reached, so peak_usage - limit_value is how far over the limit the
+-- workspace went.
+--
+-- The scope unique index is built concurrently in 680. No foreign keys (repo
+-- rule): workspace deletion removes these rows explicitly.
+CREATE TABLE IF NOT EXISTS entitlement_limit_overage (
+ workspace_id UUID NOT NULL,
+ gate TEXT NOT NULL,
+ period_start TIMESTAMPTZ NOT NULL,
+ period_end TIMESTAMPTZ NOT NULL,
+ limit_value BIGINT NOT NULL CHECK (limit_value >= 0),
+ peak_usage BIGINT NOT NULL CHECK (peak_usage >= 0),
+ observed_count BIGINT NOT NULL DEFAULT 0 CHECK (observed_count >= 0),
+ enforced_count BIGINT NOT NULL DEFAULT 0 CHECK (enforced_count >= 0),
+ first_exceeded_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ last_exceeded_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ CHECK (period_start < period_end)
+);
diff --git a/server/migrations/680_entitlement_limit_overage_scope_idx.down.sql b/server/migrations/680_entitlement_limit_overage_scope_idx.down.sql
new file mode 100644
index 0000000000..2250a16f8c
--- /dev/null
+++ b/server/migrations/680_entitlement_limit_overage_scope_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS uq_entitlement_limit_overage_scope;
diff --git a/server/migrations/680_entitlement_limit_overage_scope_idx.up.sql b/server/migrations/680_entitlement_limit_overage_scope_idx.up.sql
new file mode 100644
index 0000000000..c0ddd463e5
--- /dev/null
+++ b/server/migrations/680_entitlement_limit_overage_scope_idx.up.sql
@@ -0,0 +1,3 @@
+-- Upsert key for RecordEntitlementLimitExceeded and the per-workspace lookup.
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_entitlement_limit_overage_scope
+ ON entitlement_limit_overage (workspace_id, gate, period_start, period_end);
diff --git a/server/pkg/db/generated/entitlement_overage.sql.go b/server/pkg/db/generated/entitlement_overage.sql.go
new file mode 100644
index 0000000000..d6b23dd712
--- /dev/null
+++ b/server/pkg/db/generated/entitlement_overage.sql.go
@@ -0,0 +1,194 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: entitlement_overage.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const listEntitlementLimitOveragesForPeriod = `-- name: ListEntitlementLimitOveragesForPeriod :many
+SELECT workspace_id, gate, period_start, period_end, limit_value, peak_usage, observed_count, enforced_count, first_exceeded_at, last_exceeded_at, created_at, updated_at FROM entitlement_limit_overage
+WHERE gate = $1
+ AND period_start = $2
+ AND period_end = $3
+ORDER BY peak_usage - limit_value DESC, workspace_id
+`
+
+type ListEntitlementLimitOveragesForPeriodParams struct {
+ Gate string `json:"gate"`
+ PeriodStart pgtype.Timestamptz `json:"period_start"`
+ PeriodEnd pgtype.Timestamptz `json:"period_end"`
+}
+
+// Workspaces that went over one gate's limit in a period. Rows exist only for
+// workspaces that went over, so the count is the reach of the limit.
+func (q *Queries) ListEntitlementLimitOveragesForPeriod(ctx context.Context, arg ListEntitlementLimitOveragesForPeriodParams) ([]EntitlementLimitOverage, error) {
+ rows, err := q.db.Query(ctx, listEntitlementLimitOveragesForPeriod, arg.Gate, arg.PeriodStart, arg.PeriodEnd)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []EntitlementLimitOverage{}
+ for rows.Next() {
+ var i EntitlementLimitOverage
+ if err := rows.Scan(
+ &i.WorkspaceID,
+ &i.Gate,
+ &i.PeriodStart,
+ &i.PeriodEnd,
+ &i.LimitValue,
+ &i.PeakUsage,
+ &i.ObservedCount,
+ &i.EnforcedCount,
+ &i.FirstExceededAt,
+ &i.LastExceededAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listWorkspaceEntitlementLimitOverages = `-- name: ListWorkspaceEntitlementLimitOverages :many
+SELECT workspace_id, gate, period_start, period_end, limit_value, peak_usage, observed_count, enforced_count, first_exceeded_at, last_exceeded_at, created_at, updated_at FROM entitlement_limit_overage
+WHERE workspace_id = $1
+ORDER BY period_start DESC, gate
+`
+
+// Every recorded over-limit period of one workspace, newest period first.
+func (q *Queries) ListWorkspaceEntitlementLimitOverages(ctx context.Context, workspaceID pgtype.UUID) ([]EntitlementLimitOverage, error) {
+ rows, err := q.db.Query(ctx, listWorkspaceEntitlementLimitOverages, workspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []EntitlementLimitOverage{}
+ for rows.Next() {
+ var i EntitlementLimitOverage
+ if err := rows.Scan(
+ &i.WorkspaceID,
+ &i.Gate,
+ &i.PeriodStart,
+ &i.PeriodEnd,
+ &i.LimitValue,
+ &i.PeakUsage,
+ &i.ObservedCount,
+ &i.EnforcedCount,
+ &i.FirstExceededAt,
+ &i.LastExceededAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const recordEntitlementLimitExceeded = `-- name: RecordEntitlementLimitExceeded :one
+INSERT INTO entitlement_limit_overage (
+ workspace_id, gate, period_start, period_end, limit_value, peak_usage,
+ observed_count, enforced_count, first_exceeded_at, last_exceeded_at
+) VALUES (
+ $1, $2, $3, $4, $5, $6,
+ CASE WHEN $7::boolean THEN 1 ELSE 0 END,
+ CASE WHEN $7::boolean THEN 0 ELSE 1 END,
+ now(), now()
+)
+ON CONFLICT (workspace_id, gate, period_start, period_end) DO UPDATE
+SET limit_value = EXCLUDED.limit_value,
+ peak_usage = GREATEST(entitlement_limit_overage.peak_usage, EXCLUDED.peak_usage),
+ observed_count = entitlement_limit_overage.observed_count + EXCLUDED.observed_count,
+ enforced_count = entitlement_limit_overage.enforced_count + EXCLUDED.enforced_count,
+ last_exceeded_at = now(),
+ updated_at = now()
+RETURNING workspace_id, gate, period_start, period_end, limit_value, peak_usage, observed_count, enforced_count, first_exceeded_at, last_exceeded_at, created_at, updated_at
+`
+
+type RecordEntitlementLimitExceededParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Gate string `json:"gate"`
+ PeriodStart pgtype.Timestamptz `json:"period_start"`
+ PeriodEnd pgtype.Timestamptz `json:"period_end"`
+ LimitValue int64 `json:"limit_value"`
+ AttemptedUsage int64 `json:"attempted_usage"`
+ Observed bool `json:"observed"`
+}
+
+// One over-limit attempt. observed counts attempts that were admitted under
+// observe; otherwise the attempt was rejected under enforce.
+func (q *Queries) RecordEntitlementLimitExceeded(ctx context.Context, arg RecordEntitlementLimitExceededParams) (EntitlementLimitOverage, error) {
+ row := q.db.QueryRow(ctx, recordEntitlementLimitExceeded,
+ arg.WorkspaceID,
+ arg.Gate,
+ arg.PeriodStart,
+ arg.PeriodEnd,
+ arg.LimitValue,
+ arg.AttemptedUsage,
+ arg.Observed,
+ )
+ var i EntitlementLimitOverage
+ err := row.Scan(
+ &i.WorkspaceID,
+ &i.Gate,
+ &i.PeriodStart,
+ &i.PeriodEnd,
+ &i.LimitValue,
+ &i.PeakUsage,
+ &i.ObservedCount,
+ &i.EnforcedCount,
+ &i.FirstExceededAt,
+ &i.LastExceededAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const syncEntitlementLimitOverageLimit = `-- name: SyncEntitlementLimitOverageLimit :exec
+UPDATE entitlement_limit_overage
+SET limit_value = $1,
+ updated_at = now()
+WHERE workspace_id = $2
+ AND gate = $3
+ AND period_start = $4
+ AND period_end = $5
+ AND limit_value <> $1
+`
+
+type SyncEntitlementLimitOverageLimitParams struct {
+ LimitValue int64 `json:"limit_value"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Gate string `json:"gate"`
+ PeriodStart pgtype.Timestamptz `json:"period_start"`
+ PeriodEnd pgtype.Timestamptz `json:"period_end"`
+}
+
+// Keeps an existing row's limit current when the period's limit changes
+// without a new over-limit attempt (an upgrade mid-period), so Over is not
+// reported against a stale limit. Counts and times are left as history.
+func (q *Queries) SyncEntitlementLimitOverageLimit(ctx context.Context, arg SyncEntitlementLimitOverageLimitParams) error {
+ _, err := q.db.Exec(ctx, syncEntitlementLimitOverageLimit,
+ arg.LimitValue,
+ arg.WorkspaceID,
+ arg.Gate,
+ arg.PeriodStart,
+ arg.PeriodEnd,
+ )
+ return err
+}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 884c753d7b..b888bf5a79 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -843,6 +843,21 @@ type DingtalkGroupRoute struct {
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
+type EntitlementLimitOverage struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Gate string `json:"gate"`
+ PeriodStart pgtype.Timestamptz `json:"period_start"`
+ PeriodEnd pgtype.Timestamptz `json:"period_end"`
+ LimitValue int64 `json:"limit_value"`
+ PeakUsage int64 `json:"peak_usage"`
+ ObservedCount int64 `json:"observed_count"`
+ EnforcedCount int64 `json:"enforced_count"`
+ FirstExceededAt pgtype.Timestamptz `json:"first_exceeded_at"`
+ LastExceededAt pgtype.Timestamptz `json:"last_exceeded_at"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
type Feedback struct {
ID pgtype.UUID `json:"id"`
UserID pgtype.UUID `json:"user_id"`
diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.go
index 0e79eedec8..1c50688ccc 100644
--- a/server/pkg/db/generated/workspace_delete.sql.go
+++ b/server/pkg/db/generated/workspace_delete.sql.go
@@ -235,6 +235,16 @@ func (q *Queries) DeleteWorkspaceConnections(ctx context.Context, workspaceID pg
return err
}
+const deleteWorkspaceEntitlementLimitOverages = `-- name: DeleteWorkspaceEntitlementLimitOverages :exec
+DELETE FROM entitlement_limit_overage
+WHERE entitlement_limit_overage.workspace_id = $1
+`
+
+func (q *Queries) DeleteWorkspaceEntitlementLimitOverages(ctx context.Context, workspaceID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteWorkspaceEntitlementLimitOverages, workspaceID)
+ return err
+}
+
const deleteWorkspaceIssueRoots = `-- name: DeleteWorkspaceIssueRoots :exec
WITH deleted_wakeup_receipts AS (
DELETE FROM issue_wakeup_receipt WHERE wakeup_id IN (SELECT id FROM issue_wakeup WHERE workspace_id=$1)
diff --git a/server/pkg/db/queries/entitlement_overage.sql b/server/pkg/db/queries/entitlement_overage.sql
new file mode 100644
index 0000000000..ebbb99b1fb
--- /dev/null
+++ b/server/pkg/db/queries/entitlement_overage.sql
@@ -0,0 +1,48 @@
+-- name: RecordEntitlementLimitExceeded :one
+-- One over-limit attempt. observed counts attempts that were admitted under
+-- observe; otherwise the attempt was rejected under enforce.
+INSERT INTO entitlement_limit_overage (
+ workspace_id, gate, period_start, period_end, limit_value, peak_usage,
+ observed_count, enforced_count, first_exceeded_at, last_exceeded_at
+) VALUES (
+ @workspace_id, @gate, @period_start, @period_end, @limit_value, @attempted_usage,
+ CASE WHEN @observed::boolean THEN 1 ELSE 0 END,
+ CASE WHEN @observed::boolean THEN 0 ELSE 1 END,
+ now(), now()
+)
+ON CONFLICT (workspace_id, gate, period_start, period_end) DO UPDATE
+SET limit_value = EXCLUDED.limit_value,
+ peak_usage = GREATEST(entitlement_limit_overage.peak_usage, EXCLUDED.peak_usage),
+ observed_count = entitlement_limit_overage.observed_count + EXCLUDED.observed_count,
+ enforced_count = entitlement_limit_overage.enforced_count + EXCLUDED.enforced_count,
+ last_exceeded_at = now(),
+ updated_at = now()
+RETURNING *;
+
+-- name: ListWorkspaceEntitlementLimitOverages :many
+-- Every recorded over-limit period of one workspace, newest period first.
+SELECT * FROM entitlement_limit_overage
+WHERE workspace_id = @workspace_id
+ORDER BY period_start DESC, gate;
+
+-- name: ListEntitlementLimitOveragesForPeriod :many
+-- Workspaces that went over one gate's limit in a period. Rows exist only for
+-- workspaces that went over, so the count is the reach of the limit.
+SELECT * FROM entitlement_limit_overage
+WHERE gate = @gate
+ AND period_start = @period_start
+ AND period_end = @period_end
+ORDER BY peak_usage - limit_value DESC, workspace_id;
+
+-- name: SyncEntitlementLimitOverageLimit :exec
+-- Keeps an existing row's limit current when the period's limit changes
+-- without a new over-limit attempt (an upgrade mid-period), so Over is not
+-- reported against a stale limit. Counts and times are left as history.
+UPDATE entitlement_limit_overage
+SET limit_value = @limit_value,
+ updated_at = now()
+WHERE workspace_id = @workspace_id
+ AND gate = @gate
+ AND period_start = @period_start
+ AND period_end = @period_end
+ AND limit_value <> @limit_value;
diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sql
index 71c16e825b..e3095c4a78 100644
--- a/server/pkg/db/queries/workspace_delete.sql
+++ b/server/pkg/db/queries/workspace_delete.sql
@@ -646,6 +646,10 @@ WHERE autopilot_quota_reservation.workspace_id = $1;
DELETE FROM autopilot_quota_period
WHERE autopilot_quota_period.workspace_id = $1;
+-- name: DeleteWorkspaceEntitlementLimitOverages :exec
+DELETE FROM entitlement_limit_overage
+WHERE entitlement_limit_overage.workspace_id = $1;
+
-- name: DeleteWorkspaceAutopilotChildren :exec
WITH
deleted_triggers AS (