From 75b23748909a03a5afbf04f465e874119fdd38e7 Mon Sep 17 00:00:00 2001 From: CI Bot Date: Wed, 5 Aug 2026 16:00:20 +0000 Subject: [PATCH] feat(issueops): put the startup version reconciler behind the VersionReconciler role (bd-gkmft) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The version markers had two implementations of one rule. The direct route read bd_version and bd_version_max out of the metadata plane in cmd/bd/version_tracking.go, compared them with doctor.CompareVersions and wrote them back; the proxied route opened a unit of work and called a ReconcileVersion method on the config use case, which held its own copy of the same comparison, the same two downgrade guards and the same high-water rule. The two agreed, but nothing made them agree and no test compared them. Both now ask for a role, and the difference between the routes is which accessor answers. THE ROLE BELONGS TO NO COMMAND, and it is the only one in this programme that does not. It fires from PersistentPreRun on EVERY startup, on both routes, before the command the user typed has run — which is exactly why it went unnoticed: `bd version` prints two strings, opens no store and reaches none of this, so the state machinery was hiding behind a command that does not use it. THAT ORIGIN IS A CONSTRAINT ON THE PROMISES, not a piece of history, and the leaf doc says so where a reader will meet it. A role that runs before every command pays for itself on every command, so it does two point reads on the path that changes nothing, loads no configuration, takes no lock, repairs nothing — and, the clause that matters most, it NEVER refuses the command in front of it. A downgrade is an OUTCOME with a nil error, because an older binary is allowed to use a workspace a newer one has opened; a genuine failure is an error the CALLER logs and walks past, which both front doors do at debug level. A role whose callers must ignore its errors has to say so where the promise is made rather than leave each caller to decide. TWO METHODS, ONE ROLE. RecordedVersion and ReconcileVersion are two shapes of one question — the write's promise IS a statement about what a later read returns — which is what the governing rule permits a role to be born with, and WorkspaceConfig set the precedent. It is not padding: the direct front door needs the READ alone. autoMigrateOnVersionBump probes a read-only store first so an already-current workspace never pays for the writable open, and before this commit that probe read the metadata key by hand — the "CLI knows the storage key" shape this programme exists to remove, on the hottest path in the codebase. WHY IT IS NOT WorkspaceConfig WITH TWO MORE KEYS. Two planes, two lifetimes. A workspace setting is durable and travels with the database; these two markers are dolt-ignored, do not survive a clone and are deliberately different per machine. Publishing them through the settings plane would put a value that cannot be shared behind an interface whose whole promise is that its values are. ONE DECISION, THREE SUBSTRATES. workapi.PlanVersionReconcile is the pure planner every implementation decides through; domain.ConfigUseCase LOSES ReconcileVersion and gains SetLocalMetadata, the write half of the GetLocalMetadata it already published, so the unit-of-work body can read, plan and write in ONE transaction. Deleting the use-case method is what makes the rule single-sourced rather than duplicated under a role. CONFORMANCE. backend/conformance/version_reconciler_contract.go holds nine cases run at all three implementations with ZERO parks and zero divergences. They deliberately do NOT re-test the decision: the planner's whole table — upgrade, no-op, both refusals, the catch-up to the mark, the dotted comparison in which 1.2.0 and 1.2.0-rc1 are equal — is pinned without a database in internal/workapi/versionreconcile_test.go, and repeating it here would be testing one pure function three times over three sql-servers. What only a real backend can show is asserted instead: that a recorded marker is there for the next caller (a new transaction on the unit-of-work backend), that a refusal and a validation failure write NOTHING, that reconciliation adds no history entry at all, and that a reconciliation which CANNOT COMPLETE reports an error and leaves both markers standing. Two independent bodies plus an engine check, not three votes: dolt and embeddeddolt share internal/workapi/storeversionreconciler. The fixture carries one hook the frozen roleFixtureKit cannot supply, built at each wiring site the way CycleDetectorFixture.Exec is: the two states that matter most — a recorded version BELOW the high-water mark, and its catch-up — are states the role can never produce, so they are seeded past it. THIS IS THE FIRST COVERAGE THE DIRECT ROUTE'S RECONCILIATION HAS EVER HAD. Its round-trip tests (MigratesVersion, AlreadyMigrated, RefusesDowngrade, TracksMaxVersion) were deleted with the SQLite backend and never replaced; the note recording that is still in cmd/bd/version_tracking_test.go. The seven subtests of the deleted use-case method go with it, replaced by the exhaustive planner table plus nine cases at three backends. NO HTTP OPERATION, and that is a decision rather than an omission — recorded in the leaf doc and as A-ver-2 for the owner. The markers are clone-local: they describe the machine holding the database, so a remote client reading them learns something it cannot compare against anything it holds. The one version fact a client CAN act on, the serving binary's release, is already published as ContextResponse.bd_version, which the document already names as the only field a client may compare as a version. A write endpoint is worse: reconciliation is an effect of a PROCESS STARTING, and a client asking a server to record the client's version would be asking it to lie about which binary holds the database. If the owner wants a read-only GET /v0/beads/version, the role, the accessor and both bodies are already here. NO USER-VISIBLE CHANGE. Every outcome is identical; only three debug lines moved. One accidental behaviour became deliberate: a binary whose Version string is empty used to be handled by the downgrade guard on a populated workspace and by an equality short-circuit on an empty one, and is now an explicit ErrValidation that writes nothing either way. ENFORCEMENT. storeversionreconciler joins the cmd-bd-role-constructors deny list. The version path never named types.IssueFilter, so there is no forbidigo exception to remove. engdocs/ADDING_AN_ISSUEOPS_ROLE.md gains the two things this role taught the checklist: a role may honestly have NO HTTP surface, and a contract case may need a fixture hook for a state the role cannot produce. Verified: build, vet, gofmt clean; golangci-lint 0 issues; TestVersionReconcilerContract green at dolt (9/9), embeddeddolt (9/9) and uow (9/9); the planner unit tests, both decorator enumerations, the root layering pins, internal/jira and the internal/storage/domain/db config suite green; internal/httpapi green and `make api-check` clean with no spec or generated diff; TestReconcileVersionPersistsAcrossUOW green; TestProxiedLookup green; `-run 'TestTrackBdVersion|TestAutoMigrateOnVersionBump|TestGetVersionsSince|TestMaybeShowUpgradeNotification|TestInitDoltMetadata'` green under BEADS_TEST_EMBEDDED_DOLT and TestProxiedServerContext / TestProxiedServerInfo green under BEADS_TEST_PROXIED_SERVER; TestCorpusGolden green, so no command's JSON moved. Co-Authored-By: Claude Opus 5 (1M context) --- .golangci.yml | 2 + .../version_reconciler_contract.go | 305 ++++++++++++++++++ cmd/bd/version_proxied_server.go | 44 ++- cmd/bd/version_tracking.go | 108 ++++--- engdocs/ADDING_AN_ISSUEOPS_ROLE.md | 17 + internal/jira/tracker_test.go | 3 + internal/storage/dolt/version_reconciler.go | 24 ++ .../dolt/version_reconciler_contract_test.go | 83 +++++ internal/storage/domain/config.go | 88 +---- internal/storage/domain/db/config_test.go | 115 ++----- .../embeddeddolt/version_reconciler.go | 26 ++ .../version_reconciler_contract_test.go | 78 +++++ internal/storage/hook_version_reconciler.go | 24 ++ .../storage/role_accessor_decorator_test.go | 35 +- internal/storage/storage.go | 10 + .../uow/version_reconcile_integration_test.go | 61 ++-- internal/storage/uow/version_reconciler.go | 105 ++++++ .../uow/version_reconciler_contract_test.go | 91 ++++++ .../telemetry/role_accessor_decorator_test.go | 18 +- internal/telemetry/version_reconciler.go | 47 +++ .../versionreconciler.go | 101 ++++++ internal/workapi/versionreconcile.go | 154 +++++++++ internal/workapi/versionreconcile_test.go | 139 ++++++++ issue_roles_external_test.go | 35 ++ issueops/versionreconciler.go | 184 +++++++++++ 25 files changed, 1629 insertions(+), 268 deletions(-) create mode 100644 backend/conformance/version_reconciler_contract.go create mode 100644 internal/storage/dolt/version_reconciler.go create mode 100644 internal/storage/dolt/version_reconciler_contract_test.go create mode 100644 internal/storage/embeddeddolt/version_reconciler.go create mode 100644 internal/storage/embeddeddolt/version_reconciler_contract_test.go create mode 100644 internal/storage/hook_version_reconciler.go create mode 100644 internal/storage/uow/version_reconciler.go create mode 100644 internal/storage/uow/version_reconciler_contract_test.go create mode 100644 internal/telemetry/version_reconciler.go create mode 100644 internal/workapi/storeversionreconciler/versionreconciler.go create mode 100644 internal/workapi/versionreconcile.go create mode 100644 internal/workapi/versionreconcile_test.go create mode 100644 issueops/versionreconciler.go diff --git a/.golangci.yml b/.golangci.yml index 7ad0cd395..0bd1ff68b 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -163,6 +163,8 @@ linters: desc: "a command reaches the count role through store.Counter(), never through the constructor: the accessor is where each storage decorator adds its layer - see internal/workapi/storecounter/counter.go" - pkg: github.com/steveyegge/beads/internal/workapi/storeworkspaceconfig desc: "a command reaches the workspace-settings role through store.WorkspaceConfig(), never through the constructor: the accessor is where each storage decorator adds its layer - see internal/workapi/storeworkspaceconfig/workspaceconfig.go" + - pkg: github.com/steveyegge/beads/internal/workapi/storeversionreconciler + desc: "a command reaches the version-marker role through store.VersionReconciler(), never through the constructor: the accessor is where each storage decorator adds its layer - see internal/workapi/storeversionreconciler/versionreconciler.go" - pkg: github.com/steveyegge/beads/internal/workapi/storestats desc: "a command reaches the summary role through store.StatsReporter(), never through the constructor: the accessor is where each storage decorator adds its layer - see internal/workapi/storestats/reporter.go" - pkg: github.com/steveyegge/beads/internal/workapi/storereadycounter diff --git a/backend/conformance/version_reconciler_contract.go b/backend/conformance/version_reconciler_contract.go new file mode 100644 index 000000000..19992e854 --- /dev/null +++ b/backend/conformance/version_reconciler_contract.go @@ -0,0 +1,305 @@ +package conformance + +import ( + "context" + "errors" + "testing" + + publicops "github.com/steveyegge/beads/issueops" +) + +// This file holds the contract every implementation of +// publicops.VersionReconciler must satisfy. Each case asserts what +// issueops/versionreconciler.go PROMISES, cited by line, rather than what any +// one backend happens to do today; a backend that disagrees is parked at its +// own wiring site with skipKnownDivergence so the case still runs on the ones +// that agree. +// +// WHAT THIS CONTRACT IS FOR, given that the decision is elsewhere. Every +// backend plans through workapi.PlanVersionReconcile, and that planner's whole +// table — upgrade, no-op, both refusals, the catch-up to the mark, the dotted +// comparison — is pinned without a database in +// internal/workapi/versionreconcile_test.go. Repeating it here would be testing +// the same pure function three times over three sql-servers. What only a real +// backend can show is the SUBSTRATE half, and that is what these cases assert: +// +// - that a recorded marker is still there for the NEXT caller, which on the +// unit-of-work backend means a different transaction and on the store +// backends a different call against a plane that is deliberately not +// committed to history; +// - that a refusal and a validation failure write NOTHING, which is a +// statement about the two markers on disk rather than about the result +// struct the planner already returned; +// - that reconciliation adds no history entry on a plane that is +// dolt-ignored — the fact that lets this run on every startup at all; +// - that a reconciliation which cannot complete reports an error and leaves +// the markers standing, which is the case that matters most for a role +// nothing waits on. Its front doors log and walk past every error this +// role returns (versionreconciler.go:112-118), so a body that half-wrote +// and reported success would be invisible from the command line forever. +// +// THE MARKERS ARE GLOBAL TO A WORKSPACE and cannot be namespaced the way the +// issue contracts namespace their seeded ids: the two keys are the point, and a +// case that wrote them under a per-test name would assert nothing about the +// pair the role actually reads. Every case therefore SEEDS both markers +// explicitly through the fixture's out-of-band hook before it asserts, so the +// cases are order-independent over one shared plane rather than a sequence +// that has to run in order. +// +// There are three wirings and only TWO independent bodies between them: dolt +// and embeddeddolt both hand back internal/workapi/storeversionreconciler and +// write through their own SetLocalMetadata, so they are one vote plus an engine +// check; the unit-of-work provider is the second, and it does the whole read, +// plan and write inside one transaction. + +// VersionReconcilerFixture supplies adapter-specific storage access for the +// version-marker assertions. +type VersionReconcilerFixture struct { + // Reconciler is the surface under test. + Reconciler publicops.VersionReconciler + // RecordMarkers writes the two markers OUT OF BAND, past the role, and is + // how every case establishes the state it asserts about. It is NOT a + // roleFixtureKit hook — the kit is frozen and reaches the issues plane and + // the config plane, not the clone-local metadata one — so each wiring + // supplies its own short closure over the metadata seam that backend + // already publishes, the way the cycle contract supplies its own Exec. + // + // It exists at all because two of the states this role must handle are + // states the role CANNOT produce: a recorded version BELOW the high-water + // mark is what something outside this role leaves behind, and reconciling + // is the one thing that can never create it. + RecordMarkers func(ctx context.Context, recorded, highWaterMark string) error + // CountHistory reports how many history entries the fixture's branch has. + // A nil hook means "this backend cannot observe history", and the case that + // needs it SKIPS with that reason rather than passing quietly. + CountHistory func(context.Context) (int, error) +} + +// RunVersionReconcilerRecordsAWorkspaceWithNoMarkers pins +// versionreconciler.go:21-29 and :159-174 on the state every workspace starts +// in: nothing recorded, "" rather than a missing-row error, and a first +// reconciliation that sets BOTH markers and is visible to the next caller. +func RunVersionReconcilerRecordsAWorkspaceWithNoMarkers(t *testing.T, ctx context.Context, fixture VersionReconcilerFixture) { + t.Helper() + seedVersionMarkers(t, ctx, fixture, "", "") + + before := readVersionMarkers(t, ctx, fixture) + if before.Recorded != "" || before.HighWaterMark != "" { + t.Fatalf("RecordedVersion() = %+v on a workspace with no markers, want both empty", before) + } + + result := reconcileVersion(t, ctx, fixture, "1.2.0") + if result.Previous != "" || result.Current != "1.2.0" || !result.Migrated || result.Downgrade { + t.Fatalf("ReconcileVersion() = %+v, want {Previous:\"\" Current:1.2.0 Migrated:true}", result) + } + assertVersionMarkers(t, ctx, fixture, "1.2.0", "1.2.0") +} + +// RunVersionReconcilerAdvancesBothMarkersOnAnUpgrade pins the ordinary case — +// the one that fires once per upgrade per workspace and never again +// (versionreconciler.go:159-174). +func RunVersionReconcilerAdvancesBothMarkersOnAnUpgrade(t *testing.T, ctx context.Context, fixture VersionReconcilerFixture) { + t.Helper() + seedVersionMarkers(t, ctx, fixture, "1.2.0", "1.2.0") + + result := reconcileVersion(t, ctx, fixture, "1.3.0") + if result.Previous != "1.2.0" || result.Current != "1.3.0" || !result.Migrated || result.Downgrade { + t.Fatalf("ReconcileVersion() = %+v, want {Previous:1.2.0 Current:1.3.0 Migrated:true}", result) + } + assertVersionMarkers(t, ctx, fixture, "1.3.0", "1.3.0") +} + +// RunVersionReconcilerTreatsTheSameVersionAsANoOp pins versionreconciler.go:75-78 +// — "reconciling twice is not two migrations" — on the path that runs before +// EVERY command, which is why it is asserted as a distinguishable outcome and +// not merely as "no error". +func RunVersionReconcilerTreatsTheSameVersionAsANoOp(t *testing.T, ctx context.Context, fixture VersionReconcilerFixture) { + t.Helper() + seedVersionMarkers(t, ctx, fixture, "1.3.0", "1.3.0") + + result := reconcileVersion(t, ctx, fixture, "1.3.0") + if result.Migrated || result.Downgrade { + t.Fatalf("ReconcileVersion() = %+v on an unchanged version, want neither flag set", result) + } + if result.Previous != "1.3.0" || result.Current != "1.3.0" { + t.Fatalf("ReconcileVersion() = %+v, want Previous and Current both 1.3.0", result) + } + assertVersionMarkers(t, ctx, fixture, "1.3.0", "1.3.0") +} + +// RunVersionReconcilerRefusesADowngradeWithoutAnError pins +// versionreconciler.go:79-89: a refusal is an OUTCOME, the newer number stays, +// and the caller gets a nil error because an older binary is allowed to use a +// workspace a newer one has opened. +func RunVersionReconcilerRefusesADowngradeWithoutAnError(t *testing.T, ctx context.Context, fixture VersionReconcilerFixture) { + t.Helper() + seedVersionMarkers(t, ctx, fixture, "1.3.0", "1.3.0") + + result, err := fixture.Reconciler.ReconcileVersion(ctx, publicops.VersionReconcileRequest{CLIVersion: "1.2.0"}) + if err != nil { + t.Fatalf("ReconcileVersion(1.2.0) error = %v, want a refusal reported as an outcome", err) + } + if !result.Downgrade || result.Migrated { + t.Fatalf("ReconcileVersion() = %+v, want Downgrade with nothing migrated", result) + } + if result.Previous != "1.3.0" || result.Current != "1.3.0" { + t.Fatalf("ReconcileVersion() = %+v, want the value that STAYED reported as Current", result) + } + assertVersionMarkers(t, ctx, fixture, "1.3.0", "1.3.0") +} + +// RunVersionReconcilerRefusesAVersionBelowTheHighWaterMark pins +// versionreconciler.go:30-38, and it is the case the second marker exists for: +// the recorded version alone would ACCEPT this binary, and the mark is what +// remembers that a newer one has already prepared this workspace. +// +// The state it asserts about is one this role cannot produce, which is why the +// fixture writes it out of band. +func RunVersionReconcilerRefusesAVersionBelowTheHighWaterMark(t *testing.T, ctx context.Context, fixture VersionReconcilerFixture) { + t.Helper() + seedVersionMarkers(t, ctx, fixture, "1.2.0", "1.4.0") + + result := reconcileVersion(t, ctx, fixture, "1.3.0") + if !result.Downgrade || result.Migrated { + t.Fatalf("ReconcileVersion(1.3.0) = %+v below a 1.4.0 mark, want Downgrade", result) + } + assertVersionMarkers(t, ctx, fixture, "1.2.0", "1.4.0") +} + +// RunVersionReconcilerCatchesUpToTheHighWaterMark pins the other half of that +// guard: the mark is a CEILING rather than a value to exceed, so the binary +// that left it may record itself again, and doing so moves the marker without +// moving the mark. +func RunVersionReconcilerCatchesUpToTheHighWaterMark(t *testing.T, ctx context.Context, fixture VersionReconcilerFixture) { + t.Helper() + seedVersionMarkers(t, ctx, fixture, "1.2.0", "1.4.0") + + result := reconcileVersion(t, ctx, fixture, "1.4.0") + if !result.Migrated || result.Downgrade { + t.Fatalf("ReconcileVersion(1.4.0) = %+v at a 1.4.0 mark, want a migration", result) + } + assertVersionMarkers(t, ctx, fixture, "1.4.0", "1.4.0") +} + +// RunVersionReconcilerRefusesAnEmptyVersion pins versionreconciler.go:44-47 and +// :176 — ErrValidation, and nothing written. +// +// Both facts matter and the second one is the reason this case reads the +// markers back: recording "" over a real marker would take the downgrade guard +// down with it, and the workspace it left behind would be indistinguishable +// from one no binary had ever opened. +func RunVersionReconcilerRefusesAnEmptyVersion(t *testing.T, ctx context.Context, fixture VersionReconcilerFixture) { + t.Helper() + seedVersionMarkers(t, ctx, fixture, "1.3.0", "1.3.0") + + _, err := fixture.Reconciler.ReconcileVersion(ctx, publicops.VersionReconcileRequest{}) + if !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("ReconcileVersion(\"\") error = %v, want ErrValidation", err) + } + assertVersionMarkers(t, ctx, fixture, "1.3.0", "1.3.0") +} + +// RunVersionReconcilerLeavesTheMarkersStandingWhenItCannotComplete is the case +// that matters most for a role no user waits on. +// +// versionreconciler.go:112-118 says a genuine failure is an error the CALLER +// logs and walks past, and both front doors do exactly that at debug level. +// That makes a body which half-wrote and reported success invisible from the +// command line forever, so the promise is asserted from the other side: when +// the substrate cannot serve the call, the answer is an ERROR — not a +// zero-valued outcome that reads as a no-op — and the markers are exactly what +// they were. +// +// A canceled context is the one failure every backend can be made to have. It +// is not the only one they will meet in the field, but a body that respects +// cancellation on the way in is a body that has not written before it looked. +func RunVersionReconcilerLeavesTheMarkersStandingWhenItCannotComplete(t *testing.T, ctx context.Context, fixture VersionReconcilerFixture) { + t.Helper() + seedVersionMarkers(t, ctx, fixture, "1.3.0", "1.3.0") + + canceled, cancel := context.WithCancel(ctx) + cancel() + + if _, err := fixture.Reconciler.ReconcileVersion(canceled, publicops.VersionReconcileRequest{CLIVersion: "1.4.0"}); err == nil { + t.Fatal("ReconcileVersion() on a canceled context = nil error, want the failure reported rather than a silent no-op") + } + if _, err := fixture.Reconciler.RecordedVersion(canceled, publicops.RecordedVersionRequest{}); err == nil { + t.Fatal("RecordedVersion() on a canceled context = nil error, want the failure reported") + } + assertVersionMarkers(t, ctx, fixture, "1.3.0", "1.3.0") +} + +// RunVersionReconcilerRecordsNoHistory pins versionreconciler.go:178-182. The +// markers are clone-local and dolt-ignored, so recording one adds nothing to +// the workspace's log — the fact that lets this role run before every command +// without filling a workspace's history with the version of the binary that +// read it. +// +// The delta is taken around a reconciliation that DOES write, because a no-op +// leaving no history behind would prove nothing. +func RunVersionReconcilerRecordsNoHistory(t *testing.T, ctx context.Context, fixture VersionReconcilerFixture) { + t.Helper() + if fixture.CountHistory == nil { + t.Skip("fixture cannot observe history on this backend") + } + seedVersionMarkers(t, ctx, fixture, "1.2.0", "1.2.0") + + before, err := fixture.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory() before: %v", err) + } + if result := reconcileVersion(t, ctx, fixture, "1.3.0"); !result.Migrated { + t.Fatalf("ReconcileVersion() = %+v, want the migration this case measures", result) + } + after, err := fixture.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory() after: %v", err) + } + if after != before { + t.Fatalf("history entries %d -> %d, want a clone-local write to record none", before, after) + } +} + +// seedVersionMarkers puts the two markers in a known state past the role. +func seedVersionMarkers(t *testing.T, ctx context.Context, fixture VersionReconcilerFixture, recorded, highWaterMark string) { + t.Helper() + if fixture.RecordMarkers == nil { + t.Fatal("fixture.RecordMarkers is nil: every case seeds the markers it asserts about") + } + if err := fixture.RecordMarkers(ctx, recorded, highWaterMark); err != nil { + t.Fatalf("seed version markers (%q, %q): %v", recorded, highWaterMark, err) + } +} + +// reconcileVersion runs a reconciliation that is expected to succeed, refusal +// included: a refusal is an outcome on this role, not an error. +func reconcileVersion(t *testing.T, ctx context.Context, fixture VersionReconcilerFixture, cliVersion string) publicops.VersionReconcileResult { + t.Helper() + result, err := fixture.Reconciler.ReconcileVersion(ctx, publicops.VersionReconcileRequest{CLIVersion: cliVersion}) + if err != nil { + t.Fatalf("ReconcileVersion(%q): %v", cliVersion, err) + } + return result +} + +func readVersionMarkers(t *testing.T, ctx context.Context, fixture VersionReconcilerFixture) publicops.RecordedVersionResult { + t.Helper() + result, err := fixture.Reconciler.RecordedVersion(ctx, publicops.RecordedVersionRequest{}) + if err != nil { + t.Fatalf("RecordedVersion(): %v", err) + } + return result +} + +// assertVersionMarkers reads the pair back THROUGH THE ROLE, which is the +// promise being checked: versionreconciler.go:170-174 says a later +// RecordedVersion is what "reconciled" means, and on the unit-of-work backend +// that read is a new transaction — the only place a write that never committed +// shows up. +func assertVersionMarkers(t *testing.T, ctx context.Context, fixture VersionReconcilerFixture, recorded, highWaterMark string) { + t.Helper() + got := readVersionMarkers(t, ctx, fixture) + if got.Recorded != recorded || got.HighWaterMark != highWaterMark { + t.Fatalf("RecordedVersion() = %+v, want {Recorded:%q HighWaterMark:%q}", got, recorded, highWaterMark) + } +} diff --git a/cmd/bd/version_proxied_server.go b/cmd/bd/version_proxied_server.go index f9c504385..7d29cb486 100644 --- a/cmd/bd/version_proxied_server.go +++ b/cmd/bd/version_proxied_server.go @@ -2,25 +2,53 @@ package main import ( "context" + "errors" "fmt" "github.com/steveyegge/beads/internal/debug" - "github.com/steveyegge/beads/internal/storage/domain" "github.com/steveyegge/beads/internal/storage/uow" + "github.com/steveyegge/beads/issueops" ) +// proxiedVersionReconciler hands back the clone-local version markers for the +// proxied-server provider, through the provider's OWN capability accessor — +// the same two-step proxiedCounter performs, and for the same reason: the +// accessor is where each layer is added. +func proxiedVersionReconciler() (issueops.VersionReconciler, error) { + if uowProvider == nil { + return nil, errors.New("proxied-server UOW provider not initialized") + } + src, ok := uowProvider.(uow.VersionReconcilerSource) + if !ok { + return nil, fmt.Errorf("proxied-server provider %T does not offer the version-marker surface", uowProvider) + } + return src.VersionReconciler() +} + +// reconcileVersionProxiedServer records this binary's version on the proxied +// route, and is the twin of autoMigrateOnVersionBump's tail. +// +// This file used to open its own unit of work and hold the commit message for +// a decision made in a use case; the direct route made the SAME decision from a +// second copy of the comparison in cmd/bd. Both now ask the role, and the +// difference between the routes is which accessor answers. +// +// EVERY FAILURE HERE IS SWALLOWED TO A DEBUG LINE, deliberately, and +// issueops.VersionReconciler says that this is what its callers do. This runs +// from PersistentPreRun before every proxied command: a workspace whose markers +// cannot be read is a workspace whose commands must still run, and turning that +// into an error would refuse `bd list` over a number nobody asked for. func reconcileVersionProxiedServer(ctx context.Context) { if !versionUpgradeDetected || uowProvider == nil { return } - res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (domain.VersionReconcileResult, string, error) { - res, err := uw.ConfigUseCase().ReconcileVersion(ctx, Version) - if err != nil { - return domain.VersionReconcileResult{}, "", err - } - return res, fmt.Sprintf("bd: reconcile version -> %s", res.Current), nil - }) + reconciler, err := proxiedVersionReconciler() + if err != nil { + debug.Logf("reconcile-version: %v", err) + return + } + res, err := reconciler.ReconcileVersion(ctx, issueops.VersionReconcileRequest{CLIVersion: Version}) if err != nil { debug.Logf("reconcile-version: %v", err) return diff --git a/cmd/bd/version_tracking.go b/cmd/bd/version_tracking.go index 8ff381629..0541b7e9e 100644 --- a/cmd/bd/version_tracking.go +++ b/cmd/bd/version_tracking.go @@ -12,7 +12,9 @@ import ( "github.com/steveyegge/beads/internal/configfile" "github.com/steveyegge/beads/internal/debug" "github.com/steveyegge/beads/internal/doltserver" + "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/dolt" + "github.com/steveyegge/beads/issueops" ) // localVersionFile is the gitignored file that stores the last bd version used locally. @@ -229,10 +231,15 @@ func autoMigrateOnVersionBump(beadsDir string) { // not a `dolt remote -v` subprocess — so this doesn't save a 12s hang; // it saves an unnecessary initSchema round-trip when no migration is // needed. (be-1he) + // + // The probe asks the ROLE for the marker rather than reading the metadata + // key itself, which is why the read shares issueops.VersionReconciler with + // the write: this front door needs the read alone, and a store opened + // read-only can answer it. if roStore, roErr := dolt.NewFromConfigWithOptions(ctx, beadsDir, &dolt.Config{ReadOnly: true}); roErr == nil { - dbVersion, _ := roStore.GetLocalMetadata(ctx, "bd_version") + recorded, probeErr := recordedWorkspaceVersion(ctx, roStore) _ = roStore.Close() - if dbVersion == Version { + if probeErr == nil && recorded == Version { debug.Logf("auto-migrate: database already at version %s (ro probe)", Version) return } @@ -244,60 +251,55 @@ func autoMigrateOnVersionBump(beadsDir string) { debug.Logf("auto-migrate: failed to open database: %v", err) return } - - // Get current database version (clone-local, dolt-ignored) - dbVersion, err := store.GetLocalMetadata(ctx, "bd_version") - if err != nil { - // Failed to read version - skip migration - debug.Logf("auto-migrate: failed to read database version: %v", err) - _ = store.Close() // Best effort cleanup on error path - return - } - - // Check if migration is needed - if dbVersion == Version { - // Database is already at current version - debug.Logf("auto-migrate: database already at version %s", Version) - _ = store.Close() // Best effort cleanup on error path - return - } - - // Check for downgrade: refuse to overwrite a newer version with an older one (gt-e3uiy) - maxVersion, _ := store.GetLocalMetadata(ctx, "bd_version_max") - if dbVersion != "" && doctor.CompareVersions(Version, dbVersion) < 0 { - debug.Logf("auto-migrate: refusing downgrade from %s to %s", dbVersion, Version) - _ = store.Close() // Best effort cleanup on error path - return - } - if maxVersion != "" && doctor.CompareVersions(Version, maxVersion) < 0 { - debug.Logf("auto-migrate: refusing downgrade (max version %s > current %s)", maxVersion, Version) - _ = store.Close() // Best effort cleanup on error path - return - } - - // Perform migration: update database version - debug.Logf("auto-migrate: migrating database from %s to %s", dbVersion, Version) - if err := store.SetLocalMetadata(ctx, "bd_version", Version); err != nil { - // Migration failed - log and continue - debug.Logf("auto-migrate: failed to update database version: %v", err) - _ = store.Close() // Best effort cleanup on error path - return - } - - // Update max version tracking - if maxVersion == "" || doctor.CompareVersions(Version, maxVersion) > 0 { - if err := store.SetLocalMetadata(ctx, "bd_version_max", Version); err != nil { - debug.Logf("auto-migrate: failed to update max version: %v", err) + defer func() { + if err := store.Close(); err != nil { + debug.Logf("auto-migrate: warning: failed to close database: %v", err) } + }() + + // Everything the version markers mean — is this an upgrade, is it a + // downgrade to refuse, does the high-water mark move — is the role's, and + // the same decision answers on the proxied route. This front door reads the + // outcome and logs it. + // + // No Dolt commit is needed after it: local_metadata is dolt-ignored and + // persists in the working set for the lifetime of the server session. + reconciler, err := store.VersionReconciler() + if err != nil { + debug.Logf("auto-migrate: version markers unavailable: %v", err) + return + } + result, err := reconciler.ReconcileVersion(ctx, issueops.VersionReconcileRequest{CLIVersion: Version}) + if err != nil { + debug.Logf("auto-migrate: failed to reconcile database version: %v", err) + return } - // No Dolt commit needed — local_metadata is dolt-ignored and persists - // in the working set for the lifetime of the server session. - - // Close database - if err := store.Close(); err != nil { - debug.Logf("auto-migrate: warning: failed to close database: %v", err) + switch { + case result.Downgrade: + debug.Logf("auto-migrate: refusing downgrade from %s to %s", result.Previous, Version) + case result.Migrated: + debug.Logf("auto-migrate: successfully migrated database from %s to version %s", result.Previous, result.Current) + default: + debug.Logf("auto-migrate: database already at version %s", Version) } +} - debug.Logf("auto-migrate: successfully migrated database to version %s", Version) +// recordedWorkspaceVersion reads the marker through the role's accessor on a +// store the caller owns and closes. +// +// It takes the storage interface rather than the concrete store so the probe +// above cannot drift into using a seam the role hides; it is a helper only +// because the probe's store is opened, read and closed in one statement's +// worth of scope. +func recordedWorkspaceVersion(ctx context.Context, store storage.Storage) (string, error) { + reconciler, err := store.VersionReconciler() + if err != nil { + return "", err + } + recorded, err := reconciler.RecordedVersion(ctx, issueops.RecordedVersionRequest{}) + if err != nil { + return "", err + } + return recorded.Recorded, nil } diff --git a/engdocs/ADDING_AN_ISSUEOPS_ROLE.md b/engdocs/ADDING_AN_ISSUEOPS_ROLE.md index e6696cf1c..6bd6dc92b 100644 --- a/engdocs/ADDING_AN_ISSUEOPS_ROLE.md +++ b/engdocs/ADDING_AN_ISSUEOPS_ROLE.md @@ -130,6 +130,14 @@ in; 13 is the HTTP surface, which lands with the command rather than after it. that genuinely disagrees is parked at its WIRING site with `skipKnownDivergence`, never by weakening the case. + A case may need to establish a state the ROLE CANNOT PRODUCE — a recorded + version below its own high-water mark is one, and reconciling is the one + thing that can never create it. The kit is frozen and reaches the issues + and config planes only, so that hook is a short closure built at each + wiring site over a seam the backend already publishes, the way + `CycleDetectorFixture.Exec` is. It belongs on the fixture, documented as + out-of-band, not in the kit. + Do not add role cases to `backend/conformance`'s older `RunAll` suite: its `Factory` hands back a bare `storage.DoltStorage`, which a unit-of-work provider can never be, so a case placed there silently never runs on the @@ -163,6 +171,15 @@ in; 13 is the HTTP surface, which lands with the command rather than after it. `capability` token in `routes.go`, and that token in the document's `capabilities` vocabulary. `make api-check` is the gate. + **A role may honestly have none, and `issueops.VersionReconciler` is the + one that does.** It answers a startup hook rather than a command: its two + markers are clone-local and dolt-ignored, so they describe the machine + holding the database and mean nothing to a remote caller, and the one + version fact a client can act on is already `ContextResponse.bd_version`. + Writing that decision down — in the leaf doc, beside the promises, and in + AMBIGUITIES.md for the owner — is the work. Adding an operation because the + checklist has a row for one is not. + **The ROLES database source is the part that surprises.** `httpapi.Config` carries either a unit-of-work provider or the roles, and the roles are required TOGETHER: a new operation served from a new role adds a required diff --git a/internal/jira/tracker_test.go b/internal/jira/tracker_test.go index c134e7c13..9ea62fdc3 100644 --- a/internal/jira/tracker_test.go +++ b/internal/jira/tracker_test.go @@ -663,6 +663,9 @@ func (s *configStore) WorkspaceConfig() (issueops.WorkspaceConfig, error) { func (s *configStore) StatsReporter() (issueops.StatsReporter, error) { return nil, &storage.ErrUnsupported{Op: "StatsReporter", Backend: "jira-config-stub"} } +func (s *configStore) VersionReconciler() (issueops.VersionReconciler, error) { + return nil, &storage.ErrUnsupported{Op: "VersionReconciler", Backend: "jira-config-stub"} +} func (s *configStore) CycleDetector() (issueops.CycleDetector, error) { return nil, &storage.ErrUnsupported{Op: "CycleDetector", Backend: "jira-config-stub"} diff --git a/internal/storage/dolt/version_reconciler.go b/internal/storage/dolt/version_reconciler.go new file mode 100644 index 000000000..41b13c6d1 --- /dev/null +++ b/internal/storage/dolt/version_reconciler.go @@ -0,0 +1,24 @@ +package dolt + +import ( + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/workapi/storeversionreconciler" + "github.com/steveyegge/beads/issueops" +) + +// VersionReconciler returns the clone-local version markers for this store. +func (s *DoltStore) VersionReconciler() (issueops.VersionReconciler, error) { + return newVersionReconciler(s) +} + +// newVersionReconciler returns the version markers backed by store. +// +// The implementation is the shared one, for the reason newIssueReader gives: +// the two Dolt-backed stores differ below storage.DoltStorage, not above it, so +// a second copy here would be a copy of nothing but the constructor. +func newVersionReconciler(store *DoltStore) (issueops.VersionReconciler, error) { + if store == nil { + return nil, &storage.ErrUnsupported{Op: "newVersionReconciler", Backend: "nil"} + } + return storeversionreconciler.New(store) +} diff --git a/internal/storage/dolt/version_reconciler_contract_test.go b/internal/storage/dolt/version_reconciler_contract_test.go new file mode 100644 index 000000000..0ee203769 --- /dev/null +++ b/internal/storage/dolt/version_reconciler_contract_test.go @@ -0,0 +1,83 @@ +package dolt + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" + "github.com/steveyegge/beads/internal/workapi" +) + +// TestVersionReconcilerContract runs the VersionReconciler contract against the +// server-backed store. +// +// The cases are subtests of one parent so the whole role suite shares one store +// and one copy-on-write branch. Sharing matters here the way it does for the +// settings role and not the way it does for the issue roles: the two version +// markers are GLOBAL to a workspace and cannot be namespaced under the fixture +// prefix, so every case seeds both of them explicitly instead of relying on +// what the case before it left. setupTestStore already marks the PARENT +// parallel; no subtest here calls t.Parallel, because the no-history case takes +// a log delta. +func TestVersionReconcilerContract(t *testing.T) { + fixture, ctx, cleanup := newDoltVersionReconcilerFixture(t, "vrec") + defer cleanup() + + t.Run("RecordsAWorkspaceWithNoMarkers", func(t *testing.T) { + conformance.RunVersionReconcilerRecordsAWorkspaceWithNoMarkers(t, ctx, fixture) + }) + t.Run("AdvancesBothMarkersOnAnUpgrade", func(t *testing.T) { + conformance.RunVersionReconcilerAdvancesBothMarkersOnAnUpgrade(t, ctx, fixture) + }) + t.Run("TreatsTheSameVersionAsANoOp", func(t *testing.T) { + conformance.RunVersionReconcilerTreatsTheSameVersionAsANoOp(t, ctx, fixture) + }) + t.Run("RefusesADowngradeWithoutAnError", func(t *testing.T) { + conformance.RunVersionReconcilerRefusesADowngradeWithoutAnError(t, ctx, fixture) + }) + t.Run("RefusesAVersionBelowTheHighWaterMark", func(t *testing.T) { + conformance.RunVersionReconcilerRefusesAVersionBelowTheHighWaterMark(t, ctx, fixture) + }) + t.Run("CatchesUpToTheHighWaterMark", func(t *testing.T) { + conformance.RunVersionReconcilerCatchesUpToTheHighWaterMark(t, ctx, fixture) + }) + t.Run("RefusesAnEmptyVersion", func(t *testing.T) { + conformance.RunVersionReconcilerRefusesAnEmptyVersion(t, ctx, fixture) + }) + t.Run("LeavesTheMarkersStandingWhenItCannotComplete", func(t *testing.T) { + conformance.RunVersionReconcilerLeavesTheMarkersStandingWhenItCannotComplete(t, ctx, fixture) + }) + t.Run("RecordsNoHistory", func(t *testing.T) { + conformance.RunVersionReconcilerRecordsNoHistory(t, ctx, fixture) + }) +} + +func newDoltVersionReconcilerFixture(t *testing.T, prefix string) (conformance.VersionReconcilerFixture, context.Context, func()) { + t.Helper() + store, storeCleanup := setupTestStore(t) + ctx, cancel := testContext(t) + reconciler, err := store.VersionReconciler() + if err != nil { + cancel() + storeCleanup() + t.Fatalf("VersionReconciler(): %v", err) + } + kit := newDoltRoleFixtureKit(store, prefix) + fixture := conformance.VersionReconcilerFixture{ + Reconciler: reconciler, + // Past the role, through the store's own metadata seam: the role can + // never leave a marker below the mark, and two cases assert about + // exactly that state. + RecordMarkers: func(ctx context.Context, recorded, highWaterMark string) error { + if err := store.SetLocalMetadata(ctx, workapi.MetadataKeyVersion, recorded); err != nil { + return err + } + return store.SetLocalMetadata(ctx, workapi.MetadataKeyVersionMax, highWaterMark) + }, + CountHistory: kit.CountHistory, + } + return fixture, ctx, func() { + cancel() + storeCleanup() + } +} diff --git a/internal/storage/domain/config.go b/internal/storage/domain/config.go index 347d83ecc..bcacd05ae 100644 --- a/internal/storage/domain/config.go +++ b/internal/storage/domain/config.go @@ -3,7 +3,6 @@ package domain import ( "context" "fmt" - "strings" "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/types" @@ -44,15 +43,19 @@ type ConfigUseCase interface { GetAllConfig(ctx context.Context) (map[string]string, error) GetMetadata(ctx context.Context, key string) (string, error) GetLocalMetadata(ctx context.Context, key string) (string, error) - - ReconcileVersion(ctx context.Context, cliVersion string) (VersionReconcileResult, error) -} - -type VersionReconcileResult struct { - Previous string - Current string - Migrated bool - Downgrade bool + // SetLocalMetadata writes one clone-local, dolt-ignored value inside the + // caller's unit of work. It is the write half of GetLocalMetadata, and it + // exists because issueops.VersionReconciler's unit-of-work body reads its + // two markers, decides through the shared planner in internal/workapi and + // writes them back — all in ONE transaction, which is what makes the read + // it qualifies and the write it plans see the same snapshot. + // + // The DECISION is deliberately not here. It used to be, as a + // ReconcileVersion method on this use case, and that left the rule for + // which version may overwrite which stated twice: once here for the + // proxied route and once in cmd/bd for the direct one. Both now plan + // through workapi.PlanVersionReconcile and this seam moves bytes. + SetLocalMetadata(ctx context.Context, key, value string) error } // CreateContext bundles the read-only config inputs that bd create needs @@ -220,68 +223,11 @@ func (u *configUseCaseImpl) GetAllConfig(ctx context.Context) (map[string]string return out, nil } -func (u *configUseCaseImpl) ReconcileVersion(ctx context.Context, cliVersion string) (VersionReconcileResult, error) { - if cliVersion == "" { - return VersionReconcileResult{}, fmt.Errorf("ReconcileVersion: cliVersion must be set") +func (u *configUseCaseImpl) SetLocalMetadata(ctx context.Context, key, value string) error { + if err := u.cfgRepo.SetLocalMetadata(ctx, key, value); err != nil { + return fmt.Errorf("SetLocalMetadata: %w", err) } - - dbVersion, err := u.cfgRepo.GetLocalMetadata(ctx, "bd_version") - if err != nil { - return VersionReconcileResult{}, fmt.Errorf("ReconcileVersion: read bd_version: %w", err) - } - if dbVersion == cliVersion { - return VersionReconcileResult{Previous: dbVersion, Current: dbVersion}, nil - } - - maxVersion, err := u.cfgRepo.GetLocalMetadata(ctx, "bd_version_max") - if err != nil { - return VersionReconcileResult{}, fmt.Errorf("ReconcileVersion: read bd_version_max: %w", err) - } - - if dbVersion != "" && compareVersions(cliVersion, dbVersion) < 0 { - return VersionReconcileResult{Previous: dbVersion, Current: dbVersion, Downgrade: true}, nil - } - if maxVersion != "" && compareVersions(cliVersion, maxVersion) < 0 { - return VersionReconcileResult{Previous: dbVersion, Current: dbVersion, Downgrade: true}, nil - } - - if err := u.cfgRepo.SetLocalMetadata(ctx, "bd_version", cliVersion); err != nil { - return VersionReconcileResult{}, fmt.Errorf("ReconcileVersion: set bd_version: %w", err) - } - if maxVersion == "" || compareVersions(cliVersion, maxVersion) > 0 { - if err := u.cfgRepo.SetLocalMetadata(ctx, "bd_version_max", cliVersion); err != nil { - return VersionReconcileResult{}, fmt.Errorf("ReconcileVersion: set bd_version_max: %w", err) - } - } - - return VersionReconcileResult{Previous: dbVersion, Current: cliVersion, Migrated: true}, nil -} - -func compareVersions(v1, v2 string) int { - parts1 := strings.Split(v1, ".") - parts2 := strings.Split(v2, ".") - - maxLen := len(parts1) - if len(parts2) > maxLen { - maxLen = len(parts2) - } - - for i := 0; i < maxLen; i++ { - var p1, p2 int - if i < len(parts1) { - _, _ = fmt.Sscanf(parts1[i], "%d", &p1) - } - if i < len(parts2) { - _, _ = fmt.Sscanf(parts2[i], "%d", &p2) - } - if p1 < p2 { - return -1 - } - if p1 > p2 { - return 1 - } - } - return 0 + return nil } func (u *configUseCaseImpl) LoadCreateContext(ctx context.Context) (CreateContext, error) { diff --git a/internal/storage/domain/db/config_test.go b/internal/storage/domain/db/config_test.go index 360b78405..b0e15e091 100644 --- a/internal/storage/domain/db/config_test.go +++ b/internal/storage/domain/db/config_test.go @@ -41,14 +41,9 @@ func (s *testSuite) TestConfigSQLRepository() { s.Run("EmptyReturnsEmptyMap", s.configGetAllConfigEmpty) s.Run("ReturnsAllRows", s.configGetAllConfigAllRows) }) - s.Run("ReconcileVersion", func() { - s.Run("EmptyCliVersionErrors", s.configReconcileVersionEmptyErrors) - s.Run("FreshInstallMigratesAndSetsMax", s.configReconcileVersionFreshInstall) - s.Run("AlreadyCurrentIsNoop", s.configReconcileVersionAlreadyCurrent) - s.Run("UpgradeAdvancesVersionAndMax", s.configReconcileVersionUpgrade) - s.Run("DowngradeBelowCurrentRefused", s.configReconcileVersionDowngradeRefused) - s.Run("DowngradeBelowMaxRefused", s.configReconcileVersionDowngradeBelowMaxRefused) - s.Run("CatchUpToMaxMigrates", s.configReconcileVersionCatchUpToMax) + s.Run("LocalMetadata", func() { + s.Run("SetThenGetRoundTrips", s.configLocalMetadataRoundTrip) + s.Run("SetOverwrites", s.configLocalMetadataOverwrite) }) s.Run("UseCase", func() { s.Run("GetConfigMissingKey", s.configUseCaseGetConfigMissing) @@ -523,97 +518,35 @@ func (s *testSuite) resetLocalMetadata() { s.Require().NoError(err) } -func (s *testSuite) configReconcileVersionEmptyErrors() { - _, err := s.configUC().ReconcileVersion(s.Ctx(), "") - s.Require().Error(err) -} - -func (s *testSuite) configReconcileVersionFreshInstall() { +// The clone-local metadata plane is reached through the USE CASE here because +// issueops.VersionReconciler's unit-of-work body reads and writes its two +// markers that way, inside one transaction. +// +// WHAT USED TO BE HERE was seven subtests of a ReconcileVersion method on this +// use case: a fresh install, an upgrade, two refused downgrades, a catch-up to +// the high-water mark. That method held one of the TWO copies of the version +// decision — cmd/bd/version_tracking.go held the other, and nothing compared +// them — and both are now workapi.PlanVersionReconcile, whose table is pinned +// exhaustively and without a database in +// internal/workapi/versionreconcile_test.go. What only a real backend can +// show, that the markers persist and that a refusal writes nothing, is +// asserted at all three backends by TestVersionReconcilerContract. +func (s *testSuite) configLocalMetadataRoundTrip() { s.resetLocalMetadata() - res, err := s.configUC().ReconcileVersion(s.Ctx(), "1.2.0") + s.Require().NoError(s.configUC().SetLocalMetadata(s.Ctx(), "bd_version", "1.2.0")) + + got, err := s.configUC().GetLocalMetadata(s.Ctx(), "bd_version") s.Require().NoError(err) - s.Equal("", res.Previous) - s.Equal("1.2.0", res.Current) - s.True(res.Migrated) - s.False(res.Downgrade) + s.Equal("1.2.0", got) s.Equal("1.2.0", s.localMeta("bd_version")) - s.Equal("1.2.0", s.localMeta("bd_version_max")) } -func (s *testSuite) configReconcileVersionAlreadyCurrent() { +func (s *testSuite) configLocalMetadataOverwrite() { s.resetLocalMetadata() - r := s.configRepo() - s.Require().NoError(r.SetLocalMetadata(s.Ctx(), "bd_version", "1.2.0")) - s.Require().NoError(r.SetLocalMetadata(s.Ctx(), "bd_version_max", "1.2.0")) + s.Require().NoError(s.configUC().SetLocalMetadata(s.Ctx(), "bd_version", "1.2.0")) + s.Require().NoError(s.configUC().SetLocalMetadata(s.Ctx(), "bd_version", "1.3.0")) - res, err := s.configUC().ReconcileVersion(s.Ctx(), "1.2.0") - s.Require().NoError(err) - s.Equal("1.2.0", res.Previous) - s.Equal("1.2.0", res.Current) - s.False(res.Migrated) - s.False(res.Downgrade) -} - -func (s *testSuite) configReconcileVersionUpgrade() { - s.resetLocalMetadata() - r := s.configRepo() - s.Require().NoError(r.SetLocalMetadata(s.Ctx(), "bd_version", "1.2.0")) - s.Require().NoError(r.SetLocalMetadata(s.Ctx(), "bd_version_max", "1.2.0")) - - res, err := s.configUC().ReconcileVersion(s.Ctx(), "1.3.0") - s.Require().NoError(err) - s.Equal("1.2.0", res.Previous) - s.Equal("1.3.0", res.Current) - s.True(res.Migrated) - s.False(res.Downgrade) s.Equal("1.3.0", s.localMeta("bd_version")) - s.Equal("1.3.0", s.localMeta("bd_version_max")) -} - -func (s *testSuite) configReconcileVersionDowngradeRefused() { - s.resetLocalMetadata() - r := s.configRepo() - s.Require().NoError(r.SetLocalMetadata(s.Ctx(), "bd_version", "1.3.0")) - s.Require().NoError(r.SetLocalMetadata(s.Ctx(), "bd_version_max", "1.3.0")) - - res, err := s.configUC().ReconcileVersion(s.Ctx(), "1.2.0") - s.Require().NoError(err) - s.Equal("1.3.0", res.Previous) - s.Equal("1.3.0", res.Current) - s.False(res.Migrated) - s.True(res.Downgrade) - s.Equal("1.3.0", s.localMeta("bd_version")) - s.Equal("1.3.0", s.localMeta("bd_version_max")) -} - -func (s *testSuite) configReconcileVersionDowngradeBelowMaxRefused() { - s.resetLocalMetadata() - r := s.configRepo() - s.Require().NoError(r.SetLocalMetadata(s.Ctx(), "bd_version", "1.1.0")) - s.Require().NoError(r.SetLocalMetadata(s.Ctx(), "bd_version_max", "1.3.0")) - - res, err := s.configUC().ReconcileVersion(s.Ctx(), "1.2.0") - s.Require().NoError(err) - s.False(res.Migrated) - s.True(res.Downgrade) - s.Equal("1.1.0", s.localMeta("bd_version")) - s.Equal("1.3.0", s.localMeta("bd_version_max")) -} - -func (s *testSuite) configReconcileVersionCatchUpToMax() { - s.resetLocalMetadata() - r := s.configRepo() - s.Require().NoError(r.SetLocalMetadata(s.Ctx(), "bd_version", "1.1.0")) - s.Require().NoError(r.SetLocalMetadata(s.Ctx(), "bd_version_max", "1.3.0")) - - res, err := s.configUC().ReconcileVersion(s.Ctx(), "1.3.0") - s.Require().NoError(err) - s.Equal("1.1.0", res.Previous) - s.Equal("1.3.0", res.Current) - s.True(res.Migrated) - s.False(res.Downgrade) - s.Equal("1.3.0", s.localMeta("bd_version")) - s.Equal("1.3.0", s.localMeta("bd_version_max")) } func (s *testSuite) configUseCaseGetConfigMissing() { diff --git a/internal/storage/embeddeddolt/version_reconciler.go b/internal/storage/embeddeddolt/version_reconciler.go new file mode 100644 index 000000000..922ecb087 --- /dev/null +++ b/internal/storage/embeddeddolt/version_reconciler.go @@ -0,0 +1,26 @@ +//go:build cgo + +package embeddeddolt + +import ( + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/workapi/storeversionreconciler" + "github.com/steveyegge/beads/issueops" +) + +// VersionReconciler returns the clone-local version markers for this store. +func (s *EmbeddedDoltStore) VersionReconciler() (issueops.VersionReconciler, error) { + return newVersionReconciler(s) +} + +// newVersionReconciler returns the version markers backed by store. +// +// The implementation is the shared one: the two Dolt-backed stores differ below +// storage.DoltStorage, not above it, so a second copy here would be a copy of +// nothing but the constructor. +func newVersionReconciler(store *EmbeddedDoltStore) (issueops.VersionReconciler, error) { + if store == nil { + return nil, &storage.ErrUnsupported{Op: "newVersionReconciler", Backend: "nil"} + } + return storeversionreconciler.New(store) +} diff --git a/internal/storage/embeddeddolt/version_reconciler_contract_test.go b/internal/storage/embeddeddolt/version_reconciler_contract_test.go new file mode 100644 index 000000000..30c6283fa --- /dev/null +++ b/internal/storage/embeddeddolt/version_reconciler_contract_test.go @@ -0,0 +1,78 @@ +//go:build cgo + +package embeddeddolt_test + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" + "github.com/steveyegge/beads/internal/workapi" +) + +// TestVersionReconcilerContract runs the VersionReconciler contract against the +// embedded store, which hands back the SAME body the server-backed store does +// (internal/workapi/storeversionreconciler) and writes through the same +// SetLocalMetadata, differing only in the engine underneath. That is what this +// wiring catches; it is not an independent vote on the body. +// +// One environment for the whole suite, and here that is a correctness +// requirement rather than only a runtime one: the two version markers are +// global to a workspace, so the subtests have to run sequentially over one +// plane, each seeding the state it asserts about. +func TestVersionReconcilerContract(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "vrec") + ctx := t.Context() + fixture := newEmbeddedVersionReconcilerFixture(t, te, "vrec") + + t.Run("RecordsAWorkspaceWithNoMarkers", func(t *testing.T) { + conformance.RunVersionReconcilerRecordsAWorkspaceWithNoMarkers(t, ctx, fixture) + }) + t.Run("AdvancesBothMarkersOnAnUpgrade", func(t *testing.T) { + conformance.RunVersionReconcilerAdvancesBothMarkersOnAnUpgrade(t, ctx, fixture) + }) + t.Run("TreatsTheSameVersionAsANoOp", func(t *testing.T) { + conformance.RunVersionReconcilerTreatsTheSameVersionAsANoOp(t, ctx, fixture) + }) + t.Run("RefusesADowngradeWithoutAnError", func(t *testing.T) { + conformance.RunVersionReconcilerRefusesADowngradeWithoutAnError(t, ctx, fixture) + }) + t.Run("RefusesAVersionBelowTheHighWaterMark", func(t *testing.T) { + conformance.RunVersionReconcilerRefusesAVersionBelowTheHighWaterMark(t, ctx, fixture) + }) + t.Run("CatchesUpToTheHighWaterMark", func(t *testing.T) { + conformance.RunVersionReconcilerCatchesUpToTheHighWaterMark(t, ctx, fixture) + }) + t.Run("RefusesAnEmptyVersion", func(t *testing.T) { + conformance.RunVersionReconcilerRefusesAnEmptyVersion(t, ctx, fixture) + }) + t.Run("LeavesTheMarkersStandingWhenItCannotComplete", func(t *testing.T) { + conformance.RunVersionReconcilerLeavesTheMarkersStandingWhenItCannotComplete(t, ctx, fixture) + }) + t.Run("RecordsNoHistory", func(t *testing.T) { + conformance.RunVersionReconcilerRecordsNoHistory(t, ctx, fixture) + }) +} + +func newEmbeddedVersionReconcilerFixture(t *testing.T, te *testEnv, prefix string) conformance.VersionReconcilerFixture { + t.Helper() + reconciler, err := te.store.VersionReconciler() + if err != nil { + t.Fatalf("VersionReconciler(): %v", err) + } + kit := newEmbeddedRoleFixtureKit(te, prefix) + return conformance.VersionReconcilerFixture{ + Reconciler: reconciler, + // Past the role, through the store's own metadata seam: the role can + // never leave a marker below the mark, and two cases assert about + // exactly that state. + RecordMarkers: func(ctx context.Context, recorded, highWaterMark string) error { + if err := te.store.SetLocalMetadata(ctx, workapi.MetadataKeyVersion, recorded); err != nil { + return err + } + return te.store.SetLocalMetadata(ctx, workapi.MetadataKeyVersionMax, highWaterMark) + }, + CountHistory: kit.CountHistory, + } +} diff --git a/internal/storage/hook_version_reconciler.go b/internal/storage/hook_version_reconciler.go new file mode 100644 index 000000000..eff82dbe5 --- /dev/null +++ b/internal/storage/hook_version_reconciler.go @@ -0,0 +1,24 @@ +package storage + +import ( + "github.com/steveyegge/beads/issueops" +) + +// VersionReconciler returns the inner store's version-marker surface. +// +// It recurses, like every other accessor on this decorator, rather than being +// absent: the accessor set is uniform across the chain, so a caller never has +// to know which decorators a store is wearing. What it does NOT do is wrap the +// result, and here that is the same statement hook_workspace_config.go makes +// about a role that WRITES. +// +// This decorator's vocabulary is on_create / on_update / on_close, and every +// one of those hands a hook script an ISSUE. Recording which binary opened the +// workspace has no issue to name and no bead to describe, so there is nothing +// this layer could fire that a hook script could read. There is a second reason +// here that the settings role does not have: this one runs from PersistentPreRun +// on every startup, so a hook fired here would run a user's script before every +// command — including the ones that go on to fail on their own arguments. +func (h *HookFiringStore) VersionReconciler() (issueops.VersionReconciler, error) { + return h.inner.VersionReconciler() +} diff --git a/internal/storage/role_accessor_decorator_test.go b/internal/storage/role_accessor_decorator_test.go index 4d92c771a..e5f212a64 100644 --- a/internal/storage/role_accessor_decorator_test.go +++ b/internal/storage/role_accessor_decorator_test.go @@ -11,9 +11,9 @@ import ( "github.com/steveyegge/beads/issueops" ) -// roleAccessorNames is the thirteen-strong capability surface every storage +// roleAccessorNames is the fourteen-strong capability surface every storage // decorator has to answer for. It is written out rather than derived so that -// adding a fourteenth role to DoltStorage without deciding what each decorator +// adding a fifteenth role to DoltStorage without deciding what each decorator // does with it is a compile-or-test failure somewhere, not silence. var roleAccessorNames = []string{ "IssueLifecycle", @@ -22,6 +22,7 @@ var roleAccessorNames = []string{ "EdgeReader", "Counter", "WorkspaceConfig", + "VersionReconciler", "StatsReporter", "CycleDetector", "ReadyCounter", @@ -66,7 +67,7 @@ func assertRoleAccessorsAreDeclared(t *testing.T, decorator reflect.Type) { } } -// roleAccessorStore is a DoltStorage whose only real methods are the thirteen role +// roleAccessorStore is a DoltStorage whose only real methods are the fourteen role // accessors, each answering with a distinguishable sentinel so a test can tell // a decorated surface from a passed-through one. type roleAccessorStore struct { @@ -77,6 +78,7 @@ type roleAccessorStore struct { edges issueops.EdgeReader counter issueops.Counter settings issueops.WorkspaceConfig + versions issueops.VersionReconciler stats issueops.StatsReporter cycles issueops.CycleDetector commenter issueops.Commenter @@ -96,6 +98,7 @@ func newRoleAccessorStore() *roleAccessorStore { edges: sentinel, counter: sentinel, settings: sentinel, + versions: sentinel, stats: sentinel, cycles: sentinel, commenter: sentinel, @@ -113,6 +116,9 @@ func (s *roleAccessorStore) Counter() (issueops.Counter, error) { retur func (s *roleAccessorStore) WorkspaceConfig() (issueops.WorkspaceConfig, error) { return s.settings, s.err } +func (s *roleAccessorStore) VersionReconciler() (issueops.VersionReconciler, error) { + return s.versions, s.err +} func (s *roleAccessorStore) StatsReporter() (issueops.StatsReporter, error) { return s.stats, s.err } @@ -133,7 +139,7 @@ func (s *roleAccessorStore) DependencyEditor() (issueops.DependencyEditor, error return s.editor, s.err } -// roleAccessorSentinel implements all thirteen roles at once. Nothing calls its +// roleAccessorSentinel implements all fourteen roles at once. Nothing calls its // methods; identity is the whole point. type roleAccessorSentinel struct{} @@ -182,6 +188,12 @@ func (*roleAccessorSentinel) SetSetting(context.Context, issueops.SetSettingRequ func (*roleAccessorSentinel) UnsetSetting(context.Context, issueops.UnsetSettingRequest) (issueops.UnsetSettingResult, error) { return issueops.UnsetSettingResult{}, nil } +func (*roleAccessorSentinel) RecordedVersion(context.Context, issueops.RecordedVersionRequest) (issueops.RecordedVersionResult, error) { + return issueops.RecordedVersionResult{}, nil +} +func (*roleAccessorSentinel) ReconcileVersion(context.Context, issueops.VersionReconcileRequest) (issueops.VersionReconcileResult, error) { + return issueops.VersionReconcileResult{}, nil +} func (*roleAccessorSentinel) Stats(context.Context, issueops.StatsRequest) (issueops.StatsResult, error) { return issueops.StatsResult{}, nil } @@ -218,15 +230,16 @@ func (*roleAccessorSentinel) RemoveDependency(context.Context, issueops.RemoveDe // satisfying DoltStorage, and silently stops every completion hook on that // role. // -// Five roles are asserted the OTHER way round on purpose. Reads fire no +// Six roles are asserted the OTHER way round on purpose. Reads fire no // completion hooks, so IssueReader, IssueRelations, Counter and StatsReporter // deliberately return the inner surface unwrapped (hook_issue_reader.go, // hook_relations.go, hook_counter.go, hook_stats_reporter.go); WorkspaceConfig -// does too, and it is the one that is NOT a read — a settings write changes the -// workspace rather than a bead, so this decorator's issue-shaped hook -// vocabulary has nothing to hand a hook script (hook_workspace_config.go). -// This test pins all five as decisions rather than leaving them -// indistinguishable from the regression above. +// and VersionReconciler do too, and those two are the ones that are NOT reads — +// a settings write changes the workspace rather than a bead and a version +// marker names no bead at all, so this decorator's issue-shaped hook vocabulary +// has nothing to hand a hook script (hook_workspace_config.go, +// hook_version_reconciler.go). This test pins all six as decisions rather than +// leaving them indistinguishable from the regression above. // The four read roles are asserted the OTHER way round on purpose. Reads fire // no completion hooks, so IssueReader, IssueRelations, Counter and // CycleDetector deliberately return the inner surface unwrapped @@ -265,6 +278,7 @@ func TestHookFiringStoreWrapsTheWriteRolesAndPassesTheReadsThrough(t *testing.T) {"EdgeReader", func() (any, error) { return store.EdgeReader() }, inner.edges, false}, {"Counter", func() (any, error) { return store.Counter() }, inner.counter, false}, {"WorkspaceConfig", func() (any, error) { return store.WorkspaceConfig() }, inner.settings, false}, + {"VersionReconciler", func() (any, error) { return store.VersionReconciler() }, inner.versions, false}, {"StatsReporter", func() (any, error) { return store.StatsReporter() }, inner.stats, false}, {"CycleDetector", func() (any, error) { return store.CycleDetector() }, inner.cycles, false}, {"ReadyCounter", func() (any, error) { return store.ReadyCounter() }, inner.readyCounter, false}, @@ -308,6 +322,7 @@ func TestHookFiringStoreRoleAccessorsPropagateInnerErrors(t *testing.T) { {"EdgeReader", func() (any, error) { return store.EdgeReader() }}, {"Counter", func() (any, error) { return store.Counter() }}, {"WorkspaceConfig", func() (any, error) { return store.WorkspaceConfig() }}, + {"VersionReconciler", func() (any, error) { return store.VersionReconciler() }}, {"StatsReporter", func() (any, error) { return store.StatsReporter() }}, {"CycleDetector", func() (any, error) { return store.CycleDetector() }}, {"ReadyCounter", func() (any, error) { return store.ReadyCounter() }}, diff --git a/internal/storage/storage.go b/internal/storage/storage.go index e390a47f1..c77317da8 100644 --- a/internal/storage/storage.go +++ b/internal/storage/storage.go @@ -179,6 +179,16 @@ type Storage interface { // re-project a value into a normalized lookup table — a side effect no // issue role has anywhere to describe. WorkspaceConfig() (issueops.WorkspaceConfig, error) + + // VersionReconciler returns the clone-local version markers for this store: + // the dolt-ignored pair recording which bd binary last opened this + // workspace and the highest one that ever has. It is its own role rather + // than two more keys on WorkspaceConfig because settings are durable and + // travel with the database while these two are deliberately per-clone, and + // it is the one role here that belongs to no command — it answers a startup + // hook, so its failure costs every invocation rather than one. + VersionReconciler() (issueops.VersionReconciler, error) + // CycleDetector returns the guarded cycle-report surface for this store: its // own role because it is asked of the WHOLE graph and answers with paths, // where every Relations request names one anchor and answers with that diff --git a/internal/storage/uow/version_reconcile_integration_test.go b/internal/storage/uow/version_reconcile_integration_test.go index 1508a6824..6f1e14d9b 100644 --- a/internal/storage/uow/version_reconcile_integration_test.go +++ b/internal/storage/uow/version_reconcile_integration_test.go @@ -4,14 +4,14 @@ import ( "context" "os/exec" "path/filepath" - "strings" "testing" "github.com/stretchr/testify/require" "github.com/steveyegge/beads/internal/storage/dbproxy/proxy" - "github.com/steveyegge/beads/internal/storage/domain" "github.com/steveyegge/beads/internal/testutil" + "github.com/steveyegge/beads/internal/workapi" + publicops "github.com/steveyegge/beads/issueops" ) func newTestUOWProvider(t *testing.T) UnitOfWorkProvider { @@ -60,45 +60,42 @@ func newTestUOWProvider(t *testing.T) UnitOfWorkProvider { return provider } +// TestReconcileVersionPersistsAcrossUOW is the one version assertion that +// stays out of the conformance contract, because it is about this backend's +// TRANSACTION rather than about the role: a marker written inside a unit of +// work that is closed without a commit must not be there afterwards. +// +// The role cannot express that — every write through it commits — so the +// rolled-back leg drives the metadata seam directly, the same seam the role's +// body writes through. Everything else the old version of this test covered +// (fresh install, no-op, upgrade, persistence into a NEW unit of work) is now +// TestVersionReconcilerContract, which runs it here and on the two store +// backends instead of only here. func TestReconcileVersionPersistsAcrossUOW(t *testing.T) { provider := newTestUOWProvider(t) ctx := context.Background() - reconcileCommitted := func(cliVersion string) domain.VersionReconcileResult { - uw, err := provider.NewUOW(ctx) - require.NoError(t, err) - defer uw.Close(ctx) - res, err := uw.ConfigUseCase().ReconcileVersion(ctx, cliVersion) - require.NoError(t, err) - err = uw.Commit(ctx, "bd: reconcile version") - if err != nil && !strings.Contains(strings.ToLower(err.Error()), "nothing to commit") { - require.NoError(t, err) - } - return res - } + reconciler, err := NewVersionReconciler(provider) + require.NoError(t, err) - r := reconcileCommitted("0.5.0") - require.Equal(t, "", r.Previous) - require.Equal(t, "0.5.0", r.Current) - require.True(t, r.Migrated) + res, err := reconciler.ReconcileVersion(ctx, publicops.VersionReconcileRequest{CLIVersion: "0.5.0"}) + require.NoError(t, err) + require.Equal(t, "", res.Previous) + require.Equal(t, "0.5.0", res.Current) + require.True(t, res.Migrated) - r = reconcileCommitted("0.5.0") - require.Equal(t, "0.5.0", r.Previous, "committed bd_version must persist into a new UOW") - require.False(t, r.Migrated) - - r = reconcileCommitted("0.6.0") - require.Equal(t, "0.5.0", r.Previous) - require.Equal(t, "0.6.0", r.Current) - require.True(t, r.Migrated) + res, err = reconciler.ReconcileVersion(ctx, publicops.VersionReconcileRequest{CLIVersion: "0.6.0"}) + require.NoError(t, err) + require.Equal(t, "0.5.0", res.Previous, "a committed marker must persist into a new unit of work") + require.True(t, res.Migrated) + // Write the marker forward and abandon the unit of work. uw, err := provider.NewUOW(ctx) require.NoError(t, err) - res, err := uw.ConfigUseCase().ReconcileVersion(ctx, "0.7.0") - require.NoError(t, err) - require.True(t, res.Migrated) + require.NoError(t, uw.ConfigUseCase().SetLocalMetadata(ctx, workapi.MetadataKeyVersion, "0.7.0")) uw.Close(ctx) - r = reconcileCommitted("0.7.0") - require.Equal(t, "0.6.0", r.Previous, "rolled-back reconcile must not persist") - require.True(t, r.Migrated) + recorded, err := reconciler.RecordedVersion(ctx, publicops.RecordedVersionRequest{}) + require.NoError(t, err) + require.Equal(t, "0.6.0", recorded.Recorded, "a rolled-back marker write must not persist") } diff --git a/internal/storage/uow/version_reconciler.go b/internal/storage/uow/version_reconciler.go new file mode 100644 index 000000000..e628092d3 --- /dev/null +++ b/internal/storage/uow/version_reconciler.go @@ -0,0 +1,105 @@ +package uow + +import ( + "context" + "fmt" + + "github.com/steveyegge/beads/internal/workapi" + publicops "github.com/steveyegge/beads/issueops" +) + +// VersionReconcilerSource is the capability accessor a unit-of-work provider +// offers for the clone-local version markers, the sibling of +// WorkspaceConfigSource and CounterSource. +type VersionReconcilerSource interface { + VersionReconciler() (publicops.VersionReconciler, error) +} + +// versionReconciler reads and records the version markers through a unit of +// work. +type versionReconciler struct { + provider UnitOfWorkProvider +} + +// VersionReconciler returns the version-marker surface for this provider. +func (p *doltSQLProvider) VersionReconciler() (publicops.VersionReconciler, error) { + return NewVersionReconciler(p) +} + +// NewVersionReconciler constructs a public version-marker surface backed by +// provider. +func NewVersionReconciler(provider UnitOfWorkProvider) (publicops.VersionReconciler, error) { + if isNilUnitOfWorkProvider(provider) { + return nil, fmt.Errorf("new version reconciler: unit-of-work provider must not be nil") + } + return &versionReconciler{provider: provider}, nil +} + +var _ publicops.VersionReconciler = (*versionReconciler)(nil) + +func (r *versionReconciler) RecordedVersion(ctx context.Context, _ publicops.RecordedVersionRequest) (publicops.RecordedVersionResult, error) { + return RunTxRead(ctx, r.provider, func(ctx context.Context, uw UnitOfWork) (publicops.RecordedVersionResult, error) { + recorded, mark, err := readVersionMarkers(ctx, uw) + if err != nil { + return publicops.RecordedVersionResult{}, err + } + return publicops.RecordedVersionResult{Recorded: recorded, HighWaterMark: mark}, nil + }) +} + +// ReconcileVersion reads the markers, plans and writes inside ONE unit of work. +// +// The whole decision is inside the transaction on purpose. This backend serves +// a workspace several clients share, so two bd processes can start at the same +// moment against one database; a plan made from a read outside the transaction +// could be written after another process had already moved the marker past it, +// which is the one way this role could ever lower the high-water mark. +// +// VALIDATION HAPPENS BEFORE THE UNIT OF WORK IS OPENED, for the reason +// workspaceConfig.SetSetting gives — a refused reconciliation should cost no +// connection and no transaction, and this one runs before every command. +// +// A NO-OP AND A REFUSAL STILL OPEN THE TRANSACTION and commit nothing, which is +// how this backend answers "reconciliation records no history": the commit +// message is only spent when something was written, and RunTxResult treats a +// unit of work with nothing in it as the no-op it is. +func (r *versionReconciler) ReconcileVersion(ctx context.Context, req publicops.VersionReconcileRequest) (publicops.VersionReconcileResult, error) { + if _, err := workapi.ValidateReconcileVersion(req.CLIVersion); err != nil { + return publicops.VersionReconcileResult{}, err + } + + return RunTxResult(ctx, r.provider, func(ctx context.Context, uw UnitOfWork) (publicops.VersionReconcileResult, string, error) { + recorded, mark, err := readVersionMarkers(ctx, uw) + if err != nil { + return publicops.VersionReconcileResult{}, "", err + } + plan, err := workapi.PlanVersionReconcile(req.CLIVersion, recorded, mark) + if err != nil { + return publicops.VersionReconcileResult{}, "", err + } + + if plan.RecordVersion { + if err := uw.ConfigUseCase().SetLocalMetadata(ctx, workapi.MetadataKeyVersion, plan.Result.Current); err != nil { + return publicops.VersionReconcileResult{}, "", err + } + } + if plan.RecordHighWaterMark { + if err := uw.ConfigUseCase().SetLocalMetadata(ctx, workapi.MetadataKeyVersionMax, plan.Result.Current); err != nil { + return publicops.VersionReconcileResult{}, "", err + } + } + return plan.Result, "bd: reconcile version -> " + plan.Result.Current, nil + }) +} + +func readVersionMarkers(ctx context.Context, uw UnitOfWork) (recorded, mark string, err error) { + recorded, err = uw.ConfigUseCase().GetLocalMetadata(ctx, workapi.MetadataKeyVersion) + if err != nil { + return "", "", err + } + mark, err = uw.ConfigUseCase().GetLocalMetadata(ctx, workapi.MetadataKeyVersionMax) + if err != nil { + return "", "", err + } + return recorded, mark, nil +} diff --git a/internal/storage/uow/version_reconciler_contract_test.go b/internal/storage/uow/version_reconciler_contract_test.go new file mode 100644 index 000000000..7fc2aee8b --- /dev/null +++ b/internal/storage/uow/version_reconciler_contract_test.go @@ -0,0 +1,91 @@ +package uow + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" + "github.com/steveyegge/beads/internal/workapi" +) + +// TestVersionReconcilerContract runs the VersionReconciler contract against the +// unit-of-work provider — the one implementation that does not hand back +// internal/workapi/storeversionreconciler, so this is the wiring where a +// genuine body divergence shows up. The two store backends share that body +// between them, which makes this the SECOND of two votes rather than the third. +// +// It is also the only wiring where "the marker is still there afterwards" is a +// question with a hard answer: this body reads, plans and writes inside ONE +// transaction and every assertion reads back through a NEW one, so a write that +// never committed shows up here and nowhere else. +// +// One provider for the whole suite (each newUOWRoleFixtureProvider boots a real +// Dolt sql-server) and NO t.Parallel: this backend has no per-test +// copy-on-write branch, so the metadata plane and dolt_log are database-global +// and a parallel subtest would corrupt another subtest's seeded markers and +// history delta. +func TestVersionReconcilerContract(t *testing.T) { + ctx := context.Background() + fixture := newUOWVersionReconcilerFixture(t, ctx, "vrec") + + t.Run("RecordsAWorkspaceWithNoMarkers", func(t *testing.T) { + conformance.RunVersionReconcilerRecordsAWorkspaceWithNoMarkers(t, ctx, fixture) + }) + t.Run("AdvancesBothMarkersOnAnUpgrade", func(t *testing.T) { + conformance.RunVersionReconcilerAdvancesBothMarkersOnAnUpgrade(t, ctx, fixture) + }) + t.Run("TreatsTheSameVersionAsANoOp", func(t *testing.T) { + conformance.RunVersionReconcilerTreatsTheSameVersionAsANoOp(t, ctx, fixture) + }) + t.Run("RefusesADowngradeWithoutAnError", func(t *testing.T) { + conformance.RunVersionReconcilerRefusesADowngradeWithoutAnError(t, ctx, fixture) + }) + t.Run("RefusesAVersionBelowTheHighWaterMark", func(t *testing.T) { + conformance.RunVersionReconcilerRefusesAVersionBelowTheHighWaterMark(t, ctx, fixture) + }) + t.Run("CatchesUpToTheHighWaterMark", func(t *testing.T) { + conformance.RunVersionReconcilerCatchesUpToTheHighWaterMark(t, ctx, fixture) + }) + t.Run("RefusesAnEmptyVersion", func(t *testing.T) { + conformance.RunVersionReconcilerRefusesAnEmptyVersion(t, ctx, fixture) + }) + t.Run("LeavesTheMarkersStandingWhenItCannotComplete", func(t *testing.T) { + conformance.RunVersionReconcilerLeavesTheMarkersStandingWhenItCannotComplete(t, ctx, fixture) + }) + t.Run("RecordsNoHistory", func(t *testing.T) { + conformance.RunVersionReconcilerRecordsNoHistory(t, ctx, fixture) + }) +} + +func newUOWVersionReconcilerFixture(t *testing.T, ctx context.Context, prefix string) conformance.VersionReconcilerFixture { + t.Helper() + provider := newUOWRoleFixtureProvider(t, ctx, prefix) + // Through the capability accessor, not NewVersionReconciler: a provider + // that stopped offering the role is the regression, and a constructor call + // would hide it. + source, ok := provider.(VersionReconcilerSource) + if !ok { + t.Fatalf("provider %T does not offer the VersionReconciler accessor", provider) + } + reconciler, err := source.VersionReconciler() + if err != nil { + t.Fatalf("VersionReconciler(): %v", err) + } + kit := newUOWRoleFixtureKit(provider, prefix) + return conformance.VersionReconcilerFixture{ + Reconciler: reconciler, + // Past the role, through the metadata seam its body writes through, in + // its own committed transaction: the role can never leave a marker + // below the mark, and two cases assert about exactly that state. + RecordMarkers: func(ctx context.Context, recorded, highWaterMark string) error { + return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + if err := uw.ConfigUseCase().SetLocalMetadata(ctx, workapi.MetadataKeyVersion, recorded); err != nil { + return "", err + } + return "bd: seed version markers", + uw.ConfigUseCase().SetLocalMetadata(ctx, workapi.MetadataKeyVersionMax, highWaterMark) + }) + }, + CountHistory: kit.CountHistory, + } +} diff --git a/internal/telemetry/role_accessor_decorator_test.go b/internal/telemetry/role_accessor_decorator_test.go index 344133dea..05fa92b95 100644 --- a/internal/telemetry/role_accessor_decorator_test.go +++ b/internal/telemetry/role_accessor_decorator_test.go @@ -12,7 +12,7 @@ import ( "github.com/steveyegge/beads/issueops" ) -// roleAccessorNames is the thirteen-strong capability surface every storage +// roleAccessorNames is the fourteen-strong capability surface every storage // decorator has to answer for. It is duplicated from the sibling test in // internal/storage rather than shared because that package cannot import this // one and this one's test helpers cannot be exported back. @@ -23,6 +23,7 @@ var roleAccessorNames = []string{ "EdgeReader", "Counter", "WorkspaceConfig", + "VersionReconciler", "StatsReporter", "CycleDetector", "ReadyCounter", @@ -56,7 +57,7 @@ func TestInstrumentedStorageDeclaresEveryRoleAccessor(t *testing.T) { } } -// roleAccessorStore is a DoltStorage whose only real methods are the thirteen role +// roleAccessorStore is a DoltStorage whose only real methods are the fourteen role // accessors, each answering with a distinguishable sentinel so a test can tell // an instrumented surface from a passed-through one. type roleAccessorStore struct { @@ -72,6 +73,9 @@ func (s *roleAccessorStore) Counter() (issueops.Counter, error) { retur func (s *roleAccessorStore) WorkspaceConfig() (issueops.WorkspaceConfig, error) { return s.surface, s.err } +func (s *roleAccessorStore) VersionReconciler() (issueops.VersionReconciler, error) { + return s.surface, s.err +} func (s *roleAccessorStore) StatsReporter() (issueops.StatsReporter, error) { return s.surface, s.err } @@ -92,7 +96,7 @@ func (s *roleAccessorStore) DependencyEditor() (issueops.DependencyEditor, error return s.surface, s.err } -// roleAccessorSentinel implements all thirteen roles at once. Nothing calls its +// roleAccessorSentinel implements all fourteen roles at once. Nothing calls its // methods; identity is the whole point. type roleAccessorSentinel struct{} @@ -141,6 +145,12 @@ func (*roleAccessorSentinel) SetSetting(context.Context, issueops.SetSettingRequ func (*roleAccessorSentinel) UnsetSetting(context.Context, issueops.UnsetSettingRequest) (issueops.UnsetSettingResult, error) { return issueops.UnsetSettingResult{}, nil } +func (*roleAccessorSentinel) RecordedVersion(context.Context, issueops.RecordedVersionRequest) (issueops.RecordedVersionResult, error) { + return issueops.RecordedVersionResult{}, nil +} +func (*roleAccessorSentinel) ReconcileVersion(context.Context, issueops.VersionReconcileRequest) (issueops.VersionReconcileResult, error) { + return issueops.VersionReconcileResult{}, nil +} func (*roleAccessorSentinel) Stats(context.Context, issueops.StatsRequest) (issueops.StatsResult, error) { return issueops.StatsResult{}, nil } @@ -199,6 +209,7 @@ func TestInstrumentedStorageInstrumentsEveryRoleAccessor(t *testing.T) { {"EdgeReader", func() (any, error) { return wrapped.EdgeReader() }}, {"Counter", func() (any, error) { return wrapped.Counter() }}, {"WorkspaceConfig", func() (any, error) { return wrapped.WorkspaceConfig() }}, + {"VersionReconciler", func() (any, error) { return wrapped.VersionReconciler() }}, {"StatsReporter", func() (any, error) { return wrapped.StatsReporter() }}, {"CycleDetector", func() (any, error) { return wrapped.CycleDetector() }}, {"ReadyCounter", func() (any, error) { return wrapped.ReadyCounter() }}, @@ -240,6 +251,7 @@ func TestInstrumentedStorageRoleAccessorsPropagateInnerErrors(t *testing.T) { {"EdgeReader", func() (any, error) { return wrapped.EdgeReader() }}, {"Counter", func() (any, error) { return wrapped.Counter() }}, {"WorkspaceConfig", func() (any, error) { return wrapped.WorkspaceConfig() }}, + {"VersionReconciler", func() (any, error) { return wrapped.VersionReconciler() }}, {"StatsReporter", func() (any, error) { return wrapped.StatsReporter() }}, {"CycleDetector", func() (any, error) { return wrapped.CycleDetector() }}, {"ReadyCounter", func() (any, error) { return wrapped.ReadyCounter() }}, diff --git a/internal/telemetry/version_reconciler.go b/internal/telemetry/version_reconciler.go new file mode 100644 index 000000000..78319f71b --- /dev/null +++ b/internal/telemetry/version_reconciler.go @@ -0,0 +1,47 @@ +package telemetry + +import ( + "context" + + "github.com/steveyegge/beads/issueops" +) + +// VersionReconciler returns the inner store's version-marker surface wrapped in +// this layer's instrumentation. It recurses instead of delegating: a blind +// delegation would return the inner surface unspanned and untimed. +// +// This is the one role whose spans are emitted on EVERY command, which makes it +// the one place a startup regression would show up as a number rather than as a +// report that bd feels slow. +func (s *InstrumentedStorage) VersionReconciler() (issueops.VersionReconciler, error) { + inner, err := s.Unwrap().VersionReconciler() + if err != nil { + return nil, err + } + return s.WrapVersionReconciler(inner), nil +} + +// WrapVersionReconciler instruments guarded version-marker access with this +// storage layer's existing telemetry meter and tracer. +func (s *InstrumentedStorage) WrapVersionReconciler(inner issueops.VersionReconciler) issueops.VersionReconciler { + return &instrumentedVersionReconciler{storage: s, inner: inner} +} + +type instrumentedVersionReconciler struct { + storage *InstrumentedStorage + inner issueops.VersionReconciler +} + +func (r *instrumentedVersionReconciler) RecordedVersion(ctx context.Context, request issueops.RecordedVersionRequest) (result issueops.RecordedVersionResult, err error) { + ctx, span, started := r.storage.op(ctx, "VersionReconciler.RecordedVersion") + result, err = r.inner.RecordedVersion(ctx, request) + r.storage.done(ctx, span, started, err) + return result, err +} + +func (r *instrumentedVersionReconciler) ReconcileVersion(ctx context.Context, request issueops.VersionReconcileRequest) (result issueops.VersionReconcileResult, err error) { + ctx, span, started := r.storage.op(ctx, "VersionReconciler.ReconcileVersion") + result, err = r.inner.ReconcileVersion(ctx, request) + r.storage.done(ctx, span, started, err) + return result, err +} diff --git a/internal/workapi/storeversionreconciler/versionreconciler.go b/internal/workapi/storeversionreconciler/versionreconciler.go new file mode 100644 index 000000000..bd580634b --- /dev/null +++ b/internal/workapi/storeversionreconciler/versionreconciler.go @@ -0,0 +1,101 @@ +// Package storeversionreconciler holds the store-backed implementation of +// issueops.VersionReconciler: one shared body that every store-shaped backend's +// VersionReconciler accessor hands back. +// +// It is a package of its own for the reason internal/workapi/storereader and +// internal/workapi/storeworkspaceconfig are — see those packages' docs. A +// constructor sitting in internal/workapi would be a one-line drop-in for +// store.VersionReconciler() from any front door, and one that silently skips +// the decorators, because a decorator adds its layer in its own accessor. Down +// here the only importers are the two Dolt store packages, and the +// cmd-bd-role-constructors depguard rule in .golangci.yml makes a front door +// importing it a lint failure rather than a review comment. +// +// The accessor is the door. This is the thing behind it. +package storeversionreconciler + +import ( + "context" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/workapi" + "github.com/steveyegge/beads/issueops" +) + +// New returns the version-marker surface backed by a store handle. *DoltStore +// and *EmbeddedDoltStore answer identically because the difference between them +// is below storage.DoltStorage, not above it. +func New(store storage.DoltStorage) (issueops.VersionReconciler, error) { + if store == nil { + return nil, &issueops.ErrUnsupported{Op: "storeversionreconciler.New", Backend: "nil"} + } + return &storeVersionReconciler{store: store}, nil +} + +type storeVersionReconciler struct{ store storage.DoltStorage } + +var _ issueops.VersionReconciler = (*storeVersionReconciler)(nil) + +func (r *storeVersionReconciler) RecordedVersion(ctx context.Context, _ issueops.RecordedVersionRequest) (issueops.RecordedVersionResult, error) { + recorded, mark, err := r.readMarkers(ctx) + if err != nil { + return issueops.RecordedVersionResult{}, err + } + return issueops.RecordedVersionResult{Recorded: recorded, HighWaterMark: mark}, nil +} + +// ReconcileVersion reads the markers, decides through the shared planner and +// writes only what the plan asks for. +// +// THE TWO WRITES ARE NOT ONE TRANSACTION on this backend, and that is stated +// rather than hidden: storage.DoltStorage publishes methods, not transactions, +// so a failure between them leaves the marker moved and the mark behind. The +// consequence is bounded and benign — a mark below the marker only ever means +// the next older binary is refused by the marker instead of by the mark, which +// is the same refusal — and buying atomicity would mean a transaction-scoped +// body for two writes to a dolt-ignored plane that no other reader shares. +func (r *storeVersionReconciler) ReconcileVersion(ctx context.Context, req issueops.VersionReconcileRequest) (issueops.VersionReconcileResult, error) { + // Validate before reading anything: a refused reconciliation should cost no + // round trip, and this one runs on every startup. + if _, err := workapi.ValidateReconcileVersion(req.CLIVersion); err != nil { + return issueops.VersionReconcileResult{}, err + } + + recorded, mark, err := r.readMarkers(ctx) + if err != nil { + return issueops.VersionReconcileResult{}, err + } + plan, err := workapi.PlanVersionReconcile(req.CLIVersion, recorded, mark) + if err != nil { + return issueops.VersionReconcileResult{}, err + } + + if plan.RecordVersion { + if err := r.store.SetLocalMetadata(ctx, workapi.MetadataKeyVersion, plan.Result.Current); err != nil { + return issueops.VersionReconcileResult{}, err + } + } + if plan.RecordHighWaterMark { + if err := r.store.SetLocalMetadata(ctx, workapi.MetadataKeyVersionMax, plan.Result.Current); err != nil { + return issueops.VersionReconcileResult{}, err + } + } + return plan.Result, nil +} + +// readMarkers reads both markers, which is the whole cost of the path that +// changes nothing: two point reads of a dolt-ignored table, no configuration +// load, no second connection and no lock. Both are read even when the first one +// already decides the outcome, because RecordedVersion publishes the pair and a +// second shape of this helper would be a second thing to keep true. +func (r *storeVersionReconciler) readMarkers(ctx context.Context) (recorded, mark string, err error) { + recorded, err = r.store.GetLocalMetadata(ctx, workapi.MetadataKeyVersion) + if err != nil { + return "", "", err + } + mark, err = r.store.GetLocalMetadata(ctx, workapi.MetadataKeyVersionMax) + if err != nil { + return "", "", err + } + return recorded, mark, nil +} diff --git a/internal/workapi/versionreconcile.go b/internal/workapi/versionreconcile.go new file mode 100644 index 000000000..253a7ad30 --- /dev/null +++ b/internal/workapi/versionreconcile.go @@ -0,0 +1,154 @@ +package workapi + +import ( + "fmt" + "strings" + + "github.com/steveyegge/beads/issueops" +) + +// This file holds the DECISION half of issueops.VersionReconciler: given the +// running binary's version and the two markers a workspace currently holds, +// what should happen. It is a pure function for the reason BuildCountFilter and +// ValidateCountGroup are — every implementation decides through it, so the +// answer cannot differ by backend, and the cases that matter (a downgrade below +// the marker, a downgrade below the mark, a catch-up to the mark) are pinned in +// milliseconds without a database. +// +// It is ALSO where the duplication went. Before this role, the direct route +// compared versions in cmd/bd/version_tracking.go and the proxied route +// compared them again in a use case, each with its own copy of the dotted +// comparison; the two agreed, but nothing made them agree and no test compared +// them. The conformance contract is left to assert what only a real backend can +// show: that the markers persist, that a refusal writes nothing, and that +// neither the read nor the write touches history. + +// MetadataKeyVersion and MetadataKeyVersionMax are the two clone-local, +// dolt-ignored keys the version markers live under. +// +// They are named here rather than spelled at each call site because three +// implementations and three conformance wirings write them, and a key spelled +// differently in one of those places is a marker nothing else can find — which +// looks exactly like a workspace that was never reconciled. +const ( + MetadataKeyVersion = "bd_version" + MetadataKeyVersionMax = "bd_version_max" +) + +// VersionReconcilePlan is what a reconciliation decided, plus which of the two +// markers that decision has to write. +// +// The writes are reported as flags rather than performed here because the three +// backends reach the metadata plane differently — two through a store handle, +// one through a unit of work — and the decision is the same on all of them. +type VersionReconcilePlan struct { + // Result is what the caller returns, unchanged, once the writes below + // succeed. It is complete before any write happens, which is what makes + // "a failed reconciliation reports an error rather than a wrong outcome" + // checkable: there is no field a partial write could still be filling in. + Result issueops.VersionReconcileResult + // RecordVersion asks for MetadataKeyVersion to be set to Result.Current. + // It is set only for a migration; a no-op and a refusal both write nothing. + RecordVersion bool + // RecordHighWaterMark asks for MetadataKeyVersionMax to be set to + // Result.Current, and is a SEPARATE flag because the mark and the marker do + // not always move together: a workspace catching up to a mark a newer + // binary already left moves the marker to the mark and leaves the mark + // where it is. + RecordHighWaterMark bool +} + +// ValidateReconcileVersion checks the version a caller wants to record, and +// returns it unchanged. +// +// It is separate from the planner so a body can refuse BEFORE it reads +// anything or opens a unit of work — the same reason +// issueops.WorkspaceConfig's bodies validate ahead of RunTx. This runs on +// every startup, so a refusal that costs a round trip is a refusal that costs +// every command. +// +// The only rule at this end is that a version has to name something. Recording +// "" over a real marker would silently take the downgrade guard down with it, +// and the empty marker it left behind is indistinguishable from a workspace +// nothing has ever reconciled. +func ValidateReconcileVersion(cliVersion string) (string, error) { + if strings.TrimSpace(cliVersion) == "" { + return "", fmt.Errorf("%w: cli version must not be empty", issueops.ErrValidation) + } + return cliVersion, nil +} + +// PlanVersionReconcile decides what recording cliVersion should do to a +// workspace whose markers currently read recorded and highWaterMark. +// +// The order of the checks is the contract, not an implementation detail. An +// exact match short-circuits first, so the steady-state path — every startup +// that is not the first one after an upgrade — decides without consulting the +// mark at all. Both downgrade guards then run BEFORE any write is planned, so +// a refusal is a decision rather than a write that is undone. +func PlanVersionReconcile(cliVersion, recorded, highWaterMark string) (VersionReconcilePlan, error) { + if _, err := ValidateReconcileVersion(cliVersion); err != nil { + return VersionReconcilePlan{}, err + } + + if recorded == cliVersion { + return VersionReconcilePlan{ + Result: issueops.VersionReconcileResult{Previous: recorded, Current: recorded}, + }, nil + } + + // A marker BELOW the running binary is the ordinary upgrade. A marker above + // it means an older binary is opening a workspace a newer one has already + // prepared, and relabelling it would make the next upgrade re-run work that + // is already done. The mark catches the same thing after someone has since + // moved the marker back down; it is the only reason the second key exists. + refuse := (recorded != "" && compareDottedVersions(cliVersion, recorded) < 0) || + (highWaterMark != "" && compareDottedVersions(cliVersion, highWaterMark) < 0) + if refuse { + return VersionReconcilePlan{ + Result: issueops.VersionReconcileResult{Previous: recorded, Current: recorded, Downgrade: true}, + }, nil + } + + return VersionReconcilePlan{ + Result: issueops.VersionReconcileResult{Previous: recorded, Current: cliVersion, Migrated: true}, + RecordVersion: true, + RecordHighWaterMark: highWaterMark == "" || compareDottedVersions(cliVersion, highWaterMark) > 0, + }, nil +} + +// compareDottedVersions orders two release strings component by component, +// reading a missing or non-numeric component as 0. +// +// It is deliberately NOT a semver comparison, and issueops.VersionReconcileRequest +// says so where callers will read it: "1.2.0" and "1.2.0-rc1" compare EQUAL +// here, so a pre-release binary reconciles a workspace its release counterpart +// already recorded without either refusing the other. Both front doors have +// compared versions this way since the markers existed, and tightening it would +// start refusing binaries that work today. +func compareDottedVersions(v1, v2 string) int { + parts1 := strings.Split(v1, ".") + parts2 := strings.Split(v2, ".") + + maxLen := len(parts1) + if len(parts2) > maxLen { + maxLen = len(parts2) + } + + for i := 0; i < maxLen; i++ { + var p1, p2 int + if i < len(parts1) { + _, _ = fmt.Sscanf(parts1[i], "%d", &p1) + } + if i < len(parts2) { + _, _ = fmt.Sscanf(parts2[i], "%d", &p2) + } + if p1 < p2 { + return -1 + } + if p1 > p2 { + return 1 + } + } + return 0 +} diff --git a/internal/workapi/versionreconcile_test.go b/internal/workapi/versionreconcile_test.go new file mode 100644 index 000000000..acceff0cf --- /dev/null +++ b/internal/workapi/versionreconcile_test.go @@ -0,0 +1,139 @@ +package workapi + +import ( + "errors" + "testing" + + "github.com/steveyegge/beads/issueops" +) + +// TestPlanVersionReconcile pins the whole decision table of +// issueops.VersionReconciler in one place and with no database, so the +// conformance contract is free to assert only what a real backend can show. +// +// The two marker states a workspace reaches ONLY through something outside the +// role — a recorded version below the high-water mark — are here rather than +// there for the same reason: they are decisions, and reproducing them on three +// backends costs a seeded write per case to test arithmetic that never touches +// storage. +func TestPlanVersionReconcile(t *testing.T) { + for _, test := range []struct { + name string + cliVersion string + recorded string + highWaterMark string + want issueops.VersionReconcileResult + wantVersion bool + wantMark bool + }{ + { + name: "a workspace with no markers records both", + cliVersion: "1.2.0", + want: issueops.VersionReconcileResult{Previous: "", Current: "1.2.0", Migrated: true}, + wantVersion: true, + wantMark: true, + }, + { + name: "the same version again is a no-op", + cliVersion: "1.2.0", + recorded: "1.2.0", + highWaterMark: "1.2.0", + want: issueops.VersionReconcileResult{Previous: "1.2.0", Current: "1.2.0"}, + }, + { + name: "an upgrade advances both markers", + cliVersion: "1.3.0", + recorded: "1.2.0", + highWaterMark: "1.2.0", + want: issueops.VersionReconcileResult{Previous: "1.2.0", Current: "1.3.0", Migrated: true}, + wantVersion: true, + wantMark: true, + }, + { + name: "a binary older than the marker is refused", + cliVersion: "1.2.0", + recorded: "1.3.0", + highWaterMark: "1.3.0", + want: issueops.VersionReconcileResult{Previous: "1.3.0", Current: "1.3.0", Downgrade: true}, + }, + { + // The state only something outside this role produces, and the + // whole reason the second marker exists: the marker says 1.2.0 and + // would accept 1.3.0, the mark remembers that 1.4.0 has already + // prepared this workspace. + name: "a binary older than the mark is refused even when the marker would accept it", + cliVersion: "1.3.0", + recorded: "1.2.0", + highWaterMark: "1.4.0", + want: issueops.VersionReconcileResult{Previous: "1.2.0", Current: "1.2.0", Downgrade: true}, + }, + { + name: "catching up to the mark moves the marker and leaves the mark", + cliVersion: "1.4.0", + recorded: "1.2.0", + highWaterMark: "1.4.0", + want: issueops.VersionReconcileResult{Previous: "1.2.0", Current: "1.4.0", Migrated: true}, + wantVersion: true, + wantMark: false, + }, + { + name: "a pre-release records over the release it equals", + cliVersion: "1.4.0-rc1", + recorded: "1.4.0", + highWaterMark: "1.4.0", + want: issueops.VersionReconcileResult{Previous: "1.4.0", Current: "1.4.0-rc1", Migrated: true}, + wantVersion: true, + wantMark: false, + }, + { + name: "a missing component reads as zero", + cliVersion: "1.4", + recorded: "1.4.0", + highWaterMark: "1.4.0", + want: issueops.VersionReconcileResult{Previous: "1.4.0", Current: "1.4", Migrated: true}, + wantVersion: true, + wantMark: false, + }, + { + name: "a marker this role cannot parse reads as zero and is overwritten", + cliVersion: "1.4.0", + recorded: "unknown", + highWaterMark: "unknown", + want: issueops.VersionReconcileResult{Previous: "unknown", Current: "1.4.0", Migrated: true}, + wantVersion: true, + wantMark: true, + }, + } { + t.Run(test.name, func(t *testing.T) { + plan, err := PlanVersionReconcile(test.cliVersion, test.recorded, test.highWaterMark) + if err != nil { + t.Fatalf("PlanVersionReconcile(%q, %q, %q) error = %v", + test.cliVersion, test.recorded, test.highWaterMark, err) + } + if plan.Result != test.want { + t.Errorf("result = %+v, want %+v", plan.Result, test.want) + } + if plan.RecordVersion != test.wantVersion { + t.Errorf("RecordVersion = %v, want %v", plan.RecordVersion, test.wantVersion) + } + if plan.RecordHighWaterMark != test.wantMark { + t.Errorf("RecordHighWaterMark = %v, want %v", plan.RecordHighWaterMark, test.wantMark) + } + }) + } +} + +// TestPlanVersionReconcileRefusesAnEmptyVersion pins the one validation +// failure, and pins that it plans no write: recording "" over a real marker +// would take the downgrade guard down with it. +func TestPlanVersionReconcileRefusesAnEmptyVersion(t *testing.T) { + for _, cliVersion := range []string{"", " "} { + plan, err := PlanVersionReconcile(cliVersion, "1.2.0", "1.2.0") + if !errors.Is(err, issueops.ErrValidation) { + t.Fatalf("PlanVersionReconcile(%q, ...) error = %v, want ErrValidation", cliVersion, err) + } + if plan.RecordVersion || plan.RecordHighWaterMark { + t.Fatalf("PlanVersionReconcile(%q, ...) plans a write: %+v", cliVersion, plan) + } + } +} diff --git a/issue_roles_external_test.go b/issue_roles_external_test.go index ac73e9f51..390dff99a 100644 --- a/issue_roles_external_test.go +++ b/issue_roles_external_test.go @@ -214,6 +214,41 @@ func TestWorkspaceConfigKeepsTelemetryOutermost(t *testing.T) { } } +// TestVersionReconcilerKeepsTelemetryOutermost is the version-marker role's +// version of the pin, and the second place in this file where the read answer +// is given for a role that WRITES. +// +// The reason is the settings role's, plus one this role has on its own: it runs +// from PersistentPreRun on every startup, so a hook wrapper here would run a +// user's script before every command — including the ones that go on to fail on +// their own arguments — with no bead to hand it. +func TestVersionReconcilerKeepsTelemetryOutermost(t *testing.T) { + t.Setenv("BD_OTEL_STDOUT", "true") + instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) + if !ok { + t.Fatal("WrapStorage() did not create InstrumentedStorage") + } + + reconciler, err := storage.NewHookFiringStore(instrumented, nil).VersionReconciler() + if err != nil { + t.Fatalf("VersionReconciler() error = %v", err) + } + if got := reflect.TypeOf(reconciler).String(); got != "*telemetry.instrumentedVersionReconciler" { + t.Fatalf("outer layer = %s, want the telemetry wrapper unwrapped by the hook decorator", got) + } +} + +func TestVersionReconcilerExposesTypedUnsupportedError(t *testing.T) { + reconciler, err := (*dolt.DoltStore)(nil).VersionReconciler() + if reconciler != nil { + t.Fatalf("VersionReconciler() reconciler = %T, want nil", reconciler) + } + var unsupported *beads.ErrUnsupported + if !errors.As(err, &unsupported) { + t.Fatalf("VersionReconciler() error = %v, want *beads.ErrUnsupported", err) + } +} + func TestWorkspaceConfigExposesTypedUnsupportedError(t *testing.T) { settings, err := (*dolt.DoltStore)(nil).WorkspaceConfig() if settings != nil { diff --git a/issueops/versionreconciler.go b/issueops/versionreconciler.go new file mode 100644 index 000000000..c8ea0bd62 --- /dev/null +++ b/issueops/versionreconciler.go @@ -0,0 +1,184 @@ +package issueops + +import "context" + +// RecordedVersionRequest asks for the workspace's recorded version markers. It +// carries no fields today and exists so that adding one is an additive change +// to a type callers already name, rather than a signature change on the +// interface — the reason ListSettingsRequest is spelled the same way. +type RecordedVersionRequest struct{} + +// RecordedVersionResult is what the workspace currently records about the bd +// binaries that have opened it. +// +// BOTH FIELDS ARE CLONE-LOCAL. They live in the dolt-ignored local metadata +// plane, so they are not history, they do not sync, a fresh clone of a +// workspace has neither of them, and two machines sharing one workspace answer +// this question differently. That is the whole reason the pair exists as its +// own role rather than as two more keys on WorkspaceConfig, whose values are +// durable workspace settings that DO travel. +type RecordedVersionResult struct { + // Recorded is the version of the last bd binary that reconciled this + // workspace, or "" for a workspace no binary has reconciled yet. + // + // "" IS A NORMAL ANSWER, not an error and not a missing row to classify: + // the local metadata plane is ephemeral by construction and every reader of + // it has to treat absence as "unknown". A caller that needs to know whether + // a reconciliation has ever happened compares against "" and gets a + // truthful answer on all three backends. + Recorded string + // HighWaterMark is the HIGHEST version ever recorded here, which is not the + // same fact as Recorded and is why there are two fields rather than one. + // + // Recorded moves both up and — when something outside this role writes it — + // down; the high-water mark only ever moves up. A workspace that was opened + // by a newer binary and then by an older one keeps the newer number here, + // and that is what lets ReconcileVersion refuse a downgrade it could not + // otherwise see. It is "" exactly when nothing has ever been recorded. + HighWaterMark string +} + +// VersionReconcileRequest asks the workspace to record the running binary's +// version. +type VersionReconcileRequest struct { + // CLIVersion is the running binary's release version. It is REQUIRED: an + // empty value is ErrValidation rather than a no-op, because the one thing + // this role must never do is record "this workspace was last opened by + // nothing" over a real marker and lose the downgrade guard with it. + // + // It is compared as dotted decimal, component by component, with a + // non-numeric component reading as 0. So "1.2.0" and "1.2.0-rc1" are the + // SAME version to this role, "1.2" is lower than "1.2.1", and a version + // string with no digits at all is 0.0.0. That is the comparison both front + // doors have always used and it is stated here rather than tightened, + // because tightening it would start refusing pre-release binaries that + // reconcile cleanly today. + CLIVersion string +} + +// VersionReconcileResult reports what the reconciliation decided. +// +// THE THREE OUTCOMES ARE DISTINGUISHABLE WITHOUT AN ERROR, and that is the +// shape this role needs rather than a convenience. Its caller is a startup +// hook with no user waiting on an answer, so it must be able to tell "I moved +// the marker" from "there was nothing to do" from "I declined" while treating +// all three as success — and keep a real failure, which IS an error, separate +// from all of them. +type VersionReconcileResult struct { + // Previous is the marker as it was found: "" on a workspace nothing has + // reconciled yet. + Previous string + // Current is the marker as it stands after the call. It equals the + // request's CLIVersion when Migrated is set, and equals Previous otherwise + // — including on a refusal, where it is the value that STAYED. + Current string + // Migrated reports that the marker moved, and it is the only outcome that + // writes anything. It is false for a workspace already at this version: + // reconciling twice is not two migrations. + Migrated bool + // Downgrade reports a REFUSAL, and a refusal is not an error. + // + // It is set when the running binary is older than the marker, or older than + // the high-water mark, and it means nothing was written and the newer + // number still stands. A caller may report it, and both front doors do at + // debug level, but nothing about the command it precedes changes: an older + // binary is allowed to use a workspace a newer one has opened. What it is + // NOT allowed to do is quietly relabel that workspace as older than it is, + // because the next upgrade would then re-run the version-bump work the + // newer binary already did. + Downgrade bool +} + +// VersionReconciler describes the workspace's CLONE-LOCAL VERSION MARKERS: the +// pair of dolt-ignored values recording which bd binary last opened this +// workspace and the highest one that ever has. Like Lifecycle, Reader, Counter, +// WorkspaceConfig, StatsReporter, CycleDetector, EdgeReader and ReadyCounter, it +// is a role with its own accessor, and a new capability gets a new role rather +// than a method appended here. +// +// IT BELONGS TO NO COMMAND, and it is the only role in this program that +// does not. It fires from PersistentPreRun on EVERY startup, on both routes, +// before the command the user actually typed has run — which is precisely why +// it went unnoticed for so long: `bd version` prints two strings, opens no +// store and reaches nothing here, so the state machinery was hiding behind a +// command that does not use it. +// +// THAT ORIGIN IS A CONSTRAINT ON EVERY PROMISE BELOW, not a piece of history. +// A role that runs before every command pays for itself on every command, so: +// +// - It does exactly two round trips on the path that changes nothing (read +// the two markers) and never more than four. It loads no configuration, +// opens no second connection and takes no lock. +// - It NEVER refuses the command in front of it. A downgrade is reported as +// an outcome rather than raised as an error (see Downgrade), and a genuine +// failure — a substrate that cannot be written, a canceled context, a +// connection that dropped — is an error the CALLER is expected to log and +// walk past. Both front doors do exactly that, at debug level, and a role +// whose caller must ignore its errors has to say so where the promise is +// made rather than leave each caller to decide. +// - It repairs nothing. It does not migrate a schema, rebuild a database or +// rewrite a marker it cannot parse. Everything named "auto-migrate" around +// its CLI call site is the CLI's, and the two markers are all this role +// touches. +// +// WHY IT IS NOT WorkspaceConfig WITH TWO MORE KEYS. Those are two different +// planes with two different lifetimes. A workspace setting is durable, travels +// with the database and is the same on every machine that has it; these two +// markers are dolt-ignored, do not survive a clone, and are deliberately +// different per machine — a stale marker on one laptop says nothing about +// anyone else's. Publishing them through the settings plane would put a value +// that cannot be shared behind an interface whose whole promise is that its +// values are. +// +// BOTH METHODS BELONG TO THE ONE ROLE. They are two shapes of one question, +// which is what the governing rule permits a role to be born with: reconciling +// IS a statement about what a later read returns, and the read is the only way +// to observe that the write landed — the reconcile result reports what it +// decided, not what the workspace holds. They also cannot be separated in +// practice, because the direct front door needs the read alone: it probes a +// read-only handle first so an already-current workspace never pays for a +// writable open. +// +// There is NO HTTP surface, and that is a decision rather than an omission. +// Reconciliation is an effect of a process starting, not of a request +// arriving; a client cannot usefully ask a server to record the CLIENT's +// version, because the marker describes the binary holding the database, and +// the one version fact a client can act on — the serving binary's release — +// is already published as ContextResponse.bd_version on GET /v0/beads/context. +// An endpoint here would publish a per-clone number that a remote caller can +// neither compare against its own nor do anything with. +// +// Deterministic request-validation failures match ErrValidation; result values +// are unspecified when error is non-nil. +type VersionReconciler interface { + // RecordedVersion returns the two markers as they stand. It writes + // nothing, records no history, and answers "" for a workspace that has + // never been reconciled rather than reporting a missing row. + RecordedVersion(ctx context.Context, req RecordedVersionRequest) (RecordedVersionResult, error) + + // ReconcileVersion records the running binary's version, and is the ONLY + // way this pair is written. + // + // It moves the marker forward and raises the high-water mark to match when + // the running binary is newer than both (Migrated); it writes nothing when + // the marker already names this version (neither flag set); and it writes + // nothing and reports Downgrade when the running binary is older than + // either marker. The two markers move TOGETHER or not at all in the sense + // that matters to a reader: the mark is never lowered, and a successful + // migration always leaves the mark greater than or equal to the marker. + // + // A LATER RecordedVersion IS THE PROMISE. After a Migrated result, it + // answers with the version just recorded, from a fresh connection or a + // fresh unit of work; after a refusal or a validation failure, it answers + // with exactly what it answered before the call. That is the whole of what + // "reconciled" means here, and it is why the read shares this role. + // + // AN EMPTY CLIVersion IS ErrValidation and writes nothing. + // + // RECONCILIATION RECORDS NO HISTORY. The markers are clone-local and + // dolt-ignored, so a reconciliation adds no entry to the workspace's log on + // any backend — a fact worth stating because this runs on every startup and + // a role that appended one would fill a workspace's history with the + // version of the binary that read it. + ReconcileVersion(ctx context.Context, req VersionReconcileRequest) (VersionReconcileResult, error) +}