* test(feat): red — bd migrate schema advances schema_migrations before refusing an identity mismatch (refs be-0gfcs) validateWorkspaceIdentity runs after the shared pre-run has already opened the store and let the smart gate auto-apply a pending schema migration. The refusal (exit 1, mismatch message) is correct but arrives too late: schema_migrations has already advanced. New embedded-mode CLI integration test reproduces this by regressing schema_migrations one version and corrupting _project_id, then asserting the cursor is unchanged after a refused `bd migrate schema` -- it currently is not. * feat: green — bd migrate schema applies migrations BEFORE the workspace identity check refuses — the guard cannot prevent what it is guarding against (refs be-0gfcs) * test(feat): red — Review: bd migrate schema applies migrations BEFORE the workspace identity check refuses — the guard cannot prevent what it is guarding against (refs be-3bt2e) * feat: green — Review: bd migrate schema applies migrations BEFORE the workspace identity check refuses — the guard cannot prevent what it is guarding against (refs be-3bt2e) * fix(main): render typed open errors from the identity gate's refusal arm Maintainer review fixup for PR #6674 (adopt-pr iteration 1). Synthesis decision is request_changes with two majors and several non-gating minors. MAJOR 1 (fixed) — the gate's `default:` arm refused with a bare HandleError, so every typed open error the PREVIEW hits was reported as this gate's generic wrapper. That is two regressions against base, where the same classes surfaced from the real open and were rendered properly: (a) `bd --json` exited 1 with unstructured stderr and NO JSON body — a machine contract break for every JSON consumer; (b) the appended `BEADS_SKIP_IDENTITY_CHECK=1` hint is actively wrong for those classes, since skipping the gate leaves the real open failing identically. It matters most for schema skew: the preview runs CheckForwardDrift, so the recurring stale-binary class (#4135/#4137) now fails the preview first, and SchemaSkewError.UserMessage()'s actionable rebuild block was being replaced by a generic line plus a dead-end hint. handleFreshCloneError, RemoteMigrateGateError and the server-mode projectIdentityMismatchError refusal were bypassed the same way. The arm now mirrors the real-open arm — handleFreshCloneError, then renderTypedOpenError — before falling back to HandleErrorRespectJSON, so --json callers still get a structured body, and the override hint now lives only on the generic arm and says what it actually does. Extracted as refuseUnverifiablePreviewOpen so both halves are testable without standing up a forward-drifted workspace. Pinned by TestRefuseUnverifiablePreviewOpenRendersTypedErrors: a skew keeps its own UX and does NOT advertise the override; a skew under --json emits a schema_skew body with current/required/delta; a preview-specific error keeps the generic message, keeps the override hint, and still emits a JSON body. Proven non-vacuous — restoring the pre-fix shape (typed renderers bypassed) fails it. Note the two arms write their JSON to different streams (handleSchemaSkewJSON to stderr, HandleErrorRespectJSON to stdout); that split is pre-existing and the test documents rather than changes it. MAJOR 2 (deliberately not fixed here; filed with a measurement as mc-wbso0) — the gate is unscoped, and server mode already had the pre-migration identity guarantee (dolt/store.go:2030-2062 runs verifyProjectIdentity before initSchema at :2067). The reviewer offered scoping OR, explicitly, "keep the gate unconditional, fix Finding 1, and file the duplicate-open cost as a tracked follow-up with a measurement — not to leave both unaddressed". Taking the sanctioned alternative, because scoping carries two caveats neither reviewer priced (server-mode verification is itself conditional on `!cfg.CreateIfMissing || dbFacts.alreadyExisted`; gateway server mode is deliberately excluded from identity enforcement) and it changes hot-path startup behavior for every write command — not a change to guess at mid-adoption. Measured rather than asserted, on a healthy embedded workspace (ambient beads env unset, 2 warmup runs discarded, 8 runs of `bd config set` each way): WITH gate median 0.329s (mean 0.332, 0.317-0.362) WITHOUT gate median 0.290s (mean 0.292, 0.277-0.314) => +39ms, +14% of un-gated startup, spreads non-overlapping. That number is in mc-wbso0 along with both caveats. Also took one non-gating minor while in the file: the refusal test saved the `store` global but never zeroed it, so its closing `store != nil` assertion could pass or fail on a leftover from an earlier test. `store = nil` added. Validation: git diff --check clean; gofmt clean; go build ./... clean; go vet ./cmd/bd/ clean; golangci-lint v2.10.1 (pr.yml's pin) 0 issues; the gate's full test surface under CI's own flags (-tags gms_pure_go -race -short) 13 PASS 0 FAIL 0 SKIP, with no shared-TMPDIR sweep damage. ITERATION 2 — synthesis and scorecard both `approve`, `Required Changes: None`, four minors. Took all four; none is a merge gate, and the fixup commit already exists so none of them costs an extra push. 1. The doc comment on refuseUnverifiablePreviewOpen overstated its own coverage: it named four typed classes as "rendered exactly as the real-open arm renders them", but only schema skew can actually arrive typed from a preview. Verified each claim before rewriting the comment rather than trusting the review: handleFreshCloneError matches a post-migration string (`main_errors.go`) a non-mutating preview never produces, and both CheckRemoteMigrateGate* call sites (`embeddeddolt/store.go:442`, `dolt/store.go:3073`) are on mutating opens, never openReadOnly. projectIdentityMismatchError is a plain fmt.Errorf with no typed wrapper, so it falls to the generic arm and picks up its prefix — which matches base, where it reached the operator inside the real arm's "failed to open database: %v" wrapper. The comment now says that, names the other two calls as defensive-for-symmetry with the reason each cannot fire, and flags that handleFreshCloneError ignores jsonOutput, so making it reachable would break the --json guarantee this fix established. 2. Pinned the preview→skew WIRE, not just the renderer. TestRefuseUnverifiablePreviewOpenRendersTypedErrors hand-builds a SchemaSkewError, so it could stay green while a change to the preview's drift check moved skew back onto the generic arm — the durability gap that mattered most, since the wire is this fix's whole premise. New TestIdentityGateRendersSchemaSkewFromForwardDriftedWorkspace bootstraps a real embedded workspace, stages one schema_migrations row above the binary's latest, and drives rootCmd.PersistentPreRunE end to end, asserting the skew UX arrives and the generic identity wrapper does not. Reuses the package's existing withEmbeddedMigrateSQL helper. Counterfactual run: restoring the pre-fix bare-HandleError arm reds it on exactly the three regression assertions, printing the original bug verbatim (generic wrapper swallowing the rebuild block, plus the dead-end BEADS_SKIP_IDENTITY_CHECK hint) at a real measured v68-vs-v67 drift. 3. Re-filed the MAJOR 2 tracking artifact as bd-ocmut in the beads rig store and closed mc-wbso0 as superseded. The body was complete and correct; only the routing was wrong — the finding is about beads repo code (cmd/bd), and beads-code PR follow-ups are triaged from the beads rig store, not maintainer-city. Also added a maintainer-notes section to the PR body carrying the deferral, the +39ms measurement and the bd-ocmut pointer, so the condition the deferral rests on is discoverable in-band rather than only out-of-band. 4. isBootstrapPreviewErr breadth is now explicitly on the deferral list below; it had been dropped from it without acknowledgment, which is how a checklist item vanishes at finalize. Tracked remainder, deliberately deferred (all non-gating across both iterations): - isBootstrapPreviewErr is still bare errors.Is(err, os.ErrNotExist), so it accepts any ENOENT-wrapped dial failure, not just "no database directory"; its table test pins only a fabricated negative. Message-contract weakening, not a safety hole, and no in-tree backend registers. - a non-nil fake for TestValidateWorkspaceIdentity_NonexistentDir - the nil-guard precondition on validateWorkspaceIdentity's doc comment - the embedded-tier-only reproduction pins now noted in the PR body Validation (iteration 2): gofmt clean; go build ./... clean; go vet ./cmd/bd/ clean; CGO_ENABLED=0 go vet -tags gms_pure_go ./cmd/bd/ clean (the new file is cgo-tagged, so the no-cgo lane must still compile); golangci-lint v2.10.1 (pr.yml's pin) 0 issues; git diff --check clean. Gate surface run per-test to avoid shared-rootCmd batch false-reds: 13 PASS 0 FAIL under CI's own flags (-tags gms_pure_go -race -short), and the 3 embedded-tier tests all PASS with BEADS_TEST_EMBEDDED_DOLT=1 (new pin 5.3s, fresh-workspace 4.0s, migrate-order 25.2s) — no silent skips. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
128 lines
4.8 KiB
Go
128 lines
4.8 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
"github.com/steveyegge/beads/internal/config"
|
|
"github.com/steveyegge/beads/internal/configfile"
|
|
)
|
|
|
|
// TestIsBootstrapPreviewErr pins the classifier that decides whether the
|
|
// identity check's preview-open failure is a legitimate first run (skip
|
|
// silently) or something else (refuse). It must recognize the exact wrapping
|
|
// shape embeddeddolt produces for "no database on disk yet" and nothing else,
|
|
// including an error that merely happens to also be wrapped.
|
|
func TestIsBootstrapPreviewErr(t *testing.T) {
|
|
wrappedNotExist := fmt.Errorf("embeddeddolt: no embedded database at %s: %w", "/tmp/x/embeddeddolt", os.ErrNotExist)
|
|
wrappedOther := fmt.Errorf("dial tcp 127.0.0.1:3306: %w", errors.New("connect: connection refused"))
|
|
|
|
tests := []struct {
|
|
name string
|
|
err error
|
|
want bool
|
|
}{
|
|
{"nil error", nil, false},
|
|
{"direct os.ErrNotExist", os.ErrNotExist, true},
|
|
{"wrapped os.ErrNotExist (embedded store shape)", wrappedNotExist, true},
|
|
{"generic non-ENOENT error", errors.New("connection refused"), false},
|
|
{"wrapped non-ENOENT error", wrappedOther, false},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
if got := isBootstrapPreviewErr(tt.err); got != tt.want {
|
|
t.Errorf("isBootstrapPreviewErr(%v) = %v, want %v", tt.err, got, tt.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestPersistentPreRunRefusesWhenIdentityPreviewFailsForNonBootstrapReason is
|
|
// the MAJOR-criterion regression test for be-0gfcs round 2 (be-3bt2e): a
|
|
// preview-open failure that is NOT the legitimate first-run case must refuse
|
|
// before the real, mutating store open runs -- not silently no-op the way it
|
|
// did when the guard's own peek could fail for the same reason it exists to
|
|
// catch (an unreachable or misconfigured workspace), letting a pending schema
|
|
// migration auto-apply unexamined.
|
|
//
|
|
// Dolt server-mode with no server listening is the hermetic trigger: it is
|
|
// the same setup TestPersistentPreRunHonorsSkipStoreAnnotation's control case
|
|
// already relies on to prove PersistentPreRunE reaches, and fails, a real
|
|
// store open in this test environment -- and it fails for a connection
|
|
// reason, never an os.ErrNotExist, so it is unambiguously NOT bootstrap.
|
|
func TestPersistentPreRunRefusesWhenIdentityPreviewFailsForNonBootstrapReason(t *testing.T) {
|
|
repoDir := t.TempDir()
|
|
beadsDir := filepath.Join(repoDir, ".beads")
|
|
writeTestConfigYAML(t, beadsDir, "")
|
|
writeMetadataConfig(t, beadsDir, configfile.DoltModeServer, "identity_gate_test")
|
|
|
|
t.Chdir(repoDir)
|
|
t.Setenv("BEADS_DIR", beadsDir)
|
|
t.Setenv("BEADS_DOLT_SHARED_SERVER", "")
|
|
t.Setenv("BEADS_DOLT_SERVER_DATABASE", "")
|
|
t.Setenv("BEADS_DOLT_SERVER_PORT", "")
|
|
// If the real store open is ever reached without refusing first (the bug),
|
|
// fail fast: never auto-start a server from a test.
|
|
t.Setenv("BEADS_DOLT_AUTO_START", "0")
|
|
t.Setenv("BEADS_SKIP_IDENTITY_CHECK", "")
|
|
|
|
config.ResetForTesting()
|
|
t.Cleanup(config.ResetForTesting)
|
|
savePersistentPreRunState(t)
|
|
|
|
oldStore := store
|
|
// Zero it too: the assertion at the end of this test is that the gate did
|
|
// NOT open the real store, which a leftover non-nil global from an earlier
|
|
// test would satisfy vacuously (or fail spuriously).
|
|
store = nil
|
|
t.Cleanup(func() { store = oldStore })
|
|
|
|
if rootCmd.PersistentPreRunE == nil {
|
|
t.Fatal("rootCmd.PersistentPreRunE must be set")
|
|
}
|
|
|
|
probe := &cobra.Command{
|
|
Use: "identity-gate-refuse-probe",
|
|
RunE: func(*cobra.Command, []string) error { return nil },
|
|
}
|
|
rootCmd.AddCommand(probe)
|
|
t.Cleanup(func() { rootCmd.RemoveCommand(probe) })
|
|
|
|
oldStderr := os.Stderr
|
|
r, w, pipeErr := os.Pipe()
|
|
if pipeErr != nil {
|
|
t.Fatalf("os.Pipe: %v", pipeErr)
|
|
}
|
|
os.Stderr = w
|
|
|
|
err := rootCmd.PersistentPreRunE(probe, nil)
|
|
|
|
w.Close()
|
|
os.Stderr = oldStderr
|
|
var captured bytes.Buffer
|
|
io.Copy(&captured, r) //nolint:errcheck // best-effort drain of a test pipe
|
|
|
|
if err == nil {
|
|
t.Fatal("expected PersistentPreRunE to fail against an unreachable server-mode database; test-environment precondition broken")
|
|
}
|
|
|
|
// HandleError's returned error carries only "exit code N" in its own
|
|
// Error() string -- the real message goes to stderr (see HandleError in
|
|
// errors.go) -- so the marker must be asserted against captured stderr,
|
|
// not err.Error().
|
|
const wantMarker = "could not verify workspace identity"
|
|
if !strings.Contains(captured.String(), wantMarker) {
|
|
t.Errorf("PersistentPreRunE stderr = %q, want it to contain %q -- a preview-open failure for a reason other than first-time bootstrap must refuse before the real, mutating store open runs (be-0gfcs: the guard cannot prevent what it is guarding against if it silently no-ops here)", captured.String(), wantMarker)
|
|
}
|
|
if store != nil {
|
|
t.Error("PersistentPreRunE must not have opened the real store after refusing on an unverifiable identity preview")
|
|
}
|
|
}
|