Files
archie/internal/infrastructure/staterpc/error_test.go
T
sam f884777c5b feat(statestore): step_executions, StartStep/FinishStep under the run credential
Plan item 3 of docs/prds/execution-tree-state-machine.md (archie-core-1220), on
top of the transition tables and ErrIllegalTransition enforcement (1214/1215,
archie-core-qdbo.5):

- Migration 0017 adds step_executions -- id, org_id, workspace_id, execution_id,
  attempt, parent_id, depth, kind, name, called_execution_id, status, detail,
  tokens_used, started_at, finished_at, indexed on (execution_id, attempt, id).
  Ownership fields are stamped from the execution's row; depth is derived from
  the parent, never supplied by a caller. Existing rows gain no backfilled
  steps.
- task.Store (the workflow engine's mid-run facade) gains StartStep/FinishStep
  (5 methods, within the 8 cap), with storecontract.StepRecorder fronting them
  on the server; deadlineStore wraps both with its per-call timeout.
- The store enforces each write as one transaction: the guarded row write
  under the shared step transition table plus the transition's own
  stage_start/stage_finish event row. Staleness is decided before legality,
  the way guardTransition decides it, and the store returns the persisted
  event for the caller's post-commit publish -- the EmitDurable convention
  (the daemon's event sink skips already-persisted rows by assigned ID), which
  is why workflow.Run stops emitting stage events beside the store and no
  longer discards step-write errors: a failed start or finish parks the
  execution, and the stage does not run unrecorded. An interrupted stage
  records interrupted rather than failed; a recording failure on that
  shutdown path is logged and left to RecoverStale, which owns the
  interrupted-execution sweep in plan item 6.
- The run credential of docs/prds/orgs-and-access.md authorises StartStep and
  FinishStep on its own execution only: both requests carry the execution ID
  the grant check verifies (FinishStep carries it because the interceptor
  never reads the database), and FinishStep verifies handler-side that the
  step really is that execution's. authorizesTaskScopedCall's sanctioned
  widenings are now held as a lookup table so the next one stops growing a
  switch.
- The PRD's wire contract is StartStep(execution, attempt, parent, kind, name)
  -> step id; the responses also carry the persisted event (needed for the
  post-commit publish) and FinishStep's request carries execution_id (needed
  for the grant check) -- both noted here as deliberate additions to the PRD's
  shorthand. called_execution_id exists in the table but not yet on the wire:
  its named consumer is the workflow-call recording of plan item 4 (#1216).

Conformance drives both adapters; grant tests pin the own-execution scoping;
the wire sentinel set gains ErrInvalidStep (InvalidArgument, "step execution
invalid") for a step kind no consumer names.
2026-09-27 05:42:32 +10:00

133 lines
5.8 KiB
Go

package staterpc
import (
"context"
"errors"
"strings"
"testing"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// TestUnmapErrorPreservesContextIdentity pins the §6 deadline contract that
// unmapError must rehydrate a gRPC Canceled / DeadlineExceeded status back to
// the standard context sentinels. The agent's deadlineStore bounds each Store
// call with context.WithTimeout and the workflow consumer checks
// errors.Is(err, context.DeadlineExceeded) to mark a stage interrupted rather
// than failed (workflow.go); if unmapError folded those into a sanitised
// internal error, a merely interrupted stage would be parked as a failure.
func TestUnmapErrorPreservesContextIdentity(t *testing.T) {
tests := []struct {
name string
err error
want error
}{
{name: "cancelled", err: status.Error(codes.Canceled, context.Canceled.Error()), want: context.Canceled},
{name: "deadline exceeded", err: status.Error(codes.DeadlineExceeded, context.DeadlineExceeded.Error()), want: context.DeadlineExceeded},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := unmapError(tt.err)
if !errors.Is(got, tt.want) {
t.Fatalf("unmapError(%q) = %v, want errors.Is(err, %v)", tt.err, got, tt.want)
}
if errors.Is(got, storecontract.ErrStaleTransition) {
t.Fatalf("unmapError(%q) = %v, must not map to a store sentinel", tt.err, got)
}
})
}
}
// TestMapErrorPreservesContextIdentity pins the server side of the same §6
// contract: if the store (or a server handler) returns a context error because
// the caller's ctx expired mid-call, mapError must map it to the matching
// gRPC code rather than sanitising it into codes.Internal. Otherwise the
// client never sees the deadline identity and an interrupted stage is wrongly
// treated as a failure.
func TestMapErrorPreservesContextIdentity(t *testing.T) {
tests := []struct {
name string
err error
want error
}{
{name: "cancelled", err: context.Canceled, want: context.Canceled},
{name: "deadline exceeded", err: context.DeadlineExceeded, want: context.DeadlineExceeded},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mapped := mapError(tt.err)
if got := unmapError(mapped); !errors.Is(got, tt.want) {
t.Fatalf("mapError/unmapError round-trip for %q = %v, want errors.Is(err, %v)", tt.err, got, tt.want)
}
})
}
}
// TestUnmapErrorSentinelFidelity pins the §7 sentinel rehydration round-trip
// for each store error code, so a consumer's errors.Is(err, storecontract.ErrX) keeps
// working across the wire.
func TestUnmapErrorSentinelFidelity(t *testing.T) {
tests := []struct {
name string
store error
rehyd error
}{
{name: "stale transition", store: storecontract.ErrStaleTransition, rehyd: storecontract.ErrStaleTransition},
{name: "illegal transition", store: storecontract.ErrIllegalTransition, rehyd: storecontract.ErrIllegalTransition},
{name: "invalid step", store: storecontract.ErrInvalidStep, rehyd: storecontract.ErrInvalidStep},
{name: "binding not found", store: storecontract.ErrBindingNotFound, rehyd: storecontract.ErrBindingNotFound},
{name: "mapping not found", store: storecontract.ErrMappingNotFound, rehyd: storecontract.ErrMappingNotFound},
{name: "binding overlap", store: storecontract.ErrBindingOverlap, rehyd: storecontract.ErrBindingOverlap},
{name: "binding transition", store: storecontract.ErrBindingTransition, rehyd: storecontract.ErrBindingTransition},
{name: "already dispatched", store: storecontract.ErrAlreadyDispatched, rehyd: storecontract.ErrAlreadyDispatched},
{name: "source not found", store: storecontract.ErrSourceNotFound, rehyd: storecontract.ErrSourceNotFound},
{name: "source path taken", store: storecontract.ErrSourcePathTaken, rehyd: storecontract.ErrSourcePathTaken},
{name: "source signing stale", store: storecontract.ErrSourceSigningStale, rehyd: storecontract.ErrSourceSigningStale},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// mapError converts the store sentinel to a gRPC status; unmapError
// must recover the same sentinel. This is the round-trip the wire
// contract guarantees (§7).
mapped := mapError(tt.store)
got := unmapError(mapped)
if !errors.Is(got, tt.rehyd) {
t.Fatalf("round-trip %q -> %q: got %v, want %v", tt.store, mapped, got, tt.rehyd)
}
})
}
}
// TestUnmapErrorDoesNotLeakInternalDetail pins the §7 sanitisation rule: an
// infra/unknown error maps to codes.Internal and must not rehydrate to a store
// sentinel, the public message must not carry the raw wrapped detail (SQL
// paths, provider details), and a non-status error is returned unchanged.
func TestUnmapErrorDoesNotLeakInternalDetail(t *testing.T) {
const detail = "sql: path=/var/lib/archie/archie.db secret=abcdef"
internal := mapError(errors.New(detail))
got := unmapError(internal)
if errors.Is(got, storecontract.ErrStaleTransition) || errors.Is(got, storecontract.ErrBindingNotFound) || errors.Is(got, storecontract.ErrAlreadyDispatched) {
t.Fatalf("unmapError(internal) = %v, must not map to a store sentinel", got)
}
if st, ok := status.FromError(got); !ok || st.Code() != codes.Internal {
t.Fatalf("unmapError(internal) = %v, want a codes.Internal status", got)
}
if strings.Contains(got.Error(), detail) {
t.Fatalf("unmapError leaked raw internal detail: %q", got.Error())
}
// A raw (non-status) error is returned unchanged (not wrapped into a
// status or a store sentinel).
raw := errors.New("transport failure")
got = unmapError(raw)
if errors.Is(got, storecontract.ErrStaleTransition) {
t.Fatalf("unmapError(raw) = %v, must not map to a store sentinel", got)
}
if !errors.Is(got, raw) {
t.Fatalf("unmapError(raw) = %v, want an error chain including the original", got)
}
}