diff --git a/api/llms.txt b/api/llms.txt index 431eab4..3b93a0b 100644 --- a/api/llms.txt +++ b/api/llms.txt @@ -34,7 +34,7 @@ An agent never acts as the Owner, even through an Owner's browser session. roles: owner, maintainer, viewer; scopes: approvals:read; POST /api/v1/actions/approvals.list - budget.get [read] Show the budget mode, cap, alert threshold and usage, with unverified usage marked. roles: owner, maintainer, viewer; scopes: budget:read; POST /api/v1/actions/budget.get -- budget.set [sensitive, step-up] Change the budget mode, cap, alert threshold or rollback reserve; Owner only. +- budget.set [sensitive, step-up] Change the budget mode, cap, alert threshold, rollback reserve or provider cost sources; Owner only. roles: owner; scopes: budget:write; POST /api/v1/actions/budget.set - changelog.list [read] List the changelog entries of released work. roles: owner, maintainer, reporter, viewer, agent; scopes: catalog:read; POST /api/v1/actions/changelog.list diff --git a/api/openapi.yaml b/api/openapi.yaml index 4c00f93..b0998e1 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -401,6 +401,13 @@ paths: - day - week - month + provider_cost_sources: + items: + enum: + - anthropic + - openai + type: array + uniqueItems: true provider_hard_cap: type: boolean rollback_reserve_micros: @@ -430,7 +437,7 @@ paths: security: - bearerAuth: - budget:write - summary: Change the budget mode, cap, alert threshold or rollback reserve; Owner only. + summary: Change the budget mode, cap, alert threshold, rollback reserve or provider cost sources; Owner only. tags: - budget x-sisf-action: budget.set diff --git a/cmd/factoryd/roles.go b/cmd/factoryd/roles.go index cd42b90..2943c68 100644 --- a/cmd/factoryd/roles.go +++ b/cmd/factoryd/roles.go @@ -11,6 +11,7 @@ import ( "github.com/bestagentkits/sisf/adapters/agent/fake" "github.com/bestagentkits/sisf/cmd/factoryd/wiring" "github.com/bestagentkits/sisf/cmd/supervisor/observe" + "github.com/bestagentkits/sisf/internal/budget" "github.com/bestagentkits/sisf/internal/dispatcher" "github.com/bestagentkits/sisf/pkg/core" "github.com/bestagentkits/sisf/pkg/manifest" @@ -55,9 +56,11 @@ func setup(ctx context.Context, getenv func(string) string, zone core.Zone) (zon return zoneSetup{env: env, manifest: m, store: store, clock: clock}, nil } -// newControl builds the control zone from its setup; surfaces and decisions -// are nil for the Owner's command-line use, which serves and decides nothing. -func newControl(s zoneSetup, log *slog.Logger, surfaces *wiring.SurfaceConfig, decisions *wiring.DecisionConfig) (*wiring.Control, error) { +// newControl builds the control zone from its setup; surfaces, decisions and +// the providers' cost sources are nil for the Owner's command-line use, +// which serves, decides and reads nothing. +func newControl(s zoneSetup, log *slog.Logger, surfaces *wiring.SurfaceConfig, decisions *wiring.DecisionConfig, + providerCost map[string]budget.CostSource) (*wiring.Control, error) { settings, err := wiring.GitHubSettingsOf(s.manifest) if err != nil { return nil, err @@ -78,7 +81,7 @@ func newControl(s zoneSetup, log *slog.Logger, surfaces *wiring.SurfaceConfig, d WebhookSecret: s.env.WebhookSecret, ApprovalKey: key, Surfaces: surfaces, Decision: decisions, ListenAddr: listenOr(s.env.Listen, wiring.DefaultControlListen), AllowNonLoopback: s.env.AllowNonLoopback, Probes: wiring.ZoneProbes(s.env.AppHealthURL, s.env.DispatcherHealthURL), Clock: s.clock, Logger: log, - TrustedProxies: s.env.TrustedProxies, Reconcile: s.env.Reconcile, + TrustedProxies: s.env.TrustedProxies, Reconcile: s.env.Reconcile, ProviderCost: providerCost, }) } @@ -118,7 +121,13 @@ func runControl(ctx context.Context, args []string, getenv func(string) string, if decisions != nil { decisions.Secrets = secretSet.Resolver } - c, err := newControl(s, log, surfaces, decisions) + // The control zone alone holds the admin keys that read what the + // providers report was spent. + providerCost, err := wiring.ProviderCostFromEnv(getenv) + if err != nil { + return err + } + c, err := newControl(s, log, surfaces, decisions, providerCost) if err != nil { return err } @@ -159,7 +168,7 @@ func runPolicyApprove(ctx context.Context, args []string, getenv func(string) st return err } defer func() { _ = s.store.Close() }() - c, err := newControl(s, log, nil, nil) + c, err := newControl(s, log, nil, nil, nil) if err != nil { return err } @@ -187,7 +196,7 @@ func runPolicyRequest(ctx context.Context, args []string, getenv func(string) st return err } defer func() { _ = s.store.Close() }() - c, err := newControl(s, log, nil, nil) + c, err := newControl(s, log, nil, nil, nil) if err != nil { return err } @@ -216,7 +225,7 @@ func runIssueRetry(ctx context.Context, args []string, getenv func(string) strin return err } defer func() { _ = s.store.Close() }() - c, err := newControl(s, log, nil, nil) + c, err := newControl(s, log, nil, nil, nil) if err != nil { return err } diff --git a/cmd/factoryd/wiring/control.go b/cmd/factoryd/wiring/control.go index 11860a7..1887349 100644 --- a/cmd/factoryd/wiring/control.go +++ b/cmd/factoryd/wiring/control.go @@ -83,6 +83,10 @@ type ControlConfig struct { // Reconcile configures the polls that recover issue changes whose // webhooks were lost. Reconcile ReconcileConfig + // ProviderCost reads what the providers report was spent, by provider + // name, for the providers the budget settings name; see + // ProviderCostFromEnv. A named provider missing here holds capped runs. + ProviderCost map[string]budget.CostSource } // Control is the control zone of one factory: the HTTP server, intake, the @@ -129,6 +133,8 @@ type Control struct { // route. reportsOff is set once a pass said why it publishes none. reports *control.ReportPublisher reportsOff bool + // providerSpend reads the providers' spend for the budget gate. + providerSpend budget.ProviderSpendRefresher // budget closes the reservation of a run whose issue the control zone // blocks because the run stopped. budget *budget.Gate @@ -169,7 +175,8 @@ func NewControl(cfg ControlConfig) (*Control, error) { c := &Control{cfg: cfg, log: cfg.Logger, backoff: map[string]retryAt{}, projected: map[core.IssueRef]int64{}, progress: &github.ProgressComment{Issues: cfg.GitHub, Self: settings.Self, Factory: m.FactoryID}, progressShown: map[core.IssueRef]string{}, redactor: redact.New(redact.Config{}), - budget: budget.NewGate(budget.Config{Clock: cfg.Clock})} + budget: budget.NewGate(budget.Config{Clock: cfg.Clock}), + providerSpend: budget.ProviderSpendRefresher{Store: budget.StateStore(cfg.Store), Sources: cfg.ProviderCost, Clock: cfg.Clock}} c.Audit = audit.New(cfg.Store, cfg.Clock) reconcile, err := cfg.Reconcile.withDefaults() if err != nil { @@ -310,7 +317,8 @@ func (c *Control) Run(ctx context.Context, ln net.Listener, interval time.Durati // parks the issues whose wait for an answer is over, polling GitHub first // when an answer may not be known yet, and blocks the issues whose run // stopped without a candidate; when it is configured, -// the decision layer reads the edge's counters; the stored bug reports +// the decision layer reads the edge's counters; the providers' report of +// what was spent is read for the budget gate when it is due; the stored bug reports // past their retention are pruned, and a small batch of those waiting is // published as GitHub issues for a person to triage. Once per reconciliation // interval it asks GitHub for the issue changes no webhook delivered. Each part runs even @@ -350,6 +358,7 @@ func (c *Control) Pass(ctx context.Context) error { c.projectProgress(ctx), c.projectLifecycle(ctx), c.runDecisions(ctx), + c.providerSpend.Refresh(ctx), pruned, // Late, so publishing reports delays none of the factory's own work. c.publishReports(ctx), diff --git a/cmd/factoryd/wiring/control_provider_spend_test.go b/cmd/factoryd/wiring/control_provider_spend_test.go new file mode 100644 index 0000000..281cefb --- /dev/null +++ b/cmd/factoryd/wiring/control_provider_spend_test.go @@ -0,0 +1,47 @@ +package wiring_test + +import ( + "context" + "encoding/json" + "testing" + "time" + + "github.com/bestagentkits/sisf/internal/budget" + "github.com/bestagentkits/sisf/internal/testkit/harness" + "github.com/bestagentkits/sisf/pkg/core" + "github.com/bestagentkits/sisf/pkg/state" +) + +// spendOf is a provider that reports a fixed spend. +type spendOf core.Micros + +func (s spendOf) Spent(_ context.Context, since time.Time) (core.Micros, time.Time, error) { + return core.Micros(s), since, nil +} + +// A control pass reads the spend of the providers the budget settings name +// and stores it where the agent zone's gate reads it. +func TestAControlPassReadsTheProvidersSpend(t *testing.T) { + t.Parallel() + ctx := context.Background() + f := harness.New(t, harness.Options{ProviderCost: map[string]budget.CostSource{budget.ProviderAnthropic: spendOf(3_000_000)}}) + settings, _ := json.Marshal(budget.Settings{Mode: core.BudgetCapped, CapMicros: 10_000_000, Period: budget.PeriodDay, + ProviderHardCap: true, ProviderCostSources: []string{budget.ProviderAnthropic}}) + if err := f.ControlStore.Update(ctx, func(ctx context.Context, tx state.Tx) error { + _, err := tx.PutKV(ctx, state.KVEntry{Namespace: budget.SettingsNamespace, Key: budget.SettingsKey, Value: settings}) + return err + }); err != nil { + t.Fatal(err) + } + f.Pass() + var spend budget.ProviderSpend + if err := f.ControlStore.View(ctx, func(ctx context.Context, tx state.Tx) (err error) { + spend, _, _, err = budget.LoadProviderSpend(ctx, tx) + return err + }); err != nil { + t.Fatal(err) + } + if got := spend.Sources[budget.ProviderAnthropic].SpentMicros; got != 3_000_000 || !spend.FetchedAt.Equal(f.Clock.Now()) { + t.Fatalf("the stored provider spend: %+v, want 3 read now", spend) + } +} diff --git a/cmd/factoryd/wiring/provider_cost_env.go b/cmd/factoryd/wiring/provider_cost_env.go new file mode 100644 index 0000000..b4ffb71 --- /dev/null +++ b/cmd/factoryd/wiring/provider_cost_env.go @@ -0,0 +1,50 @@ +package wiring + +import ( + "strings" + + "github.com/bestagentkits/sisf/internal/budget" + "github.com/bestagentkits/sisf/internal/budget/providercost" + "github.com/bestagentkits/sisf/pkg/core" +) + +// The control zone's credentials for reading what the providers report +// was spent. Each admin key comes with the one workspace or project the +// factory's runs are charged to, so other work there is not counted as the +// factory's. Their names start with SISF_, which no agent environment +// accepts, so a key the control zone holds never reaches an agent. +const ( + EnvAnthropicAdminKey = "SISF_ANTHROPIC_ADMIN_KEY" + EnvAnthropicCostWorkspace = "SISF_ANTHROPIC_COST_WORKSPACE" + EnvOpenAIAdminKey = "SISF_OPENAI_ADMIN_KEY" + EnvOpenAICostProject = "SISF_OPENAI_COST_PROJECT" +) + +// ProviderCostFromEnv builds the providers' cost sources the environment +// configures. A key without its workspace or project, or the reverse, is +// refused rather than read across the whole organization. +func ProviderCostFromEnv(getenv func(string) string) (map[string]budget.CostSource, error) { + sources := map[string]budget.CostSource{} + pair := func(keyName, scopeName string) (core.SecretValue, string, error) { + key, scope := strings.TrimSpace(getenv(keyName)), strings.TrimSpace(getenv(scopeName)) + if (key == "") != (scope == "") { + return core.SecretValue{}, "", core.NewError(core.CodeInvalidArgument, keyName+" and "+scopeName+" are set together or not at all") + } + return core.NewSecretValue([]byte(key)), scope, nil + } + key, workspace, err := pair(EnvAnthropicAdminKey, EnvAnthropicCostWorkspace) + if err != nil { + return nil, err + } + if workspace != "" { + sources[budget.ProviderAnthropic] = providercost.Anthropic{AdminKey: key, WorkspaceID: workspace} + } + key, project, err := pair(EnvOpenAIAdminKey, EnvOpenAICostProject) + if err != nil { + return nil, err + } + if project != "" { + sources[budget.ProviderOpenAI] = providercost.OpenAI{AdminKey: key, ProjectID: project} + } + return sources, nil +} diff --git a/cmd/factoryd/wiring/provider_cost_env_test.go b/cmd/factoryd/wiring/provider_cost_env_test.go new file mode 100644 index 0000000..2ea0e5a --- /dev/null +++ b/cmd/factoryd/wiring/provider_cost_env_test.go @@ -0,0 +1,52 @@ +package wiring_test + +import ( + "testing" + + "github.com/bestagentkits/sisf/cmd/factoryd/wiring" + "github.com/bestagentkits/sisf/internal/budget" + "github.com/bestagentkits/sisf/pkg/agent/agentenv" + "github.com/bestagentkits/sisf/pkg/core" +) + +// Each admin key needs the one workspace or project the factory's runs +// are charged to; neither is accepted alone. +func TestAProviderCostKeyNeedsTheFactorysOwnScope(t *testing.T) { + t.Parallel() + for name, vars := range map[string]map[string]string{ + "anthropic key alone": {wiring.EnvAnthropicAdminKey: "k"}, + "anthropic workspace alone": {wiring.EnvAnthropicCostWorkspace: "wrkspc_factory"}, + "openai key alone": {wiring.EnvOpenAIAdminKey: "k"}, + "openai project alone": {wiring.EnvOpenAICostProject: "proj_factory"}, + } { + if _, err := wiring.ProviderCostFromEnv(envOf(vars)); !core.HasCode(err, core.CodeInvalidArgument) { + t.Errorf("%s: %v, want INVALID_ARGUMENT", name, err) + } + } + sources, err := wiring.ProviderCostFromEnv(envOf(map[string]string{ + wiring.EnvAnthropicAdminKey: "k", wiring.EnvAnthropicCostWorkspace: "wrkspc_factory", + wiring.EnvOpenAIAdminKey: "k", wiring.EnvOpenAICostProject: "proj_factory", + })) + if err != nil || sources[budget.ProviderAnthropic] == nil || sources[budget.ProviderOpenAI] == nil { + t.Fatalf("both providers configured: %v, %v", sources, err) + } + if sources, err := wiring.ProviderCostFromEnv(envOf(nil)); err != nil || len(sources) != 0 { + t.Fatalf("nothing configured: %v, %v", sources, err) + } +} + +// The admin keys that read the providers' spend stay in the control zone: +// no agent environment may carry them, even when an operator asks. +func TestAProviderAdminKeyNeverReachesAnAgent(t *testing.T) { + t.Parallel() + for _, name := range []string{wiring.EnvAnthropicAdminKey, wiring.EnvOpenAIAdminKey} { + if err := agentenv.Allowed(name); !core.HasCode(err, core.CodePermissionDenied) { + t.Errorf("%s may be passed to an agent: %v", name, err) + } + _, err := agentenv.Build(agentenv.Spec{Agent: "claude", Home: "/home/agent", Extra: []string{name}, + LookupEnv: func(string) (string, bool) { return "secret", true }}) + if !core.HasCode(err, core.CodePermissionDenied) { + t.Errorf("an agent environment carried %s: %v", name, err) + } + } +} diff --git a/docs/acceptance-matrix.md b/docs/acceptance-matrix.md index db26d6d..5fca5b4 100644 --- a/docs/acceptance-matrix.md +++ b/docs/acceptance-matrix.md @@ -21,7 +21,7 @@ Status meanings: **present** means the file exists in this branch and its packag | SISF-11 | `internal/policy/unapproved_policy_change_ignored_test.go` | present | | SISF-12 | `internal/auth/sso_oauth_negative_test.go` | present (against fakes, not real Google SSO) | | SISF-13 | `tests/acceptance/five_surface_parity_test.go` (with `cross_surface_approval_test.go` and `step_up_and_write_limits_test.go`) | present (CLI, REST, MCP, WebMCP tool path and dashboard forms against the wired control server and fake identity provider) | -| SISF-14 | `internal/budget/budget_modes_test.go` (with `internal/budget/budget_status_test.go` `TestUnverifiedUsageAndAMissingHardCapAreShown` for a provider without a hard cap; `internal/budget/unpriced_usage_test.go` and `internal/budget/unpriced_usage_store_test.go` for usage whose provider reported no cost, recorded as reported, charged when its run closes and warned about; `internal/dispatcher/run_spend_test.go`, `cmd/supervisor/stages/run_close_reported_cost_test.go` and `pkg/state/sqlstore/run_usage_test.go` for closing a run with the cost its ledger rows show, not the agent zone's record; `pkg/state/sqlstore/usage_ledger_trust_test.go` for the agent zone's rows dated by the store and booked only against its run's reservation, rows dated before a reservation not counting, verified usage refused, costs bounded and summed without overflow, negative costs counted as 0 and their run charged in full, and a row that states no cost leaving its run unpriced (`pkg/state/sqlstore/run_usage_test.go`; `internal/dispatcher/run_spend_test.go` also pins the limit that a run booking one micro is taken at its word); `internal/budget/budget_total_overflow_test.go` for totals near the store's cap filling the budget instead of wrapping; `pkg/state/sqlstore/budget_database_time_and_usage_test.go` for the PostgreSQL zone roles dated by the server's clock, refused verified usage and refused agent usage outside a reservation of its own factory, run and issue over plain SQL (runs only with `SISF_TEST_PG_DSN` set); `internal/budget/run_reservation_id_test.go`, `cmd/factoryd/wiring/control_stopped_run_reservation_test.go` and `cmd/supervisor/stages/run_close_own_reservation_test.go` for closing a run's reservation by its ID, never the one its run record names; `cmd/supervisor/stages/run_close_retry_test.go` and `cmd/supervisor/stages/run_close_due_bound_test.go` for retrying a failed close and abandoning one that can never succeed) | present | +| SISF-14 | `internal/budget/budget_modes_test.go` (with `internal/budget/budget_status_test.go` `TestUnverifiedUsageAndAMissingHardCapAreShown` for a provider without a hard cap; `internal/budget/unpriced_usage_test.go` and `internal/budget/unpriced_usage_store_test.go` for usage whose provider reported no cost, recorded as reported, charged when its run closes and warned about; `internal/dispatcher/run_spend_test.go`, `cmd/supervisor/stages/run_close_reported_cost_test.go` and `pkg/state/sqlstore/run_usage_test.go` for closing a run with the cost its ledger rows show, not the agent zone's record; `pkg/state/sqlstore/usage_ledger_trust_test.go` for the agent zone's rows dated by the store and booked only against its run's reservation, rows dated before a reservation not counting, verified usage refused, costs bounded and summed without overflow, negative costs counted as 0 and their run charged in full, and a row that states no cost leaving its run unpriced (`pkg/state/sqlstore/run_usage_test.go`; `internal/dispatcher/run_spend_test.go` also pins the limit that a run booking one micro is taken at its word); `internal/budget/budget_total_overflow_test.go` for totals near the store's cap filling the budget instead of wrapping; `pkg/state/sqlstore/budget_database_time_and_usage_test.go` for the PostgreSQL zone roles dated by the server's clock, refused verified usage and refused agent usage outside a reservation of its own factory, run and issue over plain SQL (runs only with `SISF_TEST_PG_DSN` set); `internal/budget/run_reservation_id_test.go`, `cmd/factoryd/wiring/control_stopped_run_reservation_test.go` and `cmd/supervisor/stages/run_close_own_reservation_test.go` for closing a run's reservation by its ID, never the one its run record names; `cmd/supervisor/stages/run_close_retry_test.go` and `cmd/supervisor/stages/run_close_due_bound_test.go` for retrying a failed close and abandoning one that can never succeed; `internal/budget/provider_spend_test.go`, `internal/budget/provider_spend_store_test.go`, `internal/budget/providercost/provider_cost_sources_test.go`, `cmd/factoryd/wiring/control_provider_spend_test.go` and `cmd/factoryd/wiring/provider_cost_env_test.go` for the providers' own report bounding what the agents report, written by the control zone alone, holding capped runs when stale but never a rollback, and its admin keys never reaching an agent) | present | | SISF-15 | `tests/acceptance/two_factories_same_upstream_test.go` | present | | SISF-16 | `internal/conformance/backend_capability_matrix_test.go` | present | | SISF-17 | `internal/decision/no_benefit_signal_ignored_test.go` | present | diff --git a/docs/adr/0007-budget-default-unlimited.md b/docs/adr/0007-budget-default-unlimited.md index 4afbd37..4da3271 100644 --- a/docs/adr/0007-budget-default-unlimited.md +++ b/docs/adr/0007-budget-default-unlimited.md @@ -16,7 +16,7 @@ The Owner asked for `unlimited` as the default budget. That must not be read as - Timeouts, max attempts, concurrency, rate limits and quotas always apply. Roles and scopes never escalate on their own. - In `capped` mode a reservation is made before a run starts. Unmeasured usage is shown as `unverified`; a provider without a hard limit is flagged. - Usage whose provider reports tokens but no cost is recorded as reported, with no cost. When the reservation of a run with such usage is closed, the part of the reservation that the run's reported costs did not cover is charged as `unverified`; the reservation is the factory's own estimate of the run's worst case. The run's booked cost, and whether some of its usage stated none, are read from the run's rows in the ledger recorded since its reservation was made, never from the dispatcher's record of the run, which the agent zone can rewrite. A run with no row at all, or with a row that states no cost, with or without tokens, is charged its whole reservation as `unverified` less what its other rows booked, as is a run the dispatcher holds no record of: what it ran is unknown, and over-charging a run stopped before its first attempt is the safe side. This holds for a run the control zone stops as well: without a record of its own it is charged in full. A run with a row of negative cost is charged its whole reservation too, since only a hand that bypassed the store writes one; sums count a negative cost as 0. The record, and the QA judgments' own tally, can only raise the charge, for an attempt whose agent reported nothing and so left no row. A zone that may not read the ledger charges the whole reservation as `unverified` rather than trust the record. All reported costs stay `unverified`: no provider confirms them, so the store refuses usage booked as verified from every zone. -- The limit of this: the agent zone does the metering. The dispatcher books what its agents reported, so a compromised agent zone can under-report a run's cost down to one micro (a millionth of the ledger currency): a run whose rows each state some cost, however small, is taken at its word, and its reservation is then released for that. No code can tell an honest small cost from a false one while the agent zone meters itself; every cost an agent reports stays unverified. What is enforced is narrower and stated exactly. The store (`pkg/state/sqlstore/budget.go`): ledger rows are append-only; a usage row or reservation the agent zone writes through the store is dated by the store's own clock, and a usage row only against an existing reservation of the run and issue it names; rows dated before a reservation was made do not count at its close; a usage entry costs at most one million in the ledger currency (`core.MaxUsageCost`, booked at the bound above it; `cliagent` clamps an agent's reported cost to it too), and every sum of money is capped instead of overflowing and counts a negative cost as 0, so a close always ends. The gate adds a period's totals and an estimate saturating at the largest amount (`internal/budget/money_sum.go`), so totals near the store's cap fill the budget rather than wrap to a negative amount that lets any reservation fit. On PostgreSQL the database holds every zone role to the same rules over plain SQL (migration 13, `pkg/state/sqlstore/budget_row_time.go`, `row_policies.go`): it dates each reservation and usage row a zone role inserts by the server's clock, whatever the row says; it refuses usage booked as verified from every zone role; it refuses agent-role usage that does not name an existing reservation of the same factory, run and issue; and, with migration 12, refuses a negative cost on new rows (rows from before that migration are not rechecked). The table owner and roles that bypass row security are exempt, as the operator's own hand. On SQLite these rules hold only through the store. Migration 13 is marked backward compatible: the previous release books no verified usage and its agent books usage only against its own run's reservation, so it keeps working against the migrated database. Usage of a run that reserved nothing, as with an unlimited budget and a run estimate of 0, is not counted. `budget.get` warns when some unverified usage states no cost, with tokens or without, and its `unpriced` total counts those rows by the same rule a run's close applies (`core.Usage.CostUnreported`). +- The limit of this: the agent zone does the metering. The dispatcher books what its agents reported, so a compromised agent zone can under-report a run's cost down to one micro (a millionth of the ledger currency): a run whose rows each state some cost, however small, is taken at its word, and its reservation is then released for that. No code can tell an honest small cost from a false one while the agent zone meters itself; every cost an agent reports stays unverified. A capped budget with a period can narrow this by naming a provider cost source: the providers' own report of what the factory's workspace or project spent, read by the control zone, is then the least the period counts as spent ([ADR 0027](0027-the-providers-own-report-bounds-what-agents-report-spent.md)); it catches under-reporting only after the provider's lag, and without a source the limit stands as stated. What is enforced is narrower and stated exactly. The store (`pkg/state/sqlstore/budget.go`): ledger rows are append-only; a usage row or reservation the agent zone writes through the store is dated by the store's own clock, and a usage row only against an existing reservation of the run and issue it names; rows dated before a reservation was made do not count at its close; a usage entry costs at most one million in the ledger currency (`core.MaxUsageCost`, booked at the bound above it; `cliagent` clamps an agent's reported cost to it too), and every sum of money is capped instead of overflowing and counts a negative cost as 0, so a close always ends. The gate adds a period's totals and an estimate saturating at the largest amount (`internal/budget/money_sum.go`), so totals near the store's cap fill the budget rather than wrap to a negative amount that lets any reservation fit. On PostgreSQL the database holds every zone role to the same rules over plain SQL (migration 13, `pkg/state/sqlstore/budget_row_time.go`, `row_policies.go`): it dates each reservation and usage row a zone role inserts by the server's clock, whatever the row says; it refuses usage booked as verified from every zone role; it refuses agent-role usage that does not name an existing reservation of the same factory, run and issue; and, with migration 12, refuses a negative cost on new rows (rows from before that migration are not rechecked). The table owner and roles that bypass row security are exempt, as the operator's own hand. On SQLite these rules hold only through the store. Migration 13 is marked backward compatible: the previous release books no verified usage and its agent books usage only against its own run's reservation, so it keeps working against the migrated database. Usage of a run that reserved nothing, as with an unlimited budget and a run estimate of 0, is not counted. `budget.get` warns when some unverified usage states no cost, with tokens or without, and its `unpriced` total counts those rows by the same rule a run's close applies (`core.Usage.CostUnreported`). ## Consequences diff --git a/docs/adr/0027-the-providers-own-report-bounds-what-agents-report-spent.md b/docs/adr/0027-the-providers-own-report-bounds-what-agents-report-spent.md new file mode 100644 index 0000000..c29ffdf --- /dev/null +++ b/docs/adr/0027-the-providers-own-report-bounds-what-agents-report-spent.md @@ -0,0 +1,33 @@ +# ADR 0027: The providers' own report bounds what the agents report spent + +## Status + +Status: proposed. It narrows the limit stated in [ADR 0007](0007-budget-default-unlimited.md), under which a compromised agent zone can under-report a run's cost down to one micro. + +## Context + +The agent zone meters its own runs: the dispatcher books what its agents report, and the store can bound and date those rows but cannot tell an honest small cost from a false one. A capped budget is therefore only as hard as the agent zone is honest. Anthropic and OpenAI both report what an organization was charged, through admin APIs an agent never needs: Anthropic's Usage and Cost Analytics API (`GET /v1/organizations/analytics/cost`, beta header `analytics-usage-cost-2026-08-24`) and OpenAI's organization Costs API (`GET /v1/organization/costs`). Their figures lag: Anthropic refreshes about every 4 hours and revises figures until about a week after the month ends. + +## Decision + +- **An Owner setting, failing closed.** `budget.set` takes `provider_cost_sources` (`anthropic`, `openai`) for a capped budget with a period of a day, a week or a month (`internal/budget/settings.go`). A budget without a period is refused: the providers report a bounded past, not everything ever spent. Removing a source is warned about when the change is approved. +- **Read by the control zone only.** The control zone reads each named provider's spend since the start of the period (`internal/budget/provider_spend_refresh.go`, `internal/budget/providercost/`), every 15 minutes (`ProviderSpendEvery`), or a minute after a failed read (`ProviderSpendRetry`), and stores it at `install/provider_spend`. The control zone writes that namespace, and the agent zone may only read it, in the store and in the PostgreSQL row policies generated from the same rule (`pkg/state/sqlstore/zone_ownership.go`); no migration is needed. The admin keys are `SISF_ANTHROPIC_ADMIN_KEY` and `SISF_OPENAI_ADMIN_KEY`, set only in the control zone's environment; no agent environment accepts a `SISF_` variable (`pkg/agent/agentenv`). +- **The factory's own workspace or project.** Each key comes with the one workspace (`SISF_ANTHROPIC_COST_WORKSPACE`) or project (`SISF_OPENAI_COST_PROJECT`) the factory's runs are charged to. A key without it is refused at start, so other work in the organization is never counted as the factory's. +- **A floor, not a ledger entry.** The gate counts a period as having spent the larger of what the agents reported and what the providers report (`internal/budget/provider_spend.go`); reservations are added on top. The providers' figure is kept apart: it is not written to the ledger and not shown as verified usage. `budget.get` shows it as `provider_spent_micros` and warns when it exceeds what the agents reported. +- **Staleness holds new capped runs, never a rollback.** A named provider whose figure is missing, damaged, or read more than 2 hours ago (`ProviderSpendMaxAge`, the age of the control zone's read, not of the provider's data) refuses a capped claim with `BUDGET_EXCEEDED`, which the dispatcher treats as a hold on every claim. A missing credential leaves the figure to go stale, so a configuration gap holds rather than drops the check. `ReserveRollback` is never held by the provider figure. A fresh figure of the previous period, as at the start of a day, neither counts nor holds: the provider has not reported the new period yet. +- **Exact money.** Amounts are parsed as decimals, never through a float, and rounded up to the micro; a negative amount, such as a credit, counts as 0. Only USD is accepted; another currency fails the read. Redirects are not followed, so an admin key is sent only to the provider. + +## Consequences + +- An agent zone that under-reports is caught only once the provider reports the spending, hours later, and only up to the cap: runs claimed before then were admitted on the agents' word. The guarantee is a bound on a period's spending after the provider's lag, not on any one run. +- The gate runs in the agent zone's dispatcher. The floor corrects what the gate admits when the reported costs are wrong, through a metering bug or a run's false report; an agent zone taken over as a whole can skip the gate, as before, and the providers' figure in `budget.get`, read by the control zone, is then how the Owner sees what was spent. +- OAuth or subscription sign-ins have no billing figure and cannot use this check. +- Both adapters are written from the providers' published API references and tested against fakes only; they are not yet proven against the live APIs. OpenAI's reference does not state the unit of `amount.value`; dollars are assumed, as its examples show. +- A provider outage longer than 2 hours holds new capped runs until it ends. + +## Acceptance test + +- The providers' figure bounds what the agents report, lagging figures do not lower it, and a missing, stale, future-dated or partial figure holds runs but not a rollback: `internal/budget/provider_spend_test.go`. +- Only the control zone writes the figure, through the store and, on PostgreSQL, over plain SQL as the agent role; reads on schedule; a failed or unconfigured provider stores nothing: `internal/budget/provider_spend_store_test.go`. +- Exact amounts, pagination, expired cursors, refused currencies and keys, and no redirect: `internal/budget/providercost/provider_cost_sources_test.go`. +- A control pass reads the spend, a key needs its scope, and no admin key reaches an agent: `cmd/factoryd/wiring/control_provider_spend_test.go`, `cmd/factoryd/wiring/provider_cost_env_test.go`. diff --git a/docs/capability-matrix.md b/docs/capability-matrix.md index 45281a0..8415eb8 100644 --- a/docs/capability-matrix.md +++ b/docs/capability-matrix.md @@ -34,3 +34,5 @@ Which deployment profile and backend can claim which capability. The profile lis ## Current status Supported operating modes: Standalone (the trusted-code profile) and Docker Compose. Both are installed and checked by `sisf init`, `sisf up` and `sisf doctor`; the conformance checker is `sisf conformance check`. Docker mode does not yet provide container sandboxing for untrusted code, and `sisf doctor` warns about it, so `safe_exec` is not claimed for either mode. Outside the simulation Docker mode builds, evaluates and releases no candidate: the supervisor cannot observe an image a sandboxed build reports ([ADR 0024](adr/0024-a-build-is-accepted-only-on-bytes-the-supervisor-received.md)). The end-to-end lifecycle on Compose and the real smoke run (`make smoke`, written but not yet run) are not yet proven. All other profiles (Kubernetes, TOSE, Cloudflare, Vercel, Render, Railway) are experimental or unsupported until proven. The profile table is in brief ยง10; ADR [0001](adr/0001-three-zones-one-deployment.md) holds the invariant. + +Provider cost sources ([ADR 0027](adr/0027-the-providers-own-report-bounds-what-agents-report-spent.md)): reading Anthropic's Usage and Cost Analytics API and OpenAI's organization Costs API is experimental. Both readers are tested against fakes built from the published API references (`internal/budget/providercost/`), not yet against the live APIs; OAuth or subscription sign-ins have no billing figure and are not supported. diff --git a/docs/guides/operations.md b/docs/guides/operations.md index 9b26354..1df8795 100644 --- a/docs/guides/operations.md +++ b/docs/guides/operations.md @@ -102,7 +102,7 @@ The application's users send bug reports through the edge to control's public re ## State and budget -`sisf state bootstrap` prepares the state store (migrations, one role per zone, the budget record). `sisf up` does this for you. The budget mode default and its confirmation are in [ADR 0007](../adr/0007-budget-default-unlimited.md); code is in `internal/budget`. `factoryd dispatcher --run-estimate-micros N` is the amount each run sets aside from the budget when it is claimed; `sisf init --budget-cap` sets it from `--run-estimate` (default a fifth of the cap), and an unlimited budget leaves it at 0. A rollback reserves through the rollback reserve that ordinary runs cannot reach and is never blocked by an exhausted budget; its nominal cost is recorded in the ledger either way (`internal/supervisor/release/rollback_budget.go`). Usage an agent reports with tokens but no cost, as the Codex CLI does, is recorded as reported, with no cost. When the run's reservation is closed, the part of it that the run's booked costs did not cover is charged as unverified (`dispatcher.CloseReservationOfRun` in `internal/dispatcher/run_spend.go`). The booked costs, and whether some usage stated none, are read from the run's rows in the ledger recorded since its reservation was made, never from the dispatcher's record of the run, which the agent zone can rewrite; a run with no row in the ledger, with no record at all (also when the control zone stops it), or with a row of negative cost, is charged its whole reservation as unverified, and one with a row that states a cost of 0, with tokens or without, the part its booked costs do not cover; a run that books any positive cost, however small, is taken at its word, since the agent zone meters itself; on PostgreSQL the database itself dates every reservation and usage row a zone role inserts by the server's clock, refuses verified usage, and refuses agent usage that does not name a reservation of its own run (migration 13; see [ADR 0007](../adr/0007-budget-default-unlimited.md) for exactly what is enforced where); the `spend.reported_cost` that `runs.inspect` shows is that record's unverified figure and decides nothing. The record can only add a charge, for an attempt that reported nothing at all. With an unlimited budget and a run estimate of 0 nothing was reserved, so that usage is not counted. `budget.get` warns when some unverified usage states no cost, with tokens or without, and its `unpriced` total counts those rows by the same rule a run's close applies (`core.Usage.CostUnreported`). When a run stops, or QA passes or holds it, the factory closes the reservation that run's claim made, found from the run's ID (`budget.RunReservationID` in `internal/budget/gate.go`); the reservation named in the agent zone's run record is not trusted. A close that fails is tried again on every QA pass until it succeeds. One that fails five times with `NOT_FOUND`, `TAMPERED` or `INVALID_ARGUMENT`, which no retry changes, is recorded as `close-abandoned/` with its code and reason, reported once, and its reservation stays held until a person settles it (`cmd/supervisor/stages/run_close_due.go`). +`sisf state bootstrap` prepares the state store (migrations, one role per zone, the budget record). `sisf up` does this for you. The budget mode default and its confirmation are in [ADR 0007](../adr/0007-budget-default-unlimited.md); code is in `internal/budget`. `factoryd dispatcher --run-estimate-micros N` is the amount each run sets aside from the budget when it is claimed; `sisf init --budget-cap` sets it from `--run-estimate` (default a fifth of the cap), and an unlimited budget leaves it at 0. A rollback reserves through the rollback reserve that ordinary runs cannot reach and is never blocked by an exhausted budget; its nominal cost is recorded in the ledger either way (`internal/supervisor/release/rollback_budget.go`). Usage an agent reports with tokens but no cost, as the Codex CLI does, is recorded as reported, with no cost. When the run's reservation is closed, the part of it that the run's booked costs did not cover is charged as unverified (`dispatcher.CloseReservationOfRun` in `internal/dispatcher/run_spend.go`). The booked costs, and whether some usage stated none, are read from the run's rows in the ledger recorded since its reservation was made, never from the dispatcher's record of the run, which the agent zone can rewrite; a run with no row in the ledger, with no record at all (also when the control zone stops it), or with a row of negative cost, is charged its whole reservation as unverified, and one with a row that states a cost of 0, with tokens or without, the part its booked costs do not cover; a run that books any positive cost, however small, is taken at its word, since the agent zone meters itself; on PostgreSQL the database itself dates every reservation and usage row a zone role inserts by the server's clock, refuses verified usage, and refuses agent usage that does not name a reservation of its own run (migration 13; see [ADR 0007](../adr/0007-budget-default-unlimited.md) for exactly what is enforced where); the `spend.reported_cost` that `runs.inspect` shows is that record's unverified figure and decides nothing. The record can only add a charge, for an attempt that reported nothing at all. With an unlimited budget and a run estimate of 0 nothing was reserved, so that usage is not counted. `budget.get` warns when some unverified usage states no cost, with tokens or without, and its `unpriced` total counts those rows by the same rule a run's close applies (`core.Usage.CostUnreported`). When a run stops, or QA passes or holds it, the factory closes the reservation that run's claim made, found from the run's ID (`budget.RunReservationID` in `internal/budget/gate.go`); the reservation named in the agent zone's run record is not trusted. A close that fails is tried again on every QA pass until it succeeds. One that fails five times with `NOT_FOUND`, `TAMPERED` or `INVALID_ARGUMENT`, which no retry changes, is recorded as `close-abandoned/` with its code and reason, reported once, and its reservation stays held until a person settles it (`cmd/supervisor/stages/run_close_due.go`). Because the agent zone meters itself, a capped budget with a period can also be bounded by what Anthropic or OpenAI report the factory spent: `budget.set` with `provider_cost_sources`, and the control zone's environment holding `SISF_ANTHROPIC_ADMIN_KEY` with `SISF_ANTHROPIC_COST_WORKSPACE`, or `SISF_OPENAI_ADMIN_KEY` with `SISF_OPENAI_COST_PROJECT`. The control zone reads the figures every 15 minutes; a period counts as spent the larger of the agents' reports and the providers' figures, and a figure missing or read more than 2 hours ago holds new capped runs, never a rollback. `budget.get` shows it as `provider_spent_micros`. See [ADR 0027](../adr/0027-the-providers-own-report-bounds-what-agents-report-spent.md). ## Decision Layer diff --git a/docs/release-notes/v0.1.0-alpha.md b/docs/release-notes/v0.1.0-alpha.md index 83f9ccb..596ef5e 100644 --- a/docs/release-notes/v0.1.0-alpha.md +++ b/docs/release-notes/v0.1.0-alpha.md @@ -50,7 +50,7 @@ This is the first alpha of SISF, a self-improving software factory in one deploy - After a unit was killed rather than stopped, an agent CLI it started can outlive it without holding the run lock, so `sisf down -v` may delete a workspace under it; after a crash check that no agent process remains ([operations](../guides/operations.md#lifecycle)). On Linux the units of a killed `sisf up` are told to stop; elsewhere they keep running until `sisf stop`. - A flood that spends the report route's global hourly limit makes genuine reports get 429, and about 1,000 distinct sources can fill the report store ([threat model](../threat-model.md#public-input-that-reaches-github-tm-01-tm-13)). - A budget reservation whose close can never succeed is abandoned and stays held until a person settles it. -- Costs are unverified: the agent zone meters its own usage and no provider confirms a cost. A run that books no usage, a usage row of cost 0 or a negative cost is charged the part of its reservation its booked costs do not cover, but a compromised agent zone that books a tiny positive cost, down to one micro, has its run's reservation released for that ([ADR 0007](../adr/0007-budget-default-unlimited.md)). +- Costs are unverified: the agent zone meters its own usage and no provider confirms a cost. A run that books no usage, a usage row of cost 0 or a negative cost is charged the part of its reservation its booked costs do not cover, but a compromised agent zone that books a tiny positive cost, down to one micro, has its run's reservation released for that ([ADR 0007](../adr/0007-budget-default-unlimited.md)). A capped budget with a period can name Anthropic or OpenAI as a provider cost source: the control zone then reads what the provider reports the factory's own workspace or project spent, and that figure is the least the period counts as spent, so under-reporting is caught once the provider reports it, hours later; a figure missing or not read for 2 hours holds new capped runs but not a rollback. Both readers are tested against fakes only ([ADR 0027](../adr/0027-the-providers-own-report-bounds-what-agents-report-spent.md)). - No upgrade, backup or restore command exists; the [maintenance guide](../guides/maintenance.md) has the manual procedures. - A migration that is not backward compatible cannot be approved yet: no command passes the Owner's approval to the migrator, so a store that has migrations applied refuses such a migration with `APPROVAL_REQUIRED`. Migration 12 is one, so a state store from a build before this release cannot be upgraded in place ([#76](https://github.com/bestagentkits/sisf/issues/76), [ADR 0013](../adr/0013-schema-migration-on-self-update.md)). diff --git a/docs/threat-model.md b/docs/threat-model.md index 6341652..642805f 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -117,7 +117,7 @@ Accepted residuals: a flood that spends the global hourly limit makes genuine re ### Run records written by the agent zone (TM-12) -When a run stops, or QA passes or holds it, the factory closes the budget reservation found from the run's ID; a reservation named in the agent zone's run record is not trusted, so a forged run record can block its own issue but cannot close another run's reservation. Build evidence is taken only from what the supervisor observes of the sandboxed build: the exit status of the test and build phases, and the nonce-tagged lines of the report phase (`cmd/supervisor/stages/image_builders.go`). The supervisor's reason for a held release is shown to the Owner only. +When a run stops, or QA passes or holds it, the factory closes the budget reservation found from the run's ID; a reservation named in the agent zone's run record is not trusted, so a forged run record can block its own issue but cannot close another run's reservation. An agent zone that under-reports what its runs cost is bounded, for a capped budget that names a provider cost source, by the provider's own report of what the factory's workspace or project spent: the control zone reads it with an admin key no agent environment accepts and stores it where only the control zone writes, and the gate counts the larger of it and the agents' reports; a figure missing or not read for 2 hours holds new capped runs but not a rollback ([ADR 0027](adr/0027-the-providers-own-report-bounds-what-agents-report-spent.md)). Accepted residual: the provider's figure lags by hours, so runs claimed in that window are admitted on the agents' word; and the gate runs in the agent zone's dispatcher, so an agent zone taken over as a whole can skip it, as before, and the provider's figure in `budget.get` is then how the Owner sees the spending. Build evidence is taken only from what the supervisor observes of the sandboxed build: the exit status of the test and build phases, and the nonce-tagged lines of the report phase (`cmd/supervisor/stages/image_builders.go`). The supervisor's reason for a held release is shown to the Owner only. ### The synthetic suite (TM-15) diff --git a/internal/budget/actions.go b/internal/budget/actions.go index 38a08ec..d342ebf 100644 --- a/internal/budget/actions.go +++ b/internal/budget/actions.go @@ -3,6 +3,7 @@ package budget import ( "context" "encoding/json" + "slices" "github.com/bestagentkits/sisf/internal/actions" "github.com/bestagentkits/sisf/internal/dispatcher" @@ -30,7 +31,8 @@ const ( setInput = `{"type":"object","additionalProperties":false,"required":["mode"],"properties":{` + `"mode":{"enum":["unlimited","capped"]},"cap_micros":{"type":"integer","minimum":0},` + `"period":{"enum":["","day","week","month"]},"alert_threshold_micros":{"type":"integer","minimum":0},` + - `"rollback_reserve_micros":{"type":"integer","minimum":0},"provider_hard_cap":{"type":"boolean"}}}` + `"rollback_reserve_micros":{"type":"integer","minimum":0},"provider_hard_cap":{"type":"boolean"},` + + `"provider_cost_sources":{"type":"array","uniqueItems":true,"items":{"enum":["anthropic","openai"]}}}}` anyOutput = `{"type":"object"}` ) @@ -53,7 +55,7 @@ func Actions(cfg ActionsConfig) ([]core.Action, error) { Sensitivity: core.SensitivityRead, Scopes: []string{"budget:read"}, Roles: []core.Role{core.RoleOwner, core.RoleMaintainer, core.RoleViewer}, Input: actions.Schema(getInput), Output: actions.Schema(anyOutput)}, Handle: h.get}, - {Spec: core.ActionSpec{Name: ActionSet, Summary: "Change the budget mode, cap, alert threshold or rollback reserve; Owner only.", + {Spec: core.ActionSpec{Name: ActionSet, Summary: "Change the budget mode, cap, alert threshold, rollback reserve or provider cost sources; Owner only.", Sensitivity: core.SensitivitySensitive, Scopes: []string{"budget:write"}, Roles: []core.Role{core.RoleOwner}, StepUp: true, Input: actions.Schema(setInput), Output: actions.Schema(anyOutput)}, Handle: h.set}, }, nil @@ -122,6 +124,9 @@ func warnings(current Settings, found bool, next Settings) []string { case next.Mode == core.BudgetCapped && found && next.CapMicros > current.CapMicros: out = append(out, "Raises the spending cap.") } + if found && slices.ContainsFunc(current.ProviderCostSources, func(s string) bool { return !slices.Contains(next.ProviderCostSources, s) }) { + out = append(out, "Stops checking spending against a provider's own report: what an agent under-reports there is no longer caught.") + } if !next.ProviderHardCap { out = append(out, "The provider has no hard cap, so the budget is not a guarantee against charges.") } diff --git a/internal/budget/gate.go b/internal/budget/gate.go index e32a842..dc7c9c1 100644 --- a/internal/budget/gate.go +++ b/internal/budget/gate.go @@ -8,6 +8,7 @@ import ( "github.com/bestagentkits/sisf/internal/dispatcher" "github.com/bestagentkits/sisf/pkg/core" + "github.com/bestagentkits/sisf/pkg/state" ) // NoticeKind says why the Owner is notified. @@ -138,11 +139,24 @@ func (g *Gate) fits(ctx context.Context, ledger core.BudgetLedger, s Settings, e if err != nil { return err } + kv, ok := ledger.(state.KV) + if !ok { + return core.NewError(core.CodeUnavailable, "the claim transaction cannot read the provider spend") + } + floor, err := providerFloor(ctx, kv, s, now) + switch { + case rollback && core.HasCode(err, core.CodeBudgetExceeded): + // A missing or stale provider figure never stops a rollback, + // which is still held to the agents' reports and the cap. + floor = 0 + case err != nil: + return err + } limit := s.CapMicros - s.RollbackReserveMicros if rollback { limit = s.CapMicros } - if addMicros(usedIn(totals), estimate) > limit { + if addMicros(usedWith(totals, floor), estimate) > limit { return core.NewError(core.CodeBudgetExceeded, "the reservation would pass the budget cap of the period", core.NextAction{Action: "budget.get", Description: "see what is spent and what remains"}) } diff --git a/internal/budget/money_sum.go b/internal/budget/money_sum.go index b4fe3e1..6119d4f 100644 --- a/internal/budget/money_sum.go +++ b/internal/budget/money_sum.go @@ -25,8 +25,3 @@ func addMicros(amounts ...core.Micros) core.Micros { } return sum } - -// usedIn is what a period holds and has spent. -func usedIn(t core.BudgetTotals) core.Micros { - return addMicros(t.Reserved, t.SpentVerified, t.SpentUnverified) -} diff --git a/internal/budget/provider_spend.go b/internal/budget/provider_spend.go new file mode 100644 index 0000000..69a73f4 --- /dev/null +++ b/internal/budget/provider_spend.go @@ -0,0 +1,108 @@ +package budget + +import ( + "context" + "encoding/json" + "time" + + "github.com/bestagentkits/sisf/pkg/core" + "github.com/bestagentkits/sisf/pkg/state" +) + +// ProviderSpendKey is where the control zone keeps what the providers +// report was spent, beside the budget settings. Only the control zone +// writes the namespace; the agent zone, whose dispatcher consults the gate, +// reads it. An agent therefore cannot lower the figure that bounds what its +// own reports may claim. +const ProviderSpendKey = "provider_spend" + +// ProviderSpendMaxAge is how long after the control zone last read the +// providers' figures they still bound new runs. Past it the control zone is +// taken to have stopped reading them, and capped runs wait. It is the age +// of the read, not of the provider's data, which lags by hours: a bound on +// that lag would hold the factory for good. +const ProviderSpendMaxAge = 2 * time.Hour + +// ProviderSpend is what the providers report the factory spent in a budget +// period, as the control zone last read it. +type ProviderSpend struct { + // PeriodStart is the start of the budget period the figures cover. + PeriodStart time.Time `json:"period_start"` + // FetchedAt is when the control zone read the figures, by its clock. + FetchedAt time.Time `json:"fetched_at"` + // Sources holds each provider's figure, by provider name. + Sources map[string]SourceSpend `json:"sources"` +} + +// SourceSpend is one provider's report of what was spent since the start +// of the period. +type SourceSpend struct { + SpentMicros core.Micros `json:"spent_micros"` + // CoveredUntil is how far the provider's data reaches; zero when the + // provider does not say. Spending after it is not in SpentMicros yet. + CoveredUntil time.Time `json:"covered_until,omitzero"` +} + +// LoadProviderSpend reads the stored figures; found is false when none were +// stored. An unreadable document is TAMPERED. +func LoadProviderSpend(ctx context.Context, kv state.KV) (p ProviderSpend, version int64, found bool, err error) { + entry, err := kv.GetKV(ctx, SettingsNamespace, ProviderSpendKey) + if core.HasCode(err, core.CodeNotFound) { + return ProviderSpend{}, 0, false, nil + } + if err != nil { + return ProviderSpend{}, 0, false, err + } + if err := json.Unmarshal(entry.Value, &p); err != nil { + return ProviderSpend{}, 0, false, core.NewError(core.CodeTampered, "the stored provider spend cannot be read") + } + return p, entry.Version, true, nil +} + +// providerFloor returns the least the current period counts as spent: the +// sum of the figures of the providers the settings name. It holds, with +// BUDGET_EXCEEDED, when a named provider's figure is missing, damaged or +// was read longer than ProviderSpendMaxAge ago, since what the agents under-report +// there would go unseen. Figures read for an earlier period do not count +// and do not hold: at the start of a period the provider has not reported +// it yet, which the fresh read of the earlier period shows. +func providerFloor(ctx context.Context, kv state.KV, s Settings, now time.Time) (core.Micros, error) { + if len(s.ProviderCostSources) == 0 { + return 0, nil + } + held := func(why string) error { + return core.NewError(core.CodeBudgetExceeded, why+"; capped runs wait until the control zone reads the provider's spend again", + core.NextAction{Action: "budget.get", Description: "see which provider's spend is missing"}) + } + p, _, found, err := LoadProviderSpend(ctx, kv) + switch { + case core.HasCode(err, core.CodeTampered): + // The control zone replaces a damaged figure on its next read. + return 0, held("the stored provider spend cannot be read") + case err != nil: + return 0, err + case !found: + return 0, held("no provider spend has been read yet") + case p.FetchedAt.After(now) || now.Sub(p.FetchedAt) > ProviderSpendMaxAge: + return 0, held("the provider spend was last read at " + p.FetchedAt.UTC().Format(time.RFC3339)) + } + period := s.Period.Start(now) + var floor core.Micros + for _, source := range s.ProviderCostSources { + spend, ok := p.Sources[source] + if !ok { + return 0, held("the spend of " + source + " was not read") + } + if p.PeriodStart.Equal(period) { + floor = addMicros(floor, spend.SpentMicros) + } + } + return floor, nil +} + +// usedWith is what a period holds and has spent when the providers report +// at least floor spent: the agents' reports count only where they reach +// beyond it. +func usedWith(t core.BudgetTotals, floor core.Micros) core.Micros { + return addMicros(t.Reserved, max(addMicros(t.SpentVerified, t.SpentUnverified), floor)) +} diff --git a/internal/budget/provider_spend_refresh.go b/internal/budget/provider_spend_refresh.go new file mode 100644 index 0000000..3209d3c --- /dev/null +++ b/internal/budget/provider_spend_refresh.go @@ -0,0 +1,115 @@ +package budget + +import ( + "context" + "encoding/json" + "errors" + "time" + + "github.com/bestagentkits/sisf/pkg/core" + "github.com/bestagentkits/sisf/pkg/state" +) + +// CostSource reads what a provider reports was spent. It runs in the +// control zone, with a credential no agent holds. +type CostSource interface { + // Spent returns what the provider reports was spent from since until + // now, and how far its data reaches (zero when it does not say). + Spent(ctx context.Context, since time.Time) (spent core.Micros, coveredUntil time.Time, err error) +} + +// ProviderSpendEvery is how often the control zone reads the providers' +// figures. The providers refresh theirs every few hours, and it stays well +// inside ProviderSpendMaxAge, so one failed read does not hold runs. +const ProviderSpendEvery = 15 * time.Minute + +// ProviderSpendRetry is how long after a failed read the providers are +// asked again. The control pass runs every second; without it, an outage +// or a rate limit would be met with a request each second. +const ProviderSpendRetry = time.Minute + +// ProviderSpendRefresher reads the spend of the providers the budget +// settings name and stores it for the gate. A provider the settings name +// that has no source here, as when its credential is not configured, is +// not read: its figure grows stale and capped runs wait, which is the safe +// side of a configuration gap. +type ProviderSpendRefresher struct { + Store Store + Sources map[string]CostSource + Clock core.Clock + + // failedAt is when the last read failed; zero after a success. + failedAt time.Time +} + +// Refresh reads the figures when the stored ones are older than +// ProviderSpendEvery or cover another period, and stores what it read. A +// provider that cannot be read keeps the rest from being stored, so the +// stored figures always hold every named provider at one instant; the +// next attempt waits ProviderSpendRetry. It is not safe for concurrent use. +func (r *ProviderSpendRefresher) Refresh(ctx context.Context) error { + var ( + settings Settings + version int64 + due bool + ) + now := r.Clock.Now() + if !r.failedAt.IsZero() && now.Sub(r.failedAt) < ProviderSpendRetry && !now.Before(r.failedAt) { + return nil + } + err := r.Store.View(ctx, func(ctx context.Context, l Ledger) error { + s, _, found, err := loadSettings(ctx, l) + if err != nil || !found || len(s.ProviderCostSources) == 0 { + return err + } + settings = s + p, v, have, err := LoadProviderSpend(ctx, l) + switch { + case core.HasCode(err, core.CodeTampered): + // A damaged figure is replaced by the next read. + entry, err := l.GetKV(ctx, SettingsNamespace, ProviderSpendKey) + if err != nil { + return err + } + version, due = entry.Version, true + return nil + case err != nil: + return err + } + version = v + due = !have || !p.PeriodStart.Equal(s.Period.Start(now)) || p.FetchedAt.After(now) || now.Sub(p.FetchedAt) >= ProviderSpendEvery + return nil + }) + if err != nil || !due { + return err + } + period := settings.Period.Start(now) + next := ProviderSpend{PeriodStart: period, FetchedAt: now, Sources: map[string]SourceSpend{}} + var failures []error + for _, name := range settings.ProviderCostSources { + source, ok := r.Sources[name] + if !ok { + failures = append(failures, core.NewError(core.CodeUnavailable, "no credential is configured to read the spend of "+name)) + continue + } + spent, covered, err := source.Spent(ctx, period) + if err != nil { + failures = append(failures, err) + continue + } + next.Sources[name] = SourceSpend{SpentMicros: spent, CoveredUntil: covered} + } + if len(failures) > 0 { + r.failedAt = now + return errors.Join(failures...) + } + r.failedAt = time.Time{} + raw, err := json.Marshal(next) + if err != nil { + return core.NewError(core.CodeInternal, "the provider spend cannot be encoded").WithCause(err) + } + return r.Store.Update(ctx, func(ctx context.Context, l Ledger) error { + _, err := l.PutKV(ctx, state.KVEntry{Namespace: SettingsNamespace, Key: ProviderSpendKey, Value: raw, Version: version}) + return err + }) +} diff --git a/internal/budget/provider_spend_store_test.go b/internal/budget/provider_spend_store_test.go new file mode 100644 index 0000000..872add8 --- /dev/null +++ b/internal/budget/provider_spend_store_test.go @@ -0,0 +1,261 @@ +package budget_test + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "sync" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgconn" + + "github.com/bestagentkits/sisf/internal/budget" + "github.com/bestagentkits/sisf/internal/dispatcher" + "github.com/bestagentkits/sisf/pkg/core" + "github.com/bestagentkits/sisf/pkg/state" + "github.com/bestagentkits/sisf/pkg/state/sqlstore" + "github.com/bestagentkits/sisf/pkg/state/sqlstore/sqlstoretest" +) + +// fakeSource is a provider's report of spending, as a test sets it. +type fakeSource struct { + mu sync.Mutex + spent core.Micros + err error + since []time.Time +} + +func (f *fakeSource) Spent(_ context.Context, since time.Time) (core.Micros, time.Time, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.since = append(f.since, since) + return f.spent, since.Add(time.Hour), f.err +} + +func (f *fakeSource) reads() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.since) +} + +// providerStore is a capped budget checked against the named providers, +// as the control zone stores it, and the stores of the control and agent +// zones; on PostgreSQL the agent connects with its own login role. +func providerStore(t *testing.T, db *sqlstoretest.Database, sources ...string) (control, agent *sqlstore.Store, agentDSN string) { + t.Helper() + ctx := context.Background() + control = db.Open(t, core.ZoneControl) + agent = db.Open(t, core.ZoneAgent) + if db.Dialect == sqlstore.DialectPostgres { + agentDSN = db.ZoneLogins(t).DSN[core.ZoneAgent] + agent = db.OpenWith(t, agentDSN, core.ZoneAgent) + } + s := capped(10*million, million) + s.Period, s.ProviderCostSources = budget.PeriodDay, sources + for key, value := range map[string]any{ + dispatcher.ConfirmationKey: dispatcher.BudgetConfirmation{Mode: core.BudgetCapped, AlertOff: true, ConfirmedAt: db.Clock.Now().Add(-time.Hour)}, + budget.SettingsKey: s, + } { + raw, _ := json.Marshal(value) + if err := control.Update(ctx, func(ctx context.Context, tx state.Tx) error { + _, err := tx.PutKV(ctx, state.KVEntry{Namespace: budget.SettingsNamespace, Key: key, Value: raw}) + return err + }); err != nil { + t.Fatal(err) + } + } + return control, agent, agentDSN +} + +func reserveIn(t *testing.T, db *sqlstoretest.Database, store *sqlstore.Store, n int, estimate core.Micros) error { + t.Helper() + gate := budget.NewGate(budget.Config{Clock: db.Clock}) + req := request(n, estimate) + req.FactoryID = sqlstoretest.Factory + return store.Update(context.Background(), func(ctx context.Context, tx state.Tx) error { + _, err := gate.Reserve(ctx, tx, req) + return err + }) +} + +// The control zone reads the provider's spend and stores it where the +// agent zone's gate reads it; the agent zone cannot write it, through the +// store or, on PostgreSQL, over plain SQL as its own role, so it cannot +// lower the figure that bounds what its reports may claim. +func TestOnlyTheControlZoneWritesTheProviderSpend(t *testing.T) { + t.Parallel() + sqlstoretest.Run(t, func(t *testing.T, db *sqlstoretest.Database) { + ctx := context.Background() + control, agent, agentDSN := providerStore(t, db, budget.ProviderAnthropic) + source := &fakeSource{spent: 9 * million} + refresher := budget.ProviderSpendRefresher{Store: budget.StateStore(control), + Sources: map[string]budget.CostSource{budget.ProviderAnthropic: source}, Clock: db.Clock} + if err := reserveIn(t, db, agent, 1, million); !core.HasCode(err, core.CodeBudgetExceeded) { + t.Fatalf("a run admitted before the provider's spend was read: %v", err) + } + if err := refresher.Refresh(ctx); err != nil { + t.Fatal(err) + } + day := budget.PeriodDay.Start(db.Clock.Now()) + if len(source.since) != 1 || !source.since[0].Equal(day) { + t.Fatalf("the provider was asked for %v, want the spend since %v", source.since, day) + } + if err := reserveIn(t, db, agent, 2, million); !core.HasCode(err, core.CodeBudgetExceeded) { + t.Fatalf("a run admitted past the provider's figure: %v", err) + } + + forged, _ := json.Marshal(budget.ProviderSpend{PeriodStart: day, FetchedAt: db.Clock.Now(), + Sources: map[string]budget.SourceSpend{budget.ProviderAnthropic: {}}}) + err := agent.Update(ctx, func(ctx context.Context, tx state.Tx) error { + entry, err := tx.GetKV(ctx, budget.SettingsNamespace, budget.ProviderSpendKey) + if err != nil { + return err + } + entry.Value = forged + _, err = tx.PutKV(ctx, entry) + return err + }) + if !core.HasCode(err, core.CodePermissionDenied) { + t.Fatalf("the agent zone rewrote the provider spend: %v", err) + } + if db.Dialect != sqlstore.DialectPostgres { + return + } + raw, err := sql.Open("pgx", agentDSN) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = raw.Close() }) + for _, statement := range []string{ + `UPDATE kv SET entry_value = '\x7b7d' WHERE namespace = 'install' AND entry_key = 'provider_spend'`, + `DELETE FROM kv WHERE namespace = 'install' AND entry_key = 'provider_spend'`, + `INSERT INTO kv (factory_id, namespace, entry_key, entry_value, version, updated_at) VALUES ('other', 'install', 'provider_spend', '\x7b7d', 1, 0)`, + } { + res, err := raw.ExecContext(ctx, statement) + var pg *pgconn.PgError + if errors.As(err, &pg) && pg.Code == "42501" { + continue + } + if err == nil { + // A row policy hides the rows instead of refusing. + if n, _ := res.RowsAffected(); n == 0 { + continue + } + } + t.Errorf("the agent role must not change the provider spend with %q: %v", statement, err) + } + if err := reserveIn(t, db, agent, 3, million); !core.HasCode(err, core.CodeBudgetExceeded) { + t.Fatalf("the provider's figure was lowered: %v", err) + } + }) +} + +// The figures are read again only every ProviderSpendEvery, or at once in a +// new period. A provider that cannot be read, or has no credential, stores +// nothing, so its figure grows stale and holds runs: a configuration gap +// fails closed. +func TestTheProviderSpendIsReadOnScheduleAndAFailureStoresNothing(t *testing.T) { + t.Parallel() + sqlstoretest.Run(t, func(t *testing.T, db *sqlstoretest.Database) { + ctx := context.Background() + control, agent, _ := providerStore(t, db, budget.ProviderAnthropic, budget.ProviderOpenAI) + anthropic, openai := &fakeSource{spent: million}, &fakeSource{spent: million} + refresher := budget.ProviderSpendRefresher{Store: budget.StateStore(control), Clock: db.Clock, + Sources: map[string]budget.CostSource{budget.ProviderAnthropic: anthropic, budget.ProviderOpenAI: openai}} + if err := refresher.Refresh(ctx); err != nil { + t.Fatal(err) + } + db.Clock.Advance(budget.ProviderSpendEvery - time.Second) + if err := refresher.Refresh(ctx); err != nil || anthropic.reads() != 1 { + t.Fatalf("read again too soon: %d reads, %v", anthropic.reads(), err) + } + db.Clock.Advance(time.Second) + if err := refresher.Refresh(ctx); err != nil || anthropic.reads() != 2 { + t.Fatalf("not read again on schedule: %d reads, %v", anthropic.reads(), err) + } + if err := reserveIn(t, db, agent, 1, million); err != nil { + t.Fatalf("a run within the providers' figures: %v", err) + } + + // One provider fails: nothing is stored, and once the last read is + // too old, runs wait while a rollback still runs. + openai.err = core.NewError(core.CodeUnavailable, "the provider is down") + for range 9 { + db.Clock.Advance(budget.ProviderSpendEvery) + if err := refresher.Refresh(ctx); !core.HasCode(err, core.CodeUnavailable) { + t.Fatalf("a failed read: %v", err) + } + } + // After a failure the providers are not asked again at once: the + // control pass runs every second. + reads := openai.reads() + db.Clock.Advance(budget.ProviderSpendRetry - time.Second) + if err := refresher.Refresh(ctx); err != nil || openai.reads() != reads { + t.Fatalf("asked again %d times within the retry delay: %v", openai.reads()-reads, err) + } + db.Clock.Advance(time.Second) + if err := refresher.Refresh(ctx); !core.HasCode(err, core.CodeUnavailable) || openai.reads() != reads+1 { + t.Fatalf("not asked again after the retry delay: %d reads, %v", openai.reads()-reads, err) + } + if err := reserveIn(t, db, agent, 2, million); !core.HasCode(err, core.CodeBudgetExceeded) { + t.Fatalf("a run admitted on a stale provider figure: %v", err) + } + gate := budget.NewGate(budget.Config{Clock: db.Clock}) + rollback := request(3, million) + rollback.FactoryID = sqlstoretest.Factory + if err := agent.Update(ctx, func(ctx context.Context, tx state.Tx) error { + _, err := gate.ReserveRollback(ctx, tx, rollback) + return err + }); err != nil { + t.Fatalf("a rollback held by a stale provider figure: %v", err) + } + + // A provider without a credential is not read and stores nothing. + delete(refresher.Sources, budget.ProviderOpenAI) + db.Clock.Advance(budget.ProviderSpendRetry) + if err := refresher.Refresh(ctx); !core.HasCode(err, core.CodeUnavailable) { + t.Fatalf("a provider without a credential: %v", err) + } + if err := reserveIn(t, db, agent, 4, million); !core.HasCode(err, core.CodeBudgetExceeded) { + t.Fatalf("a run admitted without one provider's figure: %v", err) + } + }) +} + +// A damaged figure holds capped runs but not a rollback, and is replaced +// by the next read instead of blocking it. +func TestADamagedProviderSpendIsReadAgain(t *testing.T) { + t.Parallel() + sqlstoretest.Run(t, func(t *testing.T, db *sqlstoretest.Database) { + ctx := context.Background() + control, agent, _ := providerStore(t, db, budget.ProviderAnthropic) + if err := control.Update(ctx, func(ctx context.Context, tx state.Tx) error { + _, err := tx.PutKV(ctx, state.KVEntry{Namespace: budget.SettingsNamespace, Key: budget.ProviderSpendKey, Value: []byte("{")}) + return err + }); err != nil { + t.Fatal(err) + } + if err := reserveIn(t, db, agent, 1, million); !core.HasCode(err, core.CodeBudgetExceeded) { + t.Fatalf("a run admitted on a damaged provider figure: %v", err) + } + gate := budget.NewGate(budget.Config{Clock: db.Clock}) + rollback := request(3, million) + rollback.FactoryID = sqlstoretest.Factory + if err := agent.Update(ctx, func(ctx context.Context, tx state.Tx) error { + _, err := gate.ReserveRollback(ctx, tx, rollback) + return err + }); err != nil { + t.Fatalf("a rollback held by a damaged provider figure: %v", err) + } + refresher := budget.ProviderSpendRefresher{Store: budget.StateStore(control), Clock: db.Clock, + Sources: map[string]budget.CostSource{budget.ProviderAnthropic: &fakeSource{}}} + if err := refresher.Refresh(ctx); err != nil { + t.Fatal(err) + } + if err := reserveIn(t, db, agent, 2, million); err != nil { + t.Fatalf("a run after the damaged figure was read again: %v", err) + } + }) +} diff --git a/internal/budget/provider_spend_test.go b/internal/budget/provider_spend_test.go new file mode 100644 index 0000000..80318be --- /dev/null +++ b/internal/budget/provider_spend_test.go @@ -0,0 +1,174 @@ +package budget_test + +import ( + "context" + "testing" + "time" + + "github.com/bestagentkits/sisf/internal/budget" + "github.com/bestagentkits/sisf/internal/dispatcher" + "github.com/bestagentkits/sisf/pkg/core" +) + +// day is the start of the budget day that holds start. +var day = time.Date(start.Year(), start.Month(), start.Day(), 0, 0, 0, 0, time.UTC) + +// checkedAgainst is a daily cap of 10 that the provider's own report of +// spending bounds. +func checkedAgainst(sources ...string) budget.Settings { + s := capped(10*million, million) + s.Period, s.ProviderCostSources = budget.PeriodDay, sources + return s +} + +// providerReports stores what the control zone read from the providers. +func (e *env) providerReports(period, fetched time.Time, spent map[string]core.Micros) { + e.t.Helper() + p := budget.ProviderSpend{PeriodStart: period, FetchedAt: fetched, Sources: map[string]budget.SourceSpend{}} + for name, micros := range spent { + p.Sources[name] = budget.SourceSpend{SpentMicros: micros, CoveredUntil: fetched.Add(-4 * time.Hour)} + } + e.put(budget.ProviderSpendKey, p) +} + +// agentReports books cost as reported by an agent today. +func (e *env) agentReports(n int, cost core.Micros) { + e.t.Helper() + u := usage(n, cost, false) + u.At = start + if err := e.ledger.AppendUsage(context.Background(), u); err != nil { + e.t.Fatal(err) + } +} + +// An agent zone that under-reports what its runs cost is caught once the +// provider reports more: the provider's figure is what the period counts as +// spent, so the cap stops runs the agents' own reports would still admit. +func TestTheProvidersReportBoundsWhatTheAgentsReport(t *testing.T) { + t.Parallel() + e := newEnv(t) + e.confirmCapped() + e.configure(checkedAgainst(budget.ProviderAnthropic)) + e.agentReports(1, million) + e.providerReports(day, start.Add(-time.Minute), map[string]core.Micros{budget.ProviderAnthropic: 8 * million}) + + // 8 spent and a reserve of 1 leave 1 to reserve, not the 8 the agents' + // reports would leave. + _, err := e.reserve(2, 2*million) + wantCode(t, err, core.CodeBudgetExceeded) + e.mustReserve(3, million) + + st := e.readStatus() + if st.ProviderSpentMicros == nil || *st.ProviderSpentMicros != 8*million { + t.Fatalf("the provider spend shown: %v, want 8", st.ProviderSpentMicros) + } + if st.SpentUnverifiedMicros != million { + t.Errorf("the agents' reports shown as %d, want them kept apart from the provider's figure", st.SpentUnverifiedMicros) + } + if st.AvailableMicros == nil || *st.AvailableMicros != 0 { + t.Errorf("available: %v, want 0 after the reservation", st.AvailableMicros) + } + if !warned(st, "under-report") { + t.Errorf("no warning that the provider reports more than the agents: %v", st.Warnings) + } +} + +// The agents' reports still count where they reach beyond the provider's +// figure, which lags by hours. +func TestTheAgentsReportsCountBeyondALaggingProviderFigure(t *testing.T) { + t.Parallel() + e := newEnv(t) + e.confirmCapped() + e.configure(checkedAgainst(budget.ProviderAnthropic, budget.ProviderOpenAI)) + e.agentReports(1, 7*million) + e.providerReports(day, start.Add(-time.Minute), map[string]core.Micros{budget.ProviderAnthropic: million, budget.ProviderOpenAI: million}) + _, err := e.reserve(2, 3*million) + wantCode(t, err, core.CodeBudgetExceeded) + e.mustReserve(3, 2*million) + if st := e.readStatus(); warned(st, "under-report") { + t.Errorf("a provider figure below the agents' reports was warned about: %v", st.Warnings) + } +} + +// A named provider whose figure is missing, partial, stale or dated in the +// future holds capped runs, since what the agents under-report there would +// go unseen; a rollback still runs, held to the agents' reports and the cap. +func TestAMissingOrStaleProviderFigureHoldsRunsButNotARollback(t *testing.T) { + t.Parallel() + cases := map[string]func(e *env){ + "never read": func(*env) {}, + "read too long ago": func(e *env) { + e.providerReports(day, start.Add(-budget.ProviderSpendMaxAge-time.Second), map[string]core.Micros{budget.ProviderAnthropic: 0}) + }, + "read in the future": func(e *env) { + e.providerReports(day, start.Add(time.Minute), map[string]core.Micros{budget.ProviderAnthropic: 0}) + }, + "another provider read": func(e *env) { + e.providerReports(day, start.Add(-time.Minute), map[string]core.Micros{budget.ProviderOpenAI: 0}) + }, + } + for name, setup := range cases { + t.Run(name, func(t *testing.T) { + t.Parallel() + e := newEnv(t) + e.confirmCapped() + e.configure(checkedAgainst(budget.ProviderAnthropic)) + setup(e) + _, err := e.reserve(1, million) + wantCode(t, err, core.CodeBudgetExceeded) + if _, err := e.gate.ReserveRollback(context.Background(), e.ledger, request(2, million)); err != nil { + t.Fatalf("a rollback was held by the provider figure: %v", err) + } + if st := e.readStatus(); !warned(st, "held") || st.ProviderSpentMicros != nil { + t.Errorf("the status of a held budget: %+v", st) + } + }) + } +} + +// At the start of a period the provider has reported nothing of it yet: a +// fresh read of the period before neither counts nor holds runs. +func TestAFigureOfTheLastPeriodNeitherCountsNorHolds(t *testing.T) { + t.Parallel() + e := newEnv(t) + e.confirmCapped() + e.configure(checkedAgainst(budget.ProviderAnthropic)) + e.providerReports(day.AddDate(0, 0, -1), start.Add(-time.Minute), map[string]core.Micros{budget.ProviderAnthropic: 9 * million}) + e.mustReserve(1, 8*million) +} + +// Without a named provider the gate reads no provider figure at all. +func TestNoProviderNamedReadsNoFigure(t *testing.T) { + t.Parallel() + e := newEnv(t) + e.confirmCapped() + s := checkedAgainst() + e.configure(s) + e.providerReports(day, start.Add(-time.Minute), map[string]core.Micros{budget.ProviderAnthropic: 9 * million}) + e.mustReserve(1, 8*million) +} + +func TestProviderCostSourcesNeedACapAndAPeriod(t *testing.T) { + t.Parallel() + bad := map[string]budget.Settings{ + "unlimited": {Mode: core.BudgetUnlimited, ProviderCostSources: []string{budget.ProviderAnthropic}}, + "no period": {Mode: core.BudgetCapped, CapMicros: million, ProviderCostSources: []string{budget.ProviderAnthropic}}, + "unknown": {Mode: core.BudgetCapped, CapMicros: million, Period: budget.PeriodDay, ProviderCostSources: []string{"acme"}}, + "named twice": {Mode: core.BudgetCapped, CapMicros: million, Period: budget.PeriodDay, ProviderCostSources: []string{"openai", "openai"}}, + "empty name": {Mode: core.BudgetCapped, CapMicros: million, Period: budget.PeriodDay, ProviderCostSources: []string{""}}, + } + for name, s := range bad { + if err := s.Validate(); !core.HasCode(err, core.CodeInvalidArgument) { + t.Errorf("%s: %v, want INVALID_ARGUMENT", name, err) + } + } + if err := checkedAgainst(budget.ProviderAnthropic, budget.ProviderOpenAI).Validate(); err != nil { + t.Errorf("a daily cap checked against both providers: %v", err) + } +} + +// confirmCapped confirms a capped budget at install, an hour before start. +func (e *env) confirmCapped() { + e.t.Helper() + e.confirm(dispatcher.BudgetConfirmation{Mode: core.BudgetCapped, AlertOff: true, ConfirmedAt: start.Add(-time.Hour)}) +} diff --git a/internal/budget/providercost/anthropic_cost_source.go b/internal/budget/providercost/anthropic_cost_source.go new file mode 100644 index 0000000..a7b41b7 --- /dev/null +++ b/internal/budget/providercost/anthropic_cost_source.go @@ -0,0 +1,112 @@ +package providercost + +import ( + "context" + "net/http" + "net/url" + "strings" + "time" + + "github.com/bestagentkits/sisf/pkg/core" +) + +// AnthropicURL is the Claude API. +const AnthropicURL = "https://api.anthropic.com" + +// Anthropic reads the cost an Anthropic workspace was charged, from the +// Usage and Cost Analytics API (GET /v1/organizations/analytics/cost), +// which needs an Admin API key. The figure is limited to one workspace that +// the factory alone uses, so spending of other work there is not taken for +// the factory's. +type Anthropic struct { + // BaseURL is the API's address; empty means AnthropicURL. + BaseURL string + // AdminKey is an Admin API key of the organization. + AdminKey core.SecretValue + // WorkspaceID is the workspace the factory's runs are charged to. + WorkspaceID string + HTTP *http.Client +} + +// anthropicCostReport is the part of the answer that is read. Amounts are +// in cents, as decimal strings with fractions. +type anthropicCostReport struct { + Data []struct { + Cost struct { + Amount string `json:"amount"` + Currency string `json:"currency"` + } `json:"cost"` + } `json:"data"` + DataRefreshedAt *time.Time `json:"data_refreshed_at"` + HasMore bool `json:"has_more"` + NextPage *string `json:"next_page"` +} + +// microsPerCent converts the API's cents to micros of a dollar. +const microsPerCent = 10_000 + +// Spent returns the workspace's cost from since to now, after discounts and +// before credits, and the time the provider's data was refreshed. The API +// covers at most 31 days from since, which holds a month. +func (a Anthropic) Spent(ctx context.Context, since time.Time) (core.Micros, time.Time, error) { + if a.AdminKey.IsZero() || a.WorkspaceID == "" { + return 0, time.Time{}, core.NewError(core.CodeInvalidArgument, "reading Anthropic's cost needs an admin key and the factory's workspace") + } + for attempt := 0; ; attempt++ { + spent, covered, err := a.read(ctx, since) + if err == errExpiredCursor && attempt == 0 { + continue + } + return spent, covered, err + } +} + +func (a Anthropic) read(ctx context.Context, since time.Time) (core.Micros, time.Time, error) { + base := strings.TrimSuffix(a.BaseURL, "/") + if base == "" { + base = AnthropicURL + } + var ( + spent core.Micros + covered time.Time + page string + ) + for range maxPages { + q := url.Values{} + q.Set("starting_at", since.UTC().Format(time.RFC3339)) + q.Set("workspace_ids[]", a.WorkspaceID) + q.Set("limit", "1000") + if page != "" { + q.Set("page", page) + } + req, err := http.NewRequest(http.MethodGet, base+"/v1/organizations/analytics/cost?"+q.Encode(), nil) + if err != nil { + return 0, time.Time{}, core.NewError(core.CodeInvalidArgument, "the Anthropic API address is not valid").WithCause(err) + } + req.Header.Set("x-api-key", string(a.AdminKey.Reveal())) + req.Header.Set("anthropic-version", "2023-06-01") + req.Header.Set("anthropic-beta", "analytics-usage-cost-2026-08-24") + var report anthropicCostReport + if err := getJSON(ctx, a.HTTP, req, "Anthropic", &report); err != nil { + return 0, time.Time{}, err + } + for _, row := range report.Data { + if row.Cost.Currency != "USD" { + return 0, time.Time{}, core.NewError(core.CodeNotSupported, "Anthropic reported a cost in "+row.Cost.Currency+", not USD") + } + m, err := micros(row.Cost.Amount, microsPerCent) + if err != nil { + return 0, time.Time{}, err + } + spent = add(spent, m) + } + if report.DataRefreshedAt != nil && (covered.IsZero() || report.DataRefreshedAt.Before(covered)) { + covered = report.DataRefreshedAt.UTC() + } + if !report.HasMore || report.NextPage == nil || *report.NextPage == "" { + return spent, covered, nil + } + page = *report.NextPage + } + return 0, time.Time{}, core.NewError(core.CodeUnavailable, "Anthropic's cost report has more pages than expected") +} diff --git a/internal/budget/providercost/fetch_json.go b/internal/budget/providercost/fetch_json.go new file mode 100644 index 0000000..0612f57 --- /dev/null +++ b/internal/budget/providercost/fetch_json.go @@ -0,0 +1,65 @@ +package providercost + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "time" + + "github.com/bestagentkits/sisf/pkg/core" +) + +// maxResponse bounds a provider's answer; a cost report is a few rows. +const maxResponse = 4 << 20 + +// maxPages bounds how many pages one read follows. +const maxPages = 50 + +// defaultTimeout bounds one request when the caller gives no client. +const defaultTimeout = 30 * time.Second + +// errExpiredCursor is a page cursor the provider no longer accepts; the +// read starts again from the first page. +var errExpiredCursor = core.NewError(core.CodeConflict, "the provider's page cursor expired") + +// getJSON sends req and decodes a successful answer into out. The +// provider's answer is data: only its status and the fields out names are +// read, and an error never quotes its body, which may echo the request. +func getJSON(ctx context.Context, client *http.Client, req *http.Request, provider string, out any) error { + c := http.Client{Timeout: defaultTimeout} + if client != nil { + c = *client + } + // A redirect would carry the admin key, sent in a header of the + // provider's own, to wherever it points; none is followed. + c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + resp, err := c.Do(req.WithContext(ctx)) + if err != nil { + return core.NewError(core.CodeUnavailable, provider+" did not answer the cost report").WithCause(err) + } + defer func() { _ = resp.Body.Close() }() + body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponse+1)) + switch { + case err != nil: + return core.NewError(core.CodeUnavailable, provider+"'s cost report could not be read").WithCause(err) + case len(body) > maxResponse: + return core.NewError(core.CodeUnavailable, provider+"'s cost report is larger than expected") + } + status := fmt.Sprintf("%s answered %d to the cost report", provider, resp.StatusCode) + switch { + case resp.StatusCode == http.StatusGone: + return errExpiredCursor + case resp.StatusCode == http.StatusUnauthorized: + return core.NewError(core.CodeUnauthenticated, status+"; check the admin key") + case resp.StatusCode == http.StatusForbidden: + return core.NewError(core.CodePermissionDenied, status+"; the key may not read costs") + case resp.StatusCode < 200 || resp.StatusCode > 299: + return core.NewError(core.CodeUnavailable, status) + } + if err := json.Unmarshal(body, out); err != nil { + return core.NewError(core.CodeUnavailable, provider+"'s cost report is not in the expected form").WithCause(err) + } + return nil +} diff --git a/internal/budget/providercost/money_decimal.go b/internal/budget/providercost/money_decimal.go new file mode 100644 index 0000000..2d3c791 --- /dev/null +++ b/internal/budget/providercost/money_decimal.go @@ -0,0 +1,53 @@ +// Package providercost reads what Anthropic and OpenAI report an +// organization spent, for the budget gate's provider cost floor. It runs in +// the control zone with an admin credential no agent holds, and uses only +// the standard library. +package providercost + +import ( + "math" + "math/big" + "regexp" + + "github.com/bestagentkits/sisf/pkg/core" +) + +// decimal is a decimal number as the providers write amounts: a JSON +// number, with a short exponent at most, so nothing is read loosely and no +// amount is costly to compute. +var decimal = regexp.MustCompile(`^-?[0-9]{1,30}(\.[0-9]{1,30})?([eE][+-]?[0-9]{1,2})?$`) + +// micros converts an amount written as a decimal number of units, where +// perUnit micros make one unit, to micros, rounding up: a provider's +// fraction of a micro is never dropped from what was spent. It parses +// exactly and never through a float. A negative amount, as a credit, +// counts as 0, as the ledger counts one: it never lowers what was spent. +func micros(amount string, perUnit int64) (core.Micros, error) { + if !decimal.MatchString(amount) { + return 0, core.NewError(core.CodeInvalidArgument, "the provider reported an amount that is not a plain decimal number") + } + r, ok := new(big.Rat).SetString(amount) + if !ok { + return 0, core.NewError(core.CodeInvalidArgument, "the provider reported an amount that is not a plain decimal number") + } + if r.Sign() <= 0 { + return 0, nil + } + r.Mul(r, new(big.Rat).SetInt64(perUnit)) + q, rem := new(big.Int).QuoRem(r.Num(), r.Denom(), new(big.Int)) + if rem.Sign() > 0 { + q.Add(q, big.NewInt(1)) + } + if !q.IsInt64() { + return math.MaxInt64, nil + } + return core.Micros(q.Int64()), nil +} + +// add sums amounts without wrapping, stopping at the largest amount. +func add(a, b core.Micros) core.Micros { + if b > math.MaxInt64-a { + return math.MaxInt64 + } + return a + b +} diff --git a/internal/budget/providercost/openai_cost_source.go b/internal/budget/providercost/openai_cost_source.go new file mode 100644 index 0000000..78209dd --- /dev/null +++ b/internal/budget/providercost/openai_cost_source.go @@ -0,0 +1,99 @@ +package providercost + +import ( + "context" + "encoding/json" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "github.com/bestagentkits/sisf/pkg/core" +) + +// OpenAIURL is the OpenAI API. +const OpenAIURL = "https://api.openai.com" + +// OpenAI reads the cost an OpenAI project was charged, from the +// organization Costs API (GET /v1/organization/costs), which needs an admin +// key. The figure is limited to one project that the factory alone uses. +type OpenAI struct { + // BaseURL is the API's address; empty means OpenAIURL. + BaseURL string + // AdminKey is an admin key of the organization. + AdminKey core.SecretValue + // ProjectID is the project the factory's runs are charged to. + ProjectID string + HTTP *http.Client +} + +// openAICosts is the part of the answer that is read. A value is a JSON +// number of dollars, kept as written. +type openAICosts struct { + Data []struct { + Results []struct { + Amount struct { + Value json.Number `json:"value"` + Currency string `json:"currency"` + } `json:"amount"` + } `json:"results"` + } `json:"data"` + HasMore bool `json:"has_more"` + NextPage *string `json:"next_page"` +} + +// microsPerDollar converts the API's dollars to micros. +const microsPerDollar = 1_000_000 + +// Spent returns the project's cost in daily buckets from since to now. The +// API does not say how far its data reaches, so the time is zero. +func (o OpenAI) Spent(ctx context.Context, since time.Time) (core.Micros, time.Time, error) { + if o.AdminKey.IsZero() || o.ProjectID == "" { + return 0, time.Time{}, core.NewError(core.CodeInvalidArgument, "reading OpenAI's cost needs an admin key and the factory's project") + } + base := strings.TrimSuffix(o.BaseURL, "/") + if base == "" { + base = OpenAIURL + } + var ( + spent core.Micros + page string + ) + for range maxPages { + q := url.Values{} + q.Set("start_time", strconv.FormatInt(since.Unix(), 10)) + q.Set("bucket_width", "1d") + q.Set("project_ids", o.ProjectID) + q.Set("limit", "180") + if page != "" { + q.Set("page", page) + } + req, err := http.NewRequest(http.MethodGet, base+"/v1/organization/costs?"+q.Encode(), nil) + if err != nil { + return 0, time.Time{}, core.NewError(core.CodeInvalidArgument, "the OpenAI API address is not valid").WithCause(err) + } + req.Header.Set("Authorization", "Bearer "+string(o.AdminKey.Reveal())) + var report openAICosts + if err := getJSON(ctx, o.HTTP, req, "OpenAI", &report); err != nil { + return 0, time.Time{}, err + } + for _, bucket := range report.Data { + for _, r := range bucket.Results { + if !strings.EqualFold(r.Amount.Currency, "usd") { + return 0, time.Time{}, core.NewError(core.CodeNotSupported, "OpenAI reported a cost in "+r.Amount.Currency+", not USD") + } + m, err := micros(r.Amount.Value.String(), microsPerDollar) + if err != nil { + return 0, time.Time{}, err + } + spent = add(spent, m) + } + } + if !report.HasMore || report.NextPage == nil || *report.NextPage == "" { + return spent, time.Time{}, nil + } + page = *report.NextPage + } + return 0, time.Time{}, core.NewError(core.CodeUnavailable, "OpenAI's cost report has more pages than expected") +} diff --git a/internal/budget/providercost/provider_cost_sources_test.go b/internal/budget/providercost/provider_cost_sources_test.go new file mode 100644 index 0000000..b28cab5 --- /dev/null +++ b/internal/budget/providercost/provider_cost_sources_test.go @@ -0,0 +1,185 @@ +package providercost + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "github.com/bestagentkits/sisf/pkg/core" +) + +var since = time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC) + +const testKey = "admin-key-for-tests" + +func TestAmountsAreReadExactlyAndRoundedUp(t *testing.T) { + t.Parallel() + cases := []struct { + amount string + perUnit int64 + want core.Micros + }{ + {"123.45", microsPerCent, 1_234_500}, + {"0.00001", microsPerCent, 1}, + {"0.0000001", microsPerDollar, 1}, + {"0.1", microsPerDollar, 100_000}, + {"1e-05", microsPerDollar, 10}, + {"2.5E2", microsPerDollar, 250_000_000}, + {"-3.2", microsPerDollar, 0}, + {"0", microsPerCent, 0}, + {"999999999999999999999999999999", microsPerDollar, 1<<63 - 1}, + } + for _, c := range cases { + got, err := micros(c.amount, c.perUnit) + if err != nil || got != c.want { + t.Errorf("micros(%q) = %d, %v; want %d", c.amount, got, err, c.want) + } + } + for _, bad := range []string{"", "1,5", "0x10", "1e999", "NaN", "Infinity", " 1", "1.", ".5", "1/2"} { + if _, err := micros(bad, microsPerDollar); !core.HasCode(err, core.CodeInvalidArgument) { + t.Errorf("micros(%q): %v, want INVALID_ARGUMENT", bad, err) + } + } +} + +func anthropicServer(t *testing.T, handle func(w http.ResponseWriter, r *http.Request)) Anthropic { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("x-api-key") != testKey || r.Header.Get("anthropic-beta") != "analytics-usage-cost-2026-08-24" || + r.URL.Path != "/v1/organizations/analytics/cost" || r.URL.Query().Get("workspace_ids[]") != "wrkspc_factory" || + r.URL.Query().Get("starting_at") != "2026-11-01T00:00:00Z" { + http.Error(w, "unexpected request", http.StatusBadRequest) + return + } + handle(w, r) + })) + t.Cleanup(srv.Close) + return Anthropic{BaseURL: srv.URL, AdminKey: core.NewSecretValue([]byte(testKey)), WorkspaceID: "wrkspc_factory", HTTP: srv.Client()} +} + +func TestAnthropicsCostIsSummedAcrossPages(t *testing.T) { + t.Parallel() + var expired atomic.Bool + a := anthropicServer(t, func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Query().Get("page") { + case "": + _, _ = fmt.Fprint(w, `{"data":[{"cost":{"amount":"41280.5","currency":"USD","list_amount":"0"}}],"data_refreshed_at":"2026-11-09T04:00:00Z","has_more":true,"next_page":"p2"}`) + case "p2": + if expired.CompareAndSwap(false, true) { + w.WriteHeader(http.StatusGone) + return + } + _, _ = fmt.Fprint(w, `{"data":[{"cost":{"amount":"0.00001","currency":"USD"}}],"data_refreshed_at":"2026-11-09T03:00:00Z","has_more":false,"next_page":null}`) + } + }) + spent, covered, err := a.Spent(context.Background(), since) + if err != nil { + t.Fatal(err) + } + if want := core.Micros(412_805_000 + 1); spent != want { + t.Errorf("spent %d, want %d", spent, want) + } + if !covered.Equal(time.Date(2026, 11, 9, 3, 0, 0, 0, time.UTC)) { + t.Errorf("covered until %v, want the earliest refresh of the pages", covered) + } +} + +func TestACostReportTheFactoryCannotReadIsAnError(t *testing.T) { + t.Parallel() + cases := map[string]struct { + status int + body string + code core.ErrorCode + }{ + "another currency": {200, `{"data":[{"cost":{"amount":"1","currency":"EUR"}}],"has_more":false}`, core.CodeNotSupported}, + "a loose amount": {200, `{"data":[{"cost":{"amount":"1e999","currency":"USD"}}],"has_more":false}`, core.CodeInvalidArgument}, + "not JSON": {200, ``, core.CodeUnavailable}, + "a refused key": {401, `{}`, core.CodeUnauthenticated}, + "no permission": {403, `{}`, core.CodePermissionDenied}, + "an outage": {503, `{}`, core.CodeUnavailable}, + "always expired": {410, `{}`, core.CodeConflict}, + } + for name, c := range cases { + t.Run(name, func(t *testing.T) { + t.Parallel() + a := anthropicServer(t, func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(c.status) + _, _ = fmt.Fprint(w, c.body) + }) + if _, _, err := a.Spent(context.Background(), since); !core.HasCode(err, c.code) { + t.Fatalf("%v, want %s", err, c.code) + } + }) + } +} + +// The admin key never follows a redirect to another server. +func TestTheAdminKeyIsNotSentWhereARedirectPoints(t *testing.T) { + t.Parallel() + var leaked atomic.Bool + elsewhere := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + if r.Header.Get("x-api-key") != "" || r.Header.Get("Authorization") != "" { + leaked.Store(true) + } + })) + t.Cleanup(elsewhere.Close) + a := anthropicServer(t, func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, elsewhere.URL+"/v1/organizations/analytics/cost", http.StatusFound) + }) + if _, _, err := a.Spent(context.Background(), since); !core.HasCode(err, core.CodeUnavailable) { + t.Errorf("a redirect: %v, want UNAVAILABLE", err) + } + if leaked.Load() { + t.Fatal("the admin key was sent where the redirect pointed") + } +} + +func TestAReadNeedsAKeyAndTheFactorysOwnScope(t *testing.T) { + t.Parallel() + for name, source := range map[string]interface { + Spent(context.Context, time.Time) (core.Micros, time.Time, error) + }{ + "anthropic without a workspace": Anthropic{AdminKey: core.NewSecretValue([]byte(testKey))}, + "anthropic without a key": Anthropic{WorkspaceID: "wrkspc_factory"}, + "openai without a project": OpenAI{AdminKey: core.NewSecretValue([]byte(testKey))}, + "openai without a key": OpenAI{ProjectID: "proj_factory"}, + } { + if _, _, err := source.Spent(context.Background(), since); !core.HasCode(err, core.CodeInvalidArgument) { + t.Errorf("%s: %v, want INVALID_ARGUMENT", name, err) + } + } +} + +func TestOpenAIsCostIsSummedAcrossBucketsAndPages(t *testing.T) { + t.Parallel() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + if r.Header.Get("Authorization") != "Bearer "+testKey || r.URL.Path != "/v1/organization/costs" || + q.Get("project_ids") != "proj_factory" || q.Get("start_time") != fmt.Sprint(since.Unix()) { + http.Error(w, "unexpected request", http.StatusBadRequest) + return + } + switch q.Get("page") { + case "": + _, _ = fmt.Fprint(w, `{"object":"page","data":[{"object":"bucket","start_time":1,"end_time":2,"results":[ + {"object":"organization.costs.result","amount":{"value":0.06,"currency":"usd"}}, + {"object":"organization.costs.result","amount":{"value":1e-7,"currency":"usd"}}]}],"has_more":true,"next_page":"n"}`) + default: + _, _ = fmt.Fprint(w, `{"object":"page","data":[{"object":"bucket","results":[{"amount":{"value":12.345678,"currency":"usd"}}, + {"amount":{"value":-1.5,"currency":"usd"}}]}],"has_more":false,"next_page":null}`) + } + })) + t.Cleanup(srv.Close) + o := OpenAI{BaseURL: srv.URL, AdminKey: core.NewSecretValue([]byte(testKey)), ProjectID: "proj_factory", HTTP: srv.Client()} + spent, covered, err := o.Spent(context.Background(), since) + if err != nil { + t.Fatal(err) + } + if want := core.Micros(60_000 + 1 + 12_345_678); spent != want || !covered.IsZero() { + t.Errorf("spent %d covered %v, want %d and no coverage", spent, covered, want) + } +} diff --git a/internal/budget/settings.go b/internal/budget/settings.go index 3c521be..93ed98c 100644 --- a/internal/budget/settings.go +++ b/internal/budget/settings.go @@ -65,8 +65,20 @@ type Settings struct { // ProviderHardCap states that the provider account enforces a hard limit // of its own. When false the budget is flagged as having no hard cap. ProviderHardCap bool `json:"provider_hard_cap,omitempty"` + // ProviderCostSources names the providers whose own report of what + // was spent, read by the control zone, is the least a capped period + // counts as spent, whatever the agents reported. Capped mode with a + // period only. A named source whose figure is missing or stale holds + // new runs until it is read again; see ProviderSpend. + ProviderCostSources []string `json:"provider_cost_sources,omitempty"` } +// Provider cost sources the control zone can read. +const ( + ProviderAnthropic = "anthropic" + ProviderOpenAI = "openai" +) + // Validate rejects settings that are ambiguous or cannot be enforced. func (s Settings) Validate() error { bad := func(msg string) error { return core.NewError(core.CodeInvalidArgument, msg) } @@ -83,6 +95,21 @@ func (s Settings) Validate() error { return bad("a capped budget needs a cap above zero") case s.Mode == core.BudgetCapped && s.RollbackReserveMicros >= s.CapMicros: return bad("the rollback reserve must be smaller than the cap") + case len(s.ProviderCostSources) > 0 && s.Mode != core.BudgetCapped: + return bad("a provider cost source checks a cap; choose capped to name one") + case len(s.ProviderCostSources) > 0 && s.Period == PeriodNone: + // Providers report a bounded past, not everything ever spent. + return bad("a provider cost source needs a budget period of a day, a week or a month") + } + seen := map[string]bool{} + for _, source := range s.ProviderCostSources { + if source != ProviderAnthropic && source != ProviderOpenAI { + return bad("a provider cost source must be anthropic or openai") + } + if seen[source] { + return bad("a provider cost source is named twice") + } + seen[source] = true } return nil } diff --git a/internal/budget/status.go b/internal/budget/status.go index 6b99342..d6bd075 100644 --- a/internal/budget/status.go +++ b/internal/budget/status.go @@ -24,6 +24,11 @@ type Status struct { // SpentUnverifiedMicros is usage the provider could not confirm; it is // shown apart and counts against the cap. SpentUnverifiedMicros core.Micros `json:"spent_unverified_micros"` + // ProviderSpentMicros is what the providers the settings name report + // was spent in the period, as the control zone last read it; nil when + // no provider is named or no figure counts. It is the least the period + // counts as spent, and is kept apart from what the agents reported. + ProviderSpentMicros *core.Micros `json:"provider_spent_micros,omitempty"` // AvailableMicros is what a normal run may still reserve; capped only. AvailableMicros *core.Micros `json:"available_micros,omitempty"` // Warnings are plain-language notices about the level of guarantee. @@ -50,8 +55,22 @@ func ReadStatus(ctx context.Context, src dispatcher.ConfirmationSource, ledger L return Status{}, err } st.ReservedMicros, st.SpentVerifiedMicros, st.SpentUnverifiedMicros = totals.Reserved, totals.SpentVerified, totals.SpentUnverified + floor, err := providerFloor(ctx, ledger, settings, now) + var held *core.Error + switch { + case core.HasCode(err, core.CodeBudgetExceeded) && errors.As(err, &held): + st.Warnings = append(st.Warnings, "capped runs are held: "+held.Message) + case err != nil: + return Status{}, err + case len(settings.ProviderCostSources) > 0: + st.ProviderSpentMicros = &floor + if reported := addMicros(totals.SpentVerified, totals.SpentUnverified); floor > reported { + st.Warnings = append(st.Warnings, "the providers report more spent in the period than the agents did: an agent may "+ + "under-report its costs, or something else spends through the same key or workspace; the providers' figure counts") + } + } if settings.Mode == core.BudgetCapped { - available := settings.CapMicros - settings.RollbackReserveMicros - usedIn(totals) + available := settings.CapMicros - settings.RollbackReserveMicros - usedWith(totals, floor) st.AvailableMicros = &available } if totals.SpentUnverified > 0 { diff --git a/internal/supervisor/release/trusted_go_package_dirs_generated.go b/internal/supervisor/release/trusted_go_package_dirs_generated.go index 7aaa995..5f3a8e3 100644 --- a/internal/supervisor/release/trusted_go_package_dirs_generated.go +++ b/internal/supervisor/release/trusted_go_package_dirs_generated.go @@ -35,6 +35,7 @@ var trustedGoPackageDirs = []string{ "internal/audit/", "internal/auth/", "internal/budget/", + "internal/budget/providercost/", "internal/catalog/", "internal/conformance/", "internal/control/", diff --git a/internal/testkit/harness/harness.go b/internal/testkit/harness/harness.go index 7f094ec..e6d97ee 100644 --- a/internal/testkit/harness/harness.go +++ b/internal/testkit/harness/harness.go @@ -30,6 +30,7 @@ import ( "github.com/bestagentkits/sisf/cmd/factoryd/lifecycle" "github.com/bestagentkits/sisf/cmd/factoryd/wiring" "github.com/bestagentkits/sisf/cmd/supervisor/stages" + "github.com/bestagentkits/sisf/internal/budget" "github.com/bestagentkits/sisf/internal/control" "github.com/bestagentkits/sisf/internal/dispatcher" "github.com/bestagentkits/sisf/internal/install" @@ -105,6 +106,9 @@ type Options struct { // the operator's own gh login: it names no GitHub App installation, // takes no webhooks and learns of issues only by reconciliation. OperatorToken bool + // ProviderCost reads the providers' spend for the budget gate, as the + // control zone's admin keys would. + ProviderCost map[string]budget.CostSource } // Factory is one factory running in the test process. @@ -249,7 +253,7 @@ func New(t testing.TB, opts Options) *Factory { core.ZoneApplication: control.HealthProbeFunc(func(context.Context) error { return nil }), core.ZoneAgent: control.HealthProbeFunc(f.dispatcherAlive), }, - Surfaces: f.surfaceConfig(base), Decision: opts.Decision, Reconcile: opts.Reconcile, + Surfaces: f.surfaceConfig(base), Decision: opts.Decision, Reconcile: opts.Reconcile, ProviderCost: opts.ProviderCost, }) if err != nil { t.Fatalf("harness: build the control zone: %v", err) diff --git a/tests/docs/brief_parity_test.go b/tests/docs/brief_parity_test.go index 9645661..b8919e7 100644 --- a/tests/docs/brief_parity_test.go +++ b/tests/docs/brief_parity_test.go @@ -118,12 +118,12 @@ func TestADRSetIsComplete(t *testing.T) { if err != nil { t.Fatal(err) } - if len(files) != 26 { - t.Fatalf("want 26 ADR files, got %d: %v", len(files), files) + if len(files) != 27 { + t.Fatalf("want 27 ADR files, got %d: %v", len(files), files) } // laterProposed are the ADRs after the open points that await the // Owner's acceptance. - laterProposed := map[int]bool{21: true, 22: true, 23: true, 24: true, 25: true, 26: true} + laterProposed := map[int]bool{21: true, 22: true, 23: true, 24: true, 25: true, 26: true, 27: true} nameRe := regexp.MustCompile(`^(\d{4})-[a-z0-9]+(-[a-z0-9]+)*\.md$`) required := []string{"## Status", "## Context", "## Decision", "## Consequences", "## Acceptance test"} for i, f := range files {