Files
Thomas Kosiewski 12be685b59 feat: add experimental API and CLI to manage experiment rules (#29971)
Slice 4 of 4 for runtime experiment rules: an experimental management
API and a hidden CLI, so admins can target, widen, or kill a user-scoped
experiment at runtime without a redeploy. This PR also adds a
startup-default note on the Deployment Overview page and a docs section.

## What's in it

- **API** under `/api/experimental/experiments/rules` (behind
`apiKeyMiddleware` and `httpmw.NoStore`):
- `GET` returns, per user-scoped experiment, the startup default and the
stored rule (mode, condition, revision, actor, time). Stored rules for
other experiments follow, marked `ignored`.
  - `PUT /{experiment}` takes `{mode, condition?, expected_revision}`.
- **Write path:**
- It authorizes read and update on `DeploymentConfig` before parsing
anything. A denied request gets 403 and is not audited.
- It validates next. An invalid condition returns 400 with the full CEL
diagnostics, is not audited, and leaves the rule unchanged.
- It then starts the audit and calls `experiments.WriteRule`. A stale
revision returns 409 and a transaction error returns 500; both are
audited with an empty diff.
- An identical write returns 200, creates no audit entry, and keeps the
revision.
- The audit export happens after commit. If it fails, that is logged and
the committed change stands (the existing audit contract).
- **SDK:** `ExperimentalClient.ExperimentRules` and
`ExperimentalClient.PutExperimentRule`.
- **CLI:** hidden `coder exp experiment-rules list|on|off|set|reset`.
- Write commands take `--expected-revision`. Without it they read the
current revision first, which only protects the gap between the two
calls; the help text says so.
  - A 409 prints the current rule and exits non-zero, with no retry.
- `reset` warns when the startup default is on, because reset is not a
kill switch.
- **Deployment Overview:** a note says the Experiments values are
startup defaults that runtime rules can override per user.
- **Docs:** a new "Target experiments at runtime" section in
`docs/reference/feature-stages.md` covers the modes, roles, CEL fields
and limits, reset vs. off, revisions and audit, the kill-switch
guarantee (including the rolling-upgrade requirement), frontend
freshness, fail-closed behavior, and that rules are not an authorization
boundary.

## Testing

- **HTTP:** every mode applies on the next request with no restart;
rejected writes keep the rule; RBAC (members 403 on GET and PUT;
auditors can read but not write; an invalid body from an unauthorized
caller still gets 403); malformed and ignored stored rows.
- **HA:** two coderd instances share one database. A PUT through A is
seen by B's `/api/v2/experiments` and by B's evaluator, which is the one
chatd uses.
- **Audit (enterprise, licensed):** an effective change creates one
entry whose diff carries the condition, and the entry is found before
the diff is checked. No-ops, 403s and 400s create no entry. A 409 and an
injected 500 are audited with an empty diff. A failed export keeps the
change.
- **Redaction:** a sentinel condition appears only in the rules API,
audit entries, and the server log's audit lines (Enterprise's slog audit
backend writes every audit diff there). It is absent from every other
log line, `/deployment/config`, the support bundle, and telemetry. The
test wires the slog audit backend so this is checked as stated.
- **CLI:** write and list, a conflict that is not retried, and the reset
warning.

Remote dogfood UAT through Coder Agents passed on a licensed test
deployment:
- the CLI;
- per-user results in the browser;
- 403 for members, including an invalid body;
- group targeting, including removing the user from the group;
- sentinel redaction across logs, `/deployment/config`, the support
bundle and the audit API (at that head the audit still masked the
condition; it is now tracked);
- the audit page showing the condition as changed but masked (same
note);
- the Overview note;
- the static default with `off` and `reset`;
- chatd enforcement toggled between turns.

That round tested `135aaaa41e`. The later commits are a CLI refactor and
a test addition, and a follow-up round will cover the final head.

## Follow-ups (low, not in this PR)

- A broken rule logs one error line per evaluation. Consider
rate-limiting it per experiment and revision.
- There's no API or CLI path to clear a stored rule for an experiment
that isn't user-scoped; those rules are inert and listed as `ignored`.
- A malformed stored rule is listed with zero `updated_by` and
`updated_at` values instead of omitting them.
- CLI wording: the 409 message, conflict output showing a UUID instead
of a username, a no-op write not saying nothing changed, and the parent
help lacking the `user.*` fields.
- `PutExperimentRuleRequest.mode` is not in the Swagger `required` list.
An omitted mode already returns 400.
- The dashboard's experiments query (from #29964) refreshes on mount,
window focus or reconnect once 60 seconds old, not on a timer, and its
comment says it bounds staleness. Correct the comment, or add a refetch
interval if the UI must pick up rule changes without a reload.

## Stack

1. #29869: evaluator library
2. #29898: storage and audit types
3. #29964: enforcement and discovery
4. **This PR:** control plane

> [!NOTE]
> This PR was written by an AI agent (Xum).

---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-opus-5-5` • Thinking: `high`_

---------

Signed-off-by: Thomas Kosiewski <tk@coder.com>
2026-09-29 12:23:00 +00:00

189 lines
6.7 KiB
Go

package experiments
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/codersdk"
)
// ruleLockPrefix names the advisory lock that serializes writes to one
// experiment's rule. It matches the site_configs key prefix.
const ruleLockPrefix = "experiment_rule:"
// writeLockTimeout bounds how long WriteRule waits for a concurrent writer
// of the same experiment.
const writeLockTimeout = 5 * time.Second
// RevisionConflictError is returned by WriteRule when the expected revision
// is not the current revision of the stored rule.
type RevisionConflictError struct {
Experiment codersdk.Experiment
Expected int64
// Current is the stored revision; zero means no rule is stored or the
// stored value has no readable positive revision.
Current int64
}
func (e *RevisionConflictError) Error() string {
return fmt.Sprintf("experiment %q rule is at revision %d, expected revision %d", e.Experiment, e.Current, e.Expected)
}
// WriteRule stores the mode and condition of rule as the rule for ex when
// the stored revision equals expectedRevision. The Revision, UpdatedBy and
// UpdatedAt fields of rule are ignored: WriteRule sets them.
//
// It returns the stored rule before and after the call, as read and written
// inside one transaction. Before the first write of ex, the old rule is the
// zero Rule (revision 0). When the stored mode and condition already equal
// rule's, nothing is written, changed is false and the new rule equals the
// old one. Writing inherit to an experiment without a row stores revision 1
// and counts as a change.
//
// A stored value without a readable positive revision, which only a write
// outside this API can produce, counts as revision 0: expectedRevision 0
// replaces it and the rule restarts at revision 1.
//
// A stale expectedRevision returns *RevisionConflictError. Validation errors
// can contain CEL diagnostics; return them only to the rule author and never
// log them.
func WriteRule(
ctx context.Context,
db database.Store,
actorID uuid.UUID,
ex codersdk.Experiment,
rule Rule,
expectedRevision int64,
) (oldRule, newRule Rule, changed bool, err error) {
if actorID == uuid.Nil {
return Rule{}, Rule{}, false, xerrors.New("write experiment rule: actor is required")
}
if expectedRevision < 0 {
return Rule{}, Rule{}, false, xerrors.Errorf("write experiment rule: negative expected revision %d", expectedRevision)
}
if err := ValidateRule(ex, rule); err != nil {
return Rule{}, Rule{}, false, xerrors.Errorf("invalid experiment rule: %w", err)
}
lockCtx, cancel := context.WithTimeout(ctx, writeLockTimeout)
defer cancel()
err = db.InTx(func(tx database.Store) error {
if err := tx.AcquireLock(lockCtx, database.GenLockID(ruleLockPrefix+string(ex))); err != nil {
return xerrors.Errorf("acquire experiment rule lock: %w", err)
}
current, err := readRule(ctx, tx, ex)
if err != nil {
return err
}
if current.Revision != expectedRevision {
return &RevisionConflictError{Experiment: ex, Expected: expectedRevision, Current: current.Revision}
}
oldRule = current
if current.Revision > 0 && current.Mode == rule.Mode && current.Condition == rule.Condition {
newRule = current
return nil
}
newRule = Rule{
Mode: rule.Mode,
Condition: rule.Condition,
Revision: current.Revision + 1,
UpdatedBy: actorID,
UpdatedAt: dbtime.Now(),
}
value, err := json.Marshal(newRule)
if err != nil {
return xerrors.Errorf("encode experiment rule: %w", err)
}
if err := tx.UpsertExperimentRule(ctx, database.UpsertExperimentRuleParams{
Experiment: string(ex),
Value: string(value),
}); err != nil {
return xerrors.Errorf("upsert experiment rule: %w", err)
}
changed = true
return nil
}, &database.TxOptions{Isolation: sql.LevelReadCommitted, TxIdentifier: "experiment_rule_write"})
if err != nil {
return Rule{}, Rule{}, false, err
}
return oldRule, newRule, changed, nil
}
// auditIDNamespace derives audit resource IDs from experiment names. It
// must never change: audit history groups entries by these IDs.
var auditIDNamespace = uuid.MustParse("65b7b16d-c22d-4972-adca-014b0a4b77f0")
// AuditRecord returns the audited form of rule for ex. The ID is derived
// from the experiment name, so every audit entry for one experiment shares
// it. A zero Rule (no stored rule) yields empty mode and condition with
// revision 0.
func AuditRecord(ex codersdk.Experiment, rule Rule) database.ExperimentRule {
return database.ExperimentRule{
ID: uuid.NewSHA1(auditIDNamespace, []byte(ex)),
Experiment: string(ex),
Mode: string(rule.Mode),
Condition: rule.Condition,
Revision: rule.Revision,
}
}
// ReadRules returns the stored rule of every experiment that has one,
// including experiments that do not accept runtime rules. A stored value
// the Evaluator treats as malformed is returned with an empty Mode and the
// revision WriteRule expects to replace it, which is 0 when the stored
// revision is unreadable or not positive.
func ReadRules(ctx context.Context, db database.Store) (map[codersdk.Experiment]Rule, error) {
rows, err := db.GetExperimentRules(ctx)
if err != nil {
return nil, xerrors.Errorf("get experiment rules: %w", err)
}
rules := make(map[codersdk.Experiment]Rule, len(rows))
for _, row := range rows {
rules[codersdk.Experiment(row.Experiment)] = parseStoredRule(row.Value)
}
return rules, nil
}
// readRule returns the stored rule for ex, or the zero Rule when none is
// stored or the stored revision is unreadable or not positive, so that such
// a row stays replaceable at revision 0. For a value the Evaluator treats as
// malformed but whose revision is readable, readRule returns a Rule with
// only Revision set, which never equals a valid rule.
func readRule(ctx context.Context, tx database.Store, ex codersdk.Experiment) (Rule, error) {
value, err := tx.GetExperimentRule(ctx, string(ex))
if errors.Is(err, sql.ErrNoRows) {
return Rule{}, nil
}
if err != nil {
return Rule{}, xerrors.Errorf("get experiment rule: %w", err)
}
return parseStoredRule(value), nil
}
// parseStoredRule decodes a stored value with the semantics described on
// readRule.
func parseStoredRule(value string) Rule {
var revision struct {
Revision int64 `json:"revision"`
}
// Decode errors are dropped because they can quote stored content.
// WriteRule always stores revision 1 or higher.
if err := json.Unmarshal([]byte(value), &revision); err != nil || revision.Revision < 1 {
return Rule{}
}
var rule Rule
if err := json.Unmarshal([]byte(value), &rule); err != nil || checkShape(rule) != nil {
return Rule{Revision: revision.Revision}
}
return rule
}