docs: accept migration adapter and authoring decision

This commit is contained in:
end committed 2026-10-28 15:19:51 -07:00
1 parent 213d325363
commit 3cd3f49c11
1 file changed
+38 -26
@@ -1,7 +1,7 @@
--- ---
title: "Separate migration authoring tools from lifecycle runtime adapters" title: "Separate migration authoring tools from lifecycle runtime adapters"
date: 2026-10-28 date: 2026-10-28
status: proposed status: accepted
implementation: not-started implementation: not-started
summary: Keep startup and native migration commands in a thin lifecycle adapter and source creation and reconciliation in a standalone development tool. summary: Keep startup and native migration commands in a thin lifecycle adapter and source creation and reconciliation in a standalone development tool.
tags: tags:
@@ -23,22 +23,24 @@ implemented_by: []
## Context and Problem Statement ## Context and Problem Statement
[Issue 9](https://gitea.auvem.com/corestack/go/issues/9) requires caller-selected apply/require startup policy and ready-made up, down-to and status commands using only database modules. Its completion gate also requires SQL/Go creation and timestamp-to-sequential reconciliation without manually adapting registrations. The owner chose a standalone `cmd/corestack-goose` tool, available through go install/go run without tags, with its authoring code absent from production applications. Existing `migrate.New` returns a Goose provider with global registration disabled; stock Goose Go output instead registers through init and cannot satisfy this contract. [Issue 9](https://gitea.auvem.com/corestack/go/issues/9) needs caller-selected apply/require startup policy, reusable database-only migration commands, and SQL/Go creation and timestamp-to-sequential reconciliation without manually adapting registrations. The owner selected a standalone `cmd/corestack-goose` tool, available through go install/go run without tags, with authoring code absent from production applications. Existing `migrate.New` disables global registration; stock Goose Go output registers through init and cannot satisfy that contract.
The accepted lifecycle and CLI decisions establish ordered setup, reverse cleanup, caller-owned resources, native urfave/cli commands and one shutdown budget. Preserve these boundaries and keep migrate usable without lifecycle. This proposal uses the issue and current source, with no go-toolkit sources. The standalone boundary is confirmed; the API and bounded authoring convention below are proposed defaults requiring independent review and owner acceptance before dependent implementation. Preserve the accepted lifecycle ordering, reverse cleanup, caller-owned resources, native urfave/cli commands and shutdown budget. Keep migrate usable without lifecycle. This decision uses the issue and current source, with no go-toolkit sources.
## Considered Options ## Considered Options
* Let each application wire startup and runtime commands, and manually adapt stock Goose output: least library code, but fails the requested reusable commands and unchanged generated-Go workflow. * Application-specific runtime wiring and manually adapted Goose output: least library code, but misses reusable commands and unchanged generated-Go registration.
* Include authoring behind opt-in application build tags: could satisfy the production boundary, but complicates every consumer's build and was declined in favor of a separate tool. * Application build tags for authoring: complicates consumer builds; declined in favor of a standalone tool.
* Use a thin runtime adapter plus a standalone authoring tool with a generated registration aggregate: meets the approved artifact boundary and confines source changes to a known convention. * Thin runtime adapter and standalone authoring tool with a generated registration aggregate: meets the artifact boundary with a bounded source convention.
* Rewrite arbitrary existing Go registration code during fix, or infer registrations through globals/init: broadens compatibility at substantial parser and state cost; neither is required. Support the house generated convention and reject unsupported layouts before writing. * Rewrite arbitrary Go registrations or infer them through globals/init: broader compatibility and parser/state cost than required; reject unsupported layouts instead.
## Decision Outcome ## Decision Outcome
Propose the third option in the root module, with no new dependencies or lifecycle core changes. Runtime lives in `go.auvem.com/corestack/migrate/lifecycle` (package name lifecycle; examples alias it migratelifecycle). It may import migrate's dependencies and `lifecycle/cli`; neither migrate nor lifecycle imports this adapter. Authoring entry points live only in `cmd/corestack-goose` and its internal implementation, never imported by runtime packages or generated consumer code. Choose the third option in the root module, with no new dependencies or lifecycle core changes. The owner accepted this decision, including `up-to` and single-step `down`. Implementation has not started; independent delta review precedes production code.
The proposed public runtime surface is: Runtime lives in `go.auvem.com/corestack/migrate/lifecycle` (package lifecycle, examples alias migratelifecycle). It may import migrate's dependencies and `lifecycle/cli`; neither migrate nor lifecycle imports it. Authoring lives only in `cmd/corestack-goose` and its internal implementation, never imported by runtime packages or generated consumer code.
The public runtime surface is:
```go ```go
type Policy string type Policy string
@@ -52,41 +54,51 @@ func Commands(config lifecycle.Config, modules []lifecycle.Module,
provider func(context.Context) (*goose.Provider, error)) *urfavecli.Command provider func(context.Context) (*goose.Provider, error)) *urfavecli.Command
``` ```
Module validates its name, policy and resolver without invoking the resolver. Its Setup resolves a nonnil provider after earlier database setup, then calls Up for Apply or HasPending for Require. Pending migrations produce a contextual setup error and prevent all later module setups and services; provider errors retain their causes. Zero/unknown policy and nil resolver fail rather than choosing a policy silently. The module has no Run and a no-op Teardown: it owns neither the database nor a separate provider resource. In Goose v3.29.0 Provider.Close closes the supplied database, so the adapter must not call it. The database module owns partial acquisition cleanup and closing, under existing lifecycle rules. Module validates name, policy and nonnil resolver without resolving. Setup resolves a nonnil provider after earlier database setup, then calls Up for Apply or HasPending for Require. Pending migrations fail setup before later modules/services; errors retain contextual causes. Zero/unknown policy fails. The module has no Run and no-op Teardown: the database module owns partial acquisition cleanup and closing. Never call Provider.Close, which closes the supplied database in Goose v3.29.0.
Ordinary closures supply late-bound resources: a database module's Setup opens db; the provider resolver calls migrate.New with that db, embedded files, dialect, logger and `migrations.GoMigrations()...`. Nothing is resolved while declaring commands or modules. Register the database module before the migration module and dependent services. Each resolver invocation constructs fresh Go registrations; no registry, dependency lookup, injected container, stored context, global mutable state or init is added. Resolution itself acquires no independently owned resource; any resolver that does so must clean up its failure locally. Ordinary closures bind resources: database Setup opens db; the resolver calls migrate.New with db, embedded files, dialect, logger and `migrations.GoMigrations()...`. Register database before migration and dependent services. Declaration starts nothing. Each resolution constructs fresh Go registrations, without a registry, stored context, global mutable state or init. Resolution acquires no independently owned resource; a resolver that does must clean up its failure locally.
Commands returns a fresh native group named migrate with up, down-to and status leaves. Each leaf uses `lifecycle/cli.Action` over exactly the caller-supplied database modules, suppressing their services; it does not include the startup migration module or unrelated application modules. After setup it resolves the provider and invokes the corresponding Goose method. Nil resolver/provider and provider-construction errors fail with ordinary runtime errors. Configuration/module validation, cancellation, reverse cleanup, temporary signal subscriptions and exit classification remain the existing adapter's responsibility. Construct fresh command trees/resource bindings for separate invocations; concurrent mutation/reuse is unsupported. Commands returns a fresh native `migrate` group with these leaves:
Help and invalid leaf arguments must not open the database. Use native ArgValidator before lifecycle entry to enforce no positional arguments for up/status and exactly one decimal int64 version >= 0 for down-to, returning `urfavecli.Exit(err, 2)` for usage errors. Zero means roll back all migrations; reject overflow, negative, missing and extra values. Leave the group Action unset for native help/not-found handling. Status writes a small version/state/source table to the selected command Writer and propagates write errors; up/down-to rely on configured Goose logging. No JSON format or additional flag/config schema is introduced. Existing generated-help parse exceptions remain authoritative. | Leaf | Goose provider method |
| --- | --- |
| `up` | Up |
| `up-to <version>` | UpTo |
| `down` | Down (one migration) |
| `down-to <version>` | DownTo |
| `status` | Status |
Require is a point-in-time pending check, not a transaction spanning subsequent service startup or a lock against concurrent deploys. HasPending does not acquire Goose's session locker. It can initialize Goose's version table; status can do so too. Neither runs migration bodies, but neither promises a read-only connection or zero database writes. Apply and runtime writes retain migrate.New's PostgreSQL session lock and its external-serialization requirement for other dialects. No new background worker, poller, retry policy or lock is added. Each uses `lifecycle/cli.Action` over exactly the supplied database modules, suppressing services and excluding the startup migration module and unrelated modules. After setup, resolve the provider and invoke Goose directly. Nil resolver/provider and construction failures are runtime errors. Existing adapter validation, cancellation, reverse cleanup, signals and exit classification apply. Use fresh trees/resource bindings for independent invocations; concurrent mutation/reuse is unsupported.
The independent development artifact is installed with `go install go.auvem.com/corestack/cmd/corestack-goose@<release>` or invoked from the consumer module with `go run go.auvem.com/corestack/cmd/corestack-goose ...` using its selected dependency version. Its minimal native CLI is: Help and invalid arguments must not open the database. Native ArgValidator enforces no positional arguments for up/down/status and exactly one nonnegative decimal int64 for up-to/down-to; reject negative, overflow, missing and extra values with `urfavecli.Exit(err, 2)` before lifecycle entry. Zero behavior follows Goose, including DownTo(0) rolling back all migrations. Leave the group Action unset for native help/not-found behavior; existing generated-help exceptions apply. Status writes a version/state/source table to the selected command Writer and propagates write errors. Other leaves use configured Goose logging; no extra output/config schema is added.
Require is a point-in-time check, not a startup transaction or deployment lock; HasPending takes no Goose session lock. Require and status can initialize the version table: neither runs migration bodies nor promises read-only database access. Apply and runtime writes retain migrate.New's PostgreSQL session lock and external serialization for other dialects. No new worker, retry or lock is introduced.
Install the standalone tool with `go install go.auvem.com/corestack/cmd/corestack-goose@<release>` or use `go run go.auvem.com/corestack/cmd/corestack-goose ...` from the consumer module with its selected dependency version:
```text ```text
corestack-goose create --dir ./migrations <name> sql|go corestack-goose create --dir ./migrations <name> sql|go
corestack-goose fix --dir ./migrations corestack-goose fix --dir ./migrations
``` ```
The directory must already exist. Use package migrations for generated Go files, names restricted to lowercase ASCII words separated by underscores, and reject duplicate generated identifiers before writes. No package option, alternate template option or database connection is needed. SQL uses Goose's supported CreateWithTemplate with its stock SQL template; Go supplies a custom template. Creation runs in a temporary staging directory before publishing validated output. House Go filenames are `<version>_<name>_migration.go`: append the fixed `_migration` component to Goose's staged filename, leaving SQL filenames unchanged. This keeps every allowed name, including `test`, `create_test`, `linux` and `windows`, in ordinary builds without test-file or platform suffix filtering. Factory identifiers derive from the original logical name, excluding the fixed filename component; create and fix use this same convention. No build-tag support is introduced. Do not call SetSequential, SetLogger or any global registration helper. The directory must exist. Generated Go uses package migrations and names restricted to lowercase ASCII words separated by underscores; reject duplicate identifiers before writes. Create stages Goose CreateWithTemplate output using stock SQL/custom Go templates. SQL filenames stay unchanged; Go appends `_migration` to produce `<version>_<name>_migration.go`, preventing allowed names such as test, create_test, linux or windows from triggering build filtering. Factory identifiers derive from the logical name, excluding that suffix; create and fix agree. No package/template options, build tags, database access or Goose global setters/registration helpers are added.
A generated Go file declares an unexported factory `migrationExample(version int64) *goose.Migration` returning `goose.NewGoMigration(version, &goose.GoFunc{RunTx: upExample}, &goose.GoFunc{RunTx: downExample})`, plus editable transactional up/down bodies. The tool-owned `register.go` exports `GoMigrations() []*goose.Migration` returning a new slice of calls such as `migrationExample(20261028220000)`. Create maintains this aggregate even for a SQL-only set, returning an empty slice when there are no Go migrations. That aggregate is the sole explicit registration-version surface: each literal equals the corresponding filename's numeric prefix. Calling GoMigrations twice produces separate Migration and GoFunc values for provider isolation. Generated consumer files import only Goose and the standard library; applications pass the result to migrate.New. The existing embedded-directory requirement still applies, including for Go-only sets. Each generated Go file declares an unexported `migrationExample(version int64) *goose.Migration` factory returning `goose.NewGoMigration(version, &goose.GoFunc{RunTx: upExample}, &goose.GoFunc{RunTx: downExample})`, plus editable transactional bodies. Tool-owned `register.go` exports `GoMigrations() []*goose.Migration`, returning fresh Migration/GoFunc values and a new slice of factory calls with literal versions matching filename prefixes. Maintain this sole explicit registration-version surface even for SQL-only sets (empty slice). Consumer output imports only Goose and the standard library; applications pass registrations to migrate.New. The embedded-directory requirement applies to Go-only sets too.
Fix scans SQL and house `<version>_<name>_migration.go` filenames together, preserves sequential IDs, sorts timestamp IDs numerically, and allocates sequential IDs after the highest existing sequential ID, with at least five-digit padding. Follow Goose's timestamp classification (a valid UTC timestamp after the Unix epoch), reject invalid/duplicate/overflowed numeric IDs and any resulting numeric/lexical ordering disagreement. Update filenames and regenerate aggregate literals from the same mapping; keep Go factory names independent of versions. Never replace numbers in migration bodies or parse arbitrary Go registration styles. Require the owned marker and agreement with the current filenames and factories before replacing an existing register.go; refuse handwritten or drifted registration layouts with an actionable diagnostic. Canonical reconstruction from those files and factories, compared after go/format, is sufficient; no separate aggregate AST grammar recognizer is required. Use go/format for new Go output and go/parser where needed to validate editable files' factory identity/signature and package agreement, without attempting to understand user migration logic. Editable migration bodies remain untouched. Fix scans SQL and house Go filenames together, preserves sequential IDs, sorts timestamp IDs numerically, and allocates after the highest sequential ID with at least five-digit padding. Use Goose's timestamp classification (valid UTC timestamp after Unix epoch); reject invalid/duplicate/overflowed IDs and numeric/lexical ordering disagreement. One mapping drives filename changes and aggregate literals; factory names remain version-independent. Preserve migration bytes and bodies. Validate editable factory identity/signature and package agreement with go/parser as needed, and format new Go output with go/format. Replace register.go only with its owned marker and agreement with current filenames/factories: canonical reconstruction compared after go/format suffices, without another aggregate grammar. Reject handwritten/drifted layouts with actionable diagnostics.
Both create and fix preflight the complete planned set before mutation: regular files/directories rather than symlink paths, names, version mappings, generated identifiers, aggregate agreement, destination collisions and output syntax. New destinations are opened exclusively, including renamed migration copies; no unknown destination is overwritten. Existing register.go is intentionally replaced only when recognized as tool-owned and unchanged since preflight. Use one authoring process and no concurrent editor mutations during the operation; these checks do not establish filesystem isolation against racing writers. Fix preserves original migration bytes while changing their paths and the owned aggregate. Create and fix preflight the complete planned set: regular files/directories rather than symlink paths, names, version mappings, identifiers, aggregate agreement, destination collisions and output syntax. Open new destinations exclusively, including renamed copies. Replace existing register.go only when tool-owned and unchanged since preflight. Require a single authoring process and no concurrent editor mutation; this provides no isolation against racing writers.
There is no atomic multi-file guarantee. Stage output first, publish a destination completely before removing its old source, and stop at the first write/remove failure with completed and outstanding paths in the diagnostic. Interruption can leave duplicate files, mismatched aggregate versions or temporary files; do not automatically rerun or promise rollback. Before fix, commit or separately save/back up the complete source set, including newly created/untracked migrations and edits to tracked files; ordinary version-control restore cannot recover untracked files or unsaved changes. After failure, inspect the reported paths and restore the affected source set from that commit or backup before retrying. Preflight must reject an inconsistent set. This bounded manual recovery avoids a persistent journal or transaction framework. Source renumbering never changes database history: run fix before those IDs reach any shared database; after deployment preserve IDs and add a new migration instead. The tool has no database access with which to prove deployment history. There is no atomic multi-file guarantee. Stage first, fully publish each destination before removing its source, and stop on the first write/remove failure, reporting completed/outstanding paths. Interruption may leave duplicates, aggregate mismatches or temporary files; no automatic retry or rollback. Before fix, commit or separately back up the complete source set, including untracked migrations and tracked edits; ordinary restore cannot recover untracked files or unsaved changes. On failure inspect reported paths and restore from that commit/backup before retrying; preflight rejects inconsistent sets. This manual recovery needs no persistent journal. Fix changes source IDs, never database history: use it before IDs reach a shared database; preserve deployed IDs and add migrations afterward. The tool cannot prove deployment history.
### Consequences ### Consequences
* Runtime persistence remains existing Goose schema/version history writes; new writers are development-only source creation, copies/removals and the owned aggregate replacement. Importing unused runtime code starts nothing. There is no new auth boundary, configuration service, worker, timer or dependency. * Runtime persistence remains Goose schema/version history. New writers are development-only source creation, copies/removals and owned aggregate replacement. Unused imports start nothing; no new auth boundary, configuration service or persistent process is added.
* The runtime adapter should remain thin; authoring also requires staging, preflight, collision checks and bounded failure diagnostics, so its size must be assessed during implementation rather than promised as a small line count. Include focused tests, examples and consumer docs. Touch new adapter/tool files, migrate's authoring guidance/doc comment and test fixtures; no current callers, release publication configuration or dependency changes are required. Escalate material growth, especially unsupported-source compatibility or automated crash recovery, rather than silently enlarging this PR. * Delivery touches adapter/tool files, migrate authoring guidance/doc comment, focused tests, examples and fixtures; no current callers, publication configuration or dependencies need changes. Assess authoring complexity during implementation; escalate material growth such as arbitrary-source compatibility or automated crash recovery. Consumer docs recommend the standalone flow and link Goose concepts rather than reproduce its manual.
* Before delivery, test both startup policies and require blocking later startup; all three native commands against SQLite; setup/teardown and context/error paths; usage/help with no database setup; status output errors. Build a production fixture importing only the runtime adapter and the standalone tool separately; verify the production dependency list and binary symbols exclude this project's authoring package and file-writing entry points. Goose's own upstream authoring functions may exist in module source; prove reachable application code excludes authoring rather than claiming the dependency's source is absent. * Validate both startup policies (including require blocking later startup), all five leaves against SQLite, lifecycle/context/error paths, help/usage without database setup, and status writer failures. Cover version validation and Goose zero behavior, UpTo targets and single-step Down.
* The decisive real flow must create SQL and Go migrations, fix timestamp IDs, compile the unedited generated registrations (including names `test`, `create_test` and a host-incompatible platform name such as `windows` on Linux/macOS or `linux` on Windows), apply against SQLite and verify versions, pending state and provider isolation. Also cover collisions, unsupported/drifted aggregates, duplicate IDs, mixed IDs, repeated fix and an injected partial-write failure followed by documented source restoration. Build/test both supported artifacts. These are future delivery gates, not checks performed by authoring this ADR. * Build a runtime-only production fixture and standalone tool separately. Check production dependencies/binary symbols exclude this project's authoring package and file-writing entry points; Goose's upstream authoring source may remain in the dependency. Build/test both artifacts.
* Consumer docs should recommend this standalone workflow and link Goose's concepts instead of reproducing its manual. Accepting this proposal also accepts the narrow generated layout, single-writer operation and version-control recovery boundary. Independent ADR review and explicit owner acceptance remain required; this proposed record authorizes no production implementation. * The decisive flow creates SQL/Go, fixes timestamp IDs, compiles unedited registrations (including test, create_test and a host-incompatible platform name), applies to SQLite, and verifies versions, pending state and provider isolation. Also test collisions, unsupported/drifted aggregates, duplicate/mixed IDs, repeated fix, and injected partial-write failure followed by documented source restoration. These remain delivery gates, not completed checks.
## More Information ## More Information
Feasibility is source-inspected, not yet validated end to end. Pinned Goose v3.29.0 [CreateWithTemplate](https://github.com/pressly/goose/blob/v3.29.0/create.go) exposes Version/CamelName template values and exclusively creates its output; it does not return the created path and can leave partial output on template errors, motivating staging. [Fix](https://github.com/pressly/goose/blob/v3.29.0/fix.go) only renames filenames and uses os.Rename, so it cannot maintain our aggregate or provide no-overwrite semantics. Reuse creation facilities, not this insufficient reconciliation operation. [NewGoMigration](https://github.com/pressly/goose/blob/v3.29.0/migration.go) and [provider options](https://github.com/pressly/goose/blob/v3.29.0/provider_options.go) support fresh explicit provider-local registrations. [Provider operations](https://github.com/pressly/goose/blob/v3.29.0/provider.go) and [initialization](https://github.com/pressly/goose/blob/v3.29.0/provider_run.go) establish database ownership and version-table initialization behavior. Native [argument validation](https://github.com/urfave/cli/blob/v3.14.0/command_run.go) runs before Action and supports pre-resource usage failures. These pinned sources were read locally; integration and artifact exclusion remain unverified until implementation. Feasibility is source-inspected, not validated end to end. Pinned Goose v3.29.0 [CreateWithTemplate](https://github.com/pressly/goose/blob/v3.29.0/create.go) provides Version/CamelName template values and exclusive creation, but no returned path and possible partial template-error output, motivating staging. [Fix](https://github.com/pressly/goose/blob/v3.29.0/fix.go) uses os.Rename without aggregate maintenance or no-overwrite guarantees; reuse creation, not that reconciliation. [NewGoMigration](https://github.com/pressly/goose/blob/v3.29.0/migration.go) and [provider options](https://github.com/pressly/goose/blob/v3.29.0/provider_options.go) support fresh provider-local registration. [Provider operations](https://github.com/pressly/goose/blob/v3.29.0/provider.go) and [initialization](https://github.com/pressly/goose/blob/v3.29.0/provider_run.go) establish ownership and version-table behavior. Native [argument validation](https://github.com/urfave/cli/blob/v3.14.0/command_run.go) precedes Action. These sources were read locally; integration and artifact exclusion await implementation.