Files
archie/internal/app/archied/state_store_client_test.go
T
sam 33751abe4e test(staterpc): verify State Store end-to-end and preserve context error identity (#775)
* test(state-store): real-process smoke + deadline/sentinel error contract

Add end-to-end verification for archie-core-8cda.4.7, the .4.7 State Store
verification stage against docs/prds/state-store-contract.md (rev. 2c):

- Real-process smoke coverage: build ./cmd/archie-state-store, run it against
  a minimal config on loopback, poll the readiness surface, and drive the
  State Store gRPC contract through staterpc.NewClient exactly as a consumer
  does. Covers the combined task/event/capture view, error-sentinel fidelity
  across the wire, the found=false-not-error convention, single-owner SQLite
  (the binary owns the one archie.db file; the consumer never opens a store
  file), per-call deadline behaviour, restart/recovery (SIGTERM + reopen on
  the same db), and the remote capture/mapping/binding surfaces.

- Fix a real deadline-identity gap in unmapError: a cancelled or
  deadline-exceeded context surfaced by gRPC-Go as a *status.Error was
  re-wrapped into a sanitised internal-style error, breaking
  errors.Is(err, context.Canceled/DeadlineExceeded). The agent's deadlineStore
  bounds each Store call with context.WithTimeout and the workflow consumer
  (workflow.go) uses errors.Is(err, context.DeadlineExceeded) to mark a stage
  interrupted rather than failed, so the re-wrap would wrongly park an
  interrupted task. Unmap Canceled/DeadlineExceeded codes back to the standard
  context sentinels.

- Pin the error-mapping contract in staterpc: context-identity preservation,
  sentinel round-trip fidelity for every store sentinel, and the sanitisation
  rule (an Internal error must not leak raw detail or map to a sentinel).

* test(state-store): assert single-owner SQLite composition (daemon/gateway require target)

The single-owner invariant (docs/prds/state-store-contract.md §12 step 7/8) is
that only archie-state-store opens archie.db; the daemon and gateway resolve
their task-store surface from openStateStoreAdapter, which requires
[services.state].target and opens no local store. This test pins that
composition root so a future change cannot silently reintroduce a local
*store.Store in the daemon or gateway path (dual-store ownership).

* test(state-store): skip real-process smoke tests under -short

The smoke tests build and exec the real archie-state-store binary, which is
slow enough that a -short run (e.g. a focused edit loop) should skip them.
task check (go test ./... -count=1) does not use -short, so they still run in
the full gate.

* test(state-store): fix subprocess log race under -race

The smoke test captured the subprocess's stdout/stderr in a strings.Builder
that the os/exec writer goroutine and the test reader goroutine touched
concurrently, racing under -race. Replace it with a mutex-guarded buffer, the
standard pattern for reading a running subprocess's output.

* test(state-store): satisfy lint (noctx, errorlint) on new tests

- exec.Command -> exec.CommandContext, http.Get -> NewRequestWithContext +
  Client.Do, so the subprocess and readiness polling honour the test context
  (noctx).
- errorlint: compare the raw non-status error via errors.Is rather than != on
  a wrapped error.

* docs(deployments): document State Store readiness verification and single-owner invariant

The deployment runbook described how to launch archie-state-store but not how
to verify it is healthy before starting archied. Document the -ready-addr
readiness surface (/healthz, /health/detailed state_db component) and the
single-owner invariant: one task SQLite file owned by archie-state-store, with
archied/archie-gateway never opening archie.db directly (state-store-contract
§12 step 7/8).

* fix(state-store): preserve context deadline/cancel identity in mapError

The symmetric server-side gap to the unmapError fix: if a store query fails
because the caller's context expires mid-call (§6 StoreTimeout), the handler's
mapError folded context.Canceled/DeadlineExceeded into codes.Internal. The
client would receive a sanitised internal error with no deadline identity, so
the agent's workflow consumer (errors.Is(err, context.DeadlineExceeded)) could
not distinguish an interrupted stage from a failed one.

Map a context cancel/deadline error to its matching gRPC code so unmapError
rehydrates it back to the standard context sentinel, completing the §6/§7
round-trip. Pin both directions with TestMapErrorPreservesContextIdentity.
2026-09-07 05:47:36 +10:00

109 lines
4.1 KiB
Go

package archied
import (
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/secret"
)
func TestComposeStateStoreClientRequiresTarget(t *testing.T) {
_, _, err := composeStateStoreClient(config.ServiceConnection{}, &secret.Registry{})
if err == nil {
t.Fatal("empty target should error")
}
if !strings.Contains(err.Error(), "services.state.target is required") {
t.Fatalf("unexpected error: %v", err)
}
}
func TestComposeStateStoreClientNonLoopbackFailsClosed(t *testing.T) {
for _, tt := range []struct {
name string
target string
}{
{name: "wildcard without token", target: "0.0.0.0:9090"},
{name: "hostname without token", target: "store.example.com:9090"},
} {
t.Run(tt.name, func(t *testing.T) {
_, _, err := composeStateStoreClient(config.ServiceConnection{Target: tt.target}, &secret.Registry{})
if err == nil {
t.Fatalf("non-loopback %q without a token should fail closed (docs/prds/state-store-contract.md §9)", tt.target)
}
})
}
}
func TestComposeStateStoreClientLoopbackSucceeds(t *testing.T) {
st, cleanup, err := composeStateStoreClient(config.ServiceConnection{Target: "127.0.0.1:9090"}, &secret.Registry{})
if err != nil {
t.Fatalf("loopback without token should succeed: %v", err)
}
if st == nil {
t.Fatal("expected a non-nil store adapter")
}
if cleanup == nil {
t.Fatal("expected a cleanup func")
}
cleanup() // must not panic or fail; Close() on the adapter is a no-op (§11)
}
func TestComposeStateStoreClientTokenFromTargetToken(t *testing.T) {
// Non-loopback with a configured token must not fail closed; the interceptor
// is what carries it, so the client is dialable.
st, _, err := composeStateStoreClient(config.ServiceConnection{Target: "0.0.0.0:9090", TargetToken: "secret"}, &secret.Registry{})
if err != nil {
t.Fatalf("non-loopback with a token should succeed: %v", err)
}
if st == nil {
t.Fatal("expected a non-nil store adapter")
}
}
func TestOpenStateStoreAdapterRequiresTarget(t *testing.T) {
b := newBootstrap()
b.secrets = &secret.Registry{}
// After .4.6 the daemon and gateway no longer own archie.db in-process, so
// an empty [services.state].target is a composition error, not the old
// local *store.Store default (docs/prds/state-store-contract.md §12 step 7).
if err := b.openStateStoreAdapter(); err == nil {
t.Fatal("empty services.state.target should error: the in-process store path is deleted")
}
}
func TestOpenStateStoreAdapterRemoteFailsClosed(t *testing.T) {
b := newBootstrap()
b.secrets = &secret.Registry{}
b.cfg.Services.State = config.ServiceConnection{Target: "0.0.0.0:9090"}
if err := b.openStateStoreAdapter(); err == nil {
t.Fatal("non-loopback without a token should fail closed")
}
}
// TestStateStoreSingleOwnerComposition proves the single-owner SQLite
// invariant at the composition root: both production consumers (the daemon
// Run path and the gateway RunGateway) resolve their task-store surface from
// openStateStoreAdapter, which REQUIRES [services.state].target and never
// opens archie.db directly. After .4.6 the in-process store path is deleted
// (docs/prds/state-store-contract.md §12 step 7), so an empty target is a
// startup error rather than the old local default -- if it were not, the
// daemon or gateway would open the single SQLite file behind the store
// service's back, violating no-dual-store-ownership.
func TestStateStoreSingleOwnerComposition(t *testing.T) {
b := newBootstrap()
b.secrets = &secret.Registry{}
// The daemon openStores path must not construct a local *store.Store.
// openStores only resolves secrets and the forge client, then opens chat
// sessions; the task store surface comes from the remote adapter, so no
// archie.db task file is touched. This asserts openStateStoreAdapter (the
// only task-store constructor) rejects an empty target.
if err := b.openStateStoreAdapter(); err == nil {
t.Fatal("empty services.state.target must error: the in-process store path is deleted (single owner = archie-state-store)")
}
if b.stateStore != nil {
t.Fatalf("stateStore = %p, want nil (no local store opened)", b.stateStore)
}
}