From 1a965d0a4d4c206e3cb4f8c398eb6877dc62f1a9 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Fri, 20 Nov 2026 22:55:48 -0500 Subject: [PATCH 1/9] record: harness.adoption-go-base adopt brief approved --- context/goals/harness.adoption-go-base.md | 79 +++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 context/goals/harness.adoption-go-base.md diff --git a/context/goals/harness.adoption-go-base.md b/context/goals/harness.adoption-go-base.md new file mode 100644 index 0000000..7aad17f --- /dev/null +++ b/context/goals/harness.adoption-go-base.md @@ -0,0 +1,79 @@ +# goal · harness.adoption-go-base + +- **State:** building +- **Task:** adopt +- **Branch:** adopt + +## Tasks + +1. [ ] adopt + +## Task brief · adopt + +**Problem** + +go-database, go-observability, and go-cli-sdk predate marathon 0.22.0. Nothing pins marathon's +tools, the check doesn't run lint-context or lint-references, and every capability map fails +lint-context. Hundreds of comments fall outside the five kinds, and no lint requires a +suppression's reason. + +**Behaviors** +1. Each repository's currency command exits 0 after its upgrade slice. GitHub Actions use + mise-action v5.2.10. +2. Each `mise.toml` pins marathon's tools at 0.22.0 with the `marathon/v` prefix. `mise install` + puts lint-context and lint-references on PATH, and currency reports a newer marathon tag. +3. Each check runs lint-context and lint-references once, after its module loop, and fails when + either fails. A lint missing from PATH fails the check with a message naming `mise install`. + The task description names both lints. +4. lint-context passes in each repository: + - Every capability map entry is marked `(built)` or `(planned)`, with no prose under the map + heading. + - go-observability's logs pipeline is a linked `(planned)` entry whose note holds its open + points, with the trigger as the README's Design section states it. + - A map entry that restates an exported doc comment shrinks to a name. Map prose with no other + home moves to the README or a `docs/` page. +5. Every comment in code, tests, scripts, and configuration is one of the five kinds. Doc comments + on unexported identifiers and on test functions are gone; reasoning with no other home moves + into names, exported docs, or `docs/`. The currency script's section comments become named + functions. +6. Each `.golangci.yml` enables nolintlint with `require-explanation` and `require-specific`. +7. Each STANDARDS.md gains a comment rule that cites the five kinds for source, tests, scripts, and + every configuration file (TOML, YAML, `.gitignore`). +8. The check passes locally and in CI in all three repositories. No CHANGELOG changes: no module's + `go.mod` requirements change. + +**Test seams** +- `mise run check` and `mise run currency` in each repository; the existing suites are the + regression seam. + +**Slices** +1. go-database upgrade: mise-action v5.2.10. +2. go-observability upgrade: the same. +3. go-cli-sdk upgrade: the same. +4. go-database: pin, check wiring, and context. +5. go-database: comments, nolintlint, and STANDARDS comment rule. +6. go-observability: pin, check wiring, and context, including the logs-pipeline note. +7. go-observability: comments, nolintlint, and STANDARDS comment rule. +8. go-cli-sdk: pin, check wiring, and context. +9. go-cli-sdk: comments, nolintlint, and STANDARDS comment rule. + +**Out of scope** + +Building the logs pipeline, rewriting exported doc comments, a Markdown link check, budgeting +`docs/`, releases and tags, feature or API changes, the Go templates. + +**Door** + +Two-way: every change sits on branches and pull requests, and nothing is tagged. + +## Progress + +slices 0/9 committed · standards — · spec — · editor — + +## Decisions + +- adopt: CHANGELOG entries record only changes to a module's `go.mod` requirements. (wave 1, W2) + +## Pending edits + +None. From 603473d0bf6a933231e55b79051871dcedf533df Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Fri, 20 Nov 2026 22:57:25 -0500 Subject: [PATCH 2/9] harness.adoption: mise-action v5.2.10 --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cbd2a4e..fd7b5e5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,7 +12,7 @@ jobs: steps: - uses: actions/checkout@v7.0.1 - - uses: jdx/mise-action@v5.2.7 + - uses: jdx/mise-action@v5.2.10 - name: mise run check run: mise run check From eabb08507641cd7cae0d11651085abd6696a1f1c Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Fri, 20 Nov 2026 22:58:43 -0500 Subject: [PATCH 3/9] harness.adoption: pin marathon's lints and run them in the check - mise.toml pins github:standards-lab/claude-plugins at 0.22.0 (marathon/v prefix) and sets task.run_auto_install = false, as ai-hosting does. - The check runs lint-context and lint-references once from the project root after its module loop, fails when either fails, and fails with "run mise install" when one is not on PATH; its description names both. - context/README.md: every capability map entry is (built) and links its doc.go; the map's intro and trailing paragraph go. sqlate's ownership already sits in the README's Standard section; the admin service's HTTP half being application code moves there as a bullet. - .claude/marathon.toml drops its comments. --- .claude/marathon.toml | 4 ---- README.md | 2 ++ context/README.md | 32 ++++++++++++-------------------- mise.toml | 17 ++++++++++++++++- 4 files changed, 30 insertions(+), 25 deletions(-) diff --git a/.claude/marathon.toml b/.claude/marathon.toml index 08655d8..f776fa4 100644 --- a/.claude/marathon.toml +++ b/.claude/marathon.toml @@ -1,12 +1,8 @@ -# Project kind: this repository holds production Go source, checked by `mise run check`. [project] kind = "code" check = "mise run check" -# The read-only, development-time command that reports every pin trailing its latest release; -# it reads the network, so CI never runs it. currency = "mise run currency" -# Remote platform, the commands that publish and merge a finished branch, and the CI wait. [remote] platform = "github" publish = "gh pr create" diff --git a/README.md b/README.md index 5910f70..8723b50 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,8 @@ principles: - Swapping the SQL provider is a port. The consumer owns its schema, its migrations, and its domain SQL, and those are what a swap rewrites. A library that ships its own migration set, such as `blobfs`, owns that set; the consumer declares it beneath its own. +- The HTTP half of the admin service, the route group and handler, is application code: the + reference service builds it, and the template stays engine-free. ## Packages diff --git a/context/README.md b/context/README.md index eff2b10..cdf2628 100644 --- a/context/README.md +++ b/context/README.md @@ -11,23 +11,15 @@ This context records only working knowledge the code and the README do not expre ## Capability map -The built packages are authoritative through their code and `doc.go`. Detail for what is unbuilt -is added when it is about to be built. - -- **database** wraps the pool: configuration, lifecycle, readiness, and the connectivity - sentinels. Built. -- **admin** is the database admin service over `sqlate`, generic over the consumer's migrator, - seeder, registry, catalog, and pool. `admin/doc.go` states its construction, its verbs, its - startup sequence, its errors, and its migration sets: one service administers every set its - migrator runs. Built. -- **sweep** is the general sweeper: it runs a service's reclaimers as one go-core reactor, each - cycle under the advisory lock `sweep.` and bounded by its interval. `sweep/doc.go` states - its construction, cycles, and drain. Built. -- **postgres** is the PostgreSQL provider: it constructs the pool over pgx's `database/sql` - adapter from the configuration block, and supplies no dialect — the dialect is - `sqlate/postgres`'s. Built. - -`sqlate` (`github.com/standards-lab/sqlate`), a standalone library below this one, owns -statements, sessions, transactions, the dialect, migrations, and the scripted test driver. The -HTTP half of the admin service — the route group and handler — is application code: the -reference service builds it, and the template stays engine-free. +- **database** (built): wraps the pool: configuration, lifecycle, readiness, and the + connectivity sentinels ([`doc.go`](../doc.go)). +- **admin** (built): the database admin service over `sqlate`, generic over the consumer's + migrator, seeder, registry, catalog, and pool. [`admin/doc.go`](../admin/doc.go) states its + construction, its verbs, its startup sequence, its errors, and its migration sets: one service + administers every set its migrator runs. +- **sweep** (built): the general sweeper: it runs a service's reclaimers as one go-core reactor, + each cycle under the advisory lock `sweep.` and bounded by its interval. + [`sweep/doc.go`](../sweep/doc.go) states its construction, cycles, and drain. +- **postgres** (built): the PostgreSQL provider: it constructs the pool over pgx's + `database/sql` adapter from the configuration block, and supplies no dialect — the dialect is + `sqlate/postgres`'s ([`postgres/doc.go`](../postgres/doc.go)). diff --git a/mise.toml b/mise.toml index 304416f..057e1b5 100644 --- a/mise.toml +++ b/mise.toml @@ -1,4 +1,8 @@ +[settings] +task.run_auto_install = false + [tools] +"github:standards-lab/claude-plugins" = { version = "0.22.0", version_prefix = "marathon/v" } go = "1.27.4" golangci-lint = "2.15.0" jq = "1.8.2" @@ -10,7 +14,7 @@ jq = "1.8.2" GO_MODULES = ". postgres" [tasks.check] -description = "Build, vet, format, fix, tidy, test, and lint every module; writes nothing" +description = "Build, vet, format, fix, tidy, test, and lint every module, then run lint-context and lint-references; writes nothing" run = ''' set -eu export GOWORK=off @@ -26,6 +30,17 @@ for mod in $GO_MODULES; do go test -race ./... golangci-lint run ./... done +cd "$MISE_PROJECT_ROOT" +fail=0 +for lint in lint-context lint-references; do + if ! command -v "$lint" >/dev/null; then + echo "FAIL: $lint is not on PATH; run mise install" >&2 + fail=1 + continue + fi + "$lint" || fail=1 +done +exit "$fail" ''' [tasks.currency] From 40a1376a89deb6b75e4a6df9f55c1a06ccfb5566 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Fri, 20 Nov 2026 23:01:22 -0500 Subject: [PATCH 4/9] harness.adoption: hold go-database's comments to the five kinds Doc comments on unexported identifiers and test functions, in-body and trailing comments, and unexported struct-field comments go from source and tests; package docs and docs on exported identifiers (export_test.go hooks and admin's trailing field docs included) stay unchanged. .golangci.yml enables nolintlint with require-explanation and require-specific, its rationale replaced by references to tests-and-docs.md and comments.md. mise.toml's comments give way to one reference to release-and-ci.md, and the build task's description carries the GOWORK=off reason. .gitignore drops its comments. scripts/currency.sh keeps its header and splits its scans into named report_outdated_* functions; matches loses its doc comment. STANDARDS.md gains the comment rule over source, tests, scripts, and every configuration file (TOML, YAML, .gitignore). --- .gitignore | 10 ---- .golangci.yml | 13 +++-- STANDARDS.md | 1 + admin/seed_test.go | 60 ++++------------------ admin/service.go | 41 ++------------- admin/service_test.go | 104 +++++--------------------------------- admin/sets_test.go | 58 +++++---------------- config_test.go | 10 ---- database_test.go | 14 ----- env_test.go | 2 - errors_test.go | 2 - mise.toml | 10 +--- postgres/main_test.go | 5 +- postgres/postgres.go | 8 --- postgres/postgres_test.go | 32 ------------ scripts/currency.sh | 72 ++++++++++++++------------ sweep/sweep.go | 56 +------------------- sweep/sweep_test.go | 48 ++---------------- 18 files changed, 95 insertions(+), 451 deletions(-) diff --git a/.gitignore b/.gitignore index db44c15..44f8960 100644 --- a/.gitignore +++ b/.gitignore @@ -1,18 +1,8 @@ -# go.work and go.work.sum are committed; this repo is multi-module by design. - -# Marathon session plan files. .claude/plans/ - -# marathon's task and session briefs. .claude/briefs/ - -# Per-machine mise overrides. mise.local.toml - -# Build output. bin/ -# Editor and OS. *.swp *.swo *~ diff --git a/.golangci.yml b/.golangci.yml index aa93337..083999d 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,14 +1,17 @@ -# golangci-lint v2 configuration, run per module by `mise run check`. +# golangci-lint v2 configuration, run per module by `mise run check`: the standard set plus +# testpackage and nolintlint. +# See architecture/standards/go-elemental/principles/tests-and-docs.md +# See architecture/principles/comments.md version: "2" linters: - # The standard set (errcheck, govet, ineffassign, staticcheck, unused), - # plus testpackage, which keeps tests black-box. Its skip regexp is - # narrowed to export_test.go, the one white-box file allowed: it exports - # a clock or probe hook to the black-box tests and holds no tests itself. default: standard enable: + - nolintlint - testpackage settings: + nolintlint: + require-explanation: true + require-specific: true testpackage: skip-regexp: export_test\.go diff --git a/STANDARDS.md b/STANDARDS.md index d7be637..a74ff06 100644 --- a/STANDARDS.md +++ b/STANDARDS.md @@ -14,3 +14,4 @@ The judgement calls the standards-reviewer applies to go-database, beyond what ` - `architecture/principles/service-tiers.md`: `DB.Conn`, `Config.Options`, and the `postgres` provider. - `architecture/principles/validation-first.md`: `Config.Finalize`, and `admin`'s verbs, which refuse an argument outside their domain before any I/O. - `architecture/principles/context-architecture.md`: the README and each `doc.go` are the homes. +- `architecture/principles/comments.md`: every comment is one of the five kinds, in source, tests, scripts, and every configuration file (TOML, YAML, `.gitignore`); a doc comment on an unexported identifier or a test function is not package documentation. diff --git a/admin/seed_test.go b/admin/seed_test.go index d22cc03..d497714 100644 --- a/admin/seed_test.go +++ b/admin/seed_test.go @@ -13,8 +13,6 @@ import ( "github.com/standards-lab/sqlate/sqltest" ) -// With no set configured, a seed request that names none refuses before -// any I/O and the seeder is never called. func TestSeed_NoSetRefuses(t *testing.T) { f := newFixture(t, testDialect{}, admin.Options{Seeder: &fakeSeeder{}}) n, err := f.service.Seed(context.Background(), "") @@ -26,8 +24,6 @@ func TestSeed_NoSetRefuses(t *testing.T) { } } -// Without a seeder, every seed operation refuses the same way, and States -// is empty. func TestSeed_NoSeederRefuses(t *testing.T) { s, rec := newService(t) ctx := context.Background() @@ -48,8 +44,6 @@ func TestSeed_NoSeederRefuses(t *testing.T) { } } -// A name the seeder does not declare refuses Seed and Reset before any -// I/O, and the error names it. func TestSeed_UnknownStateRefuses(t *testing.T) { f := newFixture(t, testDialect{}, admin.Options{Seed: "default", Seeder: &fakeSeeder{}}) ctx := context.Background() @@ -65,7 +59,6 @@ func TestSeed_UnknownStateRefuses(t *testing.T) { } } -// States is the seeder's list. func TestStates_ListsTheSeeders(t *testing.T) { f := newFixture(t, testDialect{}, admin.Options{Seeder: &fakeSeeder{states: []string{"default", "empty"}}}) if got := f.service.States(); !slices.Equal(got, []string{"default", "empty"}) { @@ -73,7 +66,6 @@ func TestStates_ListsTheSeeders(t *testing.T) { } } -// A request that names no set applies the configured one. func TestSeed_EmptyNameAppliesTheConfiguredSet(t *testing.T) { f := newFixture(t, testDialect{}, admin.Options{Seed: "default", Seeder: &fakeSeeder{}}) n, err := f.service.Seed(context.Background(), "") @@ -82,7 +74,6 @@ func TestSeed_EmptyNameAppliesTheConfiguredSet(t *testing.T) { } } -// A named set applies whether or not a set is configured. func TestSeed_NamedSetAppliesWithoutConfiguration(t *testing.T) { f := newFixture(t, testDialect{}, admin.Options{Seeder: &fakeSeeder{states: []string{"default", "demo"}}}) n, err := f.service.Seed(context.Background(), "demo") @@ -91,8 +82,6 @@ func TestSeed_NamedSetAppliesWithoutConfiguration(t *testing.T) { } } -// With a set configured, Start applies it by name once the schema is -// current and verified. func TestStart_AppliesTheConfiguredSet(t *testing.T) { f := newFixture(t, testDialect{}, admin.Options{Seed: "default", Seeder: &fakeSeeder{}}, clean()...) if err := f.service.Start(context.Background()); err != nil { @@ -103,8 +92,6 @@ func TestStart_AppliesTheConfiguredSet(t *testing.T) { } } -// A configured name the seeder does not declare is a configuration -// defect: Start fails before it reads or changes the schema. func TestStart_UnknownConfiguredSetFailsStartup(t *testing.T) { f := newFixture(t, testDialect{}, admin.Options{Seed: "nope", Seeder: &fakeSeeder{}}) err := f.service.Start(context.Background()) @@ -116,7 +103,6 @@ func TestStart_UnknownConfiguredSetFailsStartup(t *testing.T) { } } -// A startup seed that fails fails Start, and the service is not ready. func TestStart_SeedFailureFailsStartup(t *testing.T) { f := newFixture(t, testDialect{}, admin.Options{Seed: "default", Seeder: &fakeSeeder{seedErr: errors.New("seed failed")}}, clean()...) err := f.service.Start(context.Background()) @@ -128,8 +114,6 @@ func TestStart_SeedFailureFailsStartup(t *testing.T) { } } -// Reset with no state named brings the database to the configured one, -// and refuses when none is configured. func TestReset_EmptyNameUsesTheConfiguredSet(t *testing.T) { responses := slices.Concat(resetting(), applying(), current()) f := newFixture(t, testDialect{}, admin.Options{Seed: "default", Seeder: &fakeSeeder{}}, responses...) @@ -144,7 +128,6 @@ func TestReset_EmptyNameUsesTheConfiguredSet(t *testing.T) { } } -// States hands out a copy: changing it leaves the seeder's list alone. func TestStates_ReturnsACopy(t *testing.T) { states := []string{"default", "empty"} f := newFixture(t, testDialect{}, admin.Options{Seeder: &fakeSeeder{states: states}}) @@ -154,10 +137,6 @@ func TestStates_ReturnsACopy(t *testing.T) { } } -// Reset reverts the applied set under the lock and drops its history -// table, applies it again, seeds the named state's set, and answers with -// the state, the refreshed status, and the rows. With no OnReset hook, the -// transition is these steps alone. func TestReset_RevertsAppliesAndSeeds(t *testing.T) { responses := slices.Concat(resetting(), applying(), current()) f := newFixture(t, testDialect{}, admin.Options{Seeder: &fakeSeeder{states: []string{"default", "empty"}}}, responses...) @@ -171,8 +150,6 @@ func TestReset_RevertsAppliesAndSeeds(t *testing.T) { if !slices.Equal(f.seeder.seeded, []string{"empty"}) || !f.service.Ready() || f.rec.Pending() != 0 { t.Errorf("seeded %v, ready %v, pending %d", f.seeder.seeded, f.service.Ready(), f.rec.Pending()) } - // The downs run newest first, then the ups oldest first, each pass - // under its own lock. var order []string for _, e := range f.rec.SQL(sqltest.OpExec) { if strings.HasPrefix(e, "SELECT lock") || strings.HasPrefix(e, "DROP") || strings.HasPrefix(e, "CREATE TABLE a") || strings.HasPrefix(e, "CREATE INDEX") { @@ -188,13 +165,10 @@ func TestReset_RevertsAppliesAndSeeds(t *testing.T) { } } -// A history the transition cannot proceed from stops it at the revert, -// nothing is seeded, and the status is still read so Ready reflects the -// schema left behind. func TestReset_DirtyHistoryStopsAtTheRevert(t *testing.T) { dirty := history([]driver.Value{int64(1), "a", false}, []driver.Value{int64(2), "b", true}) f := newFixture(t, testDialect{}, admin.Options{Seeder: &fakeSeeder{}}, - exists(true), applied(), // a clean Verify first, so Ready starts true + exists(true), applied(), locked, created, dirty, unlocked, exists(true), dirty, ) @@ -210,8 +184,6 @@ func TestReset_DirtyHistoryStopsAtTheRevert(t *testing.T) { } } -// A transition that fails at the apply seeds nothing, and the status read -// after it finds the schema behind. func TestReset_FailureAtTheApply(t *testing.T) { boom := errors.New("create failed") responses := slices.Concat(resetting(), @@ -228,8 +200,6 @@ func TestReset_FailureAtTheApply(t *testing.T) { } } -// A transition that fails at the seed leaves the schema applied and -// current, and Ready reports it so. func TestReset_FailureAtTheSeed(t *testing.T) { boom := errors.New("seed failed") responses := slices.Concat(resetting(), applying(), current()) @@ -243,16 +213,12 @@ func TestReset_FailureAtTheSeed(t *testing.T) { } } -// hookCall is what an OnReset hook saw when Reset called it. type hookCall struct { state string - pending int // scripted responses not yet consumed - seeded []string // the states seeded so far + pending int + seeded []string } -// recordHook returns an OnReset hook that records each call into calls, -// with how far the fixture's script and seeder had run, and answers err. -// It reads *f at the call, so it can be wired before the fixture is built. func recordHook(f *fixture, calls *[]hookCall, err error) func(context.Context, string) error { return func(_ context.Context, state string) error { *calls = append(*calls, hookCall{state: state, pending: f.rec.Pending(), seeded: slices.Clone(f.seeder.seeded)}) @@ -260,9 +226,6 @@ func recordHook(f *fixture, calls *[]hookCall, err error) func(context.Context, } } -// Reset calls the hook once, with the state it resolved, after the revert -// and the apply have run and before the seed: at the call, only the status -// read is left of the script, and nothing is seeded. func TestReset_HookRunsBetweenTheApplyAndTheSeed(t *testing.T) { cases := []struct { name, configured, request, want string @@ -298,9 +261,6 @@ func TestReset_HookRunsBetweenTheApplyAndTheSeed(t *testing.T) { } } -// A hook that fails stops Reset before the seed: the error names the step -// and wraps the hook's, nothing is seeded, and the schema is left applied -// and current, as the status read after it finds. func TestReset_FailureAtTheHook(t *testing.T) { boom := errors.New("hook failed") var calls []hookCall @@ -319,17 +279,15 @@ func TestReset_FailureAtTheHook(t *testing.T) { } } -// Only Reset calls the hook: Start, Seed, and the schema verbs each run -// to completion without it. func TestOnReset_OtherVerbsNeverCallIt(t *testing.T) { one := history([]driver.Value{int64(1), "a", false}) responses := slices.Concat( - clean(), // Start - current(), // Status - applying(), current(), // Up - []sqltest.Response{locked, created, applied(), {}, {}, {}, unlocked, exists(true), one}, // Down 1 - []sqltest.Response{locked, created, history(), {}, {}, unlocked, exists(true), one}, // Steps +1 - []sqltest.Response{locked, {}, {}, {Affected: 1}, unlocked, exists(true), one}, // Force 1 + clean(), + current(), + applying(), current(), + []sqltest.Response{locked, created, applied(), {}, {}, {}, unlocked, exists(true), one}, + []sqltest.Response{locked, created, history(), {}, {}, unlocked, exists(true), one}, + []sqltest.Response{locked, {}, {}, {Affected: 1}, unlocked, exists(true), one}, ) var calls int opts := admin.Options{ diff --git a/admin/service.go b/admin/service.go index d392632..4f3fa6e 100644 --- a/admin/service.go +++ b/admin/service.go @@ -16,8 +16,6 @@ import ( "github.com/standards-lab/sqlate/query" ) -// reverifyInterval is the least time between two of Ready's own schema -// verifications. const reverifyInterval = 5 * time.Second var ( @@ -110,15 +108,9 @@ type Service struct { ready atomic.Bool started atomic.Bool - // mu serializes writes of ready with gen. Every write except a probe's - // increments gen, so a probe stores its finding only when no operation - // determined the schema while it read. mu sync.Mutex gen uint64 - // probe is Ready's schema verification; probing marks one in flight, - // and probed is when the last began, measured from base on the - // monotonic clock. probe func(context.Context) error probing atomic.Bool base time.Time @@ -150,7 +142,7 @@ func New(pool *database.DB, db *sqlate.DB, m *migrate.Migrator, c *query.Catalog seeder: opts.Seeder, registry: opts.Registry, logger: logger, seed: opts.Seed, onReset: opts.OnReset, probe: m.Verify, base: time.Now(), } - s.probed.Store(int64(-reverifyInterval)) // the first probe is not throttled + s.probed.Store(int64(-reverifyInterval)) return s } @@ -164,7 +156,7 @@ func (s *Service) Ready() bool { return s.ready.Load() } if !s.probing.CompareAndSwap(false, true) { - return false // another probe is verifying + return false } defer s.probing.Store(false) now := time.Since(s.base) @@ -179,7 +171,7 @@ func (s *Service) Ready() bool { defer cancel() if s.probe(ctx) == nil { s.mu.Lock() - if s.gen == gen { // no operation determined the schema meanwhile + if s.gen == gen { s.ready.Store(true) } s.mu.Unlock() @@ -207,9 +199,8 @@ func (s *Service) Start(ctx context.Context) error { err = s.migrator.Verify(ctx) } if err != nil { - return conflict(err) // the lifecycle prefixes the service name + return conflict(err) } - // A clean, complete history puts every set at its latest version. for _, l := range s.migrator.Layers() { s.logger.InfoContext(ctx, "schema current", "set", l.Name(), "version", latest(l.Migrations())) } @@ -230,9 +221,6 @@ func (s *Service) Start(ctx context.Context) error { return nil } -// logPending logs each set's pending versions, so an operator sees what a -// start applies before it runs. A dirty set logs nothing: Up refuses the -// run, and its error names the set. func (s *Service) logPending(ctx context.Context) error { sets, err := s.migrator.Status(ctx) if err != nil { @@ -311,9 +299,6 @@ func (s *Service) Reset(ctx context.Context, state string) (Transition, error) { return Transition{State: state, Schema: st, Seeded: n}, nil } -// state resolves a seed operation's state name, the configured one when it -// is empty, and refuses it before any I/O: no seeder or no name is -// [ErrSeedDisabled], an undeclared name [ErrUnknownState]. func (s *Service) state(state string) (string, error) { if state == "" { state = s.seed @@ -321,7 +306,6 @@ func (s *Service) state(state string) (string, error) { return state, s.checkState(state) } -// checkState is the refusal every seed operation applies before I/O. func (s *Service) checkState(state string) error { if s.seeder == nil || state == "" { return ErrSeedDisabled @@ -424,8 +408,6 @@ func (s *Service) Force(ctx context.Context, set string, version int) (Status, e return s.after(ctx, l.Force(ctx, version)) } -// layer resolves a verb's set name, refusing an undeclared one with -// [ErrUnknownSet] before any I/O. func (s *Service) layer(set string) (migrate.Layer, error) { l, ok := s.migrator.Layer(set) if !ok { @@ -434,9 +416,6 @@ func (s *Service) layer(set string) (migrate.Layer, error) { return l, nil } -// after returns the state following a mutating operation, or the -// operation's error once the status is read, so Ready follows the schema -// the operation left behind. func (s *Service) after(ctx context.Context, err error) (Status, error) { if err != nil { _, _ = s.Status(ctx) @@ -445,10 +424,6 @@ func (s *Service) after(ctx context.Context, err error) (Status, error) { return s.Status(ctx) } -// settle records a determined schema state in the ready flag: true on a -// clean, current schema, false on a dirty, pending, or unrecognized one. -// Any other error, such as a cancelled context or a lost connection, -// determines nothing and leaves the flag. func (s *Service) settle(err error) { switch { case err == nil: @@ -458,8 +433,6 @@ func (s *Service) settle(err error) { } } -// setReady records an operation's determined schema state, counting the -// write so a probe in flight does not overwrite it. func (s *Service) setReady(ready bool) { s.mu.Lock() defer s.mu.Unlock() @@ -467,8 +440,6 @@ func (s *Service) setReady(ready bool) { s.ready.Store(ready) } -// conflict wraps [ErrConflict] around a refusal the schema's state causes, -// once. func conflict(err error) error { switch { case err == nil, errors.Is(err, ErrConflict): @@ -547,8 +518,6 @@ func (s *Service) Diagnose(ctx context.Context) (Diagnostics, error) { return d, nil } -// serverVersion runs the dialect's version statement and returns its one -// text column; no row is an empty version. func (s *Service) serverVersion(ctx context.Context, statement string) (string, error) { rows, err := s.db.QueryContext(ctx, statement) if err != nil { @@ -564,7 +533,6 @@ func (s *Service) serverVersion(ctx context.Context, statement string) (string, return version, s.db.MapError(rows.Err()) } -// versions lists the migrations' versions, empty rather than nil. func versions(ms []migrate.Migration) []int { out := make([]int, 0, len(ms)) for _, m := range ms { @@ -573,7 +541,6 @@ func versions(ms []migrate.Migration) []int { return out } -// latest is the version of a set's last migration, 0 for an empty set. func latest(ms []migrate.Migration) int { if len(ms) == 0 { return 0 diff --git a/admin/service_test.go b/admin/service_test.go index 41a1a8e..c7bb5cc 100644 --- a/admin/service_test.go +++ b/admin/service_test.go @@ -21,8 +21,6 @@ import ( "github.com/standards-lab/sqlate/sqltest" ) -// set is the migration set every test administers: one transactional -// migration and one that runs outside a transaction. var set = []migrate.Migration{ {Version: 1, Name: "a", Up: "CREATE TABLE a (x int)", Down: "DROP TABLE a", Transactional: true}, {Version: 2, Name: "b", Up: "CREATE INDEX CONCURRENTLY ix ON a (x)", Down: "DROP INDEX CONCURRENTLY ix"}, @@ -47,7 +45,6 @@ func history(rows ...[]driver.Value) sqltest.Response { return sqltest.Response{Columns: historyCols, Rows: rows} } -// applied is the history of the whole set, clean. func applied() sqltest.Response { var rows [][]driver.Value for _, m := range set { @@ -56,51 +53,38 @@ func applied() sqltest.Response { return history(rows...) } -// clean is the script of a Start over a complete, clean history: Verify -// alone, since a clean history puts the set at its latest version. func clean() []sqltest.Response { return []sqltest.Response{exists(true), applied()} } -// applying is the script of an Up over an empty database: the lock, the -// history table, the empty history, each migration's statements, and the -// unlock. func applying() []sqltest.Response { rs := []sqltest.Response{locked, created, history()} for _, m := range set { if m.Transactional { - rs = append(rs, sqltest.Response{}, sqltest.Response{}) // up, insert + rs = append(rs, sqltest.Response{}, sqltest.Response{}) } else { - rs = append(rs, sqltest.Response{}, sqltest.Response{}, sqltest.Response{}) // dirty, up, clean + rs = append(rs, sqltest.Response{}, sqltest.Response{}, sqltest.Response{}) } } return append(rs, unlocked) } -// resetting is the script of a Reset over the whole applied set: the lock, -// the history table, the complete history, each migration's statements in -// reverse, the history table's drop, and the unlock. func resetting() []sqltest.Response { rs := []sqltest.Response{locked, created, applied()} for _, s := range slices.Backward(set) { if s.Transactional { - rs = append(rs, sqltest.Response{}, sqltest.Response{}) // down, delete + rs = append(rs, sqltest.Response{}, sqltest.Response{}) } else { - rs = append(rs, sqltest.Response{}, sqltest.Response{}, sqltest.Response{}) // dirty, down, delete + rs = append(rs, sqltest.Response{}, sqltest.Response{}, sqltest.Response{}) } } - return append(rs, sqltest.Response{}, unlocked) // drop + return append(rs, sqltest.Response{}, unlocked) } -// current is the script of a Status over a complete, clean history: the -// history table's existence, then the history. func current() []sqltest.Response { return []sqltest.Response{exists(true), applied()} } -// testDialect is the stub dialect with the two capabilities an engine -// sub-module supplies: the lock the migrator takes, and the server-version -// statement Diagnose reads. type testDialect struct{ sqltest.Dialect } func (testDialect) Lock(ctx context.Context, conn *sql.Conn, name string) error { @@ -121,8 +105,6 @@ func (testDialect) Unlock(ctx context.Context, conn *sql.Conn, name string) erro func (testDialect) ServerVersion() string { return "SELECT version()" } -// fakeSeeder declares its states (default alone when none are set), -// records the names it was asked to seed, and answers with a fixed count. type fakeSeeder struct { verifyErr error seedErr error @@ -148,20 +130,15 @@ func (f *fakeSeeder) Seed(_ context.Context, state string) (admin.Seeded, error) return admin.Seeded{"things": 2}, nil } -// A *Service takes part in a lifecycle.Coordinator's startup and readiness -// as the Value of a graph.Dependency, with no adapter. var ( _ lifecycle.Starter = (*admin.Service)(nil) _ lifecycle.ReadinessChecker = (*admin.Service)(nil) ) -// fakeRegistry is one domain's compiled statements. type fakeRegistry []admin.Entry func (r fakeRegistry) Registry() []admin.Entry { return r } -// started wraps the fake pool in the provider's lifecycle object, started, -// the way the composition root hands it to the admin service. func started(t *testing.T, pool *sql.DB) *database.DB { t.Helper() cfg := database.Config{Name: "test"} @@ -182,16 +159,11 @@ type fixture struct { seeder *fakeSeeder } -// newFixture builds the service over the fake pool with dialect d, the -// migration set as the one set "app", the library's own patterns, a -// one-statement registry, and opts, whose Seeder, when set, is the fake the -// fixture exposes. func newFixture(t *testing.T, d sqlate.Dialect, opts admin.Options, responses ...sqltest.Response) fixture { t.Helper() return newSetsFixture(t, []migrate.Set{{Name: "app", Migrations: set}}, d, opts, responses...) } -// newSetsFixture is newFixture over a migrator running sets. func newSetsFixture(t *testing.T, sets []migrate.Set, d sqlate.Dialect, opts admin.Options, responses ...sqltest.Response) fixture { t.Helper() pool, rec := sqltest.Open(t, responses...) @@ -247,8 +219,6 @@ func TestNew_PanicsOnWiringDefects(t *testing.T) { wantPanic(t, "without a Seeder", func() { admin.New(base, db, m, catalog, admin.Options{Seed: "default"}) }) } -// Start on a complete, clean history verifies and reports ready without -// taking the lock or writing, and verifies the seeder's statements once. func TestStart_CleanHistoryIsReady(t *testing.T) { f := newFixture(t, testDialect{}, admin.Options{Seeder: &fakeSeeder{}}, clean()...) if f.service.Ready() { @@ -268,8 +238,6 @@ func TestStart_CleanHistoryIsReady(t *testing.T) { } } -// Start on an empty database reads the pending set, applies it under the -// lock, then verifies. func TestStart_PendingHistoryIsApplied(t *testing.T) { responses := slices.Concat([]sqltest.Response{exists(false), exists(false)}, applying(), clean()) s, rec := newService(t, responses...) @@ -284,8 +252,6 @@ func TestStart_PendingHistoryIsApplied(t *testing.T) { } } -// A dirty history is a state startup cannot correct: Start fails, the -// service stays not ready, and nothing runs against the schema. func TestStart_DirtyHistoryFailsStartup(t *testing.T) { s, rec := newService(t, exists(true), history([]driver.Value{int64(1), "a", false}, []driver.Value{int64(2), "b", true})) @@ -298,8 +264,6 @@ func TestStart_DirtyHistoryFailsStartup(t *testing.T) { } } -// A seeder whose statements do not prepare fails startup and clears -// readiness the schema check had set. func TestStart_SeederVerifyFailureClearsReady(t *testing.T) { f := newFixture(t, testDialect{}, admin.Options{Seeder: &fakeSeeder{}}, clean()...) f.seeder.verifyErr = errors.New("seed statement does not prepare") @@ -312,8 +276,6 @@ func TestStart_SeederVerifyFailureClearsReady(t *testing.T) { } } -// Status reads the set's head, latest version, and pending versions, -// marks each migration, and refreshes Ready. func TestStatus_ReportsHeadAndPending(t *testing.T) { s, rec := newService(t, exists(true), history([]driver.Value{int64(1), "a", false})) st, err := s.Status(context.Background()) @@ -335,8 +297,6 @@ func TestStatus_ReportsHeadAndPending(t *testing.T) { } } -// Verify on a pending schema reports the pending versions and leaves the -// service not ready; on a complete one it sets ready. func TestVerify_RefreshesReady(t *testing.T) { s, _ := newService(t, exists(true), history([]driver.Value{int64(1), "a", false}), @@ -354,7 +314,6 @@ func TestVerify_RefreshesReady(t *testing.T) { } } -// The verbs reject arguments outside their domain before any I/O. func TestVerbs_ValidateBeforeIO(t *testing.T) { s, rec := newService(t) ctx := context.Background() @@ -374,7 +333,6 @@ func TestVerbs_ValidateBeforeIO(t *testing.T) { } } -// Up applies the set and answers with the refreshed status. func TestUp_ReturnsRefreshedStatus(t *testing.T) { responses := append(applying(), current()...) s, rec := newService(t, responses...) @@ -387,8 +345,6 @@ func TestUp_ReturnsRefreshedStatus(t *testing.T) { } } -// Force to a version outside the set is refused before any I/O, and Ready -// is left as the last operation found it. func TestForce_OutsideTheSetIsRefusedBeforeIO(t *testing.T) { s, rec := newService(t, clean()...) ctx := context.Background() @@ -405,15 +361,11 @@ func TestForce_OutsideTheSetIsRefusedBeforeIO(t *testing.T) { } } -// Steps applies the next pending migration and reverts the last applied -// one, each answering with the refreshed status. func TestSteps_AppliesAndReverts(t *testing.T) { one := history([]driver.Value{int64(1), "a", false}) s, rec := newService(t, - // Steps +1 over an empty database: app 1 up, insert. locked, created, history(), sqltest.Response{}, sqltest.Response{}, unlocked, exists(true), one, - // Steps -1 over the whole set: app 2 dirty, down, delete. locked, created, applied(), sqltest.Response{}, sqltest.Response{}, sqltest.Response{}, unlocked, exists(true), one, ) @@ -434,8 +386,6 @@ func TestSteps_AppliesAndReverts(t *testing.T) { } } -// Down reverts the named set's last migration and answers with the -// refreshed status. func TestDown_RevertsAndReportsStatus(t *testing.T) { s, rec := newService(t, locked, created, applied(), sqltest.Response{}, sqltest.Response{}, sqltest.Response{}, unlocked, @@ -453,8 +403,6 @@ func TestDown_RevertsAndReportsStatus(t *testing.T) { } } -// An operation that fails without determining the schema's state, such as -// one whose context is cancelled, leaves Ready where it stood. func TestReady_SurvivesAnAbortedOperation(t *testing.T) { s, _ := newService(t, clean()...) if err := s.Start(context.Background()); err != nil || !s.Ready() { @@ -476,13 +424,11 @@ func TestReady_SurvivesAnAbortedOperation(t *testing.T) { } } -// A service a status found behind becomes ready again once the schema is -// corrected out of band: Ready verifies it. func TestReady_ReverifiesACorrectedSchema(t *testing.T) { s, rec := newService(t, slices.Concat( - clean(), // Start - []sqltest.Response{exists(true), history([]driver.Value{int64(1), "a", false})}, // Status: behind - current(), // Ready's verify: corrected + clean(), + []sqltest.Response{exists(true), history([]driver.Value{int64(1), "a", false})}, + current(), )...) ctx := context.Background() if err := s.Start(ctx); err != nil { @@ -499,8 +445,6 @@ func TestReady_ReverifiesACorrectedSchema(t *testing.T) { } } -// Ready's verify runs at most once per interval: a second probe inside it -// reports not ready without reading the schema again. func TestReady_ReverifyIsThrottled(t *testing.T) { behind := []sqltest.Response{exists(true), history([]driver.Value{int64(1), "a", false})} s, rec := newService(t, slices.Concat(clean(), behind, behind)...) @@ -520,8 +464,6 @@ func TestReady_ReverifyIsThrottled(t *testing.T) { } } -// behindService is a started service a status found behind, so its Ready -// probes. func behindService(t *testing.T) *admin.Service { t.Helper() s, _ := newService(t, slices.Concat( @@ -536,7 +478,6 @@ func behindService(t *testing.T) *admin.Service { return s } -// Concurrent probes of a not-ready service verify the schema once. func TestReady_ConcurrentProbesVerifyOnce(t *testing.T) { s := behindService(t) var probes atomic.Int32 @@ -559,14 +500,12 @@ func TestReady_ConcurrentProbesVerifyOnce(t *testing.T) { } } -// A probe slower than the interval still excludes a second one: a Ready -// while it reads reports not ready without verifying. func TestReady_ProbesNeverOverlap(t *testing.T) { s := behindService(t) var probes atomic.Int32 entered, release := make(chan struct{}), make(chan struct{}) admin.SetProbe(s, func(context.Context) error { - if probes.Add(1) == 1 { // only the first blocks, so an overlap fails rather than hangs + if probes.Add(1) == 1 { entered <- struct{}{} <-release } @@ -585,13 +524,11 @@ func TestReady_ProbesNeverOverlap(t *testing.T) { } } -// An operation that determines the schema while a probe reads wins: the -// probe's clean verify does not overwrite the status it found behind. func TestReady_ProbeYieldsToAConcurrentFinding(t *testing.T) { s, _ := newService(t, slices.Concat( clean(), - []sqltest.Response{exists(true), history([]driver.Value{int64(1), "a", false})}, // Status: behind - []sqltest.Response{exists(true), history([]driver.Value{int64(1), "a", false})}, // Status during the probe + []sqltest.Response{exists(true), history([]driver.Value{int64(1), "a", false})}, + []sqltest.Response{exists(true), history([]driver.Value{int64(1), "a", false})}, )...) ctx := context.Background() if err := s.Start(ctx); err != nil { @@ -604,7 +541,7 @@ func TestReady_ProbeYieldsToAConcurrentFinding(t *testing.T) { admin.SetProbe(s, func(context.Context) error { entered <- struct{}{} <-release - return nil // a stale finding: the schema was current when it read + return nil }) done := make(chan bool) go func() { done <- s.Ready() }() @@ -618,8 +555,6 @@ func TestReady_ProbeYieldsToAConcurrentFinding(t *testing.T) { } } -// Before a successful Start, Ready reports the last operation's finding -// without reading the schema itself. func TestReady_NoVerifyBeforeStart(t *testing.T) { s, rec := newService(t) if s.Ready() || len(rec.Calls()) != 0 { @@ -627,8 +562,6 @@ func TestReady_NoVerifyBeforeStart(t *testing.T) { } } -// Ready is the schema's alone: a seeder whose statements do not prepare -// fails Verify but leaves a current schema ready. func TestVerify_SeederFailureLeavesTheSchemaReady(t *testing.T) { f := newFixture(t, testDialect{}, admin.Options{Seeder: &fakeSeeder{}}, clean()...) f.seeder.verifyErr = errors.New("seed statement does not prepare") @@ -640,8 +573,6 @@ func TestVerify_SeederFailureLeavesTheSchemaReady(t *testing.T) { } } -// A refusal the schema's state causes is ErrConflict, with the migrator's -// sentinel still in the chain. func TestUp_DirtySetIsAConflict(t *testing.T) { dirty := history([]driver.Value{int64(1), "a", false}, []driver.Value{int64(2), "b", true}) s, _ := newService(t, locked, created, dirty, unlocked, exists(true), dirty) @@ -654,8 +585,6 @@ func TestUp_DirtySetIsAConflict(t *testing.T) { } } -// A failed ping fails Diagnose with the ping's error and reads nothing -// further. func TestDiagnose_FailingPing(t *testing.T) { s, rec := newService(t) ctx, cancel := context.WithCancel(context.Background()) @@ -669,8 +598,6 @@ func TestDiagnose_FailingPing(t *testing.T) { } } -// Diagnose pings through the lifecycle object, reads the server's version -// through the dialect's capability, and reports the pool's counters. func TestDiagnose_ReadsTheVersionThroughTheCapability(t *testing.T) { s, rec := newService(t, sqltest.Response{Columns: []string{"version"}, Rows: [][]driver.Value{{"TestDB 1.0"}}}) d, err := s.Diagnose(context.Background()) @@ -685,8 +612,6 @@ func TestDiagnose_ReadsTheVersionThroughTheCapability(t *testing.T) { } } -// A dialect without the capability yields diagnostics with no version and -// no query. func TestDiagnose_OmitsTheVersionWithoutTheCapability(t *testing.T) { f := newFixture(t, sqltest.Dialect{}, admin.Options{}) d, err := f.service.Diagnose(context.Background()) @@ -698,8 +623,6 @@ func TestDiagnose_OmitsTheVersionWithoutTheCapability(t *testing.T) { } } -// The catalog read is the dump for inspection: the namespace, every -// pattern with its tier and slots, and no I/O. func TestCatalog_ReadsThePatternsWithoutIO(t *testing.T) { s, rec := newService(t) c := s.Catalog() @@ -716,8 +639,6 @@ func TestCatalog_ReadsThePatternsWithoutIO(t *testing.T) { } } -// The statements read walks the registry: one domain, its statement's -// declarations and parameters, and no I/O. func TestStatements_ReadTheRegistryWithoutIO(t *testing.T) { s, rec := newService(t) inv := s.Statements() @@ -733,7 +654,6 @@ func TestStatements_ReadTheRegistryWithoutIO(t *testing.T) { } } -// Without a registry the inventory is empty rather than nil. func TestStatements_NoRegistryReportsNoDomains(t *testing.T) { pool, _ := sqltest.Open(t) db := sqlate.Wrap(pool, testDialect{}) diff --git a/admin/sets_test.go b/admin/sets_test.go index 0cd1283..3b26aa4 100644 --- a/admin/sets_test.go +++ b/admin/sets_test.go @@ -15,8 +15,6 @@ import ( "github.com/standards-lab/sqlate/sqltest" ) -// base is a shipped set beneath the consumer's own: one transactional -// migration over its own history table. var base = migrate.Set{ Name: "base", Table: "base_version", @@ -25,31 +23,23 @@ var base = migrate.Set{ }, } -// twoSets is the migrator every test here administers: base, then the -// consumer's set "app" over the default table. var twoSets = []migrate.Set{base, {Name: "app", Migrations: set}} -// baseApplied is base's history, clean and complete. func baseApplied() sqltest.Response { return history([]driver.Value{int64(1), "base", false}) } -// bothCurrent is the script of a Status or a Verify over both sets clean -// and complete. func bothCurrent() []sqltest.Response { return []sqltest.Response{exists(true), baseApplied(), exists(true), applied()} } -// applyingBoth is the script of an Up over an empty database: the lock, -// both history tables read empty, base's migration, app's two, and the -// unlock. func applyingBoth() []sqltest.Response { return []sqltest.Response{ locked, created, history(), created, history(), - {}, {}, // base 1: up, insert - {}, {}, // app 1: up, insert - {}, {}, {}, // app 2: dirty, up, clean + {}, {}, + {}, {}, + {}, {}, {}, unlocked, } } @@ -59,8 +49,6 @@ func newSetsService(t *testing.T, opts admin.Options, responses ...sqltest.Respo return newSetsFixture(t, twoSets, testDialect{}, opts, responses...) } -// Status reports one entry per set, in declared order, each with its own -// table, head, latest, and pending versions; one pending set clears Ready. func TestSets_StatusReportsEverySet(t *testing.T) { f := newSetsService(t, admin.Options{}, exists(true), baseApplied(), exists(true), history([]driver.Value{int64(1), "a", false})) @@ -80,14 +68,12 @@ func TestSets_StatusReportsEverySet(t *testing.T) { } } -// Start on an empty database logs each set's pending versions before it -// applies them, then each set's head once current. func TestSets_StartLogsPendingBySet(t *testing.T) { var buf bytes.Buffer logger := slog.New(slog.NewTextHandler(&buf, nil)) responses := slices.Concat( - []sqltest.Response{exists(false)}, // Verify stops at base - []sqltest.Response{exists(false), exists(false)}, // the pending read + []sqltest.Response{exists(false)}, + []sqltest.Response{exists(false), exists(false)}, applyingBoth(), bothCurrent(), ) @@ -110,18 +96,15 @@ func TestSets_StartLogsPendingBySet(t *testing.T) { } } -// Reset reverts the consumer's set before the one it builds on, dropping -// each history table once its set is reverted, then applies both in -// declared order. func TestSets_ResetRevertsInReverseOrder(t *testing.T) { resetting := []sqltest.Response{ locked, created, baseApplied(), created, applied(), - {}, {}, {}, // app 2: dirty, down, delete - {}, {}, // app 1: down, delete - {}, // drop schema_version - {}, {}, // base 1: down, delete - {}, // drop base_version + {}, {}, {}, + {}, {}, + {}, + {}, {}, + {}, unlocked, } responses := slices.Concat(resetting, applyingBoth(), bothCurrent()) @@ -149,21 +132,14 @@ func TestSets_ResetRevertsInReverseOrder(t *testing.T) { } } -// A dirty consumer set refuses Up; Force on that set by name clears it -// without touching the schema or base's history, and Up then completes. func TestSets_ForceRepairsTheNamedDirtySet(t *testing.T) { dirtyApp := history([]driver.Value{int64(1), "a", false}, []driver.Value{int64(2), "b", true}) responses := slices.Concat( - // Up refused at the preflight. []sqltest.Response{locked, created, baseApplied(), created, dirtyApp, unlocked}, []sqltest.Response{exists(true), baseApplied(), exists(true), dirtyApp}, - // The status read after the refusal. []sqltest.Response{exists(true), baseApplied(), exists(true), dirtyApp}, - // Force app to 1: create, delete above, mark clean (affects the - // row, so no insert). []sqltest.Response{locked, {}, {}, {Affected: 1}, unlocked}, []sqltest.Response{exists(true), baseApplied(), exists(true), history([]driver.Value{int64(1), "a", false})}, - // Up applies app 2. []sqltest.Response{locked, created, baseApplied(), created, history([]driver.Value{int64(1), "a", false}), {}, {}, {}, unlocked}, bothCurrent(), ) @@ -205,8 +181,6 @@ func TestSets_ForceRepairsTheNamedDirtySet(t *testing.T) { } } -// A revert of the set beneath one with applied migrations is refused, and -// nothing runs against the schema. func TestSets_DownBelowAnAppliedSetIsRefused(t *testing.T) { f := newSetsService(t, admin.Options{}, slices.Concat( @@ -227,8 +201,6 @@ func TestSets_DownBelowAnAppliedSetIsRefused(t *testing.T) { } } -// A verb that names no set, or one the migrator does not run, is refused -// before any I/O, ahead of its other arguments. func TestSets_UnknownSetRefusedBeforeIO(t *testing.T) { f := newSetsService(t, admin.Options{}) ctx := context.Background() @@ -249,15 +221,13 @@ func TestSets_UnknownSetRefusedBeforeIO(t *testing.T) { } } -// With one set pending and another dirty, Start logs nothing as applying: -// Up refuses the run, and startup fails naming the dirty set. func TestSets_StartOverADirtySetLogsNoApply(t *testing.T) { var buf bytes.Buffer dirtyApp := history([]driver.Value{int64(1), "a", false}, []driver.Value{int64(2), "b", true}) f := newSetsService(t, admin.Options{Logger: slog.New(slog.NewTextHandler(&buf, nil))}, - exists(false), // Verify stops at base, pending - exists(false), exists(true), dirtyApp, // the pending read - locked, created, history(), created, dirtyApp, unlocked, // Up refused + exists(false), + exists(false), exists(true), dirtyApp, + locked, created, history(), created, dirtyApp, unlocked, ) err := f.service.Start(context.Background()) if !errors.Is(err, migrate.ErrDirty) || !strings.Contains(err.Error(), `"app"`) { @@ -268,8 +238,6 @@ func TestSets_StartOverADirtySetLogsNoApply(t *testing.T) { } } -// A history row the set does not carry, as a newer replica leaves it, is -// Status's error, and it clears a Ready an earlier check had set. func TestSets_StatusOverAnUnknownRowClearsReady(t *testing.T) { newer := history([]driver.Value{int64(1), "a", false}, []driver.Value{int64(2), "b", false}, []driver.Value{int64(3), "c", false}) f := newSetsService(t, admin.Options{}, diff --git a/config_test.go b/config_test.go index 6e93c93..8056826 100644 --- a/config_test.go +++ b/config_test.go @@ -10,8 +10,6 @@ import ( "github.com/standards-lab/go-database" ) -// validConfig satisfies the one required field; everything else exercises -// defaults under test. func validConfig() database.Config { return database.Config{Name: "app"} } @@ -36,7 +34,6 @@ func TestConfig_MergeOverlaysSetFields(t *testing.T) { if base.Port == nil || *base.Port != 5433 { t.Errorf("Port = %v, want 5433", base.Port) } - // Fields the overlay leaves unset keep the base values. if base.Name != "app" { t.Errorf("Name = %s, want app", base.Name) } @@ -45,7 +42,6 @@ func TestConfig_MergeOverlaysSetFields(t *testing.T) { } } -// Every field an overlay sets replaces the base's. func TestConfig_MergeOverlaysEveryField(t *testing.T) { base := database.Config{ Host: "a", Name: "a", User: "a", Password: "a", Port: new(1), @@ -79,7 +75,6 @@ func TestConfig_MergeOverlaysEveryField(t *testing.T) { } } -// Finalized reports whether Finalize has filled every pointer New reads. func TestConfig_Finalized(t *testing.T) { cfg := validConfig() if cfg.Finalized() { @@ -111,7 +106,6 @@ func TestConfig_MergeOptionsKeyWise(t *testing.T) { if got := base.Options["sslmode"]; got != "require" { t.Errorf("Options[sslmode] = %s, want require", got) } - // An overlay key overrides without dropping the others. if got := base.Options["application_name"]; got != "svc" { t.Errorf("Options[application_name] = %s, want svc", got) } @@ -137,7 +131,6 @@ func TestConfig_FinalizeDefaults(t *testing.T) { if cfg.Host != "localhost" { t.Errorf("Host = %s, want localhost", cfg.Host) } - // Port keeps no base default: 5432 is a provider fact. if cfg.Port != nil { t.Errorf("Port = %v, want nil", cfg.Port) } @@ -254,7 +247,6 @@ func TestConfig_FinalizeMalformedEnvFails(t *testing.T) { } func TestConfig_FinalizeZeroEnvDisablesOverrides(t *testing.T) { - // The zero Env names no variables, so ambient values cannot leak in. t.Setenv("TEST_DATABASE_HOST", "db.internal") cfg := validConfig() @@ -339,8 +331,6 @@ func TestConfig_Validate(t *testing.T) { } func TestConfig_ValidateAllowsZeroPools(t *testing.T) { - // Zero means unlimited open connections and no idle pool, per - // database/sql semantics; both survive defaults and validation. cfg := validConfig() cfg.MaxOpenConns = new(0) cfg.MaxIdleConns = new(0) diff --git a/database_test.go b/database_test.go index 9fd54de..a1869f9 100644 --- a/database_test.go +++ b/database_test.go @@ -15,22 +15,15 @@ import ( "github.com/standards-lab/go-database" ) -// A *DB takes part in a lifecycle.Coordinator's startup, shutdown, and -// readiness as the Value of a graph.Dependency, with no adapter. var ( _ lifecycle.Subsystem = (*database.DB)(nil) _ lifecycle.ReadinessChecker = (*database.DB)(nil) ) -// stubConnector produces connections that consult its failure flag on every -// ping, so connectivity can be broken and restored mid-test — including for -// connections the pool has cached. type stubConnector struct { fail atomic.Bool } -// errDial and errPing are the stub's driver errors, so a test can match the -// cause a failure wraps. var ( errDial = errors.New("dial refused") errPing = errors.New("ping refused") @@ -132,8 +125,6 @@ func TestNew_AppliesPoolSettings(t *testing.T) { } } -// Conn returns the pool New wrapped, and ConnTimeout the configured -// conn_timeout. func TestDB_Accessors(t *testing.T) { cfg := database.Config{Name: "app", ConnTimeout: new(config.Duration(3 * time.Second))} if err := cfg.Finalize(""); err != nil { @@ -179,7 +170,6 @@ func TestDB_StartFailureWrapsSentinelAndCause(t *testing.T) { if !errors.Is(err, database.ErrConnectionFailed) { t.Errorf("errors.Is(err, ErrConnectionFailed) = false for %v", err) } - // The dual wrap keeps the driver's cause legible. if !strings.Contains(err.Error(), "dial refused") { t.Errorf("error = %v, want it to carry the driver cause", err) } @@ -231,8 +221,6 @@ func TestDB_Ping(t *testing.T) { func TestDB_ShutdownBeforeStart(t *testing.T) { db := newTestDB(t, &stubConnector{}) - // Closing a lazy pool that never connected is a clean no-op, so the - // drain-after-failed-startup path cannot compound the failure. if err := db.Shutdown(context.Background()); err != nil { t.Errorf("Shutdown before Start = %v, want nil", err) } @@ -243,8 +231,6 @@ func TestDB_ShutdownAfterFailedStart(t *testing.T) { connector.fail.Store(true) db := newTestDB(t, connector) - // The Coordinator shuts down a participant whose Start failed; that - // Shutdown closes the pool cleanly and leaves the DB not ready. if err := db.Start(context.Background()); err == nil { t.Fatal("Start succeeded against a refusing connector") } diff --git a/env_test.go b/env_test.go index 189cfe5..1cddf74 100644 --- a/env_test.go +++ b/env_test.go @@ -6,8 +6,6 @@ import ( "github.com/standards-lab/go-database" ) -// Every name derives from the prefix through config.EnvName with the -// "database" segment; this pins the full set a consumer binds to. func TestNewEnv(t *testing.T) { env := database.NewEnv("app") diff --git a/errors_test.go b/errors_test.go index 1a10a98..18a1497 100644 --- a/errors_test.go +++ b/errors_test.go @@ -10,8 +10,6 @@ import ( "github.com/standards-lab/go-database" ) -// A connectivity failure from Start or Ping carries the sentinel, which is -// sqlate's, and the driver's own error, each matchable through errors.Is. func TestErrConnectionFailed_DualWrapFromStartAndPing(t *testing.T) { connector := &stubConnector{} db := newTestDB(t, connector) diff --git a/mise.toml b/mise.toml index 057e1b5..afcaa32 100644 --- a/mise.toml +++ b/mise.toml @@ -1,3 +1,4 @@ +# See architecture/standards/go-elemental/principles/release-and-ci.md [settings] task.run_auto_install = false @@ -7,9 +8,6 @@ go = "1.27.4" golangci-lint = "2.15.0" jq = "1.8.2" -# Space-separated list of module directories, kept in sync with the go.work -# use-list; check, currency, and upgrade loop over it. "." is the base -# module; provider sub-modules are added as they are built. [env] GO_MODULES = ". postgres" @@ -52,7 +50,6 @@ description = "Upgrade every module's go directive and direct requirements and t run = ''' set -eu export GOWORK=off -# The go directive follows the current Go minor, with no toolchain line. go_minor=$(mise latest go | cut -d. -f1,2) for mod in $GO_MODULES; do cd "$MISE_PROJECT_ROOT/$mod" @@ -65,11 +62,8 @@ cd "$MISE_PROJECT_ROOT" mise upgrade --bump --local ''' -# Each module builds with the workspace off, resolving its pins the way a -# consumer does, so a pin that no longer builds fails here and in CI rather -# than being masked by go.work. [tasks.build] -description = "Build all modules standalone (GOWORK=off)" +description = "Build every module in GO_MODULES standalone with GOWORK=off, resolving its pins as a consumer does" run = ''' set -e for mod in $GO_MODULES; do diff --git a/postgres/main_test.go b/postgres/main_test.go index 760e566..dbd0b5d 100644 --- a/postgres/main_test.go +++ b/postgres/main_test.go @@ -4,12 +4,9 @@ import ( "os" "testing" "time" - _ "time/tzdata" // Europe/London loads on a host without a zone database. + _ "time/tzdata" ) -// TestMain runs the package's tests with time.Local set to Europe/London, -// so a time the package returned in time.Local, not time.UTC, fails the -// tests' == comparisons whatever zone the host runs in. func TestMain(m *testing.M) { london, err := time.LoadLocation("Europe/London") if err != nil { diff --git a/postgres/postgres.go b/postgres/postgres.go index 40a039f..0598ab4 100644 --- a/postgres/postgres.go +++ b/postgres/postgres.go @@ -42,10 +42,6 @@ func New(cfg database.Config) (*database.DB, error) { return database.New(stdlib.OpenDB(*connCfg, stdlib.OptionAfterConnect(scanUTC)), cfg), nil } -// scanUTC registers, on each new connection's type map, a timestamptz codec -// that returns its values in time.UTC; pgx's default codec returns them in -// time.Local, and the session's TimeZone does not change that. timestamp -// needs no codec: pgx already returns it in time.UTC. func scanUTC(_ context.Context, conn *pgx.Conn) error { conn.TypeMap().RegisterType(&pgtype.Type{ Name: "timestamptz", @@ -55,8 +51,6 @@ func scanUTC(_ context.Context, conn *pgx.Conn) error { return nil } -// connConfig composes the connection URL from cfg, parses it, and sets the -// password and connect timeout on the parsed config. func connConfig(cfg database.Config) (*pgx.ConnConfig, error) { for key := range cfg.Options { if reservedOptions[key] { @@ -79,8 +73,6 @@ func connConfig(cfg database.Config) (*pgx.ConnConfig, error) { Path: "/" + cfg.Name, } if strings.HasPrefix(cfg.Host, "/") { - // A Unix-socket directory is no URL authority: pgx reads it, and - // the port naming the socket file, from the query. query.Set("host", cfg.Host) query.Set("port", strconv.Itoa(port)) } else { diff --git a/postgres/postgres_test.go b/postgres/postgres_test.go index ea72cd8..2d0b9bb 100644 --- a/postgres/postgres_test.go +++ b/postgres/postgres_test.go @@ -30,16 +30,12 @@ func finalizedConfig(t *testing.T) database.Config { return cfg } -// session is what a client sent the test server: its startup parameters -// and, answering a cleartext-password request, its password. type session struct { params map[string]string password string err error } -// serve answers every connection on ln as a server that asks for a -// cleartext password and then refuses it, reporting each session it sees. func serve(t *testing.T, ln net.Listener) <-chan session { t.Helper() sessions := make(chan session, 4) @@ -92,8 +88,6 @@ func handshake(conn net.Conn) session { return s } -// connect starts a pool built from cfg against the test server and returns -// the session the server saw; the server's refusal fails Start. func connect(t *testing.T, cfg database.Config, sessions <-chan session) session { t.Helper() if err := cfg.Finalize(""); err != nil { @@ -119,11 +113,8 @@ func connect(t *testing.T, cfg database.Config, sessions <-chan session) session } } -// noTLS keeps the session in cleartext, so the test server reads it. var noTLS = map[string]string{"sslmode": "disable"} -// socketDir makes a short directory for a Unix socket, whose path is -// limited to about a hundred bytes. func socketDir(t *testing.T) string { t.Helper() dir, err := os.MkdirTemp("", "pg") @@ -134,9 +125,6 @@ func socketDir(t *testing.T) string { return dir } -// New only builds the pool: a server listening at the configured address -// has no connection waiting once New returns, and readiness stays false -// until Start. func TestNew_ConstructsWithoutIO(t *testing.T) { ln, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)}) if err != nil { @@ -154,8 +142,6 @@ func TestNew_ConstructsWithoutIO(t *testing.T) { } t.Cleanup(func() { _ = db.Conn().Close() }) - // A dial completes its handshake into the listener's backlog before it - // returns, so an Accept that times out finds that New never dialed. _ = ln.SetDeadline(time.Now().Add(50 * time.Millisecond)) if conn, err := ln.Accept(); err == nil { _ = conn.Close() @@ -166,9 +152,6 @@ func TestNew_ConstructsWithoutIO(t *testing.T) { } } -// A TCP host and port reach the server, carrying the user and database, -// and the password arrives intact whatever characters it holds, since it -// never passes through the connection URL. func TestNew_ConnectsOverTCPWithThePassword(t *testing.T) { ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { @@ -190,8 +173,6 @@ func TestNew_ConnectsOverTCPWithThePassword(t *testing.T) { } } -// A host that is a path is a Unix-socket directory, and the port, 5432 -// unless set, names the socket file in it. func TestNew_UnixSocketHost(t *testing.T) { cases := []struct { name string @@ -218,8 +199,6 @@ func TestNew_UnixSocketHost(t *testing.T) { } } -// Whether a user is required varies by provider and auth mode, so the -// config leaves it optional and the connection carries the OS user. func TestNew_EmptyUserFallsBackToTheOSUser(t *testing.T) { osUser, err := user.Current() if err != nil { @@ -238,8 +217,6 @@ func TestNew_EmptyUserFallsBackToTheOSUser(t *testing.T) { } } -// Finalized is the one check: a config missing any field New reads panics, -// though its ConnTimeout is set. func TestNew_PanicsOnPartlyFinalizedConfig(t *testing.T) { cfg := finalizedConfig(t) cfg.MaxOpenConns = nil @@ -309,10 +286,6 @@ func TestNew_PanicsOnUnfinalizedConfig(t *testing.T) { _, _ = postgres.New(database.Config{Name: "app"}) } -// serveTimestamptz answers every connection on ln as a server that admits -// the login and returns at, as a one-row timestamptz column, for any -// SELECT, in text through the simple protocol and in binary through the -// extended one. It reports each connection's failure on the channel. func serveTimestamptz(t *testing.T, ln net.Listener, at time.Time) <-chan error { t.Helper() errs := make(chan error, 4) @@ -344,7 +317,6 @@ func answerTimestamptz(conn net.Conn, at time.Time) error { return err } be.Send(&pgproto3.AuthenticationOk{}) - // pgx runs the simple protocol only on a server reporting these. be.Send(&pgproto3.ParameterStatus{Name: "standard_conforming_strings", Value: "on"}) be.Send(&pgproto3.ParameterStatus{Name: "client_encoding", Value: "UTF8"}) be.Send(&pgproto3.BackendKeyData{ProcessID: 1, SecretKey: []byte{0, 0, 0, 1}}) @@ -415,10 +387,6 @@ func answerTimestamptz(conn net.Conn, at time.Time) error { } } -// Every time a workspace library returns is in time.UTC: a timestamptz -// read through the pool New builds is the UTC instant, not that instant in -// time.Local (Europe/London, from TestMain), in pgx's text format and in -// its binary one. func TestNew_ReadsTimestamptzInUTC(t *testing.T) { want := time.Date(2026, 7, 1, 12, 30, 15, 123456000, time.UTC) cases := []struct { diff --git a/scripts/currency.sh b/scripts/currency.sh index 7d9d0fc..f7a7257 100755 --- a/scripts/currency.sh +++ b/scripts/currency.sh @@ -16,8 +16,6 @@ report() { stale=1 } -# matches prints each match of a grep pattern in the given files that exist. -# A missing file or no match is no output; any other grep error fails. matches() { local pattern=$1 file local files=() @@ -29,45 +27,55 @@ matches() { grep -ho "$pattern" "${files[@]}" || [ $? -eq 1 ] } -go_minor=$(mise latest go | cut -d. -f1,2) - -for mod in $GO_MODULES; do - # Direct requirements with a newer version within their major. +report_outdated_requirements() { + local mod=$1 updates line updates=$(cd "$mod" && go list -m -u -f \ '{{if and (not .Main) (not .Indirect) .Update}}{{.Path}} {{.Version}} -> {{.Update.Version}}{{end}}' all) while read -r line; do - [ -n "$line" ] && report "$mod/go.mod: $line" + if [ -n "$line" ]; then + report "$mod/go.mod: $line" + fi done <<<"$updates" +} - # The go directive's minor against the current Go minor. +report_outdated_go_directive() { + local mod=$1 go_minor=$2 directive directive=$(cd "$mod" && go mod edit -json | jq -r .Go | cut -d. -f1,2) [ "$directive" = "$go_minor" ] || report "$mod/go.mod: go $directive -> go $go_minor" -done +} -# mise tools pinned below their latest version. -outdated=$(mise outdated --bump --local --json | - jq -r 'to_entries[] | "\(.key) \(.value.requested) -> \(.value.bump)"') -while read -r line; do - [ -n "$line" ] && report "mise.toml: $line" -done <<<"$outdated" +report_outdated_mise_tools() { + local outdated line + outdated=$(mise outdated --bump --local --json | + jq -r 'to_entries[] | "\(.key) \(.value.requested) -> \(.value.bump)"') + while read -r line; do + if [ -n "$line" ]; then + report "mise.toml: $line" + fi + done <<<"$outdated" +} -# The workflows of the project root and of the git top-level, de-duplicated. -# They are one directory when the project is the repository, and two when the -# repository nests the project in a subdirectory, as the template repository -# does. A project not yet in git has only its own. -root=$(pwd -P) -top=$(git rev-parse --show-toplevel 2>/dev/null || echo "$root") -workflows=("$root"/.github/workflows/*.yml) -[ "$top" = "$root" ] || workflows+=("$top"/.github/workflows/*.yml) +report_outdated_actions() { + local root top actions uses action pin repo latest + root=$(pwd -P) + top=$(git rev-parse --show-toplevel 2>/dev/null || echo "$root") + local workflows=("$root"/.github/workflows/*.yml) + [ "$top" = "$root" ] || workflows+=("$top"/.github/workflows/*.yml) + actions=$(matches 'uses: *[^ ]*@[^ ]*' "${workflows[@]}" | sed 's/uses: *//' | sort -u) + for uses in $actions; do + action=${uses%@*} + pin=${uses#*@} + repo=$(echo "$action" | cut -d/ -f1,2) + latest=$(gh api "repos/$repo/releases/latest" --jq .tag_name) + [ "$pin" = "$latest" ] || report ".github/workflows: $action $pin -> $latest" + done +} -# GitHub Actions pinned below the action's latest release. -actions=$(matches 'uses: *[^ ]*@[^ ]*' "${workflows[@]}" | sed 's/uses: *//' | sort -u) -for uses in $actions; do - action=${uses%@*} - pin=${uses#*@} - repo=$(echo "$action" | cut -d/ -f1,2) - latest=$(gh api "repos/$repo/releases/latest" --jq .tag_name) - [ "$pin" = "$latest" ] || report ".github/workflows: $action $pin -> $latest" +go_minor=$(mise latest go | cut -d. -f1,2) +for mod in $GO_MODULES; do + report_outdated_requirements "$mod" + report_outdated_go_directive "$mod" "$go_minor" done - +report_outdated_mise_tools +report_outdated_actions exit "$stale" diff --git a/sweep/sweep.go b/sweep/sweep.go index 160ca03..659a7ff 100644 --- a/sweep/sweep.go +++ b/sweep/sweep.go @@ -120,7 +120,7 @@ type Options struct { // its readiness is the reactor's alone. type Sweeper struct { db *sqlate.DB - locker sqlate.TryLocker // nil when unlocked + locker sqlate.TryLocker regs []Registration names map[string]bool tick time.Duration @@ -128,10 +128,8 @@ type Sweeper struct { logger *slog.Logger wake *reactor.Waker r *reactor.Reactor[time.Time] - now func() time.Time // the clock that bounds a cycle; time.Now outside tests + now func() time.Time - // mu guards the due state: each reclaimer's last cycle, by its - // delivery's time, and the reclaimers nudged since their last cycle. mu sync.Mutex last map[string]time.Time nudged map[string]bool @@ -219,8 +217,6 @@ func (s *Sweeper) Nudge(name string) { s.nudge(name) } -// nudge is [Sweeper.Nudge] for a name known to be registered: it marks -// name due and asks the reactor for a delivery. func (s *Sweeper) nudge(name string) { s.mu.Lock() s.nudged[name] = true @@ -242,14 +238,6 @@ func (s *Sweeper) Ready() bool { return s.r.Ready() } // Err yields the reactor's failure while running; see [reactor.Reactor.Err]. func (s *Sweeper) Err() <-chan error { return s.r.Err() } -// handle is the reactor's Func: it runs the cycle of each reclaimer due at -// now, in the list's order, until the drain begins. A cycle that yields -// leaves its reclaimer due and the waker nudged, so the reclaimers after it -// run in this delivery and every due reclaimer runs again, in order, in the -// next: each gets at most one interval in turn. It returns an error -// only when ctx ends, which is the drain's cancellation, so that error is -// the reactor's; every other failure is reported and left to the next -// cycle, and the reactor continues. func (s *Sweeper) handle(ctx context.Context, now time.Time) error { drain := reactor.Draining(ctx) for _, reg := range s.regs { @@ -269,8 +257,6 @@ func (s *Sweeper) handle(ctx context.Context, now time.Time) error { return nil } -// due reports whether reg is due at now, and if so consumes its nudge and -// records now as its last cycle. func (s *Sweeper) due(reg Registration, now time.Time) bool { s.mu.Lock() nudged := s.nudged[reg.Name] @@ -285,16 +271,6 @@ func (s *Sweeper) due(reg Registration, now time.Time) bool { return true } -// cycle claims reg's lock and runs its passes while one reports more, -// whatever its error, which is reported and never ends the cycle, for at -// most reg's interval from the claim. A cycle still reporting more once -// the interval has passed yields: it marks reg nudged, as [Sweeper.Nudge] -// does, so reg stays due and the delivery that nudge earns resumes its -// backlog without waiting out an interval. A lock held elsewhere runs no -// pass and reports nothing; a failure to claim it is logged at warn and -// leaves the work to the next cycle. The claim is released when the cycle -// ends, on every path. It returns ctx's error once ctx ends, and nil -// otherwise. func (s *Sweeper) cycle(ctx context.Context, drain <-chan struct{}, reg Registration) error { if s.locker != nil { release, claimed, err := s.claim(ctx, reg.Name) @@ -313,34 +289,22 @@ func (s *Sweeper) cycle(ctx context.Context, drain <-chan struct{}, reg Registra } p, ran := s.pass(ctx, drain, reg) if err := ctx.Err(); err != nil { - // The drain's cancellation ended the pass: its outcome is the - // cancellation's, which the reactor reports, not the pass's. return err } if !ran { return nil } s.opts.OnPass(ctx, p) - // more alone decides: a failed pass that reports more is followed - // by another, since a reclaimer's passes are idempotent. A gate - // failure ran no pass, so it reports no more and ends the cycle. if !p.More { return nil } if s.now().Sub(start) >= reg.Policy.Interval { - // Yield: reg stays due, and the delivery the nudge earns - // resumes its backlog after the reclaimers behind it. s.nudge(reg.Name) return nil } } } -// claim pins a connection and tries the lock "sweep." on it. It -// returns the release, which unlocks and then closes the connection, and -// whether the lock was taken; a lock not taken leaves nothing held. Its -// error is ctx's alone: any other failure is logged and reported as not -// claimed. func (s *Sweeper) claim(ctx context.Context, name string) (release func(), claimed bool, err error) { lock := "sweep." + name conn, err := s.db.Conn(ctx) @@ -356,21 +320,14 @@ func (s *Sweeper) claim(ctx context.Context, name string) (release func(), claim return nil, false, nil } return func() { - // The unlock outlives ctx, so a cycle the drain cancelled still - // releases its claim before the connection returns to the pool. if err := s.locker.Unlock(context.WithoutCancel(ctx), conn, lock); err != nil { s.logger.WarnContext(ctx, "sweep release failed", "reclaimer", name, "error", s.db.MapError(err)) - // A session whose unlock failed may still hold the lock; - // discard it rather than return it to the pool, so the - // session's end releases it. _ = conn.Raw(func(any) error { return driver.ErrBadConn }) } _ = conn.Close() }, true, nil } -// claimFailed logs a failure to claim name's lock, unless ctx ended, in -// which case it returns ctx's error. func (s *Sweeper) claimFailed(ctx context.Context, name string, err error) error { if cerr := ctx.Err(); cerr != nil { return cerr @@ -379,9 +336,6 @@ func (s *Sweeper) claimFailed(ctx context.Context, name string, err error) error return nil } -// pass runs one pass of reg, holding the gate shared when the sweeper has -// one. ran is false when the wait on the gate was ended by ctx or the -// drain, which runs no pass and reports nothing. func (s *Sweeper) pass(ctx context.Context, drain <-chan struct{}, reg Registration) (p Pass, ran bool) { p.Name = reg.Name start := time.Now() @@ -401,8 +355,6 @@ func (s *Sweeper) pass(ctx context.Context, drain <-chan struct{}, reg Registrat return p, true } -// share holds the gate shared, waiting until ctx ends or the drain begins. -// ended reports a wait either ended, which holds nothing. func (s *Sweeper) share(ctx context.Context, drain <-chan struct{}) (release func(), ended bool, err error) { wait, cancel := context.WithCancel(ctx) defer cancel() @@ -425,7 +377,6 @@ func (s *Sweeper) share(ctx context.Context, drain <-chan struct{}) (release fun return release, false, nil } -// closed reports whether ch is closed; a nil ch never is. func closed(ch <-chan struct{}) bool { select { case <-ch: @@ -435,9 +386,6 @@ func closed(ch <-chan struct{}) bool { } } -// logPasses returns the default hook: a pass that returned an error logged -// at warn on logger as "sweep pass failed", with the reclaimer, whether it -// reported more, its duration, and the error; any other pass not at all. func logPasses(logger *slog.Logger) Hook { return func(ctx context.Context, p Pass) { if p.Err == nil { diff --git a/sweep/sweep_test.go b/sweep/sweep_test.go index c6684fb..9df7171 100644 --- a/sweep/sweep_test.go +++ b/sweep/sweep_test.go @@ -19,32 +19,25 @@ import ( "github.com/standards-lab/sqlate/sqltest" ) -// t0 is the first delivery's time in the tests that drive the handler. var t0 = time.Date(2026, 10, 15, 12, 0, 0, 0, time.UTC) -// flag scripts the one boolean row a try-lock or unlock statement reads. func flag(b bool) sqltest.Response { return sqltest.Response{Columns: []string{"ok"}, Rows: [][]driver.Value{{b}}} } -// claimed scripts one cycle whose claim is granted and released. func claimed() []sqltest.Response { return []sqltest.Response{flag(true), flag(true)} } -// result is one scripted pass outcome. type result struct { more bool err error } -// reclaimer is a fake Reclaimer: it returns its scripted results in order, -// then (false, nil), and records each budget it was given. block, when -// set, runs inside each pass before it returns. type reclaimer struct { mu sync.Mutex results []result budgets []int block func(ctx context.Context) error - log *[]string // shared order log, when set + log *[]string name string } @@ -74,7 +67,6 @@ func (r *reclaimer) passes() int { return len(r.budgets) } -// passes collects the hook's reports. type passes struct { mu sync.Mutex got []sweep.Pass @@ -92,8 +84,6 @@ func (p *passes) all() []sweep.Pass { return slices.Clone(p.got) } -// logs is a logger whose output a test reads, safe for the reactor's -// goroutine to write. type logs struct { mu sync.Mutex buf bytes.Buffer @@ -113,7 +103,6 @@ func (l *logs) String() string { func (l *logs) logger() *slog.Logger { return slog.New(slog.NewTextHandler(l, nil)) } -// fixture is a sweeper over a scripted locking pool. type fixture struct { s *sweep.Sweeper pool *sql.DB @@ -136,7 +125,6 @@ func newFixture(t *testing.T, dialect sqlate.Dialect, regs []sweep.Registration, return fixture{s: s, pool: pool, rec: rec, logs: l} } -// locks returns the lock statements recorded, each with its lock's name. func locks(rec *sqltest.Recorder) []string { var out []string for _, c := range rec.Calls() { @@ -157,8 +145,6 @@ func wantLocks(t *testing.T, rec *sqltest.Recorder, want ...string) { } } -// await receives from ch, failing the test if nothing arrives in time, so a -// sweeper that never gets there fails rather than hangs. func await[T any](t *testing.T, ch <-chan T, what string) T { t.Helper() select { @@ -171,8 +157,6 @@ func await[T any](t *testing.T, ch <-chan T, what string) T { } } -// shutdown drains s within a bound, so a drain that never ends fails the -// test rather than hangs it. func shutdown(s *sweep.Sweeper) error { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() @@ -264,10 +248,6 @@ func TestNew_WiringDefectsPanic(t *testing.T) { } func TestHandle_TicksAtTheSmallestInterval(t *testing.T) { - // The tick is the smallest interval, 1m, so a reclaimer is due half a - // tick, 30s, before its own interval has passed: slow's 5m makes it due - // from 4m30s. A tick of the largest interval would make it due from - // 4m-30m, and one of the middle interval from 2m30s. var order []string slow := &reclaimer{name: "slow", log: &order} f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{ @@ -349,8 +329,6 @@ func TestHandle_PassesWhileMoreUnderOneClaim(t *testing.T) { wantLocks(t, f.rec, try+"sweep.files", unlock+"sweep.files") } -// clock is a fake clock for a sweeper's cycle bound, which a reclaimer's -// pass advances so a cycle runs past its interval without sleeping. type clock struct { mu sync.Mutex t time.Time @@ -368,8 +346,6 @@ func (c *clock) advance(d time.Duration) { c.t = c.t.Add(d) } -// endless is a reclaimer that reports more on every pass, each pass -// advancing c by step. func endless(name string, log *[]string, c *clock, step time.Duration) *reclaimer { results := make([]result, 100) for i := range results { @@ -383,8 +359,6 @@ func endless(name string, log *[]string, c *clock, step time.Duration) *reclaime func TestHandle_ACycleYieldsAtItsIntervalAndStaysDue(t *testing.T) { c := &clock{t: t0} - // Each pass takes 20s of a 1m interval, so the cycle yields after the - // third, still reporting more. r := endless("files", nil, c, 20*time.Second) f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{reg("files", r, time.Minute, 1)}, time.Second, sweep.Options{}) sweep.SetClock(f.s, c.now) @@ -399,8 +373,6 @@ func TestHandle_ACycleYieldsAtItsIntervalAndStaysDue(t *testing.T) { } wantLocks(t, f.rec, try+"sweep.files", unlock+"sweep.files") - // The next delivery, a second later and well inside the interval, runs - // the yielded reclaimer again. f.rec.Queue(claimed()...) if err := handle(context.Background(), t0.Add(time.Second)); err != nil { t.Fatalf("second handle: %v", err) @@ -435,9 +407,6 @@ func TestHandle_AYieldingCycleLetsTheReclaimersAfterItRun(t *testing.T) { func TestHandle_ACycleWhoseLastPassReportsNoMoreIsNotLeftDue(t *testing.T) { c := &clock{t: t0} - // The one pass outlasts the 1m interval but reports no more, so the - // cycle ends rather than yields, and the reclaimer waits out its - // interval. r := &reclaimer{block: func(context.Context) error { c.advance(2 * time.Minute) return nil @@ -551,7 +520,6 @@ func TestHandle_NudgeRunsOnlyTheNamedReclaimer(t *testing.T) { t.Errorf("passes = %q, want %q", order, want) } - // The nudge was consumed: a delivery before the interval runs nothing. if err := handle(context.Background(), t0.Add(2*time.Second)); err != nil { t.Fatalf("handle: %v", err) } @@ -587,10 +555,8 @@ func TestHandle_EachReclaimerRunsOnItsOwnInterval(t *testing.T) { at time.Duration want []string }{ - {0, []string{"fast", "slow"}}, // every reclaimer is due at start - {29 * time.Second, nil}, // under the interval less half a tick - // A tick a little short of the interval, as a tick after a - // nudge's delivery is, still counts. + {0, []string{"fast", "slow"}}, + {29 * time.Second, nil}, {time.Minute - time.Second, []string{"fast"}}, {2 * time.Minute, []string{"fast"}}, {3*time.Minute - time.Second, []string{"fast", "slow"}}, @@ -693,8 +659,6 @@ func TestHandle_AnEndedContextReturnsItsErrorAndReleasesTheClaim(t *testing.T) { wantLocks(t, f.rec, try+"sweep.files", unlock+"sweep.files") } -// gateLog is a Gate that records each acquisition and release in a shared -// log, or fails with err. type gateLog struct { log *[]string err error @@ -743,7 +707,6 @@ func TestHandle_AGateFailureIsReportedAndRunsNoPass(t *testing.T) { wantLocks(t, f.rec, try+"sweep.files", unlock+"sweep.files") } -// waiting is a Gate over a reactor.Gate that signals each wait it begins. type waiting struct { g *reactor.Gate began chan struct{} @@ -810,8 +773,6 @@ func TestSweeper_EveryReclaimerIsDueAtStart(t *testing.T) { } func TestSweeper_AYieldingCycleNudgesTheReactor(t *testing.T) { - // The interval is an hour, so a second delivery that comes at all comes - // from the yield's nudge, not a tick. c := &clock{t: t0} ran := make(chan struct{}, 2) r := &reclaimer{results: []result{{more: true}}, block: func(context.Context) error { @@ -838,8 +799,6 @@ func TestSweeper_TheDrainStartsNoFurtherPassAndLetsTheOneInFlightFinish(t *testi entered := make(chan struct{}) var readyInPass bool var s *sweep.Sweeper - // The pass in flight returns, reporting more, only once the drain has - // begun: the cycle must not start another. r := &reclaimer{results: []result{{more: true}, {more: true}}, block: func(ctx context.Context) error { readyInPass = s.Ready() close(entered) @@ -877,7 +836,6 @@ func TestSweeper_TheDrainsCancellationIsTheReactorsError(t *testing.T) { <-ctx.Done() return ctx.Err() }} - // CancelWithin cancels the pass at half the shutdown timeout. f := newFixture(t, sqltest.LockingDialect{}, []sweep.Registration{reg("files", r, time.Hour, 1)}, 20*time.Millisecond, sweep.Options{OnPass: p.hook}) f.rec.Queue(claimed()...) From 2d29dd2b66e900d016a6a87f40e43c422cdf56d8 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Fri, 20 Nov 2026 23:01:55 -0500 Subject: [PATCH 5/9] harness.adoption: keep removed comments' needed reasoning in package docs Per the corrected comment rule, reasoning a reader needs that sat only in removed unexported comments moves to a home: sweep's package doc says a cycle the drain cancelled still releases its claim (the unlock outlives ctx); admin's package doc says a re-verification yields to an operation that determined the schema while it read, and an aborted operation leaves Ready as it was (the gen counter's purpose); postgres's TestMain names its zone nonUTCLocalZone. The rest of the removed reasoning was already in exported docs, package docs, or test names. --- admin/doc.go | 5 ++++- postgres/main_test.go | 6 ++++-- sweep/doc.go | 3 ++- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/admin/doc.go b/admin/doc.go index 95cbe36..f7576a2 100644 --- a/admin/doc.go +++ b/admin/doc.go @@ -61,7 +61,10 @@ // [Service.Ready] reports the schema alone, as the last operation that // determined it found it; once Start has succeeded, a not-ready service // re-verifies at most once per five seconds. A true Ready is not -// re-checked. +// re-checked. A re-verification's finding yields to any operation that +// determined the schema while it read, and an operation that determines +// nothing, such as one a cancelled context or a lost connection ends, +// leaves Ready as it was. // // # Operations // diff --git a/postgres/main_test.go b/postgres/main_test.go index dbd0b5d..ff81bd6 100644 --- a/postgres/main_test.go +++ b/postgres/main_test.go @@ -7,11 +7,13 @@ import ( _ "time/tzdata" ) +const nonUTCLocalZone = "Europe/London" + func TestMain(m *testing.M) { - london, err := time.LoadLocation("Europe/London") + local, err := time.LoadLocation(nonUTCLocalZone) if err != nil { panic(err) } - time.Local = london + time.Local = local os.Exit(m.Run()) } diff --git a/sweep/doc.go b/sweep/doc.go index 0eeed9b..829c5cf 100644 --- a/sweep/doc.go +++ b/sweep/doc.go @@ -52,7 +52,8 @@ // progress still costs passes back to back for that interval, which is why // a reclaimer reports more only while a further pass can make progress. // The drain ends a cycle sooner. The claim is released when the cycle -// ends, on every path: unlocked, then the connection closed. A failure to +// ends, on every path, a cycle the drain cancelled included: unlocked, +// then the connection closed. A failure to // claim or to release the lock is logged at warn, and a connection whose // unlock failed is discarded rather than pooled, so the session's end // releases the lock. From a1e86a1ff70826269cf9993e2fbeb8d6c1a21f34 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Fri, 20 Nov 2026 23:04:44 -0500 Subject: [PATCH 6/9] harness.adoption: standards review Align the check's lint step, the upgrade task's description, and the currency script with go-observability and go-cli-sdk, and name lint-context and lint-references in the README's check line. --- README.md | 2 +- mise.toml | 6 +++--- scripts/currency.sh | 8 +++++--- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 8723b50..ffe5939 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ principles: The repository uses a Go workspace and [mise](https://mise.jdx.dev): ``` -mise run check # build, vet, format, fix, tidy, test, and lint every module; writes nothing +mise run check # build, vet, format, fix, tidy, test, and lint every module, then lint-context and lint-references; writes nothing mise run currency # report requirements, Go, tools, and actions behind their latest mise run upgrade # upgrade every module's go directive and requirements, and the tools, to their latest ``` diff --git a/mise.toml b/mise.toml index afcaa32..8d5962a 100644 --- a/mise.toml +++ b/mise.toml @@ -34,9 +34,9 @@ for lint in lint-context lint-references; do if ! command -v "$lint" >/dev/null; then echo "FAIL: $lint is not on PATH; run mise install" >&2 fail=1 - continue + elif ! "$lint"; then + fail=1 fi - "$lint" || fail=1 done exit "$fail" ''' @@ -46,7 +46,7 @@ description = "Report every requirement, Go version, tool, and action pin behind run = "scripts/currency.sh" [tasks.upgrade] -description = "Upgrade every module's go directive and direct requirements and the local mise tools to their latest, rewriting go.mod and mise.toml" +description = "Upgrade every module's go directive to the current Go minor, with no toolchain line, and its direct requirements and the local mise tools to their latest, rewriting go.mod and mise.toml" run = ''' set -eu export GOWORK=off diff --git a/scripts/currency.sh b/scripts/currency.sh index f7a7257..7ab80a4 100755 --- a/scripts/currency.sh +++ b/scripts/currency.sh @@ -1,7 +1,9 @@ #!/usr/bin/env bash # currency reports every dependency, toolchain, and pin that trails its latest # release, one line each, and exits non-zero when it reports any. It reads the -# network and writes nothing. Run it through `mise run currency`. +# network and writes nothing. Run it through `mise run currency`. The actions it +# checks are those of the project root's workflows and, when the repository nests +# the project in a subdirectory, of the git top-level's. # # Each scan captures its command's output in a variable before reading it, so # under set -e a scan command that fails (a go list missing a go.sum entry) @@ -56,10 +58,10 @@ report_outdated_mise_tools() { } report_outdated_actions() { - local root top actions uses action pin repo latest + local root top workflows actions uses action pin repo latest root=$(pwd -P) top=$(git rev-parse --show-toplevel 2>/dev/null || echo "$root") - local workflows=("$root"/.github/workflows/*.yml) + workflows=("$root"/.github/workflows/*.yml) [ "$top" = "$root" ] || workflows+=("$top"/.github/workflows/*.yml) actions=$(matches 'uses: *[^ ]*@[^ ]*' "${workflows[@]}" | sed 's/uses: *//' | sort -u) for uses in $actions; do From e25a027a103cd655ab840d05d7d7152ef0fbe2b4 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Fri, 20 Nov 2026 23:07:21 -0500 Subject: [PATCH 7/9] harness.adoption: map entries name their homes --- context/README.md | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/context/README.md b/context/README.md index cdf2628..59662be 100644 --- a/context/README.md +++ b/context/README.md @@ -11,15 +11,7 @@ This context records only working knowledge the code and the README do not expre ## Capability map -- **database** (built): wraps the pool: configuration, lifecycle, readiness, and the - connectivity sentinels ([`doc.go`](../doc.go)). -- **admin** (built): the database admin service over `sqlate`, generic over the consumer's - migrator, seeder, registry, catalog, and pool. [`admin/doc.go`](../admin/doc.go) states its - construction, its verbs, its startup sequence, its errors, and its migration sets: one service - administers every set its migrator runs. -- **sweep** (built): the general sweeper: it runs a service's reclaimers as one go-core reactor, - each cycle under the advisory lock `sweep.` and bounded by its interval. - [`sweep/doc.go`](../sweep/doc.go) states its construction, cycles, and drain. -- **postgres** (built): the PostgreSQL provider: it constructs the pool over pgx's - `database/sql` adapter from the configuration block, and supplies no dialect — the dialect is - `sqlate/postgres`'s ([`postgres/doc.go`](../postgres/doc.go)). +- **database** (built): [doc.go](../doc.go). +- **admin** (built): [admin/doc.go](../admin/doc.go). +- **sweep** (built): [sweep/doc.go](../sweep/doc.go). +- **postgres** (built): [postgres/doc.go](../postgres/doc.go). From cecc592c348f4c2e865b64127e5f40ead5777edf Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Fri, 20 Nov 2026 23:08:41 -0500 Subject: [PATCH 8/9] harness.adoption: editor pass --- context/goals/harness.adoption-go-base.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/context/goals/harness.adoption-go-base.md b/context/goals/harness.adoption-go-base.md index 7aad17f..281b2c0 100644 --- a/context/goals/harness.adoption-go-base.md +++ b/context/goals/harness.adoption-go-base.md @@ -68,11 +68,11 @@ Two-way: every change sits on branches and pull requests, and nothing is tagged. ## Progress -slices 0/9 committed · standards — · spec — · editor — +slices 9/9 committed · standards ✓ · spec ✓ (1 round: behavior 4 map entries) · editor ✓ ## Decisions -- adopt: CHANGELOG entries record only changes to a module's `go.mod` requirements. (wave 1, W2) +None. ## Pending edits From e571dac1de261219bb09b30d248871c4a0926d1d Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Sat, 21 Nov 2026 05:17:38 -0500 Subject: [PATCH 9/9] record: harness.adoption-go-base adopt shipped --- context/goals/harness.adoption-go-base.md | 70 ++--------------------- 1 file changed, 4 insertions(+), 66 deletions(-) diff --git a/context/goals/harness.adoption-go-base.md b/context/goals/harness.adoption-go-base.md index 281b2c0..e6fdfad 100644 --- a/context/goals/harness.adoption-go-base.md +++ b/context/goals/harness.adoption-go-base.md @@ -1,74 +1,12 @@ # goal · harness.adoption-go-base -- **State:** building -- **Task:** adopt -- **Branch:** adopt +- **State:** idle +- **Task:** none +- **Branch:** none ## Tasks -1. [ ] adopt - -## Task brief · adopt - -**Problem** - -go-database, go-observability, and go-cli-sdk predate marathon 0.22.0. Nothing pins marathon's -tools, the check doesn't run lint-context or lint-references, and every capability map fails -lint-context. Hundreds of comments fall outside the five kinds, and no lint requires a -suppression's reason. - -**Behaviors** -1. Each repository's currency command exits 0 after its upgrade slice. GitHub Actions use - mise-action v5.2.10. -2. Each `mise.toml` pins marathon's tools at 0.22.0 with the `marathon/v` prefix. `mise install` - puts lint-context and lint-references on PATH, and currency reports a newer marathon tag. -3. Each check runs lint-context and lint-references once, after its module loop, and fails when - either fails. A lint missing from PATH fails the check with a message naming `mise install`. - The task description names both lints. -4. lint-context passes in each repository: - - Every capability map entry is marked `(built)` or `(planned)`, with no prose under the map - heading. - - go-observability's logs pipeline is a linked `(planned)` entry whose note holds its open - points, with the trigger as the README's Design section states it. - - A map entry that restates an exported doc comment shrinks to a name. Map prose with no other - home moves to the README or a `docs/` page. -5. Every comment in code, tests, scripts, and configuration is one of the five kinds. Doc comments - on unexported identifiers and on test functions are gone; reasoning with no other home moves - into names, exported docs, or `docs/`. The currency script's section comments become named - functions. -6. Each `.golangci.yml` enables nolintlint with `require-explanation` and `require-specific`. -7. Each STANDARDS.md gains a comment rule that cites the five kinds for source, tests, scripts, and - every configuration file (TOML, YAML, `.gitignore`). -8. The check passes locally and in CI in all three repositories. No CHANGELOG changes: no module's - `go.mod` requirements change. - -**Test seams** -- `mise run check` and `mise run currency` in each repository; the existing suites are the - regression seam. - -**Slices** -1. go-database upgrade: mise-action v5.2.10. -2. go-observability upgrade: the same. -3. go-cli-sdk upgrade: the same. -4. go-database: pin, check wiring, and context. -5. go-database: comments, nolintlint, and STANDARDS comment rule. -6. go-observability: pin, check wiring, and context, including the logs-pipeline note. -7. go-observability: comments, nolintlint, and STANDARDS comment rule. -8. go-cli-sdk: pin, check wiring, and context. -9. go-cli-sdk: comments, nolintlint, and STANDARDS comment rule. - -**Out of scope** - -Building the logs pipeline, rewriting exported doc comments, a Markdown link check, budgeting -`docs/`, releases and tags, feature or API changes, the Go templates. - -**Door** - -Two-way: every change sits on branches and pull requests, and nothing is tagged. - -## Progress - -slices 9/9 committed · standards ✓ · spec ✓ (1 round: behavior 4 map entries) · editor ✓ +1. [x] adopt ## Decisions