refactor(postgres,mcp,archieui,task,prreview,playbook): cut comments down to what the code does

This commit is contained in:
sam committed 2026-10-03 22:01:54 +10:00
1 parent 2fc11b60e1
commit 1bd738cfe8
38 files changed
+209 -827

No files matched your search

+1 -5
View File
@@ -7,11 +7,7 @@ import (
"github.com/jackc/pgx/v5/pgconn"
)
// clip limits s to n bytes without splitting a UTF-8 rune. It is the exact
// write-side normalisation the SQLite store applied before inserting event
// detail, transition detail, park reasons and review payloads: a generated
// query that drops it lets an oversized value through where the old store
// truncated it.
// clip limits s to n bytes without splitting a UTF-8 rune.
func clip(s string, n int) string {
if len(s) <= n {
return s
@@ -73,11 +73,8 @@ func (s *EDA) PutHarnessSecret(ctx context.Context, secret harnesssecret.Secret)
return nil
}
// sealHarnessSecret JSON-marshals the token set and encrypts it under
// bindingcipher.HarnessSecretDomain -- its own domain separator, distinct
// from BindingDomain's, so a row cannot be relocated between the two tables
// and still authenticate. OAuth tokens require a configured encryption key;
// the binding store's legacy plaintext fallback does not apply here.
// sealHarnessSecret encrypts the token set under HarnessSecretDomain. An
// encryption key is required.
func (s *EDA) sealHarnessSecret(payload harnessSecretPayload) (string, error) {
if s.cipher == nil {
return "", errors.New("postgres: harness secrets require an encryption key")
@@ -230,12 +230,9 @@ func (s *Store) BindSubject(ctx context.Context, id identity.IdentityID, subject
return tx.Commit(ctx)
}
// BootstrapIdentities seeds the system identity and the configured legacy
// names idempotently, migrating any forge tasks that still carry a legacy
// name to the stable id. Each legacy name is derived through
// identity.FromLegacyName, so a name this store cannot turn into an identity is
// reported rather than silently skipped -- the file loader refuses the same
// names (configuration.validateIdentities).
// BootstrapIdentities seeds the system identity and the legacy names, and
// moves tasks carrying a legacy name to its stable id. Invalid names are
// errors.
func (s *Store) BootstrapIdentities(ctx context.Context, legacyNames []string) error {
values := make([]identity.Identity, 0, len(legacyNames)+1)
values = append(values, identity.System())
@@ -89,11 +89,8 @@ func AcquireAll(ctx context.Context, pool *pgxpool.Pool, names []string) (releas
return release, nil
}
// Backup writes a whole-database pg_dump archive to out. It takes no claim:
// pg_dump reads one consistent snapshot, so it is safe against serving
// processes, which is what the update installer needs. The archive goes to a
// scratch file and replaces out only once pg_restore can read it back, so a
// failed run never costs the previous good snapshot.
// Backup writes a pg_dump archive to out, replacing it only once pg_restore
// can read the new archive.
func Backup(ctx context.Context, databaseURL, out string) error {
tmp, err := os.CreateTemp(filepath.Dir(out), filepath.Base(out)+".tmp*")
if err != nil {
@@ -134,14 +131,9 @@ func ValidateSnapshot(ctx context.Context, path string) ([]string, error) {
return tables, nil
}
// Restore replaces the whole database with the snapshot at from. It is
// destructive: every write after the snapshot is lost. It refuses unless it
// can claim every service role, so no serving process is running and none can
// start until it finishes; a claim that cannot be checked is a refusal too.
//
// pg_restore --clean drops only what the archive holds, so tables a later
// migration created are dropped first; otherwise they would survive into the
// restored schema and break the next upgrade's migration.
// Restore replaces the whole database with the snapshot at from. It refuses
// unless it can claim every service role. Tables the archive lacks are
// dropped first.
func Restore(ctx context.Context, databaseURL, from string) error {
tables, err := ValidateSnapshot(ctx, from)
if err != nil {
+1 -12
View File
@@ -1,11 +1,3 @@
// Orgs, workspaces, memberships and agent assignments: the Postgres
// implementation of internal/domain/org's contracts, plus the resumable
// default org/workspace upgrade the State Store runs at boot
//
// The upgrade refuses nothing itself; the refusal to serve scoped calls
// until it has finished is enforced by the boot order -- the State Store
// runs this upgrade before its gRPC listener starts, and a failed upgrade
// fails the boot (fail closed) rather than serving records with no org.
package postgres
import (
@@ -244,10 +236,7 @@ func (s *Store) UpgradeDefaultOrg(ctx context.Context) error {
}
// runUpgradePhase stamps one phase's tables and records its ledger row in one
// transaction, after making sure the default org and workspace exist and
// every agent identity belongs to the default org. An interrupted phase
// leaves no ledger row, so the next start re-runs it from the beginning --
// every stamp is idempotent on rows the upgrade has not covered yet.
// transaction. An interrupted phase reruns from the start.
func (s *Store) runUpgradePhase(ctx context.Context, name string, stamps []func(context.Context, *postgresdb.Queries) (int64, error)) error {
tx, err := s.pool.Begin(ctx)
if err != nil {
+4 -18
View File
@@ -96,17 +96,8 @@ func (s *Resources) Audit(ctx context.Context, table string, keys []string, limi
return entries, nil
}
// PutResource applies one control-plane resource write.
//
// It is idempotent per request ID: a write whose (org_id, kind, request_id) is already
// in resource_history returns that revision instead of writing a second one, so a
// retry that reached the store twice is still one revision. The ledger is what
// carries the key -- resource_history outlives the row it describes -- so a
// replay of a revision whose resource an operator removed re-creates that row
// rather than answering with a revision the store no longer holds. The
// alternative is a write that reports a version for a kind that is absent: the
// caller cannot tell the difference, and a kind can stay gone while every
// process believes it holds a value.
// PutResource applies one control-plane resource write, idempotent per
// request ID.
func (s *Resources) PutResource(ctx context.Context, write storecontract.ResourceWrite) (_ storecontract.Resource, retErr error) {
if err := checkResourceKey(write.OrgID, write.Kind); err != nil {
return storecontract.Resource{}, err
@@ -197,13 +188,8 @@ func appendResourceRevision(ctx context.Context, queries *postgresdb.Queries, wr
return history, nil
}
// replayedResource answers a write whose request ID resource_history already
// holds. The ledger's revision is the answer and a replay writes nothing, with
// one repair: when the resource that revision describes is no longer the current
// row, the row is re-created from it. That is the state an operator removing a
// resource leaves behind, and without the repair the store answers with a
// revision it does not hold, so the caller reads a version for a kind that is
// absent and the kind stays absent.
// replayedResource answers a repeated request ID with its recorded revision,
// re-creating the row if it was removed since.
func (s *Resources) replayedResource(ctx context.Context, queries *postgresdb.Queries, tx pgx.Tx, existing postgresdb.ResourceByRequestRow) (storecontract.Resource, error) {
if _, err := queries.ResourceByKind(ctx, postgresdb.ResourceByKindParams{OrgID: existing.OrgID, Kind: existing.Kind}); errors.Is(err, pgx.ErrNoRows) {
if _, err := queries.ReinsertResource(ctx, postgresdb.ReinsertResourceParams{
+13 -36
View File
@@ -20,12 +20,8 @@ import (
// bus after the write commits, and the daemon's event sink skips
// already-persisted rows by their assigned ID -- the EmitDurable convention.
// StartStep records a StepExecution entering running: the row is created
// pending, guarded into running under the shared step transition table, and
// the stage_start event is appended in the same transaction. The execution's
// row is locked for the whole write, so its status check cannot race the
// guarded updates, and org and workspace are stamped from it -- the request's
// ownership fields are ignored, like every owned record.
// StartStep creates a step and moves it to running, appending stage_start in
// the same transaction. Org and workspace come from the execution row.
func (s *Store) StartStep(ctx context.Context, start task.StepStart) (int64, events.Event, error) {
if !task.ValidStepKind(start.Kind) {
return 0, events.Event{}, fmt.Errorf("%w: unknown step kind %q", storecontract.ErrInvalidStep, start.Kind)
@@ -98,11 +94,8 @@ func (s *Store) StartStep(ctx context.Context, start task.StepStart) (int64, eve
return stepID, event, nil
}
// verifyCallStep refuses a call step whose callee is not this run's own:
// the callee's call_parent_task_id must name the recording execution, or the
// call step cannot record (a missing callee is the caller's stale view).
// Without this check a cancel of the recording run would sweep work it never
// started.
// verifyCallStep refuses a call step whose callee is not this execution's
// own.
func (s *Store) verifyCallStep(ctx context.Context, q *postgresdb.Queries, start task.StepStart) error {
if start.CalledExecutionID == 0 {
return nil
@@ -151,11 +144,9 @@ type stepParentState struct {
underTerminal bool
}
// FinishStep moves one step to its outcome under the shared step transition
// table, writing the stage_finish event in the same transaction and returning
// it for the caller's post-commit publish. A step that is missing, that is
// not the named execution's, or whose status does not match from is stale; an
// off-table from->to pair is refused as an illegal transition.
// FinishStep moves a step to its outcome and returns the stage_finish event.
// A missing, foreign or mismatched step is stale; a disallowed pair is
// illegal.
func (s *Store) FinishStep(ctx context.Context, finish task.StepFinish) (events.Event, error) {
tx, err := s.pool.Begin(ctx)
if err != nil {
@@ -245,12 +236,8 @@ func stepEventData(to taskstate.StepStatus, durationMS int64, detail string) map
return data
}
// ListSteps reads one execution's recorded steps, every attempt oldest first
// when attempt is 0, or just the one it names. It is the dashboard run
// detail's authoritative source,
// replacing the fold over stage_start/stage_finish events tasks.stage used to
// back -- unlike StartStep/FinishStep, this is a plain read with no
// transition to guard, so it takes no transaction.
// ListSteps returns an execution's steps, for every attempt when attempt is
// 0.
func (s *Store) ListSteps(ctx context.Context, executionID int64, attempt int) ([]task.StepExecution, error) {
rows, err := s.queries().ListStepExecutions(ctx, postgresdb.ListStepExecutionsParams{
ExecutionID: executionID, Attempt: int64(attempt),
@@ -287,14 +274,8 @@ func stepParentID(parentID int64) pgtype.Int8 {
return pgtype.Int8{Int64: parentID, Valid: parentID != 0}
}
// CancelExecution is the one cancel path: one transaction moves every
// non-terminal StepExecution of the execution's current attempt to cancelled --
// one event row each -- and the execution itself to the status the operator
// action names, under the shared execution transition table. Staleness is
// decided before legality, as guardTransition decides it, and the audit row
// lands in the same write. The caller cancels the in-memory context after this
// commits; the worker's next step write then fails ErrStaleTransition and
// stops.
// CancelExecution cancels the current attempt's open steps and moves the
// execution to `to`, in one transaction with events and an audit row.
func (s *Store) CancelExecution(ctx context.Context, taskID int64, reason, to string) ([]int64, error) {
tx, err := s.pool.Begin(ctx)
if err != nil {
@@ -367,12 +348,8 @@ func (s *Store) CancelExecution(ctx context.Context, taskID int64, reason, to st
return ids, nil
}
// cancelWaitedCallees cancels each callee the caller was still waiting on
// through its own CancelExecution, under its own lifecycle, in the caller's
// write's aftermath -- the callee's own steps and its own move to the same
// destination. A chain of calls is bounded by the call depth the enqueue
// enforces, so the recursion is finite; a callee that cannot be cancelled is
// reported, and the caller's own record stands either way.
// cancelWaitedCallees cancels each callee the caller was waiting on.
// Failures are reported; the caller's cancel stands.
func (s *Store) cancelWaitedCallees(ctx context.Context, waiting []postgresdb.WaitingCallStepsRow, reason, to string) error {
var failures []error
for _, call := range waiting {
+20 -57
View File
@@ -18,11 +18,8 @@ import (
"github.com/samcharles93/archie-core/internal/taskstate"
)
// Store is the PostgreSQL implementation of the State Store. It carries the
// full task/event/identity/status surface behind the storecontract interfaces,
// with the control-plane resource surface embedded from Resources. The pool is
// process-scoped and owned by the composition (internal/app/archied), not by
// the Store, so Close is a no-op.
// Store is the PostgreSQL State Store. The pool belongs to the caller, so
// Close is a no-op.
type Store struct {
pool *pgxpool.Pool
*Resources
@@ -37,16 +34,9 @@ func (s *Store) queries() *postgresdb.Queries {
return postgresdb.New(s.pool)
}
// guardTransition locks the task's row and checks the status write the caller
// is about to perform: a row whose status is not the expected from is stale
// (ErrStaleTransition), a from->to pair outside the shared transition table is
// refused with ErrIllegalTransition.
// Staleness is decided first, so
// a caller that is wrong about the row's state gets the stale sentinel even
// when its pair is also unroutable. The row stays locked for the caller's
// transaction, so the checks cannot race the guarded write that follows.
// A missing row is stale, matching what the guarded update alone used to
// return.
// guardTransition locks the task row and checks the transition: a status
// other than from is ErrStaleTransition, a disallowed pair is
// ErrIllegalTransition. A missing row is stale.
func guardTransition(ctx context.Context, q *postgresdb.Queries, taskID int64, from, to string) error {
status, err := q.LockTaskStatus(ctx, taskID)
if errors.Is(err, pgx.ErrNoRows) {
@@ -74,11 +64,8 @@ func (s *Store) Close() error { return nil }
// JSON-safe floor that keeps synthetic issue numbers clear of real ones.
const syntheticIssueNumberBase = 1_000_000_000_000_000
// structuredPayloadBytes is the write-side bound the store applies to a
// structured payload (review_payload today, task outputs now). A value that
// would exceed it is refused for outputs -- clipped JSON does not parse, and a
// caller must receive an object or nothing -- where the legacy review payload
// is still clipped.
// structuredPayloadBytes bounds structured payloads. Oversized outputs are
// refused; review payloads are clipped.
const structuredPayloadBytes = 4000
// taskFromRow maps the generated task row to the workflow.Task the daemon and
@@ -159,11 +146,8 @@ func (s *Store) EnqueueIssue(ctx context.Context, owner, repo string, number int
return n > 0, nil
}
// EnqueueChatTask inserts a queued chat-sourced task and returns the full row.
// The store allocates the synthetic issue number durably so processes sharing
// the database cannot generate the same value. inputs are the task's workflow
// inputs (the operator trigger's pr_number, for instance); a chat task carries
// no binding provenance, so the insert is the only writer of that column.
// EnqueueChatTask inserts a queued chat task with a store-allocated synthetic
// issue number.
func (s *Store) EnqueueChatTask(ctx context.Context, owner, repo, title, body, wf, identity string, inputs map[string]any) (*workflow.Task, error) {
encoded, err := task.EncodeInputs(inputs)
if err != nil {
@@ -226,11 +210,8 @@ func (s *Store) ClaimByIssue(ctx context.Context, owner, repo string, number int
return taskFromRow(t), nil
}
// Transition moves a task to a new status and records the audit detail. The
// from status guards the update; a mismatch returns ErrStaleTransition without
// writing an audit row, and a from->to pair outside the shared transition
// table returns ErrIllegalTransition. Transitioning to parked also stores
// detail as ParkReason in the same transaction.
// Transition moves a task from `from` to `to` with an audit row. Parking
// also stores detail as ParkReason.
func (s *Store) Transition(ctx context.Context, taskID int64, from, to, detail string) error {
tx, err := s.pool.Begin(ctx)
if err != nil {
@@ -295,11 +276,7 @@ func (s *Store) ParkTask(ctx context.Context, taskID int64, from, detail, class
// Update persists mutable task fields written by workflows.
func (s *Store) Update(ctx context.Context, t *workflow.Task) error {
// The row write is where a run's outputs land.
// An encoded set past the bound the store applies to a structured payload
// is refused rather than clipped: clipped JSON does not parse, and a caller
// would receive a broken object as a value. The engine turns the refusal
// into a park, so nothing silently loses its structured result.
// Oversized outputs are refused, not clipped.
outputs, err := task.EncodeOutputs(t.Outputs)
if err != nil {
return fmt.Errorf("store: encode task %d outputs: %w", t.ID, err)
@@ -414,12 +391,8 @@ func (s *Store) RetryTask(ctx context.Context, taskID int64, fromStatus, wf, ret
})
}
// RespondReviewGate is the review gate response write:
// one guarded
// requeue that records the operator's answer, increments rereview_rounds for
// a re-review only, and writes one audit row -- all in one transaction. The
// cap is checked under the row lock the transition guard takes, so two
// simultaneous re-reviews cannot both spend the last round.
// RespondReviewGate records the operator's gate answer and requeues, counting
// re-reviews against the cap under the row lock.
func (s *Store) RespondReviewGate(ctx context.Context, taskID int64, fromStatus, gate string, rereview bool, maxRounds int) error {
tx, err := s.pool.Begin(ctx)
if err != nil {
@@ -520,11 +493,8 @@ func (s *Store) ArchiveTask(ctx context.Context, taskID int64, fromStatus string
return eventID, nil
}
// RecoverStale re-queues tasks left running by a crashed or replaced daemon
// and, in the same transaction, moves the steps those executions left running
// to the step transition table's interrupted outcome: one event row per step
// transition and the execution's audit row land in the same write. The next
// attempt starts with fresh steps; earlier attempts are never rewritten.
// RecoverStale requeues tasks left running and marks their running steps
// interrupted, in one transaction.
func (s *Store) RecoverStale(ctx context.Context) (int64, error) {
tx, err := s.pool.Begin(ctx)
if err != nil {
@@ -671,12 +641,9 @@ func (s *Store) TaskByID(ctx context.Context, taskID int64) (*workflow.Task, err
return taskFromRow(t), nil
}
// StartCall enqueues the callee of callerTaskID's workflow.call step.
// The store owns the table, so it re-checks
// both runtime invariants the engine checks: the caller must be running and
// the call must not pass workflow.MaxCallDepth. The callee inherits the
// caller's org, workspace, identity, owner and repo, and takes a fresh
// synthetic issue number, the same allocator chat tasks use.
// StartCall enqueues a workflow.call callee inheriting the caller's org,
// workspace, identity and repo. The caller must be running and within
// workflow.MaxCallDepth.
func (s *Store) StartCall(ctx context.Context, callerTaskID int64, wf string, inputs map[string]any) (*workflow.Task, error) {
encoded, err := task.EncodeInputs(inputs)
if err != nil {
@@ -703,11 +670,7 @@ func (s *Store) StartCall(ctx context.Context, callerTaskID int64, wf string, in
return taskFromRow(callee), nil
}
// callRefusal names why EnqueueCallTask inserted nothing. The three refusals
// are distinct failures an operator reads differently: a missing caller is a
// problem, a caller that is not running is a stale retry, and a depth
// refusal is the limit doing its job. The two behavioural ones carry the
// caller's detail in the log and the sentinel across the wire.
// callRefusal explains why EnqueueCallTask inserted nothing.
func (s *Store) callRefusal(ctx context.Context, callerTaskID int64) error {
caller, err := s.queries().TaskByID(ctx, callerTaskID)
if errors.Is(err, pgx.ErrNoRows) {