From 2ec2d245005a2a106a48f50cb83b7634744ecb6b Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Tue, 24 Nov 2026 19:39:53 -0500 Subject: [PATCH 1/8] pgvector-go: upgrade to sqlate v0.8.0, claude-plugins 0.24.0, mise-action v5.3.0 --- .github/workflows/ci.yml | 2 +- go.mod | 2 +- go.sum | 4 ++-- mise.toml | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fd7b5e5..336063a 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.10 + - uses: jdx/mise-action@v5.3.0 - name: mise run check run: mise run check diff --git a/go.mod b/go.mod index 717bd86..f853716 100644 --- a/go.mod +++ b/go.mod @@ -4,5 +4,5 @@ go 1.27 require ( github.com/standards-lab/go-core v0.12.0 - github.com/standards-lab/sqlate v0.7.0 + github.com/standards-lab/sqlate v0.8.0 ) diff --git a/go.sum b/go.sum index 887392a..3ddda1c 100644 --- a/go.sum +++ b/go.sum @@ -1,4 +1,4 @@ github.com/standards-lab/go-core v0.12.0 h1:sqrzK6QSppEYpwvVAyiWgzNuOsjfK0Kwe86GPuZpHsU= github.com/standards-lab/go-core v0.12.0/go.mod h1:Yl/R+gM9YWczsePBCKXdPGh3FSdZ/5i8SapLIh3BDHU= -github.com/standards-lab/sqlate v0.7.0 h1:GVb3OCDXwSS9RCxQ2BRIfV73zwBeJBhkvDLBJnTYd/U= -github.com/standards-lab/sqlate v0.7.0/go.mod h1:pikNmGf/z3x46SBWFXgt/xKIDZuquSgCoXy5OWBFFR4= +github.com/standards-lab/sqlate v0.8.0 h1:G1uUIWmc2DxJz5YhtBvIlftfURnb3b2RKsYB59Wa03Y= +github.com/standards-lab/sqlate v0.8.0/go.mod h1:pikNmGf/z3x46SBWFXgt/xKIDZuquSgCoXy5OWBFFR4= diff --git a/mise.toml b/mise.toml index 8d5962a..4a98bf5 100644 --- a/mise.toml +++ b/mise.toml @@ -3,7 +3,7 @@ task.run_auto_install = false [tools] -"github:standards-lab/claude-plugins" = { version = "0.22.0", version_prefix = "marathon/v" } +"github:standards-lab/claude-plugins" = { version = "0.24.0", version_prefix = "marathon/v" } go = "1.27.4" golangci-lint = "2.15.0" jq = "1.8.2" From 25db8f84d50bdb06f7f373be4d03036c782c056d Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Tue, 24 Nov 2026 19:42:27 -0500 Subject: [PATCH 2/8] pgvector-go: admin reports extension declarations in Status and readiness - admin.Status gains Extensions (json "extensions"), one admin.ExtensionStatus per declaration in declared order; empty, never nil, when none is declared. admin declares its own entity because migrate.ExtensionStatus has no json tags. - Status.Ready is false when a declaration does not match: an active one matches only when installed at a non-empty default, a removed one only when not installed. This covers pending, unavailable, and no-update-path. - conflict() wraps ErrExtensionUnavailable and ErrNoUpdatePath in ErrConflict; settle() marks the service not ready on both. - Start's pending log reads Migrator.Extensions after the dirty-set check and logs "extension pending; applying" (extension, installed, default) before the pending sets; removed pending declarations are logged the same way. - Status reads sets first, then extensions; an Extensions read error is returned unwrapped (it is I/O, not a schema conflict). - Changelog Unreleased records the sqlate v0.8.0 requirement and the above. README unchanged: it does not document Status or readiness. --- CHANGELOG.md | 21 ++++ admin/doc.go | 19 ++-- admin/entities.go | 24 ++++- admin/extensions_test.go | 203 +++++++++++++++++++++++++++++++++++++++ admin/service.go | 56 ++++++++--- admin/service_test.go | 7 +- 6 files changed, 306 insertions(+), 24 deletions(-) create mode 100644 admin/extensions_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 9be4b42..61601ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,27 @@ only; the `postgres` sub-module keeps its own. ## [Unreleased] +### Added + +- `admin.Status.Extensions` (`extensions` in JSON), one `admin.ExtensionStatus` per extension + declaration the migrator manages, in declared order: its name, whether it is removed, the + installed version and the database's default version (each empty when absent), and whether it + is pending. The list is empty, never nil, when no extension is declared. +- `Service.Start` logs each pending extension as `extension pending; applying`, with its name and + its installed and default versions, beside the pending sets before it applies them. + +### Changed + +- `Status.Ready`, and the service's readiness with it, is false while any extension declaration + does not match the database: one pending, one the database does not offer, or one with no + update path from its installed version to the default. +- `migrate.ErrExtensionUnavailable` and `migrate.ErrNoUpdatePath`, from `Service.Start`, + `Service.Verify`, and the schema verbs, wrap in `admin.ErrConflict` with the migrate sentinel + still in the chain, and mark the service not ready. +- The `sqlate` requirement is v0.8.0, which adds database extension declarations to `migrate`: + `migrate.Options.Extensions`, `Migrator.Extensions`, the `migrate.ExtensionCatalog` dialect + capability, and the `ErrExtensionUnavailable` and `ErrNoUpdatePath` sentinels. + ## [v0.12.0] - 2026-11-11 The sweeper's configuration is a trailing Options struct, not variadic option functions: diff --git a/admin/doc.go b/admin/doc.go index f7576a2..cd0f385 100644 --- a/admin/doc.go +++ b/admin/doc.go @@ -53,11 +53,13 @@ // The Service is not a Stopper: it holds nothing the pool's shutdown does // not release. // -// [Service.Start] applies pending migrations, verifies the seeder, and -// applies the configured seed set, idempotently at every start. A dirty -// set, or a history a set does not carry, fails startup, and a failed Start -// stops the process, so an operator repairs the schema through the verbs of -// another replica or starts a process against the corrected database. +// [Service.Start] applies pending extensions and migrations, verifies the +// seeder, and applies the configured seed set, idempotently at every start. +// A dirty set, a history a set does not carry, or a declared extension the +// database does not offer or cannot update to its default fails startup, +// and a failed Start stops the process, so an operator repairs the schema +// through the verbs of another replica or starts a process against the +// corrected database. // [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 @@ -71,10 +73,11 @@ // The schema verbs run the migrator's function of their name, and the seed // verbs the seeder's: // -// - [Service.Verify] checks every set's history and the seeder's -// statements. +// - [Service.Verify] checks every extension declaration, every set's +// history, and the seeder's statements. // - [Service.Status] reads the schema into a [Status]: one [SetStatus] -// per set, and one [MigrationInfo] per migration. +// per set, one [MigrationInfo] per migration, and one +// [ExtensionStatus] per extension declaration. // - [Service.Up] applies every set's pending migrations. // - [Service.Down] reverts, [Service.Steps] applies or reverts, and // [Service.Force] sets the history version of the set each names. diff --git a/admin/entities.go b/admin/entities.go index 9c5ca72..f5dedd4 100644 --- a/admin/entities.go +++ b/admin/entities.go @@ -32,11 +32,13 @@ type Pool struct { WaitDuration time.Duration `json:"wait_duration"` } -// Status is the schema's state: Ready when every set is clean and current, -// and each set's state in declared order. +// Status is the schema's state: Ready when every set is clean and current +// and every extension declaration matches the database, each set's state, +// and each extension declaration's state, in declared order. type Status struct { - Ready bool `json:"ready"` - Sets []SetStatus `json:"sets"` + Ready bool `json:"ready"` + Sets []SetStatus `json:"sets"` + Extensions []ExtensionStatus `json:"extensions"` } // SetStatus is one migration set's state. @@ -50,6 +52,20 @@ type SetStatus struct { Migrations []MigrationInfo `json:"migrations"` } +// ExtensionStatus is one extension declaration's state. A declaration +// matches the database when its extension is installed at the default +// version the database offers, or, when Removed, is not installed; Pending +// marks a mismatch Up resolves, so an extension the database does not offer, +// or one with no update path to the default, is neither matched nor +// pending. +type ExtensionStatus struct { + Name string `json:"name"` + Removed bool `json:"removed"` + Installed string `json:"installed"` // empty when not installed + Default string `json:"default"` // empty when the database does not offer it + Pending bool `json:"pending"` +} + // MigrationInfo describes one migration of a set. type MigrationInfo struct { Version int `json:"version"` diff --git a/admin/extensions_test.go b/admin/extensions_test.go new file mode 100644 index 0000000..291457f --- /dev/null +++ b/admin/extensions_test.go @@ -0,0 +1,203 @@ +package admin_test + +import ( + "bytes" + "context" + "database/sql/driver" + "encoding/json" + "errors" + "log/slog" + "slices" + "strings" + "testing" + + "github.com/standards-lab/go-database/admin" + "github.com/standards-lab/sqlate/migrate" + "github.com/standards-lab/sqlate/sqltest" +) + +type extensionDialect struct{ testDialect } + +func (extensionDialect) ExtensionState(param string) string { + return "SELECT installed, default, path FROM extensions WHERE name = " + param +} + +func (extensionDialect) ActivateExtension(name string) []string { + return []string{`CREATE EXTENSION IF NOT EXISTS "` + name + `"`, `ALTER EXTENSION "` + name + `" UPDATE`} +} + +func (extensionDialect) RemoveExtension(name string) string { + return `DROP EXTENSION IF EXISTS "` + name + `" RESTRICT` +} + +var _ migrate.ExtensionCatalog = extensionDialect{} + +func extState(installed, def driver.Value, path bool) sqltest.Response { + return sqltest.Response{Columns: []string{"installed", "default", "path"}, Rows: [][]driver.Value{{installed, def, path}}} +} + +var ( + extCurrent = extState("0.8.0", "0.8.0", true) + extMissing = extState(nil, "0.8.0", false) + extUnavailable = extState(nil, nil, false) + extNoPath = extState("0.5.0", "0.8.0", false) +) + +func newExtensionService(t *testing.T, declared []migrate.Extension, opts admin.Options, responses ...sqltest.Response) fixture { + t.Helper() + return newMigratorFixture(t, []migrate.Set{{Name: "app", Migrations: set}}, extensionDialect{}, + migrate.Options{Extensions: declared}, opts, responses...) +} + +var vector = []migrate.Extension{{Name: "vector"}} + +func TestExtensions_StatusListsNoneWhenUndeclared(t *testing.T) { + s, _ := newService(t, current()...) + st, err := s.Status(context.Background()) + if err != nil { + t.Fatalf("Status: %v", err) + } + if st.Extensions == nil || len(st.Extensions) != 0 || !st.Ready { + t.Fatalf("status = %+v", st) + } + out, err := json.Marshal(st) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(out), `"extensions":[]`) { + t.Errorf("json = %s", out) + } +} + +func TestExtensions_StatusReportsEachDeclarationInOrder(t *testing.T) { + declared := []migrate.Extension{{Name: "vector"}, {Name: "hstore"}, {Name: "old", Removed: true}} + f := newExtensionService(t, declared, admin.Options{}, + slices.Concat(current(), []sqltest.Response{extCurrent, extMissing, extState("1.0", "1.0", true)})...) + st, err := f.service.Status(context.Background()) + if err != nil { + t.Fatalf("Status: %v", err) + } + want := []admin.ExtensionStatus{ + {Name: "vector", Installed: "0.8.0", Default: "0.8.0"}, + {Name: "hstore", Default: "0.8.0", Pending: true}, + {Name: "old", Removed: true, Installed: "1.0", Default: "1.0", Pending: true}, + } + if !slices.Equal(st.Extensions, want) { + t.Errorf("extensions = %+v, want %+v", st.Extensions, want) + } + out, err := json.Marshal(st.Extensions[0]) + if err != nil { + t.Fatal(err) + } + if got := string(out); got != `{"name":"vector","removed":false,"installed":"0.8.0","default":"0.8.0","pending":false}` { + t.Errorf("json = %s", got) + } + if f.rec.Pending() != 0 { + t.Errorf("pending responses = %d", f.rec.Pending()) + } +} + +func TestExtensions_MismatchClearsReady(t *testing.T) { + cases := map[string]struct { + declared []migrate.Extension + matched sqltest.Response + mismatch sqltest.Response + }{ + "pending": {vector, extCurrent, extMissing}, + "removed pending": {[]migrate.Extension{{Name: "vector", Removed: true}}, extState(nil, "0.8.0", false), extCurrent}, + "unavailable": {vector, extCurrent, extUnavailable}, + "no update path": {vector, extCurrent, extNoPath}, + } + for name, c := range cases { + t.Run(name, func(t *testing.T) { + f := newExtensionService(t, c.declared, admin.Options{}, + slices.Concat(current(), []sqltest.Response{c.matched}, current(), []sqltest.Response{c.mismatch})...) + ctx := context.Background() + if st, err := f.service.Status(ctx); err != nil || !st.Ready || !f.service.Ready() { + t.Fatalf("matching Status = %+v, %v; ready %v", st, err, f.service.Ready()) + } + st, err := f.service.Status(ctx) + if err != nil { + t.Fatalf("Status: %v", err) + } + if st.Ready || f.service.Ready() { + t.Errorf("ready over a mismatched declaration: %+v", st) + } + }) + } +} + +func TestExtensions_FaultIsAConflict(t *testing.T) { + faults := map[string]struct { + state sqltest.Response + sentinel error + }{ + "unavailable": {extUnavailable, migrate.ErrExtensionUnavailable}, + "no update path": {extNoPath, migrate.ErrNoUpdatePath}, + } + conflict := func(t *testing.T, verb string, err, sentinel error) { + t.Helper() + if !errors.Is(err, admin.ErrConflict) || !errors.Is(err, sentinel) { + t.Errorf("%s = %v, want ErrConflict and %v", verb, err, sentinel) + } + } + for name, fault := range faults { + t.Run(name+"/start", func(t *testing.T) { + f := newExtensionService(t, vector, admin.Options{}, fault.state) + conflict(t, "Start", f.service.Start(context.Background()), fault.sentinel) + if f.service.Ready() || len(f.rec.SQL(sqltest.OpExec)) != 0 { + t.Error("a faulted Start reported ready or wrote") + } + }) + t.Run(name+"/verify", func(t *testing.T) { + f := newExtensionService(t, vector, admin.Options{}, extCurrent, exists(true), applied(), fault.state) + ctx := context.Background() + if err := f.service.Verify(ctx); err != nil || !f.service.Ready() { + t.Fatalf("clean Verify = %v, ready %v", err, f.service.Ready()) + } + conflict(t, "Verify", f.service.Verify(ctx), fault.sentinel) + if f.service.Ready() { + t.Error("ready after a faulted Verify") + } + }) + t.Run(name+"/up", func(t *testing.T) { + f := newExtensionService(t, vector, admin.Options{}, slices.Concat( + current(), []sqltest.Response{extCurrent}, + []sqltest.Response{locked, created, applied(), fault.state, unlocked}, + current(), []sqltest.Response{fault.state}, + )...) + ctx := context.Background() + if st, err := f.service.Status(ctx); err != nil || !f.service.Ready() { + t.Fatalf("clean Status = %+v, %v", st, err) + } + _, err := f.service.Up(ctx) + conflict(t, "Up", err, fault.sentinel) + if f.service.Ready() || f.rec.Pending() != 0 { + t.Errorf("ready %v, pending responses %d", f.service.Ready(), f.rec.Pending()) + } + }) + } +} + +func TestExtensions_StartLogsPendingBeforeApplying(t *testing.T) { + var buf bytes.Buffer + f := newExtensionService(t, vector, admin.Options{Logger: slog.New(slog.NewTextHandler(&buf, nil))}, slices.Concat( + []sqltest.Response{extMissing}, + current(), []sqltest.Response{extMissing}, + []sqltest.Response{locked, created, applied(), extMissing, {}, {}, unlocked}, + []sqltest.Response{extCurrent}, current(), + )...) + if err := f.service.Start(context.Background()); err != nil { + t.Fatalf("Start: %v", err) + } + if !f.service.Ready() || f.rec.Pending() != 0 { + t.Errorf("ready = %v, pending responses = %d", f.service.Ready(), f.rec.Pending()) + } + want := `msg="extension pending; applying" extension=vector installed="" default=0.8.0` + if !strings.Contains(buf.String(), want) { + t.Errorf("log lacks %s:\n%s", want, buf.String()) + } + if execs := f.rec.SQL(sqltest.OpExec); !slices.Contains(execs, `CREATE EXTENSION IF NOT EXISTS "vector"`) { + t.Errorf("execs = %q", execs) + } +} diff --git a/admin/service.go b/admin/service.go index 4f3fa6e..0ca66a2 100644 --- a/admin/service.go +++ b/admin/service.go @@ -34,8 +34,9 @@ var ( // ErrConflict reports an operation the schema's state refuses: a dirty // or pending set, a history its set does not carry, a migration with no - // down, or a set order the migrator forbids. The migrate sentinel stays - // in the chain. + // down, a set order the migrator forbids, a pending extension, or a + // declared extension the database does not offer or cannot update to + // its default version. The migrate sentinel stays in the chain. ErrConflict = errors.New("schema conflict") ) @@ -147,7 +148,8 @@ func New(pool *database.DB, db *sqlate.DB, m *migrate.Migrator, c *query.Catalog } // Ready reports the schema as the last operation that determined it found -// it: every set's history clean and current. Once Start has succeeded, a +// it: every set's history clean and current, and every extension +// declaration matched. Once Start has succeeded, a // not-ready service re-verifies the schema itself, one probe at a time, at // most once per five seconds, and bounded by the pool's conn_timeout. A // true Ready is not re-checked. @@ -179,8 +181,9 @@ func (s *Service) Ready() bool { return s.ready.Load() } -// Start refuses an undeclared Options.Seed, brings every set to its head -// (logging the pending migrations first), verifies the seeder's statements, +// Start refuses an undeclared Options.Seed, brings every extension +// declaration and every set to its head (logging the pending extensions and +// migrations first), verifies the seeder's statements, // and applies the configured seed set; the service is ready once all pass. func (s *Service) Start(ctx context.Context) error { if s.seed != "" { @@ -231,6 +234,15 @@ func (s *Service) logPending(ctx context.Context) error { return nil } } + exts, err := s.migrator.Extensions(ctx) + if err != nil { + return err + } + for _, e := range exts { + if e.Pending { + s.logger.InfoContext(ctx, "extension pending; applying", "extension", e.Name, "installed", e.Installed, "default", e.Default) + } + } for _, st := range sets { if len(st.Pending) > 0 { s.logger.InfoContext(ctx, "schema pending; applying", "set", st.Name, "versions", versions(st.Pending)) @@ -316,8 +328,8 @@ func (s *Service) checkState(state string) error { return nil } -// Verify checks that every set's history is clean and current and, when it -// is, that the seeder's statements prepare; the error names the set or +// Verify checks that every extension declaration matches the database and +// every set's history is clean and current and, when they are, that the seeder's statements prepare; the error names the set or // statement at fault. func (s *Service) Verify(ctx context.Context) error { err := s.migrator.Verify(ctx) @@ -331,14 +343,19 @@ func (s *Service) Verify(ctx context.Context) error { return nil } -// Status reads every set's state in declared order. +// Status reads every set's state and every extension declaration's state, +// each in declared order. func (s *Service) Status(ctx context.Context) (Status, error) { sets, err := s.migrator.Status(ctx) if err != nil { s.settle(err) return Status{}, conflict(err) } - st := Status{Ready: true, Sets: make([]SetStatus, 0, len(sets))} + exts, err := s.migrator.Extensions(ctx) + if err != nil { + return Status{}, err + } + st := Status{Ready: true, Sets: make([]SetStatus, 0, len(sets)), Extensions: make([]ExtensionStatus, 0, len(exts))} for i, l := range s.migrator.Layers() { ss := sets[i] out := SetStatus{ @@ -356,6 +373,14 @@ func (s *Service) Status(ctx context.Context) (Status, error) { } st.Sets = append(st.Sets, out) } + for _, e := range exts { + if !matched(e) { + st.Ready = false + } + st.Extensions = append(st.Extensions, ExtensionStatus{ + Name: e.Name, Removed: e.Removed, Installed: e.Installed, Default: e.Default, Pending: e.Pending, + }) + } s.setReady(st.Ready) return st, nil } @@ -428,7 +453,8 @@ func (s *Service) settle(err error) { switch { case err == nil: s.setReady(true) - case errors.Is(err, migrate.ErrDirty), errors.Is(err, migrate.ErrPending), errors.Is(err, migrate.ErrUnknownVersion): + case errors.Is(err, migrate.ErrDirty), errors.Is(err, migrate.ErrPending), errors.Is(err, migrate.ErrUnknownVersion), + errors.Is(err, migrate.ErrExtensionUnavailable), errors.Is(err, migrate.ErrNoUpdatePath): s.setReady(false) } } @@ -446,7 +472,8 @@ func conflict(err error) error { return err case errors.Is(err, migrate.ErrDirty), errors.Is(err, migrate.ErrPending), errors.Is(err, migrate.ErrUnknownVersion), errors.Is(err, migrate.ErrNoDown), - errors.Is(err, migrate.ErrAboveApplied), errors.Is(err, migrate.ErrBelowPending): + errors.Is(err, migrate.ErrAboveApplied), errors.Is(err, migrate.ErrBelowPending), + errors.Is(err, migrate.ErrExtensionUnavailable), errors.Is(err, migrate.ErrNoUpdatePath): return fmt.Errorf("%w: %w", ErrConflict, err) } return err @@ -541,6 +568,13 @@ func versions(ms []migrate.Migration) []int { return out } +func matched(e migrate.ExtensionStatus) bool { + if e.Removed { + return e.Installed == "" + } + return e.Default != "" && e.Installed == e.Default +} + 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 c7bb5cc..fac7460 100644 --- a/admin/service_test.go +++ b/admin/service_test.go @@ -165,10 +165,15 @@ func newFixture(t *testing.T, d sqlate.Dialect, opts admin.Options, responses .. } func newSetsFixture(t *testing.T, sets []migrate.Set, d sqlate.Dialect, opts admin.Options, responses ...sqltest.Response) fixture { + t.Helper() + return newMigratorFixture(t, sets, d, migrate.Options{}, opts, responses...) +} + +func newMigratorFixture(t *testing.T, sets []migrate.Set, d sqlate.Dialect, mopts migrate.Options, opts admin.Options, responses ...sqltest.Response) fixture { t.Helper() pool, rec := sqltest.Open(t, responses...) db := sqlate.Wrap(pool, d) - m, err := migrate.New(db, sets, migrate.Options{}) + m, err := migrate.New(db, sets, mopts) if err != nil { t.Fatalf("migrate.New: %v", err) } From 3216e071743612d59f42c6e8c8d718bf9eece137 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Tue, 24 Nov 2026 19:44:22 -0500 Subject: [PATCH 3/8] pgvector-go: the postgres/pgvector module resolves a configured metric with ParseMetric A new nested module, github.com/standards-lab/go-database/postgres/pgvector, requiring only sqlate's postgres/pgvector v0.1.0. Its package exports ParseMetric and ErrUnknownMetric, and Metric as a type alias of sqlate's pgvector.Metric (imported as sqlvector), so it declares no type of its own. ParseMetric matches a name exactly against sqlate's Metrics() and refuses any other with an error wrapping ErrUnknownMetric and quoting the name, before any I/O. doc.go shows pgvector-go used directly (NewVector for a parameter, sql.Null[pgvector.Vector] with Slice for a nullable column, domain types on []float32) and a configured metric's OpClass and Operator in use, and limits importing the module the way a provider's is. GO_MODULES and go.work include the module; README and STANDARDS.md name it and its dependency line; its CHANGELOG.md records [Unreleased]. The release workflow derives the changelog from the tag prefix, so postgres/pgvector/v0.1.0 needs no change there. --- README.md | 8 +++++ STANDARDS.md | 10 +++---- go.work | 1 + mise.toml | 2 +- postgres/pgvector/CHANGELOG.md | 17 +++++++++++ postgres/pgvector/doc.go | 50 ++++++++++++++++++++++++++++++++ postgres/pgvector/go.mod | 5 ++++ postgres/pgvector/go.sum | 20 +++++++++++++ postgres/pgvector/metric.go | 27 +++++++++++++++++ postgres/pgvector/metric_test.go | 39 +++++++++++++++++++++++++ 10 files changed, 173 insertions(+), 6 deletions(-) create mode 100644 postgres/pgvector/CHANGELOG.md create mode 100644 postgres/pgvector/doc.go create mode 100644 postgres/pgvector/go.mod create mode 100644 postgres/pgvector/go.sum create mode 100644 postgres/pgvector/metric.go create mode 100644 postgres/pgvector/metric_test.go diff --git a/README.md b/README.md index db68498..0fd769a 100644 --- a/README.md +++ b/README.md @@ -7,10 +7,13 @@ holds four things: - the database admin service, built over the `sqlate` library - the sweeper, which runs a service's reclaimers - the Postgres provider +- the pgvector module, which resolves a configured distance metric `github.com/standards-lab/go-database` is the base module, holding the `database` package at its root and `admin` and `sweep` beside it. `github.com/standards-lab/go-database/postgres` is a nested sub-module that pins the driver and is released on its own tags. +`github.com/standards-lab/go-database/postgres/pgvector` is a nested sub-module that requires +sqlate's `postgres/pgvector` and is released on its own tags. ## Standard @@ -22,6 +25,9 @@ principles: - The base module depends on the standard library, `go-core`, and `sqlate`; the driver enters a consumer's graph only through the `postgres` sub-module, imported once at the composition root. +- The `postgres/pgvector` sub-module depends on the standard library and sqlate's + `postgres/pgvector`. Importing it is limited the way a provider's is: the composition root, the + migrations, and the packages the application's design documentation declares. - [`sqlate`](https://github.com/standards-lab/sqlate) owns the SQL layer above the pool: statements, sessions, transactions, and the dialect. The composition root wraps the pool this library constructs with `sqlate.Wrap` and the engine's dialect from `sqlate/postgres`, and the @@ -46,6 +52,8 @@ principles: It imports no reclaimer; a library's reclaimer satisfies its interface. - `postgres` is the PostgreSQL provider: it constructs the pool over pgx's `database/sql` adapter from the configuration block. +- `pgvector` resolves the pgvector distance metric an application's configuration names into + sqlate's metric table, and its package doc shows pgvector-go's vector types used directly. ## Development diff --git a/STANDARDS.md b/STANDARDS.md index cf45564..b34719b 100644 --- a/STANDARDS.md +++ b/STANDARDS.md @@ -3,15 +3,15 @@ The judgement calls the standards-reviewer applies to go-database, beyond what `mise run check` enforces. - A change that alters documented behavior updates the README and the affected `doc.go` in the same change. -- `architecture/standards/go-elemental/principles/dependencies.md`: the base module's and `postgres`'s `go.mod`. -- `architecture/standards/go-elemental/principles/tests-and-docs.md`: the doc.go inventory of `database`, `admin`, `sweep` and `postgres`, and the unit tier over sqlate's `sqltest`, the `database` tests' stub driver and the `postgres` tests' in-test `pgproto3` server. -- `architecture/standards/go-elemental/principles/topology-and-naming.md`: the base module with `database`, `admin` and `sweep`, and the `postgres` provider sub-module and its tags. -- `architecture/standards/go-elemental/principles/release-and-ci.md`: the check, currency and upgrade tasks over `GO_MODULES`, which matches `go.work`'s use-list, and a changelog per module, `CHANGELOG.md` and `postgres/CHANGELOG.md`. +- `architecture/standards/go-elemental/principles/dependencies.md`: the base module's, `postgres`'s and `postgres/pgvector`'s `go.mod`; `postgres/pgvector`'s requires sqlate's `postgres/pgvector`. +- `architecture/standards/go-elemental/principles/tests-and-docs.md`: the doc.go inventory of `database`, `admin`, `sweep`, `postgres` and `pgvector`, and the unit tier over sqlate's `sqltest`, the `database` tests' stub driver and the `postgres` tests' in-test `pgproto3` server. +- `architecture/standards/go-elemental/principles/topology-and-naming.md`: the base module with `database`, `admin` and `sweep`, the `postgres` provider sub-module and its tags, and the `postgres/pgvector` sub-module and its tags. +- `architecture/standards/go-elemental/principles/release-and-ci.md`: the check, currency and upgrade tasks over `GO_MODULES`, which matches `go.work`'s use-list, and a changelog per module, `CHANGELOG.md`, `postgres/CHANGELOG.md` and `postgres/pgvector/CHANGELOG.md`. - `architecture/standards/go-elemental/principles/lifecycle-and-context.md`: `DB`'s `Start`, `Shutdown` and `Ready`, and `admin.Service`'s `Start` and `Ready`; the constructors' panics on an unfinalized `Config` or a missing pool, and `postgres.New`'s error on a reserved option. - `architecture/standards/go-elemental/principles/baseline-standards.md`: `Config`'s pool-size and timeout defaults, and `admin`, which takes every migration set, seed set, catalog and registry from its consumer. - `architecture/standards/go-elemental/principles/utc-times.md`: `postgres.New`'s connections, which scan `timestamptz` in UTC. - `architecture/standards/go-elemental/principles/construction-and-execution.md`: `sweep.New` takes its configuration as a trailing `sweep.Options` whose zero value keeps the defaults. - `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/validation-first.md`: `Config.Finalize`, and `admin`'s verbs, which refuse an argument outside their domain before any I/O, and `pgvector.ParseMetric`, which refuses an unknown metric name before any I/O. - `architecture/principles/context-architecture.md`: the README and each `doc.go`. - `architecture/principles/comments.md`: every comment. diff --git a/go.work b/go.work index b9e09f5..3ae98c2 100644 --- a/go.work +++ b/go.work @@ -3,4 +3,5 @@ go 1.27 use ( . ./postgres + ./postgres/pgvector ) diff --git a/mise.toml b/mise.toml index 4a98bf5..1fe10d7 100644 --- a/mise.toml +++ b/mise.toml @@ -9,7 +9,7 @@ golangci-lint = "2.15.0" jq = "1.8.2" [env] -GO_MODULES = ". postgres" +GO_MODULES = ". postgres postgres/pgvector" [tasks.check] description = "Build, vet, format, fix, tidy, test, and lint every module, then run lint-context and lint-references; writes nothing" diff --git a/postgres/pgvector/CHANGELOG.md b/postgres/pgvector/CHANGELOG.md new file mode 100644 index 0000000..a397d9b --- /dev/null +++ b/postgres/pgvector/CHANGELOG.md @@ -0,0 +1,17 @@ +# Changelog + +All notable changes to the pgvector module (`github.com/standards-lab/go-database/postgres/pgvector`) +are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and the module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). This +changelog covers this sub-module only; the base module and the `postgres` provider keep their own. + +## [Unreleased] + +### Added + +- `ParseMetric` resolves a distance metric name, matched exactly, to its entry in the metric + table of sqlate's `postgres/pgvector` v0.1.0, without I/O. `Metric` is an alias of sqlate's + type. A name outside the table returns an error that wraps `ErrUnknownMetric` and quotes the + name. + +[Unreleased]: https://github.com/standards-lab/go-database/commits/HEAD/postgres/pgvector diff --git a/postgres/pgvector/doc.go b/postgres/pgvector/doc.go new file mode 100644 index 0000000..a4ebe74 --- /dev/null +++ b/postgres/pgvector/doc.go @@ -0,0 +1,50 @@ +// Package pgvector resolves the pgvector distance metric an application's +// configuration names into sqlate's metric table: +// +// - [Metric], sqlate's pgvector metric, under this package's name +// - [ParseMetric], which resolves a metric name to its [Metric] +// - [ErrUnknownMetric], the error a name outside the table wraps +// +// The package imports only the standard library and sqlate's +// postgres/pgvector, and declares no type of its own. Importing this module +// is limited the way a provider's is: the composition root, the migrations, +// and the packages the application's design documentation declares. +// +// # Vectors +// +// Those packages use pgvector-go (github.com/pgvector/pgvector-go) +// directly; this package does not import it. Domain types hold []float32. +// pgvector.NewVector wraps one for a parameter, and a nullable column scans +// into sql.Null[pgvector.Vector], whose Slice returns the []float32: +// +// import ( +// "database/sql" +// +// "github.com/pgvector/pgvector-go" +// ) +// +// _, err := db.ExecContext(ctx, "UPDATE doc SET embedding = $1 WHERE id = $2", +// pgvector.NewVector(d.Embedding), d.ID) +// +// var embedding sql.Null[pgvector.Vector] +// if err := row.Scan(&d.ID, &embedding); err != nil { +// return err +// } +// if embedding.Valid { +// d.Embedding = embedding.V.Slice() +// } +// +// # Metrics from configuration +// +// A metric named in configuration resolves with [ParseMetric] before any +// I/O; its OpClass builds the index and its Operator orders the query: +// +// import vecmetric "github.com/standards-lab/go-database/postgres/pgvector" +// +// metric, err := vecmetric.ParseMetric(cfg.Metric) +// if err != nil { +// return err +// } +// index := "CREATE INDEX doc_embedding ON doc USING hnsw (embedding " + metric.OpClass + ")" +// nearest := "SELECT id FROM doc ORDER BY embedding " + metric.Operator + " $1 LIMIT 5" +package pgvector diff --git a/postgres/pgvector/go.mod b/postgres/pgvector/go.mod new file mode 100644 index 0000000..ce211c1 --- /dev/null +++ b/postgres/pgvector/go.mod @@ -0,0 +1,5 @@ +module github.com/standards-lab/go-database/postgres/pgvector + +go 1.27 + +require github.com/standards-lab/sqlate/postgres/pgvector v0.1.0 diff --git a/postgres/pgvector/go.sum b/postgres/pgvector/go.sum new file mode 100644 index 0000000..b10af4f --- /dev/null +++ b/postgres/pgvector/go.sum @@ -0,0 +1,20 @@ +github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= +github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4= +github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds= +github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao= +github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/standards-lab/sqlate v0.8.0 h1:G1uUIWmc2DxJz5YhtBvIlftfURnb3b2RKsYB59Wa03Y= +github.com/standards-lab/sqlate v0.8.0/go.mod h1:pikNmGf/z3x46SBWFXgt/xKIDZuquSgCoXy5OWBFFR4= +github.com/standards-lab/sqlate/postgres v0.9.0 h1:l6PXEZ3GQM4+0zekxlSONhyHjpQU8g8StAS16bBqzZE= +github.com/standards-lab/sqlate/postgres v0.9.0/go.mod h1:8a/0yo/fS50qc8gdXm/4PQd074FSXBhjCj1rav7xVCU= +github.com/standards-lab/sqlate/postgres/pgvector v0.1.0 h1:hivV8KOcof2EzaEtWCJsHhTOCaqu1ahQd4D1pEHkgJ0= +github.com/standards-lab/sqlate/postgres/pgvector v0.1.0/go.mod h1:1IoWphV8iPSGfB4sXyHEMJGoGL5Q7tc234VLlg9WgPs= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= +golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= diff --git a/postgres/pgvector/metric.go b/postgres/pgvector/metric.go new file mode 100644 index 0000000..fb59336 --- /dev/null +++ b/postgres/pgvector/metric.go @@ -0,0 +1,27 @@ +package pgvector + +import ( + "errors" + "fmt" + + sqlvector "github.com/standards-lab/sqlate/postgres/pgvector" +) + +// Metric is sqlate's pgvector metric: its name, its distance operator, and +// its index operator class. +type Metric = sqlvector.Metric + +// ErrUnknownMetric reports a metric name that is none of sqlate's metrics. +var ErrUnknownMetric = errors.New("unknown pgvector metric") + +// ParseMetric returns the metric of sqlate's table whose Name is name, +// matched exactly, without I/O. Any other name returns an error that wraps +// [ErrUnknownMetric] and quotes name. +func ParseMetric(name string) (Metric, error) { + for _, m := range sqlvector.Metrics() { + if m.Name == name { + return m, nil + } + } + return Metric{}, fmt.Errorf("%w: %q", ErrUnknownMetric, name) +} diff --git a/postgres/pgvector/metric_test.go b/postgres/pgvector/metric_test.go new file mode 100644 index 0000000..aaafda7 --- /dev/null +++ b/postgres/pgvector/metric_test.go @@ -0,0 +1,39 @@ +package pgvector_test + +import ( + "errors" + "strings" + "testing" + + "github.com/standards-lab/go-database/postgres/pgvector" + sqlvector "github.com/standards-lab/sqlate/postgres/pgvector" +) + +func TestParseMetric_ResolvesEachMetricByItsName(t *testing.T) { + for _, want := range sqlvector.Metrics() { + got, err := pgvector.ParseMetric(want.Name) + if err != nil { + t.Errorf("ParseMetric(%q): %v", want.Name, err) + continue + } + if got != want { + t.Errorf("ParseMetric(%q) = %+v, want %+v", want.Name, got, want) + } + } +} + +func TestParseMetric_RefusesANameOutsideTheTable(t *testing.T) { + for _, name := range []string{"manhattan", "Cosine", ""} { + got, err := pgvector.ParseMetric(name) + if !errors.Is(err, pgvector.ErrUnknownMetric) { + t.Errorf("ParseMetric(%q) error = %v, want ErrUnknownMetric", name, err) + continue + } + if !strings.Contains(err.Error(), `"`+name+`"`) { + t.Errorf("ParseMetric(%q) error = %q, want it to name the input", name, err) + } + if got != (pgvector.Metric{}) { + t.Errorf("ParseMetric(%q) = %+v, want the zero Metric", name, got) + } + } +} From e78b7b7de094d3abe66000c197f1e240c95c68c4 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Tue, 24 Nov 2026 19:45:55 -0500 Subject: [PATCH 4/8] pgvector-go: a compose PostgreSQL with pgvector, and currency over its image compose.yml names the project go-database and includes compose/postgres.yml, which publishes 127.0.0.1:${POSTGRES_PORT:-5438} and keeps its data on tmpfs as a test-only harness. compose/postgres/Dockerfile is sqlate's canonical image copied verbatim (postgres:19.0-alpine, pgvector 0.8.7 from source, its HEALTHCHECK). mise run db:up / db:down drive compose directly; there is no db:reset, since tmpfs leaves nothing to drop. GO_DATABASE_DSN follows POSTGRES_PORT. scripts/currency.sh is sqlate's, verbatim: it adds the image-line, Dockerfile FROM and source-ARG checks, with crane (aqua:google/go-containerregistry 0.22.1) installed by mise. The old script's paragraph on failing scans explained a mechanism, which no allowed comment kind covers; sqlate's header already states the behavior ("A scan command that fails fails currency") as part of the script's documentation, so the paragraph is dropped. README documents the stack; STANDARDS.md's release-and-ci line names it. --- README.md | 11 +++++- STANDARDS.md | 2 +- compose.yml | 5 +++ compose/postgres.yml | 7 ++++ compose/postgres/Dockerfile | 21 ++++++++++ mise.toml | 12 +++++- scripts/currency.sh | 78 ++++++++++++++++++++++++++++++++----- 7 files changed, 123 insertions(+), 13 deletions(-) create mode 100644 compose.yml create mode 100644 compose/postgres.yml create mode 100644 compose/postgres/Dockerfile diff --git a/README.md b/README.md index 0fd769a..7738f77 100644 --- a/README.md +++ b/README.md @@ -61,10 +61,19 @@ 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, then lint-context and lint-references; writes nothing -mise run currency # report requirements, Go, tools, and actions behind their latest +mise run currency # report requirements, Go, tools, actions, images, and Dockerfile source ARGs behind their latest mise run upgrade # upgrade every module's go directive and requirements, and the tools, to their latest +mise run db:up # build and start the compose PostgreSQL and wait until it is healthy +mise run db:down # stop PostgreSQL, discarding its data ``` +`compose.yml` runs PostgreSQL with pgvector on port 5438; `POSTGRES_PORT` moves it, and +`GO_DATABASE_DSN` in `mise.toml` follows it. The service builds from +`compose/postgres/Dockerfile`, a copy of sqlate's canonical PostgreSQL image: its `FROM` line is +the one image pin, `ARG PGVECTOR_VERSION` the extension's, and `mise run currency` reports either +when it trails its latest. The stack is a test-only harness that keeps its data on tmpfs, so every +`db:up` starts empty. + ## License [Apache License 2.0](LICENSE). diff --git a/STANDARDS.md b/STANDARDS.md index b34719b..fbc4d34 100644 --- a/STANDARDS.md +++ b/STANDARDS.md @@ -6,7 +6,7 @@ The judgement calls the standards-reviewer applies to go-database, beyond what ` - `architecture/standards/go-elemental/principles/dependencies.md`: the base module's, `postgres`'s and `postgres/pgvector`'s `go.mod`; `postgres/pgvector`'s requires sqlate's `postgres/pgvector`. - `architecture/standards/go-elemental/principles/tests-and-docs.md`: the doc.go inventory of `database`, `admin`, `sweep`, `postgres` and `pgvector`, and the unit tier over sqlate's `sqltest`, the `database` tests' stub driver and the `postgres` tests' in-test `pgproto3` server. - `architecture/standards/go-elemental/principles/topology-and-naming.md`: the base module with `database`, `admin` and `sweep`, the `postgres` provider sub-module and its tags, and the `postgres/pgvector` sub-module and its tags. -- `architecture/standards/go-elemental/principles/release-and-ci.md`: the check, currency and upgrade tasks over `GO_MODULES`, which matches `go.work`'s use-list, and a changelog per module, `CHANGELOG.md`, `postgres/CHANGELOG.md` and `postgres/pgvector/CHANGELOG.md`. +- `architecture/standards/go-elemental/principles/release-and-ci.md`: the check, currency and upgrade tasks over `GO_MODULES`, which matches `go.work`'s use-list, the compose stack of `compose.yml` and `compose/postgres`, a test-only harness on tmpfs, and a changelog per module, `CHANGELOG.md`, `postgres/CHANGELOG.md` and `postgres/pgvector/CHANGELOG.md`. - `architecture/standards/go-elemental/principles/lifecycle-and-context.md`: `DB`'s `Start`, `Shutdown` and `Ready`, and `admin.Service`'s `Start` and `Ready`; the constructors' panics on an unfinalized `Config` or a missing pool, and `postgres.New`'s error on a reserved option. - `architecture/standards/go-elemental/principles/baseline-standards.md`: `Config`'s pool-size and timeout defaults, and `admin`, which takes every migration set, seed set, catalog and registry from its consumer. - `architecture/standards/go-elemental/principles/utc-times.md`: `postgres.New`'s connections, which scan `timestamptz` in UTC. diff --git a/compose.yml b/compose.yml new file mode 100644 index 0000000..0e550db --- /dev/null +++ b/compose.yml @@ -0,0 +1,5 @@ +# See README.md +name: go-database + +include: + - compose/postgres.yml diff --git a/compose/postgres.yml b/compose/postgres.yml new file mode 100644 index 0000000..453b94e --- /dev/null +++ b/compose/postgres.yml @@ -0,0 +1,7 @@ +services: + postgres: + build: + context: postgres + ports: + - "127.0.0.1:${POSTGRES_PORT:-5438}:5432" + tmpfs: /var/lib/postgresql diff --git a/compose/postgres/Dockerfile b/compose/postgres/Dockerfile new file mode 100644 index 0000000..f43d348 --- /dev/null +++ b/compose/postgres/Dockerfile @@ -0,0 +1,21 @@ +# See README.md +FROM postgres:19.0-alpine + +ARG PGVECTOR_VERSION=0.8.7 + +ADD https://github.com/pgvector/pgvector.git#v${PGVECTOR_VERSION} /usr/src/pgvector + +RUN apk add --no-cache --virtual .build-deps build-base \ + && cd /usr/src/pgvector \ + && make with_llvm=no OPTFLAGS="" \ + && make install with_llvm=no \ + && cd / \ + && rm -rf /usr/src/pgvector \ + && apk del .build-deps + +ENV POSTGRES_USER=app \ + POSTGRES_PASSWORD=app \ + POSTGRES_DB=app + +HEALTHCHECK --start-period=30s --start-interval=1s --interval=5s --timeout=3s --retries=5 \ + CMD ["pg_isready", "-h", "127.0.0.1", "-U", "app", "-d", "app"] diff --git a/mise.toml b/mise.toml index 1fe10d7..20c2294 100644 --- a/mise.toml +++ b/mise.toml @@ -7,9 +7,11 @@ task.run_auto_install = false go = "1.27.4" golangci-lint = "2.15.0" jq = "1.8.2" +"aqua:google/go-containerregistry" = "0.22.1" [env] GO_MODULES = ". postgres postgres/pgvector" +GO_DATABASE_DSN = "postgres://app:app@127.0.0.1:{{ get_env(name='POSTGRES_PORT', default='5438') }}/app?sslmode=disable" [tasks.check] description = "Build, vet, format, fix, tidy, test, and lint every module, then run lint-context and lint-references; writes nothing" @@ -42,7 +44,7 @@ exit "$fail" ''' [tasks.currency] -description = "Report every requirement, Go version, tool, and action pin behind its latest; writes nothing" +description = "Report every requirement, Go version, tool, action pin, image tag, and Dockerfile source ARG behind its latest; writes nothing" run = "scripts/currency.sh" [tasks.upgrade] @@ -115,3 +117,11 @@ for mod in $GO_MODULES; do (cd "$mod" && golangci-lint run ./...) done ''' + +[tasks."db:up"] +description = "Build and start the compose PostgreSQL and wait until it is healthy" +run = "docker compose up -d --wait --build" + +[tasks."db:down"] +description = "Stop the compose PostgreSQL, discarding its data" +run = "docker compose down" diff --git a/scripts/currency.sh b/scripts/currency.sh index 7ab80a4..e6bc92f 100755 --- a/scripts/currency.sh +++ b/scripts/currency.sh @@ -3,11 +3,10 @@ # 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`. 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) -# fails currency instead of reporting nothing. +# the project in a subdirectory, of the git top-level's. A compose Dockerfile's +# `ARG _VERSION` whose `ADD` fetches a GitHub repository at `v${_VERSION}` +# is compared with that repository's highest semver tag. A scan command that fails +# fails currency. set -euo pipefail cd "$MISE_PROJECT_ROOT" export GOWORK=off @@ -58,11 +57,7 @@ report_outdated_mise_tools() { } report_outdated_actions() { - local root top workflows actions uses action pin repo latest - 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) + local actions uses action pin repo latest actions=$(matches 'uses: *[^ ]*@[^ ]*' "${workflows[@]}" | sed 's/uses: *//' | sort -u) for uses in $actions; do action=${uses%@*} @@ -73,6 +68,66 @@ report_outdated_actions() { done } +latest_dotted_release_tag() { + local image=$1 pin=$2 suffix dotted_release_pattern latest + suffix=${pin#"${pin%%[!0-9.]*}"} + dotted_release_pattern="^[0-9]+(\.[0-9]+)+${suffix//./\\.}\$" + latest=$(crane ls "$image" | grep -E "$dotted_release_pattern" | sed "s/${suffix}\$//" | sort -V | tail -n1) || return + echo "$latest$suffix" +} + +report_outdated_image_lines() { + local images ref image pin latest + images=$(matches '^ *image: *[^ ]*' compose.yml compose/*.yml "${workflows[@]}" | + sed 's/^ *image: *//' | tr -d "\"'" | sort -u) + for ref in $images; do + image=${ref%:*} + pin=${ref##*:} + latest=$(latest_dotted_release_tag "$image" "$pin") + [ "$pin" = "$latest" ] || report "images: $image $pin -> $latest" + done +} + +report_outdated_dockerfile_bases() { + local dockerfile ref image pin latest + for dockerfile in compose/*/Dockerfile; do + [ -e "$dockerfile" ] || continue + ref=$(sed -n '/^FROM /{s/^FROM *\([^ ]*\).*/\1/p;q;}' "$dockerfile") + image=${ref%:*} + pin=${ref##*:} + latest=$(latest_dotted_release_tag "$image" "$pin") + [ "$pin" = "$latest" ] || report "$dockerfile: $image $pin -> $latest" + done +} + +latest_semver_git_tag() { + local repo=$1 tags latest + tags=$(GIT_TERMINAL_PROMPT=0 git ls-remote --tags --refs "https://github.com/$repo.git") || return + latest=$(echo "$tags" | sed -n 's|.*refs/tags/v\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\)$|\1|p' | sort -V | tail -n1) + [ -n "$latest" ] || return 1 + echo "$latest" +} + +report_outdated_dockerfile_args() { + local dockerfile args name pin repo latest + for dockerfile in compose/*/Dockerfile; do + [ -e "$dockerfile" ] || continue + args=$(sed -n 's/^ARG *\([A-Za-z0-9_]*_VERSION\)=\([^ ]*\) *$/\1 \2/p' "$dockerfile") + while read -r name pin; do + [ -n "$name" ] || continue + repo=$(sed -n "s|^ADD *https://github\.com/\([^/ ]*/[^/ ]*\)\.git#v\\\${$name} .*|\1|p" "$dockerfile") + [ -n "$repo" ] || continue + latest=$(latest_semver_git_tag "$repo") + [ "$pin" = "$latest" ] || report "$dockerfile: $repo $pin -> $latest" + done <<<"$args" + done +} + +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) + go_minor=$(mise latest go | cut -d. -f1,2) for mod in $GO_MODULES; do report_outdated_requirements "$mod" @@ -80,4 +135,7 @@ for mod in $GO_MODULES; do done report_outdated_mise_tools report_outdated_actions +report_outdated_image_lines +report_outdated_dockerfile_bases +report_outdated_dockerfile_args exit "$stale" From c024fda5e64e6ec2932fccebffb9dc253996df77 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Tue, 24 Nov 2026 19:49:05 -0500 Subject: [PATCH 5/8] pgvector-go: the pgvector module's integration tier, run locally by mise run acceptance The tier sits behind the integration build tag and uses GO_DATABASE_DSN and sqlate's postgres/pgtest: - admin.Start over a migrator declaring vector activates it in a scratch database made with pgtest.Create, where vector is absent first; Status then reports it installed at the image default, not pending, and Ready. - A vector column round-trips pgvector.NewVector values and a NULL through sql.Null[pgvector.Vector] and Slice, over pgtest's pgx database/sql pool. - Each metric of sqlate's Metrics, resolved by ParseMetric, orders a nearest-neighbor query to a different row (l2, cosine and inner product disagree on the data); a metric with no expected row fails the test. mise run integration runs the tier against a running stack; mise run acceptance runs db:up, integration, and db:down whatever the result, and prints docker compose logs on failure. The check's vet, fix and lint run with the integration tag for every module in place of their untagged runs, since the tagged run covers every untagged file too; build and test stay untagged. go.mod gains, for the tests only, pgvector-go v0.4.1, go-database v0.13.0, sqlate v0.8.0 and sqlate's postgres v0.9.0, with a replace of go-database to ../.. until v0.13.0 is tagged. The README, doc.go and STANDARDS.md name the tier and its test-only requirements; the CHANGELOG records no tests, so it is unchanged. --- README.md | 13 +++- STANDARDS.md | 2 +- mise.toml | 24 ++++++-- postgres/pgvector/admin_live_test.go | 88 +++++++++++++++++++++++++++ postgres/pgvector/doc.go | 8 ++- postgres/pgvector/go.mod | 20 +++++- postgres/pgvector/go.sum | 18 ++++++ postgres/pgvector/vector_live_test.go | 79 ++++++++++++++++++++++++ 8 files changed, 242 insertions(+), 10 deletions(-) create mode 100644 postgres/pgvector/admin_live_test.go create mode 100644 postgres/pgvector/vector_live_test.go diff --git a/README.md b/README.md index 7738f77..07681a7 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,8 @@ principles: - The base module depends on the standard library, `go-core`, and `sqlate`; the driver enters a consumer's graph only through the `postgres` sub-module, imported once at the composition root. - The `postgres/pgvector` sub-module depends on the standard library and sqlate's - `postgres/pgvector`. Importing it is limited the way a provider's is: the composition root, the + `postgres/pgvector`; its integration tier alone also requires pgvector-go, the base module, and + sqlate's `postgres`, so they enter its `go.mod` as test-only requirements. Importing it is limited the way a provider's is: the composition root, the migrations, and the packages the application's design documentation declares. - [`sqlate`](https://github.com/standards-lab/sqlate) owns the SQL layer above the pool: statements, sessions, transactions, and the dialect. The composition root wraps the pool this @@ -65,6 +66,8 @@ mise run currency # report requirements, Go, tools, actions, images, and Docke mise run upgrade # upgrade every module's go directive and requirements, and the tools, to their latest mise run db:up # build and start the compose PostgreSQL and wait until it is healthy mise run db:down # stop PostgreSQL, discarding its data +mise run integration # run the integration tier against the running stack +mise run acceptance # db:up, integration, then db:down whatever the result; prints the stack's log on failure ``` `compose.yml` runs PostgreSQL with pgvector on port 5438; `POSTGRES_PORT` moves it, and @@ -74,6 +77,14 @@ the one image pin, `ARG PGVECTOR_VERSION` the extension's, and `mise run currenc when it trails its latest. The stack is a test-only harness that keeps its data on tmpfs, so every `db:up` starts empty. +The `postgres/pgvector` module's integration tier sits behind the `integration` build tag and +runs against the stack: `admin.Start` activating a declared `vector` extension, a `vector` +column round-tripping pgvector-go values and NULL, and each metric's operator ordering a +nearest-neighbor query. Each test makes its own throwaway database through sqlate's +`postgres/pgtest`. The tier runs on a developer's machine only, through `mise run acceptance`, +and needs Docker; CI runs `mise run check`, which vets, fixes, and lints the tier with its tag +but runs only the unit tier. + ## License [Apache License 2.0](LICENSE). diff --git a/STANDARDS.md b/STANDARDS.md index fbc4d34..872e1e7 100644 --- a/STANDARDS.md +++ b/STANDARDS.md @@ -4,7 +4,7 @@ The judgement calls the standards-reviewer applies to go-database, beyond what ` - A change that alters documented behavior updates the README and the affected `doc.go` in the same change. - `architecture/standards/go-elemental/principles/dependencies.md`: the base module's, `postgres`'s and `postgres/pgvector`'s `go.mod`; `postgres/pgvector`'s requires sqlate's `postgres/pgvector`. -- `architecture/standards/go-elemental/principles/tests-and-docs.md`: the doc.go inventory of `database`, `admin`, `sweep`, `postgres` and `pgvector`, and the unit tier over sqlate's `sqltest`, the `database` tests' stub driver and the `postgres` tests' in-test `pgproto3` server. +- `architecture/standards/go-elemental/principles/tests-and-docs.md`: the doc.go inventory of `database`, `admin`, `sweep`, `postgres` and `pgvector`, and the unit tier over sqlate's `sqltest`, the `database` tests' stub driver and the `postgres` tests' in-test `pgproto3` server; and `postgres/pgvector`'s integration tier, behind the `integration` tag, over sqlate's `postgres/pgtest` against the compose stack, run locally by `mise run acceptance`. - `architecture/standards/go-elemental/principles/topology-and-naming.md`: the base module with `database`, `admin` and `sweep`, the `postgres` provider sub-module and its tags, and the `postgres/pgvector` sub-module and its tags. - `architecture/standards/go-elemental/principles/release-and-ci.md`: the check, currency and upgrade tasks over `GO_MODULES`, which matches `go.work`'s use-list, the compose stack of `compose.yml` and `compose/postgres`, a test-only harness on tmpfs, and a changelog per module, `CHANGELOG.md`, `postgres/CHANGELOG.md` and `postgres/pgvector/CHANGELOG.md`. - `architecture/standards/go-elemental/principles/lifecycle-and-context.md`: `DB`'s `Start`, `Shutdown` and `Ready`, and `admin.Service`'s `Start` and `Ready`; the constructors' panics on an unfinalized `Config` or a missing pool, and `postgres.New`'s error on a reserved option. diff --git a/mise.toml b/mise.toml index 20c2294..6654ce8 100644 --- a/mise.toml +++ b/mise.toml @@ -14,7 +14,7 @@ GO_MODULES = ". postgres postgres/pgvector" GO_DATABASE_DSN = "postgres://app:app@127.0.0.1:{{ get_env(name='POSTGRES_PORT', default='5438') }}/app?sslmode=disable" [tasks.check] -description = "Build, vet, format, fix, tidy, test, and lint every module, then run lint-context and lint-references; writes nothing" +description = "Build, vet, format, fix, tidy, test, and lint every module, vetting, fixing, and linting the integration tier with its tag but running only the unit tier, then run lint-context and lint-references; writes nothing" run = ''' set -eu export GOWORK=off @@ -22,13 +22,13 @@ for mod in $GO_MODULES; do echo "check: $mod" cd "$MISE_PROJECT_ROOT/$mod" go build ./... - go vet ./... + go vet -tags integration ./... unformatted=$(gofmt -l .) if [ -n "$unformatted" ]; then echo "gofmt: unformatted files:"; echo "$unformatted"; exit 1; fi - go fix -diff ./... + go fix -diff -tags integration ./... go mod tidy -diff go test -race ./... - golangci-lint run ./... + golangci-lint run --build-tags integration ./... done cd "$MISE_PROJECT_ROOT" fail=0 @@ -118,6 +118,22 @@ for mod in $GO_MODULES; do done ''' +[tasks.integration] +description = "Run the integration tier of postgres/pgvector against the PostgreSQL named by GO_DATABASE_DSN" +run = ''' +cd postgres/pgvector +go test -race -tags integration -count=1 ./... +''' + +[tasks.acceptance] +description = "The one-shot engine proof: db:up, integration, then db:down whatever the result, printing the stack's log on failure" +run = ''' +set -e +trap 'rc=$?; [ $rc -eq 0 ] || docker compose logs; mise run db:down; exit $rc' EXIT +mise run db:up +mise run integration +''' + [tasks."db:up"] description = "Build and start the compose PostgreSQL and wait until it is healthy" run = "docker compose up -d --wait --build" diff --git a/postgres/pgvector/admin_live_test.go b/postgres/pgvector/admin_live_test.go new file mode 100644 index 0000000..230c689 --- /dev/null +++ b/postgres/pgvector/admin_live_test.go @@ -0,0 +1,88 @@ +//go:build integration + +package pgvector_test + +import ( + "context" + "database/sql" + "slices" + "testing" + + "github.com/standards-lab/go-database" + "github.com/standards-lab/go-database/admin" + "github.com/standards-lab/sqlate/migrate" + "github.com/standards-lab/sqlate/postgres/pgtest" + sqlvector "github.com/standards-lab/sqlate/postgres/pgvector" + "github.com/standards-lab/sqlate/query" +) + +const dsnEnv = "GO_DATABASE_DSN" + +var declared = migrate.Options{Extensions: []migrate.Extension{{Name: sqlvector.Extension}}} + +func vectorSet(up, down string) []migrate.Set { + return []migrate.Set{{Name: "vec", Table: "vec_history", Migrations: []migrate.Migration{ + {Version: 1, Name: "table", Up: up, Down: down, Transactional: true}, + }}} +} + +func text(t testing.TB, pool *sql.DB, q string, args ...any) string { + t.Helper() + var s string + if err := pool.QueryRowContext(context.Background(), q, args...).Scan(&s); err != nil { + t.Fatalf("%s: %v", q, err) + } + return s +} + +func installedVersion(t testing.TB, pool *sql.DB) string { + t.Helper() + return text(t, pool, "SELECT COALESCE((SELECT extversion FROM pg_extension WHERE extname = $1), '')", sqlvector.Extension) +} + +func imageDefaultVersion(t testing.TB, pool *sql.DB) string { + t.Helper() + v := text(t, pool, "SELECT COALESCE((SELECT default_version FROM pg_available_extensions WHERE name = $1), '')", sqlvector.Extension) + if v == "" { + t.Fatalf("the image does not offer %s", sqlvector.Extension) + } + return v +} + +func TestLive_AdminStartActivatesVectorAtTheImageDefault(t *testing.T) { + ctx := context.Background() + d := pgtest.Create(t, dsnEnv, "vec") + if got := installedVersion(t, d.Pool); got != "" { + t.Fatalf("vector in the scratch database is at %q before Start, want it absent", got) + } + def := imageDefaultVersion(t, d.Pool) + + db := d.Session() + m, err := migrate.New(db, vectorSet("CREATE TABLE doc (id integer PRIMARY KEY, embedding vector(3))", "DROP TABLE doc"), declared) + if err != nil { + t.Fatalf("migrate.New: %v", err) + } + cfg := database.Config{Name: "test"} + if err := cfg.Finalize(""); err != nil { + t.Fatal(err) + } + s := admin.New(database.New(d.Pool, cfg), db, m, query.MustCatalog(query.Patterns()), admin.Options{}) + if err := s.Start(ctx); err != nil { + t.Fatalf("Start: %v", err) + } + + if got := installedVersion(t, d.Pool); got != def { + t.Errorf("vector after Start is at %q, want the image default %q", got, def) + } + st, err := s.Status(ctx) + if err != nil { + t.Fatalf("Status: %v", err) + } + want := []admin.ExtensionStatus{{Name: sqlvector.Extension, Installed: def, Default: def}} + if !slices.Equal(st.Extensions, want) { + t.Errorf("Status.Extensions = %+v, want %+v", st.Extensions, want) + } + if !st.Ready || !s.Ready() { + t.Errorf("Status.Ready = %v, Ready() = %v, want both true", st.Ready, s.Ready()) + } +} diff --git a/postgres/pgvector/doc.go b/postgres/pgvector/doc.go index a4ebe74..c40ccd5 100644 --- a/postgres/pgvector/doc.go +++ b/postgres/pgvector/doc.go @@ -6,9 +6,11 @@ // - [ErrUnknownMetric], the error a name outside the table wraps // // The package imports only the standard library and sqlate's -// postgres/pgvector, and declares no type of its own. Importing this module -// is limited the way a provider's is: the composition root, the migrations, -// and the packages the application's design documentation declares. +// postgres/pgvector, and declares no type of its own; pgvector-go, +// go-database, and sqlate's postgres are requirements of its integration +// tests only. Importing this module is limited the way a provider's is: the +// composition root, the migrations, and the packages the application's +// design documentation declares. // // # Vectors // diff --git a/postgres/pgvector/go.mod b/postgres/pgvector/go.mod index ce211c1..c77ca7c 100644 --- a/postgres/pgvector/go.mod +++ b/postgres/pgvector/go.mod @@ -2,4 +2,22 @@ module github.com/standards-lab/go-database/postgres/pgvector go 1.27 -require github.com/standards-lab/sqlate/postgres/pgvector v0.1.0 +require ( + github.com/pgvector/pgvector-go v0.4.1 + github.com/standards-lab/go-database v0.13.0 + github.com/standards-lab/sqlate v0.8.0 + github.com/standards-lab/sqlate/postgres v0.9.0 + github.com/standards-lab/sqlate/postgres/pgvector v0.1.0 +) + +require ( + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/pgx/v5 v5.13.0 // indirect + github.com/jackc/puddle/v2 v2.2.3 // indirect + github.com/standards-lab/go-core v0.12.0 // indirect + golang.org/x/sync v0.22.0 // indirect + golang.org/x/text v0.41.0 // indirect +) + +replace github.com/standards-lab/go-database => ../.. diff --git a/postgres/pgvector/go.sum b/postgres/pgvector/go.sum index b10af4f..f423c7d 100644 --- a/postgres/pgvector/go.sum +++ b/postgres/pgvector/go.sum @@ -1,5 +1,8 @@ github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= @@ -8,13 +11,28 @@ github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4= github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds= github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao= github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/pgvector/pgvector-go v0.4.1 h1:Oaj0mC0Ky8KaTweNHHpLwyFlN6a0nUFoo1vgSFTEhPI= +github.com/pgvector/pgvector-go v0.4.1/go.mod h1:4fSXyjl1TYAIdByAql6JazKWRr2s7J0g4hcRY5cBFCk= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/standards-lab/go-core v0.12.0 h1:sqrzK6QSppEYpwvVAyiWgzNuOsjfK0Kwe86GPuZpHsU= +github.com/standards-lab/go-core v0.12.0/go.mod h1:Yl/R+gM9YWczsePBCKXdPGh3FSdZ/5i8SapLIh3BDHU= github.com/standards-lab/sqlate v0.8.0 h1:G1uUIWmc2DxJz5YhtBvIlftfURnb3b2RKsYB59Wa03Y= github.com/standards-lab/sqlate v0.8.0/go.mod h1:pikNmGf/z3x46SBWFXgt/xKIDZuquSgCoXy5OWBFFR4= github.com/standards-lab/sqlate/postgres v0.9.0 h1:l6PXEZ3GQM4+0zekxlSONhyHjpQU8g8StAS16bBqzZE= github.com/standards-lab/sqlate/postgres v0.9.0/go.mod h1:8a/0yo/fS50qc8gdXm/4PQd074FSXBhjCj1rav7xVCU= github.com/standards-lab/sqlate/postgres/pgvector v0.1.0 h1:hivV8KOcof2EzaEtWCJsHhTOCaqu1ahQd4D1pEHkgJ0= github.com/standards-lab/sqlate/postgres/pgvector v0.1.0/go.mod h1:1IoWphV8iPSGfB4sXyHEMJGoGL5Q7tc234VLlg9WgPs= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/postgres/pgvector/vector_live_test.go b/postgres/pgvector/vector_live_test.go new file mode 100644 index 0000000..ff04a0d --- /dev/null +++ b/postgres/pgvector/vector_live_test.go @@ -0,0 +1,79 @@ +//go:build integration + +package pgvector_test + +import ( + "context" + "database/sql" + "slices" + "testing" + + "github.com/pgvector/pgvector-go" + vecmetric "github.com/standards-lab/go-database/postgres/pgvector" + "github.com/standards-lab/sqlate/postgres/pgtest" + sqlvector "github.com/standards-lab/sqlate/postgres/pgvector" +) + +func TestLive_VectorColumnRoundTripsValuesAndNull(t *testing.T) { + ctx := context.Background() + d := pgtest.MigratedWith(t, dsnEnv, "vec", declared, + vectorSet("CREATE TABLE doc (id integer PRIMARY KEY, embedding vector(3))", "DROP TABLE doc")...) + stored := map[int][]float32{1: {1, 2, 3}, 2: {-0.5, 0.25, 1e-3}, 3: nil} + for id, v := range stored { + var arg any + if v != nil { + arg = pgvector.NewVector(v) + } + if _, err := d.Pool.ExecContext(ctx, "INSERT INTO doc (id, embedding) VALUES ($1, $2)", id, arg); err != nil { + t.Fatalf("insert %d: %v", id, err) + } + } + for id, want := range stored { + var got sql.Null[pgvector.Vector] + if err := d.Pool.QueryRowContext(ctx, "SELECT embedding FROM doc WHERE id = $1", id).Scan(&got); err != nil { + t.Fatalf("select %d: %v", id, err) + } + if got.Valid != (want != nil) { + t.Errorf("row %d: Valid = %v, want %v", id, got.Valid, want != nil) + continue + } + if got.Valid && !slices.Equal(got.V.Slice(), want) { + t.Errorf("row %d: Slice() = %v, want %v", id, got.V.Slice(), want) + } + } +} + +func TestLive_EachMetricOrdersItsOwnNearestRow(t *testing.T) { + ctx := context.Background() + d := pgtest.MigratedWith(t, dsnEnv, "vec", declared, + vectorSet("CREATE TABLE item (name text PRIMARY KEY, embedding vector(2) NOT NULL)", "DROP TABLE item")...) + rows := map[string][]float32{ + "aligned": {10, 0}, + "long": {20, 15}, + "close": {1, 0.5}, + } + for name, v := range rows { + if _, err := d.Pool.ExecContext(ctx, "INSERT INTO item (name, embedding) VALUES ($1, $2)", name, pgvector.NewVector(v)); err != nil { + t.Fatalf("insert %s: %v", name, err) + } + } + probe := pgvector.NewVector([]float32{1, 0}) + nearest := map[string]string{"l2": "close", "cosine": "aligned", "inner product": "long"} + + for _, m := range sqlvector.Metrics() { + t.Run(m.Name, func(t *testing.T) { + want, ok := nearest[m.Name] + if !ok { + t.Fatalf("no expected nearest row for metric %q", m.Name) + } + metric, err := vecmetric.ParseMetric(m.Name) + if err != nil { + t.Fatalf("ParseMetric(%q): %v", m.Name, err) + } + q := "SELECT name FROM item ORDER BY embedding " + metric.Operator + " $1 LIMIT 1" + if got := text(t, d.Pool, q, probe); got != want { + t.Errorf("%s nearest to %v = %q, want %q", q, probe.Slice(), got, want) + } + }) + } +} From 08d495367af5f56e2f254ccd4bbb4ede7a6d18f9 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Tue, 24 Nov 2026 19:50:33 -0500 Subject: [PATCH 6/8] pgvector-go: standards review: admin's doc comments reflowed and Verify's names the extension at fault (tests-and-docs, comments); the metric tests fail on an empty or changed metric table (tests-and-docs) --- admin/service.go | 15 ++++++++------- postgres/pgvector/metric_test.go | 6 +++++- postgres/pgvector/vector_live_test.go | 15 +++++++-------- 3 files changed, 20 insertions(+), 16 deletions(-) diff --git a/admin/service.go b/admin/service.go index 0ca66a2..77464c9 100644 --- a/admin/service.go +++ b/admin/service.go @@ -149,10 +149,10 @@ func New(pool *database.DB, db *sqlate.DB, m *migrate.Migrator, c *query.Catalog // Ready reports the schema as the last operation that determined it found // it: every set's history clean and current, and every extension -// declaration matched. Once Start has succeeded, a -// not-ready service re-verifies the schema itself, one probe at a time, at -// most once per five seconds, and bounded by the pool's conn_timeout. A -// true Ready is not re-checked. +// declaration matched. Once Start has succeeded, a not-ready service +// re-verifies the schema itself, one probe at a time, at most once per five +// seconds, and bounded by the pool's conn_timeout. A true Ready is not +// re-checked. func (s *Service) Ready() bool { if s.ready.Load() || !s.started.Load() { return s.ready.Load() @@ -183,8 +183,8 @@ func (s *Service) Ready() bool { // Start refuses an undeclared Options.Seed, brings every extension // declaration and every set to its head (logging the pending extensions and -// migrations first), verifies the seeder's statements, -// and applies the configured seed set; the service is ready once all pass. +// migrations first), verifies the seeder's statements, and applies the +// configured seed set; the service is ready once all pass. func (s *Service) Start(ctx context.Context) error { if s.seed != "" { if err := s.checkState(s.seed); err != nil { @@ -329,7 +329,8 @@ func (s *Service) checkState(state string) error { } // Verify checks that every extension declaration matches the database and -// every set's history is clean and current and, when they are, that the seeder's statements prepare; the error names the set or +// every set's history is clean and current and, when they are, that the +// seeder's statements prepare; the error names the extension, set, or // statement at fault. func (s *Service) Verify(ctx context.Context) error { err := s.migrator.Verify(ctx) diff --git a/postgres/pgvector/metric_test.go b/postgres/pgvector/metric_test.go index aaafda7..14790bc 100644 --- a/postgres/pgvector/metric_test.go +++ b/postgres/pgvector/metric_test.go @@ -10,7 +10,11 @@ import ( ) func TestParseMetric_ResolvesEachMetricByItsName(t *testing.T) { - for _, want := range sqlvector.Metrics() { + metrics := sqlvector.Metrics() + if len(metrics) == 0 { + t.Fatal("sqlate's metric table is empty") + } + for _, want := range metrics { got, err := pgvector.ParseMetric(want.Name) if err != nil { t.Errorf("ParseMetric(%q): %v", want.Name, err) diff --git a/postgres/pgvector/vector_live_test.go b/postgres/pgvector/vector_live_test.go index ff04a0d..70ed2cc 100644 --- a/postgres/pgvector/vector_live_test.go +++ b/postgres/pgvector/vector_live_test.go @@ -60,15 +60,14 @@ func TestLive_EachMetricOrdersItsOwnNearestRow(t *testing.T) { probe := pgvector.NewVector([]float32{1, 0}) nearest := map[string]string{"l2": "close", "cosine": "aligned", "inner product": "long"} - for _, m := range sqlvector.Metrics() { - t.Run(m.Name, func(t *testing.T) { - want, ok := nearest[m.Name] - if !ok { - t.Fatalf("no expected nearest row for metric %q", m.Name) - } - metric, err := vecmetric.ParseMetric(m.Name) + if got := len(sqlvector.Metrics()); got != len(nearest) { + t.Fatalf("sqlate has %d metrics, the test expects a nearest row for %d", got, len(nearest)) + } + for name, want := range nearest { + t.Run(name, func(t *testing.T) { + metric, err := vecmetric.ParseMetric(name) if err != nil { - t.Fatalf("ParseMetric(%q): %v", m.Name, err) + t.Fatalf("ParseMetric(%q): %v", name, err) } q := "SELECT name FROM item ORDER BY embedding " + metric.Operator + " $1 LIMIT 1" if got := text(t, d.Pool, q, probe); got != want { From 8db491e51145b8dce308d5e768c95ff6dd38fc6e Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Tue, 24 Nov 2026 19:54:23 -0500 Subject: [PATCH 7/8] pgvector-go: editor: context and README prose --- README.md | 9 +++++---- context/README.md | 12 ++++++++++-- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 07681a7..673a293 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # go-database go-database is an SQL infrastructure library for Standards Lab's Go Elemental standard. It -holds four things: +holds five things: - the connection pool, with its configuration, lifecycle, and readiness - the database admin service, built over the `sqlate` library @@ -26,9 +26,10 @@ principles: - The base module depends on the standard library, `go-core`, and `sqlate`; the driver enters a consumer's graph only through the `postgres` sub-module, imported once at the composition root. - The `postgres/pgvector` sub-module depends on the standard library and sqlate's - `postgres/pgvector`; its integration tier alone also requires pgvector-go, the base module, and - sqlate's `postgres`, so they enter its `go.mod` as test-only requirements. Importing it is limited the way a provider's is: the composition root, the - migrations, and the packages the application's design documentation declares. + `postgres/pgvector`. Only its integration tier requires pgvector-go, the base module, and + sqlate's `postgres`, so its `go.mod` lists them as test-only requirements. Like a provider, it + is imported only by the composition root, the migrations, and the packages the application's + design documentation declares. - [`sqlate`](https://github.com/standards-lab/sqlate) owns the SQL layer above the pool: statements, sessions, transactions, and the dialect. The composition root wraps the pool this library constructs with `sqlate.Wrap` and the engine's dialect from `sqlate/postgres`, and the diff --git a/context/README.md b/context/README.md index 9cb3302..f508b82 100644 --- a/context/README.md +++ b/context/README.md @@ -3,7 +3,8 @@ go-database is the SQL infrastructure library of Go Elemental, the Standards Lab organization's Go implementation of the Elemental Architecture. It holds the connection pool with its configuration, lifecycle, and readiness; the database admin service over the `sqlate` -library; the general sweeper; and the driver, isolated in the `postgres` provider sub-module. +library; the general sweeper; the driver, isolated in the `postgres` provider sub-module; and the +`postgres/pgvector` sub-module, which resolves a configured pgvector distance metric. The README and each package's `doc.go` document this repository. The [Go Elemental](https://github.com/standards-lab/architecture/blob/main/standards/go-elemental/README.md) standard states the principles it follows. @@ -13,8 +14,15 @@ The README and each package's `doc.go` document this repository. The - **database** (built): the connection pool, with its configuration, lifecycle, readiness, and connectivity sentinels ([doc.go](../doc.go)). - **admin** (built): the database admin service over `sqlate`, which administers every migration - set its migrator runs ([admin/doc.go](../admin/doc.go)). + set its migrator runs and reports every extension declaration in its status and readiness + ([admin/doc.go](../admin/doc.go)). - **sweep** (built): the general sweeper that runs a service's reclaimers ([sweep/doc.go](../sweep/doc.go)). - **postgres** (built): the PostgreSQL provider, which constructs the pool over pgx's `database/sql` adapter ([postgres/doc.go](../postgres/doc.go)). +- **postgres/pgvector** (built): the sub-module whose `ParseMetric` resolves a configured + distance metric into sqlate's metric table, and whose package doc shows pgvector-go used + directly ([postgres/pgvector/doc.go](../postgres/pgvector/doc.go)). +- **integration tier** (built): a compose PostgreSQL with pgvector, and the live tests behind the + `integration` tag that run against it locally through `mise run acceptance` + ([README](../README.md#development)). From b21a0bb4ab1f6c59ad160025b1cd865b7c94da65 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Tue, 24 Nov 2026 19:54:54 -0500 Subject: [PATCH 8/8] pgvector-go: changelogs record v0.13.0 and postgres/pgvector v0.1.0 --- CHANGELOG.md | 7 +++++-- postgres/pgvector/CHANGELOG.md | 5 ++++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 61601ee..f1533c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,10 +3,12 @@ All notable changes to `github.com/standards-lab/go-database` are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). This changelog covers the base module -only; the `postgres` sub-module keeps its own. +only; the `postgres` and `postgres/pgvector` sub-modules each keep their own. ## [Unreleased] +## [v0.13.0] - 2026-11-24 + ### Added - `admin.Status.Extensions` (`extensions` in JSON), one `admin.ExtensionStatus` per extension @@ -417,7 +419,8 @@ depends on the standard library and `github.com/standards-lab/go-core v0.1.0`. so an unknown field or trailing content in a curated seed file fails the decode. Idempotency stays in the load function's SQL, where the conflict target is known. -[Unreleased]: https://github.com/standards-lab/go-database/compare/v0.12.0...HEAD +[Unreleased]: https://github.com/standards-lab/go-database/compare/v0.13.0...HEAD +[v0.13.0]: https://github.com/standards-lab/go-database/compare/v0.12.0...v0.13.0 [v0.12.0]: https://github.com/standards-lab/go-database/compare/v0.11.0...v0.12.0 [v0.11.0]: https://github.com/standards-lab/go-database/compare/v0.10.0...v0.11.0 [v0.10.0]: https://github.com/standards-lab/go-database/compare/v0.9.0...v0.10.0 diff --git a/postgres/pgvector/CHANGELOG.md b/postgres/pgvector/CHANGELOG.md index a397d9b..aa0afc4 100644 --- a/postgres/pgvector/CHANGELOG.md +++ b/postgres/pgvector/CHANGELOG.md @@ -7,6 +7,8 @@ changelog covers this sub-module only; the base module and the `postgres` provid ## [Unreleased] +## [v0.1.0] - 2026-11-24 + ### Added - `ParseMetric` resolves a distance metric name, matched exactly, to its entry in the metric @@ -14,4 +16,5 @@ changelog covers this sub-module only; the base module and the `postgres` provid type. A name outside the table returns an error that wraps `ErrUnknownMetric` and quotes the name. -[Unreleased]: https://github.com/standards-lab/go-database/commits/HEAD/postgres/pgvector +[Unreleased]: https://github.com/standards-lab/go-database/compare/postgres/pgvector/v0.1.0...HEAD +[v0.1.0]: https://github.com/standards-lab/go-database/releases/tag/postgres/pgvector/v0.1.0