beads/cmd/bd/backend_registry_contract_test.go
Julian Knutsen 2f1e8be3ca
feat(backends): registry Remote + OpenWith options; beads.OpenBestAvailableWith for embedders (#7188)
* feat(backends): registry Remote + optional OpenWith(ctx, dir, OpenOptions)

Slice S1: backends.Backend gains Remote bool and an optional
OpenWith(ctx, beadsDir, OpenOptions{Credential, HTTPClient, UserAgent}) so a
registered extension backend can honor a per-open credential instead of
dialing with a process-global client — the motivating case is one embedder
process serving many workspaces with distinct credentials. Open keeps
working unmodified for every existing backend: Backend.OpenWithOptions calls
OpenWith when present, otherwise falls back to Open and ignores
HTTPClient/UserAgent, but refuses (ErrCredentialWithoutOpenWith) rather than
silently dropping a non-nil Credential.

Public beads.OpenBestAvailableWith(ctx, beadsDir, opts) carries this through
the SDK surface (mirrored in beads_nocgo.go and aliased in backend/backend.go
and beads.go); OpenBestAvailable is now that call with a zero OpenOptions,
identical to its prior behavior for Dolt, embedded Dolt, and every registered
backend. The plain-Dolt path (no registered backend) applies the same
Credential refusal, since Dolt has no per-open credential seam either.

doltserver.ResolvePhysicalRoots now checks backends.IsRemote(cfg.GetBackend())
before every Dolt-mode branch, including the shared-server check (which reads
only env/config.yaml and never consults cfg) — without this ordering, a global
BEADS_DOLT_SHARED_SERVER=1 would hijack a remote-backend workspace into
reporting a bogus local Dolt root it will never open.

Tests: backends_test new file open_with_test.go covers OpenWithOptions
dispatch/back-compat/Credential refusal and Remote/IsRemote; root package
open_backend_selection_test.go adds a fake OpenWith registrant proving
dispatch and option pass-through through OpenBestAvailableWith, zero-options
back-compat for every path (registered w/ and w/o OpenWith, plain Dolt), and
the Credential-without-OpenWith refusal on both paths; doltserver
physical_root_test.go adds the registered-remote-backend case including the
shared-server-override ordering regression test. Verified under both cgo and
nocgo builds. Live-mutated each new guard (the Credential refusal, the
OpenWith dispatch, the ResolvePhysicalRoots remote-backend case, and the
plain-Dolt Credential refusal) one at a time and confirmed RED before
reverting to GREEN.

No HTTP client code added; that is a later slice.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fixup(backends): address Opus review findings on OpenWith (M1-M3, L1-L2)

- M1: frame cmd/bd store-open errors for remote backends as unreachable
  server failures instead of Dolt-shaped "failed to open database"
  advice (openStoreErrorMessage, backendNameForErrorFraming), with tests.
- M2: rewrite the OpenBestAvailable/OpenBestAvailableWith back-compat
  subtest to assert fixed expected outcomes (error identity/message,
  returned store behavior) now that the two functions are identical,
  instead of comparing them to each other.
- M3: document and enforce the OpenWith contract: an implementation that
  receives a non-nil Credential it cannot type-assert to its expected
  type must refuse with the new ErrUnsupportedCredential sentinel,
  verified with a fake registrant.
- L1: document that a nil OpenOptions.Credential means the backend's
  default/ambient auth, and that multi-tenant embedders must pass a
  non-nil Credential (RequireCredential deferred to S2).
- L2: fail closed on HTTPClient/UserAgent passed to a backend without
  OpenWith, mirroring the existing Credential refusal, via new
  ErrHTTPClientWithoutOpenWith/ErrUserAgentWithoutOpenWith sentinels.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* build(bazel): auto-sync BUILD files

Applied from the bazel-sync-patch artifact of https://github.com/gastownhall/beads/actions/runs/37195230844
(`make bazel-sync`: gazelle, tools/bazel/go_srcs.py, bazel mod tidy).
Only BUILD.bazel, MODULE.bazel and MODULE.bazel.lock are ever pushed; see
scripts/bazel-autofix-push.sh.

* fix(backends): keep the store-open error chain through the remote framing

Maintainer review fixes for the adopted PR (iteration 1).

openStoreErrorMessage returned a string, so ensureStoreActiveWithContext
rebuilt its error from text (%s) where base wrapped the open error with %w,
and the chain ended at the CLI's framing. Prime tells a store-open timeout
apart from a generic "storage unavailable" only through
errors.Is(err, context.DeadlineExceeded) on what ensureStoreActiveWithContext
returns (cmd/bd/prime.go), so the flattening silently downgraded that
diagnostic for every backend, Dolt included, not just the new Remote ones.

Replace the helper with openStoreError, which returns an error wrapping err
with %w on both arms. The message text is unchanged: "failed to open
database: <err>" for Dolt and any registered backend that is not Remote,
"failed to reach remote backend %q: <err>" for a Remote one. direct_mode.go
wraps the result with %w ahead of its Hint line; main.go keeps printing it
through HandleError("%v", ...), which only formats.

Tests:

- TestOpenStoreErrorFramesRemoteBackends (renamed from
  TestOpenStoreErrorMessageFramesRemoteBackends) now also asserts errors.Is
  on every arm, and the exact original text for the non-Remote arms.
- TestEnsureStoreActiveKeepsOpenErrorChain drives the real
  ensureStoreActiveWithContext against a registered backend whose open
  outlives its context, for a local and a Remote backend, and requires
  errors.Is(err, context.DeadlineExceeded) plus the framing prefix and the
  Hint line.
- TestFormatMemoriesForPrimeTimesOutOpeningRegisteredBackend is the
  unstubbed twin of TestFormatMemoriesForPrimeTimesOutOpeningStore and
  requires the timeout banner, not the "storage unavailable" one.

Measured at this head: turning direct_mode.go's outer %w into %v reddens
both chain-test rows and the prime test; turning the helper's %w into %v
reddens the framing test as well.

Non-gating cleanup in the same area:

- beads_cgo.go, beads_nocgo.go: OpenBestAvailableWith's doc and dispatch
  comments said only a non-nil Credential is refused. The code also refuses
  a non-nil HTTPClient and a non-empty UserAgent, each with its own
  ErrXWithoutOpenWith sentinel.
- internal/doltserver/physical_root.go: the Mode doc lists "remote-backend",
  and the RemoteBackend doc covers a registered Remote backend as well as a
  Dolt server on a non-local host.
- open_backend_selection_test.go: the plain-Dolt refusal test is a table
  over Credential, HTTPClient and UserAgent (renamed
  TestOpenBestAvailableWithRefusesPerOpenOptionsOnPlainDolt). Disabling the
  nocgo HTTPClient arm or the cgo UserAgent arm reddens only that row. The
  zero-options test's comment had the delegation backwards and pointed at
  beads.go; OpenBestAvailable delegates to OpenBestAvailableWith in
  beads_cgo.go and beads_nocgo.go.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
2026-10-04 09:34:36 -07:00

229 lines
8.6 KiB
Go

package main
import (
"context"
"errors"
"fmt"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/backends"
)
var (
errRegistryReadWrite = errors.New("registry read-write open")
errRegistryReadOnly = errors.New("registry read-only open")
)
func registerContractBackend(t *testing.T, name string) {
t.Helper()
backends.Register(name, backends.Backend{
Open: func(context.Context, string) (storage.DoltStorage, error) {
return nil, errRegistryReadWrite
},
OpenReadOnly: func(context.Context, string) (storage.DoltStorage, error) {
return nil, errRegistryReadOnly
},
WorkspaceIsBeadsDir: true,
})
t.Cleanup(func() { backends.Deregister(name) })
}
// registerContractRemoteBackend is registerContractBackend plus Remote: true,
// for tests of the IsRemote-aware store-open error framing.
func registerContractRemoteBackend(t *testing.T, name string) {
t.Helper()
backends.Register(name, backends.Backend{
Open: func(context.Context, string) (storage.DoltStorage, error) {
return nil, errRegistryReadWrite
},
OpenReadOnly: func(context.Context, string) (storage.DoltStorage, error) {
return nil, errRegistryReadOnly
},
WorkspaceIsBeadsDir: true,
Remote: true,
})
t.Cleanup(func() { backends.Deregister(name) })
}
// registerContractBlockingBackend registers a backend whose opens block until
// ctx is done and then fail with an error wrapping ctx.Err() — the shape of a
// dial that never completes — so a test can see whether a store-open timeout
// survives the CLI's error framing.
func registerContractBlockingBackend(t *testing.T, name string, remote bool) {
t.Helper()
open := func(ctx context.Context, _ string) (storage.DoltStorage, error) {
<-ctx.Done()
return nil, fmt.Errorf("dial contract backend: %w", ctx.Err())
}
backends.Register(name, backends.Backend{
Open: open,
OpenReadOnly: open,
WorkspaceIsBeadsDir: true,
Remote: remote,
})
t.Cleanup(func() { backends.Deregister(name) })
}
func writeContractBackendConfig(t *testing.T, backend string) string {
t.Helper()
beadsDir := t.TempDir()
if err := (&configfile.Config{Backend: backend}).Save(beadsDir); err != nil {
t.Fatalf("save metadata.json: %v", err)
}
return beadsDir
}
func TestRegisteredBackendDispatchesReadWriteAndReadOnly(t *testing.T) {
const name = "contract"
registerContractBackend(t, name)
beadsDir := writeContractBackendConfig(t, name)
if err := validateConfiguredBackend(&configfile.Config{Backend: name}, beadsDir); err != nil {
t.Fatalf("validateConfiguredBackend() rejected registered backend: %v", err)
}
if _, err := newDoltStoreFromConfig(t.Context(), beadsDir); !errors.Is(err, errRegistryReadWrite) {
t.Fatalf("read-write factory error = %v, want %v", err, errRegistryReadWrite)
}
if _, err := newReadOnlyStoreFromConfig(t.Context(), beadsDir); !errors.Is(err, errRegistryReadOnly) {
t.Fatalf("read-only factory error = %v, want %v", err, errRegistryReadOnly)
}
}
func TestRegisteredBackendDrivesWorkspaceDiscovery(t *testing.T) {
const name = "contract-discovery"
registerContractBackend(t, name)
if !registeredBackendWorkspaceIsBeadsDir(&configfile.Config{Backend: name}) {
t.Fatal("registered backend did not expose its .beads workspace")
}
if registeredBackendWorkspaceIsBeadsDir(&configfile.Config{Backend: "unregistered"}) {
t.Fatal("unregistered backend exposed a .beads workspace")
}
if registeredBackendWorkspaceIsBeadsDir(&configfile.Config{Backend: configfile.BackendDolt}) {
t.Fatal("Dolt must retain its existing database discovery path")
}
}
func TestOSSRegistersNoRemovedBackends(t *testing.T) {
for _, name := range []string{
configfile.BackendPostgres,
configfile.BackendMySQL,
configfile.BackendSQLite,
} {
if backends.Registered(name) {
t.Errorf("OSS unexpectedly registered removed backend %q", name)
}
if err := validateConfiguredBackend(&configfile.Config{Backend: name}, t.TempDir()); err == nil {
t.Errorf("OSS unexpectedly accepted removed backend %q", name)
}
}
}
// TestOpenStoreErrorFramesRemoteBackends is the M1 fix: a registered Remote
// backend's open failure must not be announced as "failed to open database" —
// there is no database, only a network client that could not reach or was
// refused by its remote server — while every other backend (Dolt, or a
// registered backend that is not Remote) keeps the original wording so this
// is additive. Every framing must keep the underlying error in the chain.
func TestOpenStoreErrorFramesRemoteBackends(t *testing.T) {
const remoteName = "contract-remote-error"
const localName = "contract-local-error"
registerContractRemoteBackend(t, remoteName)
registerContractBackend(t, localName)
underlying := errors.New("dial tcp 127.0.0.1:1: connect: connection refused")
got := openStoreError(remoteName, underlying)
msg := got.Error()
if !strings.Contains(msg, "remote backend") || !strings.Contains(msg, remoteName) {
t.Errorf("remote backend message = %q, want it to name the remote backend", msg)
}
if strings.Contains(msg, "failed to open database") {
t.Errorf("remote backend message = %q, want no Dolt-shaped \"failed to open database\" framing", msg)
}
if !strings.Contains(msg, underlying.Error()) {
t.Errorf("remote backend message = %q, want it to include the underlying error %v", msg, underlying)
}
if !errors.Is(got, underlying) {
t.Errorf("remote backend error = %v, want it to wrap the underlying error %v", got, underlying)
}
for _, name := range []string{localName, configfile.BackendDolt, "unregistered"} {
got := openStoreError(name, underlying)
if want := "failed to open database: " + underlying.Error(); got.Error() != want {
t.Errorf("backend %q message = %q, want the original framing %q", name, got, want)
}
if !errors.Is(got, underlying) {
t.Errorf("backend %q error = %v, want it to wrap the underlying error %v", name, got, underlying)
}
}
}
// TestEnsureStoreActiveKeepsOpenErrorChain drives the real
// ensureStoreActiveWithContext (prime's stubbed timeout test cannot see its
// framing) against a registered backend whose open outlives its context. The
// remote-aware framing must still wrap the open error: prime tells a
// store-open timeout apart from a generic "storage unavailable" only through
// errors.Is(err, context.DeadlineExceeded), so a framing that flattens the
// chain into text silently downgrades that diagnostic for every backend.
func TestEnsureStoreActiveKeepsOpenErrorChain(t *testing.T) {
tests := []struct {
name string
backend string
remote bool
wantPrefix string
}{
{
name: "local",
backend: "contract-open-chain-local",
wantPrefix: "failed to open database: ",
},
{
name: "remote",
backend: "contract-open-chain-remote",
remote: true,
wantPrefix: `failed to reach remote backend "contract-open-chain-remote": `,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
registerContractBlockingBackend(t, tt.backend, tt.remote)
t.Setenv("BEADS_DIR", writeContractBackendConfig(t, tt.backend))
oldStore, oldStoreActive := store, storeActive
store, storeActive = nil, false
t.Cleanup(func() { store, storeActive = oldStore, oldStoreActive })
ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond)
defer cancel()
err := ensureStoreActiveWithContext(ctx)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("ensureStoreActiveWithContext() error = %v, want it to wrap context.DeadlineExceeded", err)
}
if msg := err.Error(); !strings.HasPrefix(msg, tt.wantPrefix) || !strings.Contains(msg, "\nHint: ") {
t.Errorf("ensureStoreActiveWithContext() error = %q, want prefix %q and a Hint line", msg, tt.wantPrefix)
}
})
}
}
// TestBackendNameForErrorFramingReadsMetadata covers direct mode's path to
// openStoreError: it has no cfg in scope at the open call site, so it must
// load metadata.json itself to learn the configured backend name.
func TestBackendNameForErrorFramingReadsMetadata(t *testing.T) {
const name = "contract-error-framing-metadata"
registerContractRemoteBackend(t, name)
beadsDir := writeContractBackendConfig(t, name)
if got := backendNameForErrorFraming(beadsDir); got != name {
t.Errorf("backendNameForErrorFraming(%q) = %q, want %q", beadsDir, got, name)
}
// A directory with no metadata.json at all must degrade to "" (plain
// Dolt framing) rather than erroring.
if got := backendNameForErrorFraming(t.TempDir()); got != "" {
t.Errorf("backendNameForErrorFraming(no metadata.json) = %q, want \"\"", got)
}
}