diff --git a/README.md b/README.md index 594c2ab..34a2e5a 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,9 @@ SQL templating for Go: authored `.sql` files made dynamic and composable, with a dialect and a conventions linter. `github.com/standards-lab/sqlate` is the base module, and it imports only the standard library. -The PostgreSQL dialect is the `postgres` sub-module and the linter is the `sqlint` sub-module, -each released on its own tags. +The `postgres` sub-module is the PostgreSQL dialect, the `postgres/pgvector` sub-module names +the pgvector extension, and the `sqlint` sub-module is the linter. Each sub-module is released on +its own tags. ## The problem @@ -114,30 +115,42 @@ Three conventions the library keeps are stricter than a reader might expect: advisory lock, the extension statements, and the engine's native forms. Its `pgtest` package gives an integration test its own throwaway database, migrated or empty, dropped when the test ends. +- `postgres/pgvector` (sub-module) names the pgvector extension: its catalog name, `vector`, and + the metric table of the `vector` type, each metric's distance operator and index operator + class. Its `sqlint.toml` exports pgvector's native forms. It imports only the standard + library; its tests take `postgres` for `pgtest`. - `sqlint` (sub-module) is the conventions linter as a package, with the command at `sqlint/cmd/sqlint`. ## Development -The repository is a Go workspace of three modules. Tasks run through +The repository is a Go workspace of four modules. Tasks run through [mise](https://mise.jdx.dev): ```sh mise run check # build, vet, format, fix, tidy, unit tier, lint, sqlint, lint-context, lint-references; writes nothing -mise run currency # report requirements, Go, tools, actions, and images 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, keeping its data mise run db:reset # stop PostgreSQL and drop its data -mise run integration # run the integration tier against the running PostgreSQL +mise run integration # run the integration tier of postgres and postgres/pgvector against the running PostgreSQL mise run acceptance # run db:up and integration, then db:reset whatever the result ``` `compose.yml` runs PostgreSQL on port 5433, beside a service's own on 5432; `POSTGRES_PORT` moves it. The service builds from `compose/postgres/Dockerfile`, whose `FROM` line is its one -image pin and which carries its configuration and health check; `mise run currency` reports a -pin behind its latest. `mise.toml` sets `SQLATE_DSN`, whose port follows the same variable. The -integration tier is not part of CI. +image pin and which carries its configuration and health check. The Dockerfile builds pgvector +from source at `ARG PGVECTOR_VERSION`, the extension's one version pin +([the image](docs/features.md#an-image-with-pgvector)). `mise run currency` reports either pin +when it trails its latest: it compares the `FROM` tag with the image's tags, and the `ARG` with +the highest semver tag of the GitHub repository that the `ADD` line fetches. `mise.toml` sets +`SQLATE_DSN`, whose port follows `POSTGRES_PORT`. + +The integration tier covers two modules, `postgres` and `postgres/pgvector`, each behind the +`integration` build tag. `mise run integration` runs both against the running PostgreSQL, and +`mise run acceptance` starts the compose PostgreSQL, runs both, and drops its data. The tier runs +on a developer's machine, not in CI. The compose PostgreSQL reports healthy once it accepts TCP connections to the app database. The probe goes over TCP, not the socket, because the first start's initialization runs a temporary diff --git a/STANDARDS.md b/STANDARDS.md index a4b16aa..49e61f8 100644 --- a/STANDARDS.md +++ b/STANDARDS.md @@ -3,9 +3,9 @@ The judgement calls the standards-reviewer applies to sqlate, beyond what `mise run check` enforces. - A change that alters documented behavior updates the guide, `README.md` and `docs/`, in the same change. -- `architecture/standards/go-elemental/principles/dependencies.md`: the three modules' `go.mod` files. +- `architecture/standards/go-elemental/principles/dependencies.md`: the four modules' `go.mod` files. - `architecture/standards/go-elemental/principles/tests-and-docs.md`: the doc.go inventory of every package, and the unit tier over `sqltest`. -- `architecture/standards/go-elemental/principles/topology-and-naming.md`: the base module and the `postgres` and `sqlint` sub-modules, and their tags. +- `architecture/standards/go-elemental/principles/topology-and-naming.md`: the base module and the `postgres`, `postgres/pgvector`, and `sqlint` sub-modules, and their tags. - `architecture/standards/go-elemental/principles/release-and-ci.md`: the check, currency, and a changelog per module. - `architecture/standards/go-elemental/principles/dsl-driven-services.md`: `query`, `header`, and every authored `.sql` file, the library's patterns included. - `architecture/standards/go-elemental/principles/baseline-standards.md`: `query`'s guards and projections, which take every name and bound from their caller. diff --git a/compose/postgres/Dockerfile b/compose/postgres/Dockerfile index 95e75de..f43d348 100644 --- a/compose/postgres/Dockerfile +++ b/compose/postgres/Dockerfile @@ -1,6 +1,18 @@ # 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 diff --git a/context/README.md b/context/README.md index c9a3ce2..a20ac6d 100644 --- a/context/README.md +++ b/context/README.md @@ -31,6 +31,10 @@ express. ([sqltest/doc.go](../sqltest/doc.go)). - **postgres** (built): the PostgreSQL dialect sub-module, with `pgtest` for integration tests' throwaway databases ([postgres/doc.go](../postgres/doc.go)). +- **postgres/pgvector** (built): the pgvector extension sub-module. It names the extension's + catalog name, `vector`, and the `vector` type's metric table, exports pgvector's native forms + to sqlint, and proves the extension stage and the per-space index recipe in its own + integration tier ([postgres/pgvector/doc.go](../postgres/pgvector/doc.go)). - **sqlint** (built): the conventions linter sub-module and its command ([sqlint/doc.go](../sqlint/doc.go)). - **Dollar-quoted strings in sqlint** (planned): `sqlint` strips PostgreSQL dollar-quoted bodies diff --git a/context/goals/v1.data.extensions.md b/context/goals/v1.data.extensions.md index 0019a68..4eaa040 100644 --- a/context/goals/v1.data.extensions.md +++ b/context/goals/v1.data.extensions.md @@ -8,114 +8,148 @@ 1. [x] extension-stage 2. [x] sqlint-extensions -3. [ ] pgvector-sql +3. [x] pgvector-sql 4. [ ] pgvector-go 5. [ ] principles -## Task brief · sqlint-extensions +## Task brief · pgvector-sql **Problem** -sqlint keeps native forms out of standard-tier files only for the configured engine. When a module -uses a Postgres extension such as pgvector, nothing stops that extension's operators, types or -functions from appearing in a standard-tier file, so the file passes as portable when it isn't. -The goal needs an `extensions` key whose listed modules add their native forms to the engine's deny -list. A listed module must either declare its forms or give a reason why it has none; otherwise it -is refused. pgvector-sql then builds the first such module, and it needs postgres's extension -capability and `pgtest.MigratedWith` released, built against sqlate v0.8.0. +The extension stage and sqlint's `extensions` key exist, but no extension module uses them yet. +pgvector, the first case, needs four things: + +- a module that names its native forms, its catalog name and its metrics; +- an image that builds it from source, with a pin that currency watches; +- live proof against that image that the stage manages it and that the per-space partial HNSW + index works; +- a real export that sqlint's key resolves, so that sqlint can be released. + +pgvector-go then builds on this module's released metric table. **Behaviors** -1. A module's `sqlint.toml` accepts a top-level `extensions` list of strings. `Load` refuses each of - these, one error line each, beginning `sqlint.toml:`: - - a value that isn't a list of strings; - - an empty entry; - - a repeated entry; - - any `extensions` while `engine` is unset. -2. `Load` accepts `[export] reason`, a string, beside `[export.native_forms]`. It also tells a - `native_forms` table declared empty apart from an absent one. So an extension module's own file, - with `native_forms = {}` and a `reason`, loads clean. -3. Each entry is found the way `engine` is. When its first segment contains a dot it is a module - path, resolved through the `Resolver` to the version go.mod pins, workspace and replace included. - Otherwise it is a directory of the tree. An entry that doesn't resolve, or that has no - `sqlint.toml`, is a finding against `sqlint.toml` naming `extensions` and the entry, the way a - failed engine lookup is reported today. The rest of the tree is still linted. -4. A listed module is accepted when its export has at least one native form, or an empty - `native_forms` table beside a non-empty `reason`. Anything else is refused, including a missing - table or an empty table with no reason. A refusal is a finding against `sqlint.toml` that names - the entry and says it exports neither native forms nor a reason. A refused module adds no forms, - and the rest of the tree is still linted. -5. An accepted module's forms join the engine's deny list. They are matched exactly where the - engine's are: - - in standard-tier files only; - - in roles whose `native_forms` switch is on, overrides included; - - against code with literals, quoted identifiers and comments stripped. - - Native-tier files are never checked against them. A form whose expression doesn't compile is a - finding against `sqlint.toml` naming the entry and the form, and the module's other forms still - apply. -6. A finding from an extension's form names the listed entry beside the form's name. For example: - `"<=>" (cosine_distance, from ) in a standard-tier file; declare the tier native and name - the port`. The same form name may appear in the engine and in several extensions. Findings from - the engine's forms are unchanged. -7. sqlint never reads the `native:` header. It stays free text, and the guide documents the - convention that a native file using an extension names that extension there - (`native: postgres, pgvector — <=> cosine distance`). -8. postgres and sqlint require sqlate v0.8.0. Each builds, tests and lints with the workspace off. -9. The guide's sqlint section documents: - - the `extensions` key and how entries are found; - - an extension module's export: forms, or an empty table with a `reason`; - - the `Load` refusals and the findings against `sqlint.toml`; - - the extension finding's message; - - the `native:` header convention; - - that review keeps the `extensions` list in step with `migrate.Options.Extensions`, since - sqlint can't read Go values. -10. sqlint's changelog records the key and the v0.8.0 requirement under Unreleased. postgres's - changelog records `v0.9.0`: the additions now under Unreleased, plus the v0.8.0 requirement. +1. A new module, `github.com/standards-lab/sqlate/postgres/pgvector`, with its own `go.mod`, + changelog and `doc.go`. Its package names: + - the extension's catalog name, `vector`; + - the metrics `l2`, `cosine` and `inner product`, mapped to the operators `<->`, `<=>` and `<#>` + and to the opclasses `vector_l2_ops`, `vector_cosine_ops` and `vector_ip_ops`. + + The table covers the `vector` type only and has no distance-function field. The package imports + only the standard library. +2. The module's `sqlint.toml` exports `[export.native_forms]`. Each form is named after pgvector's + own name, so a finding reads `"<=>" (cosine_distance, from )`. The forms are: + - the six distance operators, each named for its function: `<->` l2_distance, `<#>` + negative_inner_product, `<=>` cosine_distance, `<+>` l1_distance, `<~>` hamming_distance and + `<%>` jaccard_distance; + - `vector` only where a type goes (`AS vector`, `vector(`), and `halfvec` and `sparsevec` as bare + words; + - the index methods `hnsw` and `ivfflat` after `USING`; + - the callable functions `l2_distance`, `inner_product`, `cosine_distance`, `l1_distance`, + `hamming_distance`, `jaccard_distance`, `vector_dims`, `vector_norm`, `l2_norm`, + `l2_normalize`, `binary_quantize`, `subvector`, `array_to_vector`, `array_to_halfvec` and + `array_to_sparsevec`, each followed by `(`; + - the `hnsw.*` and `ivfflat.*` settings. + + No form matches an unquoted identifier named `vector`, and none matches a portable statement. +3. sqlate's root `sqlint.toml` lists the module under `extensions`, and the root check resolves it + through the committed go.work. The check fails if the module's export is refused or a form + doesn't compile. +4. The compose image is still `FROM postgres:19.0-alpine`. On top of it, the image builds pgvector + from source: + - the version is `ARG PGVECTOR_VERSION`, with a default of the latest tag (0.8.7); + - the source is fetched by `ADD` from pgvector's git repository at `v${PGVECTOR_VERSION}`; + - both `make` and `make install` run with `with_llvm=no`, and `make` also runs with + `OPTFLAGS=""`; + - the build tools are removed in the same layer. + + `pg_available_extensions` then offers `vector` at that version, and the HEALTHCHECK, user and + database are unchanged. +5. Currency also reads Dockerfile ARGs. In each compose Dockerfile, an `ARG _VERSION=` + whose `ADD` line names a GitHub `.git#v${_VERSION}` URL is compared with that + repository's highest semver tag, read from tags rather than releases. A trailing ARG is + reported as `: / -> `, and currency exits non-zero. Other + ARGs are ignored, and a failed lookup fails currency. +6. The module's integration tier, behind the `integration` tag and using `SQLATE_DSN` and + `pgtest`, proves the stage against the image: + - `MigratedWith` and a declaration of `vector` install it at the image's default; + - `Extensions` reports it installed at the default and not pending, and `Verify` passes; + - a removal is refused while a `vector` column depends on the extension, and succeeds once a set + migration drops the column. +7. The same tier proves the per-space recipe on one untyped `vector` column, with a partial HNSW + index per space over a typed cast (`(embedding::vector(n)) `, `WHERE space = `): + - a query that repeats the cast and the space predicate plans an index scan on its space's + index; + - the same query without the cast doesn't use the index; + - an insert of the wrong dimension into an indexed space fails. + + The tier uses enough rows, or a planner setting, that the plan assertion is deterministic, and + every metric in the metric table is exercised through its opclass and operator. +8. `mise run integration` runs the integration tier of both `postgres` and the new module, and + `mise run acceptance` covers both. The check, build, tidy, test and lint tasks include the new + module, and go.work uses it. +9. The guide documents: + - the module: the extension name, the metric table, its forms, and why the root config lists it + although no `Options.Extensions` declares it (a test-only listing); + - the canonical Dockerfile, with its pin and build flags, and that a consumer copies it; + - the currency ARG check; + - the per-space recipe, its repeated cast and its dimension check; + - that the integration tier now covers two modules. +10. The new module's changelog records `v0.1.0`. sqlint's changelog turns Unreleased into `v0.5.0`. **Test seams** -- `sqlint.Load` over configuration text (behaviors 1–2). -- `sqlint.Lint` over `fstest.MapFS` fixture trees. Extension modules are fixtures, found either as - directories of the tree or through a stub `Resolver` keyed by module path (behaviors 3–6). No - pgvector module is needed. +- The module's unit tests: the metric table, and each form, parsed from the module's own + `sqlint.toml` with BurntSushi/toml, matched against a positive and a portable sample + (behaviors 1–2). +- The root check's sqlint run under go.work (behavior 3). +- `mise run currency` against the Dockerfile (behavior 5). +- `pgtest.MigratedWith` and `migrate.Migrator` in the module's integration tier, through + `mise run acceptance` (behaviors 4, 6 and 7). **Slices** -1. Upgrade sqlate: postgres and sqlint move from sqlate v0.7.0 to v0.8.0. postgres's changelog gets - its `v0.9.0` entry and sqlint's gets the requirement under Unreleased. Done when a fresh - `mise run currency` exits 0 (rerun it, since the Go proxy's version list lags new tags) and the - check passes. -2. The `extensions` key in `Load`: the list, its refusals, `extensions` without `engine`, and - `[export] reason` with an empty `native_forms` table. Unit tests, and the guide's configuration - block and prose. -3. Lookup and the deny list in `Lint`: - - entries found as module paths or directories; - - lookup failures and refused modules reported against `sqlint.toml`; - - accepted forms joining the deny list in standard-tier files only; - - bad expressions reported; - - the finding naming the entry. - - Unit tests over fixture modules, the guide's checks and the `native:` header convention, and - sqlint's changelog under Unreleased. +1. The module, its export and the root listing. + - The package, with the extension name and the metric table. + - The `sqlint.toml` forms, with unit tests. + - go.work, the module list in the mise tasks, and the root `extensions` entry. + - The guide's module and forms prose, and the changelog entries for the module and sqlint. + + Done when the check passes with the module listed. +2. The image and its currency. + - The Dockerfile builds pgvector 0.8.7 from source. + - currency.sh gains the generic ARG check. + - The guide's Dockerfile and currency prose. + + Done when `mise run db:up` offers `vector` 0.8.7, currency exits 0, and lowering the ARG default + by hand makes currency report pgvector trailing. +3. The live proof. + - The module's integration tier proves the stage and the per-space recipe; its `go.mod` requires + `postgres` v0.9.0. + - `mise run integration` runs both modules. + - The guide's recipe and integration prose. + + Done when `mise run acceptance` passes and the check passes. **Out of scope** -- The `sqlate/postgres/pgvector` module, its forms, and any `extensions` entry in sqlate's own - configuration. pgvector-sql does these. -- Checking `extensions` against `migrate.Options.Extensions`. -- Enforcing extension names in the `native:` header. -- Requiring an engine to export native forms. An engine with none still yields an empty list. -- Releasing sqlint, and stripping dollar-quoted bodies before matching. +- go-database's helpers, compose stack and integration tier (pgvector-go). +- `halfvec`, `sparsevec`, `bit` and `l1` in the metric table, and any distance function or score + conversion in the API. +- Forms for vector arithmetic and for `avg` and `sum` over vectors, which no expression can tell + apart from core SQL. +- Upgrading the ARG in `mise run upgrade`, as with the `FROM` line. +- An integration job in CI. Vetting and linting the integration suites under their tag. +- Releasing `postgres` or the base module, neither of which changes. **Door** -One-way for the `postgres/v0.9.0` tag. Once it is pushed, postgres's `ExtensionCatalog` methods -and `pgtest.MigratedWith` are public at that version, requiring sqlate v0.8.0. sqlint's -`extensions` key, the export's `reason`, and the finding format merge unreleased. They stay two-way -until pgvector-sql releases sqlint. +One-way for both tags. Once `sqlint/v0.5.0` is pushed, the `extensions` key, `[export] reason` +and the extension finding format are public. Once `postgres/pgvector/v0.1.0` is pushed, the +extension name, the metric table and the exported forms are public. The Dockerfile, the currency +check and the tests stay two-way. **Release** -`postgres/v0.9.0` +`sqlint/v0.5.0`, `postgres/pgvector/v0.1.0` ## Decisions @@ -123,14 +157,16 @@ until pgvector-sql releases sqlint. built from source, pgvector pinned by `ARG PGVECTOR_VERSION`. Rejected: pgvector/pgvector's Debian images, PGDG on Debian, and a version declared in Go. - plan: Shipped migration sets declare no extensions; only the application does. -- plan: Module paths `sqlate/postgres/pgvector` and `go-database/postgres/pgvector`; the latter uses - pgvector-go's root module over `database/sql` and depends on the former's metric table. +- plan: go-database's module is `go-database/postgres/pgvector`. It uses pgvector-go's root module + over `database/sql` and depends on `sqlate/postgres/pgvector`'s metric table. - extension-stage: A removed declaration still installed is pending: `Verify` unwraps to `ErrPending` and `Extensions` marks it pending, so `admin.Status` reports it not `Ready`. -- sqlint-extensions: sqlint stays unreleased; pgvector-sql's Release line adds `sqlint/v0.5.0` - once pgvector's real forms have exercised the key. - sqlint-extensions: rejected sqlfluff and squawk, which lint against a fixed dialect and can't read a module's exported deny list. +- pgvector-sql: go-database copies sqlate's canonical `compose/postgres/Dockerfile` and the ARG + check in `scripts/currency.sh`. +- pgvector-sql: an extension module's live proof runs in its own module's integration tier, with + that module requiring `postgres` for `pgtest`. The engine module never requires its extensions. ## Pending edits @@ -147,3 +183,15 @@ until pgvector-sql releases sqlint. - coordinator · `context/postgres-extensions.md`, "sqlint": an extension module with no forms declares an empty `[export.native_forms]` table beside `[export] reason`, not `forms = []`; an `extensions` entry is a module path or a directory of the tree. +- coordinator · `context/postgres-extensions.md`, the image build: `make install` also needs + `with_llvm=no`, since the official image's PostgreSQL is built `--with-llvm` (llvm21); the + extension's catalog name is `vector`, not `pgvector`; pgvector publishes git tags but no GitHub + releases, so currency reads tags (`git ls-remote --tags`). +- coordinator · `roadmap/sqlate-test-tier.toml`: create the goal ("sqlate's test-tier + follow-ups", repos `["sqlate"]`), whose summary lists: the check doesn't vet, fix or lint the + `integration`-tagged suites of `postgres` and `postgres/pgvector` with their tag, as + tests-and-docs.md and release-and-ci.md require; sqlate has no CI integration job, and building + pgvector adds about 10 seconds to one; the live tests' `text` helper in + `postgres/migrate_live_test.go` and its copy in `postgres/pgvector` lose a Scan error; + pgvector's forms tests copy sqlint's stripping, and can go through `sqlint.Lint` once + `sqlint/v0.5.0` is tagged. `roadmap/index.toml`: add it to `backlog`. diff --git a/docs/features.md b/docs/features.md index c4ea704..fedf429 100644 --- a/docs/features.md +++ b/docs/features.md @@ -6,8 +6,8 @@ The package documentation (`go doc`) is the reference for each name's exact sign The packages form two layers. The root package is the session layer every statement runs through. `query` and `migrate` are the two capabilities built over it: authored statements, and schema versioning that replaces a third-party migration dependency. `header` is the grammar -both read, `sqltest` is the driver their tests run over, and the two sub-modules are the -engine and the linter. +both read, `sqltest` is the driver their tests run over, and the three sub-modules are the +engine, an extension of the engine, and the linter. ## sqlate: the session layer @@ -571,7 +571,7 @@ role's, every check is on, and no source is registered. # The engine whose export names the native forms, and the pattern sources. engine = "github.com/standards-lab/sqlate/postgres" # Modules whose exported native forms join the engine's; listing any requires an engine. -# extensions = ["github.com/example/sqlate-pgvector"] +# extensions = ["github.com/standards-lab/sqlate/postgres/pgvector"] [sources] sql = "github.com/standards-lab/sqlate" @@ -645,10 +645,11 @@ failures against `sqlint.toml` and lints the rest of the tree with what resolved error; the module's other forms still apply. An accepted module's forms are matched exactly where the engine's are, and a finding from one names -the entry beside the form: `"<=>" (cosine_distance, from github.com/example/sqlate-pgvector) in a -standard-tier file; declare the tier native and name the port`. A name the engine and an extension -both export is matched and reported for each. A native file that uses an extension's syntax names -the extension in its free-text `native:` header, `native: postgres, pgvector — <=> cosine distance`; +the entry beside the form: +`"<=>" (cosine_distance, from github.com/standards-lab/sqlate/postgres/pgvector) in a standard-tier +file; declare the tier native and name the port`. A name the engine and an extension both export +is matched and reported for each. A native file that uses an extension's syntax names the +extension in its free-text `native:` header, `native: postgres, pgvector — <=> cosine distance`; the linter does not read that header, so review checks it. The linter cannot read Go values either, so review keeps the `extensions` list in step with `migrate.Options.Extensions`. @@ -773,3 +774,156 @@ still open on it, such as a started process's pool, is ended rather than holding the drop is retried while the server reports a session still closing. A create that fails is followed by a drop too, since a create that timed out can still finish on the server. The package imports `testing`, so only test files import it. + +## postgres/pgvector: the pgvector extension + +`github.com/standards-lab/sqlate/postgres/pgvector` names what a program needs to know of +pgvector, PostgreSQL's vector similarity extension. It imports only the standard library, so a +module that builds queries over pgvector takes its names without taking a driver. It is tagged +`postgres/pgvector/vX.Y.Z`. + +`pgvector.Extension` is the extension's catalog name, `vector`: the name an application declares +in `migrate.Options.Extensions` and `CREATE EXTENSION` installs. `pgvector.Metrics()` returns +the metric table of the `vector` type, one `Metric` per distance metric, each with its distance +operator and the operator class an HNSW or IVFFlat index builds for it: + +| `Metric` | `Name` | `Operator` | `OpClass` | +|---|---|---|---| +| `L2` | `l2` | `<->` | `vector_l2_ops` | +| `Cosine` | `cosine` | `<=>` | `vector_cosine_ops` | +| `InnerProduct` | `inner product` | `<#>` | `vector_ip_ops` | + +The table covers `vector` only. `halfvec`, `sparsevec`, `bit`, and the L1 metric are left out +until an application's space, described [below](#a-space-per-dimension-on-one-column), needs +them. + +The module's `sqlint.toml` exports pgvector's native forms, for a consumer that lists the module +under sqlint's `extensions`. Each form is named for pgvector's own name for what it matches: + +- the distance operators, named for their functions: `l2_distance` (`<->`), + `negative_inner_product` (`<#>`), `cosine_distance` (`<=>`), `l1_distance` (`<+>`), + `hamming_distance` (`<~>`), and `jaccard_distance` (`<%>`); +- `vector` where a type goes, a cast's `AS vector` before `)` or `[`, and `vector(` with a + dimension; `halfvec` and `sparsevec` anywhere as words; +- `hnsw` and `ivfflat`, the index methods after `USING`; +- the functions, named with `()` so they stay apart from the operators that share their names: + `l2_distance()`, `inner_product()`, `cosine_distance()`, `l1_distance()`, + `hamming_distance()`, `jaccard_distance()`, `vector_dims()`, `vector_norm()`, `l2_norm()`, + `l2_normalize()`, `binary_quantize()`, `subvector()`, `array_to_vector()`, + `array_to_halfvec()`, and `array_to_sparsevec()`, each matched as a call; +- `hnsw.*` and `ivfflat.*`, the extension's settings. + +A column, table, or alias named `vector` matches no form, and neither does a portable statement. +The engine's `cast` form already denies `::vector`. + +sqlate's own `sqlint.toml` lists the module under `extensions` although no `Options.Extensions` +in the repository declares pgvector. The listing is a test: the root check resolves the module +through the committed `go.work`, so the check fails when sqlint refuses the module's export or +a form does not compile. + +### A space per dimension on one column + +An application that stores embeddings of several models, each with its own dimension, keeps them +in one untyped `vector` column and a `space` column naming the model. Each space gets a partial +HNSW index over the column cast to its dimension, with the operator class of its metric: + +```sql +CREATE TABLE item ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + space integer NOT NULL, + embedding vector NOT NULL +); + +CREATE INDEX item_space1_l2 ON item + USING hnsw ((embedding::vector(3)) vector_l2_ops) WHERE space = 1; +CREATE INDEX item_space2_cosine ON item + USING hnsw ((embedding::vector(4)) vector_cosine_ops) WHERE space = 2; +``` + +A query uses a space's index only when it repeats both the cast and the space predicate, and +orders by the cast expression with the metric's operator under a `LIMIT`: + +```sql +SELECT id FROM item WHERE space = 1 ORDER BY embedding::vector(3) <-> $1 LIMIT 5; +``` + +Without the cast, `ORDER BY embedding <-> $1` does not match the index's expression, and the +engine scans the space's rows instead. The cast also checks the dimension: an insert into an +indexed space computes the index's expression, so a vector of the wrong dimension fails with +`expected 3 dimensions` and the row is not written. A space with no index accepts any dimension. + +The operator and the operator class come from the module's metric table, so a program builds +both statements from a `Metric` rather than spelling them. + +### An image with pgvector + +The official PostgreSQL image does not ship pgvector, so sqlate's compose image builds it from +source. `compose/postgres/Dockerfile` is the canonical Dockerfile: a consumer that declares +pgvector copies it to its own `compose/postgres/Dockerfile` and keeps its pins current. + +```dockerfile +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"] +``` + +The image has two pins. `FROM` pins PostgreSQL; `ARG PGVECTOR_VERSION` pins pgvector, and the +`ADD` line fetches pgvector's git repository at the tag `v${PGVECTOR_VERSION}`, so the `ARG` is +the extension's one version source. `pg_available_extensions` then offers `vector` at that +version, and `CREATE EXTENSION vector` installs it. + +The build flags: + +- `with_llvm=no`, on both `make` and `make install`, skips the LLVM bitcode for PostgreSQL's + JIT. The image's PostgreSQL is built with LLVM support, so without the flag `make install` + looks for the matching `clang`, which the Alpine build tools do not provide, and fails. +- `OPTFLAGS=""`, on `make`, drops pgvector's default `-march=native`, so the build does not tie + the image to the CPU of the machine that built it. + +The build tools are installed as a virtual package and removed, with the source, in the same +layer, so the image grows by only the extension, about 5 MB. + +`mise run currency` reads both pins. It compares the `FROM` tag with the image's tags. It +compares an `ARG _VERSION=` whose `ADD` line fetches +`https://github.com//.git#v${_VERSION}` with that repository's highest semver +tag; it reads tags, not GitHub releases, because pgvector publishes no releases. A trailing `ARG` +is reported as `compose/postgres/Dockerfile: pgvector/pgvector 0.8.6 -> 0.8.7` and fails +currency, and a failed lookup fails it too. Currency ignores every other `ARG`. `mise run upgrade` +does not move the `ARG`, so a maintainer raises it by hand. + +### The integration tier + +The module's integration tier, behind the `integration` build tag, runs against the compose +image through `SQLATE_DSN` and `pgtest`, with a throwaway database per test. For the extension +stage, it proves that: + +- a declaration of `pgvector.Extension` in `migrate.Options.Extensions` installs `vector` at the + image's default version, after which `Extensions` reports it current and `Verify` passes; +- a removal is refused while a `vector` column depends on the extension, and succeeds once a set + migration drops the column. + +For the per-space recipe, with one space per metric of the table, it proves that: + +- a query that repeats the cast and the space predicate plans an index scan on its space's index; +- the same query without the cast uses none of the indexes; +- an insert of the wrong dimension into an indexed space fails. + +`mise run integration` runs this tier with the `postgres` module's, and `mise run acceptance` +starts the compose PostgreSQL, runs both tiers, and drops its data. diff --git a/docs/glossary.md b/docs/glossary.md index 505a272..5a33f37 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -123,8 +123,8 @@ text. - **Producer**: a module, or a directory with its own `sqlint.toml`, whose `[export]` table declares what a consumer reads from it: a pattern directory, an overlay directory, native forms. -- **Native form**: one entry of the deny list an engine exports: a regular expression, keyed - by a name, that detects one of the engine's native operations in a standard-tier file. A - match fails the linter under that name. +- **Native form**: one entry of the deny list an engine or an extension exports: a regular + expression, keyed by a name, that detects one of that engine's or extension's native operations + in a standard-tier file. A match fails the linter under that name. - **Finding**: one convention a file fails: the path, the line when the check has one, and the message. diff --git a/go.work b/go.work index 901d496..59e4c00 100644 --- a/go.work +++ b/go.work @@ -3,5 +3,6 @@ go 1.27 use ( . ./postgres + ./postgres/pgvector ./sqlint ) diff --git a/mise.toml b/mise.toml index 2e5802c..a02f646 100644 --- a/mise.toml +++ b/mise.toml @@ -10,7 +10,7 @@ jq = "1.8.2" "aqua:google/go-containerregistry" = "0.22.1" [env] -GO_MODULES = ". postgres sqlint" +GO_MODULES = ". postgres postgres/pgvector sqlint" SQLATE_DSN = "postgres://app:app@127.0.0.1:{{ get_env(name='POSTGRES_PORT', default='5433') }}/app?sslmode=disable" [tasks.check] @@ -46,7 +46,7 @@ exit "$fail" ''' [tasks.currency] -description = "Report every requirement, Go version, tool, action pin, and image tag 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] @@ -123,8 +123,14 @@ done ''' [tasks.integration] -description = "Run the integration tier against the PostgreSQL named by SQLATE_DSN" -run = "cd postgres && go test -race -tags integration -count=1 ./..." +description = "Run the integration tier of postgres and postgres/pgvector against the PostgreSQL named by SQLATE_DSN" +run = ''' +set -e +for mod in postgres postgres/pgvector; do + echo "==> integration: $mod" + (cd "$mod" && go test -race -tags integration -count=1 ./...) +done +''' [tasks.acceptance] description = "The one-shot engine proof: db:up, integration, then db:reset regardless of the result, printing the stack's log on failure" diff --git a/postgres/pgvector/CHANGELOG.md b/postgres/pgvector/CHANGELOG.md new file mode 100644 index 0000000..07ccf9a --- /dev/null +++ b/postgres/pgvector/CHANGELOG.md @@ -0,0 +1,31 @@ +# Changelog + +All notable changes to the pgvector extension module +(`github.com/standards-lab/sqlate/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 PostgreSQL dialect keep their own. + +## [Unreleased] + +## [v0.1.0] - 2026-11-24 + +The first release of the pgvector extension module. It imports only the standard library. + +### Added + +- `Extension`, pgvector's catalog name, `vector`. +- `Metric`, with `Name`, `Operator`, and `OpClass`, and the metric table of the `vector` type: + `L2` (`l2`: `<->`, `vector_l2_ops`), `Cosine` (`cosine`: `<=>`, `vector_cosine_ops`), and + `InnerProduct` (`inner product`: `<#>`, `vector_ip_ops`), returned in that order by `Metrics()`. +- `sqlint.toml` exporting pgvector's native forms for sqlint's `extensions` key: the six + distance operators, the `vector` type where a type goes and `halfvec` and `sparsevec` + anywhere, `USING hnsw` and `USING ivfflat`, fifteen functions called by name, and the + `hnsw.*` and `ivfflat.*` settings. + +Requires `github.com/standards-lab/sqlate v0.8.0` and +`github.com/standards-lab/sqlate/postgres v0.9.0` for the integration tier only; the package +imports neither. + +[Unreleased]: https://github.com/standards-lab/sqlate/compare/postgres/pgvector/v0.1.0...HEAD +[v0.1.0]: https://github.com/standards-lab/sqlate/releases/tag/postgres/pgvector/v0.1.0 diff --git a/postgres/pgvector/doc.go b/postgres/pgvector/doc.go new file mode 100644 index 0000000..9432fc7 --- /dev/null +++ b/postgres/pgvector/doc.go @@ -0,0 +1,22 @@ +// Package pgvector names what sqlate needs to know of pgvector, the +// PostgreSQL extension for vector similarity search: +// +// - [Extension], the extension's catalog name, the name an application +// declares to the migrator and CREATE EXTENSION installs +// - [Metric], one distance metric of the vector type: its name, its +// distance operator, and its index operator class +// - [L2], [Cosine], and [InnerProduct], the three metrics +// - [Metrics], the metric table, in that order +// +// The table covers the vector type only. The package imports only the +// standard library, so a module that builds queries over pgvector depends +// on the names here without depending on a driver. +// +// # Native forms +// +// The sqlint.toml beside this file exports pgvector's native forms: its +// distance operators, its types where a type goes, its index methods, its +// functions, and its settings, each a regular expression under the name a +// finding reports. A consumer lists this module under sqlint's extensions +// to deny them in standard-tier files. +package pgvector diff --git a/postgres/pgvector/extension_live_test.go b/postgres/pgvector/extension_live_test.go new file mode 100644 index 0000000..aa6693e --- /dev/null +++ b/postgres/pgvector/extension_live_test.go @@ -0,0 +1,137 @@ +//go:build integration + +package pgvector_test + +import ( + "context" + "errors" + "testing" + + "github.com/standards-lab/sqlate" + "github.com/standards-lab/sqlate/migrate" + "github.com/standards-lab/sqlate/postgres/pgtest" + "github.com/standards-lab/sqlate/postgres/pgvector" +) + +const dsnEnv = "SQLATE_DSN" + +var declared = []migrate.Extension{{Name: pgvector.Extension}} + +func vectorSet(migrations ...migrate.Migration) []migrate.Set { + return []migrate.Set{{Name: "vec", Table: "vec_history", Migrations: migrations}} +} + +var docTable = migrate.Migration{ + Version: 1, Name: "doc", + Up: "CREATE TABLE doc (id integer PRIMARY KEY, embedding vector(3))", + Down: "DROP TABLE doc", Transactional: true, +} + +func text(t testing.TB, db *sqlate.DB, q string, args ...any) string { + t.Helper() + rows, err := db.QueryContext(context.Background(), q, args...) + if err != nil { + t.Fatalf("%s: %v", q, err) + } + defer func() { _ = rows.Close() }() + var s string + if !rows.Next() || rows.Scan(&s) != nil { + t.Fatalf("%s: no row: %v", q, rows.Err()) + } + return s +} + +func installedVersion(t testing.TB, db *sqlate.DB) string { + t.Helper() + return text(t, db, "SELECT COALESCE((SELECT extversion FROM pg_extension WHERE extname = $1), '')", pgvector.Extension) +} + +func imageDefaultVersion(t testing.TB, db *sqlate.DB) string { + t.Helper() + v := text(t, db, "SELECT COALESCE((SELECT default_version FROM pg_available_extensions WHERE name = $1), '')", pgvector.Extension) + if v == "" { + t.Fatalf("the image does not offer %s", pgvector.Extension) + } + return v +} + +func migratorOver(t testing.TB, db *sqlate.DB, sets []migrate.Set, opts migrate.Options) *migrate.Migrator { + t.Helper() + m, err := migrate.New(db, sets, opts) + if err != nil { + t.Fatal(err) + } + return m +} + +func statusOf(t testing.TB, m *migrate.Migrator) migrate.ExtensionStatus { + t.Helper() + got, err := m.Extensions(context.Background()) + if err != nil { + t.Fatalf("Extensions: %v", err) + } + if len(got) != 1 { + t.Fatalf("Extensions = %+v, want one status", got) + } + return got[0] +} + +func TestLive_DeclaredVectorInstallsAtTheImageDefault(t *testing.T) { + ctx := context.Background() + opts := migrate.Options{Extensions: declared} + d := pgtest.MigratedWith(t, dsnEnv, "vec", opts, vectorSet(docTable)...) + db := d.Session() + def := imageDefaultVersion(t, db) + if got := installedVersion(t, db); got != def { + t.Fatalf("vector after MigratedWith is at %q, want the image default %q", got, def) + } + + m := migratorOver(t, db, vectorSet(docTable), opts) + want := migrate.ExtensionStatus{Name: pgvector.Extension, Installed: def, Default: def} + if got := statusOf(t, m); got != want { + t.Errorf("Extensions = %+v, want %+v", got, want) + } + if err := m.Verify(ctx); err != nil { + t.Errorf("Verify: %v", err) + } +} + +func TestLive_RemovedVectorWaitsForItsDependentColumn(t *testing.T) { + ctx := context.Background() + d := pgtest.MigratedWith(t, dsnEnv, "vec", migrate.Options{Extensions: declared}, vectorSet(docTable)...) + db := d.Session() + def := imageDefaultVersion(t, db) + removed := migrate.Options{Extensions: []migrate.Extension{{Name: pgvector.Extension, Removed: true}}} + + blocked := migratorOver(t, db, vectorSet(docTable), removed) + err := blocked.Up(ctx) + extErr, ok := errors.AsType[*migrate.ExtensionError](err) + if !ok || extErr.Extension != pgvector.Extension { + t.Fatalf("Up removing vector under a dependent column = %v, want an *ExtensionError naming vector", err) + } + if !errors.Is(err, sqlate.ErrDependentObjects) { + t.Errorf("Up = %v, want it over sqlate.ErrDependentObjects", err) + } + if got := installedVersion(t, db); got != def { + t.Errorf("vector after the refused removal is at %q, want %q still", got, def) + } + if got := statusOf(t, blocked); !got.Pending || !got.Removed { + t.Errorf("Extensions after the refused removal = %+v, want a pending removal", got) + } + + dropColumn := migrate.Migration{ + Version: 2, Name: "drop embedding", + Up: "ALTER TABLE doc DROP COLUMN embedding", + Down: "ALTER TABLE doc ADD COLUMN embedding vector(3)", Transactional: true, + } + m := migratorOver(t, db, vectorSet(docTable, dropColumn), removed) + if err := m.Up(ctx); err != nil { + t.Fatalf("Up after the column's drop: %v", err) + } + if got := installedVersion(t, db); got != "" { + t.Errorf("vector after Up is at %q, want it dropped", got) + } + if err := m.Verify(ctx); err != nil { + t.Errorf("Verify after the removal: %v", err) + } +} diff --git a/postgres/pgvector/forms_test.go b/postgres/pgvector/forms_test.go new file mode 100644 index 0000000..7b7b598 --- /dev/null +++ b/postgres/pgvector/forms_test.go @@ -0,0 +1,161 @@ +package pgvector_test + +import ( + "maps" + "regexp" + "slices" + "strings" + "testing" + + "github.com/BurntSushi/toml" +) + +var positives = map[string][]string{ + "l2_distance": {"SELECT id FROM items ORDER BY embedding <-> {{probe}}"}, + "negative_inner_product": {"SELECT id FROM items ORDER BY embedding <#> {{probe}}"}, + "cosine_distance": {"SELECT id FROM items ORDER BY embedding<=>{{probe}} LIMIT 5"}, + "l1_distance": {"SELECT id FROM items ORDER BY embedding <+> {{probe}}"}, + "hamming_distance": {"SELECT id FROM items ORDER BY bits <~> {{probe}}"}, + "jaccard_distance": {"SELECT id FROM items ORDER BY bits <%> {{probe}}"}, + + "vector": { + "SELECT CAST({{probe}} AS vector)", + "SELECT CAST({{probe}} AS VECTOR(3))", + "SELECT CAST({{probe}} AS vector[])", + "CREATE TABLE items (id bigint, embedding vector(1536))", + "SELECT id FROM items WHERE embedding = CAST({{probe}} AS vector (3))", + }, + "halfvec": {"CREATE TABLE items (embedding halfvec(3))", "SELECT CAST({{probe}} AS HALFVEC)"}, + "sparsevec": {"CREATE TABLE items (embedding sparsevec(5))"}, + + "hnsw": {"CREATE INDEX ON items USING hnsw (embedding vector_l2_ops)", "CREATE INDEX ON items using HNSW(embedding)"}, + "ivfflat": {"CREATE INDEX ON items USING ivfflat (embedding vector_ip_ops) WITH (lists = 100)"}, + + "l2_distance()": {"SELECT l2_distance(a, b) FROM items"}, + "inner_product()": {"SELECT inner_product (a, b) FROM items"}, + "cosine_distance()": {"SELECT COSINE_DISTANCE(a, b) FROM items"}, + "l1_distance()": {"SELECT l1_distance(a, b) FROM items"}, + "hamming_distance()": {"SELECT hamming_distance(a, b) FROM items"}, + "jaccard_distance()": {"SELECT jaccard_distance(a, b) FROM items"}, + "vector_dims()": {"SELECT vector_dims(embedding) FROM items"}, + "vector_norm()": {"SELECT vector_norm(embedding) FROM items"}, + "l2_norm()": {"SELECT l2_norm(embedding) FROM items"}, + "l2_normalize()": {"SELECT l2_normalize(embedding) FROM items"}, + "binary_quantize()": {"SELECT binary_quantize(embedding) FROM items"}, + "subvector()": {"SELECT subvector(embedding, 1, 3) FROM items"}, + "array_to_vector()": {"SELECT array_to_vector({{values}}, 3, true)"}, + "array_to_halfvec()": {"SELECT array_to_halfvec({{values}}, 3, true)"}, + "array_to_sparsevec()": {"SELECT array_to_sparsevec({{values}}, 5, true)"}, + + "hnsw.*": {"SET hnsw.ef_search = 100", "SET LOCAL hnsw.iterative_scan = relaxed_order"}, + "ivfflat.*": {"SET ivfflat.probes = 10"}, +} + +var portables = []string{ + "SELECT vector FROM items", + "SELECT id, vector AS v FROM items WHERE vector IS NOT NULL", + "SELECT embedding AS vector FROM items", + "SELECT embedding AS vector, id FROM items", + "INSERT INTO items (id, vector) VALUES ({{id}}, {{vector}})", + "INSERT INTO vector (id) VALUES ({{id}})", + "UPDATE items SET vector = {{vector}} WHERE id = {{id}}", + "SELECT vector.id FROM items AS vector", + "SELECT id FROM items WHERE kind = 'vector(3) <=> AS vector USING hnsw' -- l2_distance(a, b)", + `SELECT "vector(3)", "halfvec" FROM items /* SET hnsw.ef_search = 1 */`, + "SELECT id FROM items WHERE a <> b AND c <= d AND e >= f AND g < -h ORDER BY id", + "SELECT count(*) FROM items WHERE a % 2 = 0 AND b ~ 'x' AND c + d > 0", + "CREATE INDEX items_embedding ON items USING btree (embedding)", + "SELECT id, subvectors, vectorize, distance FROM items", +} + +func forms(t *testing.T) map[string]*regexp.Regexp { + t.Helper() + var config struct { + Export struct { + NativeForms map[string]string `toml:"native_forms"` + } `toml:"export"` + } + if _, err := toml.DecodeFile("sqlint.toml", &config); err != nil { + t.Fatal(err) + } + out := make(map[string]*regexp.Regexp, len(config.Export.NativeForms)) + for name, expr := range config.Export.NativeForms { + re, err := regexp.Compile(expr) + if err != nil { + t.Fatalf("native_forms.%s: %v", name, err) + } + out[name] = re + } + return out +} + +func codeOnly(sql string) string { + var b strings.Builder + var quote byte + inBlock := false + for i := 0; i < len(sql); i++ { + switch { + case inBlock: + if strings.HasPrefix(sql[i:], "*/") { + inBlock = false + i++ + } + case quote != 0: + if sql[i] == quote { + quote = 0 + b.WriteByte(sql[i]) + } + case sql[i] == '\'' || sql[i] == '"': + quote = sql[i] + b.WriteByte(sql[i]) + case strings.HasPrefix(sql[i:], "--"): + return b.String() + case strings.HasPrefix(sql[i:], "/*"): + inBlock = true + i++ + default: + b.WriteByte(sql[i]) + } + } + return b.String() +} + +func matching(forms map[string]*regexp.Regexp, sql string) []string { + code := codeOnly(sql) + var names []string + for name, re := range forms { + if re.MatchString(code) { + names = append(names, name) + } + } + slices.Sort(names) + return names +} + +func TestForms_AreTheInventory(t *testing.T) { + got := slices.Sorted(maps.Keys(forms(t))) + want := slices.Sorted(maps.Keys(positives)) + if !slices.Equal(got, want) { + t.Fatalf("native_forms names %v, want %v", got, want) + } +} + +func TestForms_EachMatchesItsSampleAlone(t *testing.T) { + all := forms(t) + for name, samples := range positives { + for _, sql := range samples { + if got := matching(all, sql); !slices.Equal(got, []string{name}) { + t.Errorf("%s matches %v, want [%s]", sql, got, name) + } + } + } +} + +func TestForms_MatchNoPortableStatement(t *testing.T) { + all := forms(t) + for _, sql := range portables { + if got := matching(all, sql); len(got) > 0 { + t.Errorf("%s matches %v, want none", sql, got) + } + } +} diff --git a/postgres/pgvector/go.mod b/postgres/pgvector/go.mod new file mode 100644 index 0000000..63ab2ae --- /dev/null +++ b/postgres/pgvector/go.mod @@ -0,0 +1,18 @@ +module github.com/standards-lab/sqlate/postgres/pgvector + +go 1.27 + +require ( + github.com/BurntSushi/toml v1.6.0 + github.com/standards-lab/sqlate v0.8.0 + github.com/standards-lab/sqlate/postgres v0.9.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 + golang.org/x/sync v0.22.0 // indirect + golang.org/x/text v0.41.0 // indirect +) diff --git a/postgres/pgvector/go.sum b/postgres/pgvector/go.sum new file mode 100644 index 0000000..6829892 --- /dev/null +++ b/postgres/pgvector/go.sum @@ -0,0 +1,32 @@ +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= +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/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/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/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/metric.go b/postgres/pgvector/metric.go new file mode 100644 index 0000000..30aa2e7 --- /dev/null +++ b/postgres/pgvector/metric.go @@ -0,0 +1,28 @@ +package pgvector + +// Extension is pgvector's name in the catalog. +const Extension = "vector" + +// Metric is one distance metric over the vector type: Name is the metric's +// name, Operator the distance operator that orders by it, and OpClass the +// index operator class an HNSW or IVFFlat index builds for that operator. +type Metric struct { + Name string + Operator string + OpClass string +} + +var ( + // L2 is Euclidean distance. + L2 = Metric{Name: "l2", Operator: "<->", OpClass: "vector_l2_ops"} + // Cosine is cosine distance. + Cosine = Metric{Name: "cosine", Operator: "<=>", OpClass: "vector_cosine_ops"} + // InnerProduct is the negative inner product. + InnerProduct = Metric{Name: "inner product", Operator: "<#>", OpClass: "vector_ip_ops"} +) + +// Metrics returns the metric table, L2, Cosine, and InnerProduct, in a +// slice the caller owns. +func Metrics() []Metric { + return []Metric{L2, Cosine, InnerProduct} +} diff --git a/postgres/pgvector/metric_test.go b/postgres/pgvector/metric_test.go new file mode 100644 index 0000000..f2f93f8 --- /dev/null +++ b/postgres/pgvector/metric_test.go @@ -0,0 +1,22 @@ +package pgvector_test + +import ( + "slices" + "testing" + + "github.com/standards-lab/sqlate/postgres/pgvector" +) + +func TestMetrics_ReturnsL2CosineAndInnerProductInOrder(t *testing.T) { + want := []pgvector.Metric{pgvector.L2, pgvector.Cosine, pgvector.InnerProduct} + if got := pgvector.Metrics(); !slices.Equal(got, want) { + t.Fatalf("Metrics() = %v, want %v", got, want) + } +} + +func TestMetrics_ReturnsASliceTheCallerOwns(t *testing.T) { + pgvector.Metrics()[0].Operator = "changed" + if got := pgvector.Metrics()[0]; got != pgvector.L2 { + t.Fatalf("Metrics()[0] = %v after a caller's write, want %v", got, pgvector.L2) + } +} diff --git a/postgres/pgvector/space_live_test.go b/postgres/pgvector/space_live_test.go new file mode 100644 index 0000000..b2020c8 --- /dev/null +++ b/postgres/pgvector/space_live_test.go @@ -0,0 +1,179 @@ +//go:build integration + +package pgvector_test + +import ( + "context" + "database/sql" + "fmt" + "strings" + "testing" + + "github.com/standards-lab/sqlate/migrate" + "github.com/standards-lab/sqlate/postgres/pgtest" + "github.com/standards-lab/sqlate/postgres/pgvector" +) + +const rowsPerSpace = 200 + +type space struct { + id int + dims int + metric pgvector.Metric + index string +} + +func spacesPerMetric() []space { + var spaces []space + for i, m := range pgvector.Metrics() { + id := i + 1 + spaces = append(spaces, space{ + id: id, + dims: i + 3, + metric: m, + index: fmt.Sprintf("item_space%d_%s", id, strings.ReplaceAll(m.Name, " ", "_")), + }) + } + return spaces +} + +func (s space) createIndex() string { + return fmt.Sprintf("CREATE INDEX %s ON item USING hnsw ((embedding::vector(%d)) %s) WHERE space = %d", + s.index, s.dims, s.metric.OpClass, s.id) +} + +func (s space) seed() string { + return fmt.Sprintf("INSERT INTO item (space, embedding) "+ + "SELECT %d, CAST(ARRAY(SELECT sin(g * k) FROM generate_series(1, %d) AS k) AS vector) "+ + "FROM generate_series(1, %d) AS g", s.id, s.dims, rowsPerSpace) +} + +func (s space) nearestWithCast() string { + return fmt.Sprintf("SELECT id FROM item WHERE space = %d ORDER BY embedding::vector(%d) %s $1 LIMIT 5", + s.id, s.dims, s.metric.Operator) +} + +func (s space) nearestWithoutCast() string { + return fmt.Sprintf("SELECT id FROM item WHERE space = %d ORDER BY embedding %s $1 LIMIT 5", + s.id, s.metric.Operator) +} + +func (s space) probe() string { + return vectorLiteral(s.dims) +} + +func vectorLiteral(dims int) string { + parts := make([]string, dims) + for i := range parts { + parts[i] = fmt.Sprintf("%d", i+1) + } + return "[" + strings.Join(parts, ",") + "]" +} + +func perSpaceSet(spaces []space) []migrate.Set { + migrations := []migrate.Migration{{ + Version: 1, Name: "item", + Up: "CREATE TABLE item (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, space integer NOT NULL, embedding vector NOT NULL)", + Down: "DROP TABLE item", Transactional: true, + }} + for _, s := range spaces { + migrations = append(migrations, + migrate.Migration{ + Version: len(migrations) + 1, Name: s.index, + Up: s.createIndex(), Down: "DROP INDEX " + s.index, Transactional: true, + }, + migrate.Migration{ + Version: len(migrations) + 2, Name: s.index + " rows", + Up: s.seed(), Down: fmt.Sprintf("DELETE FROM item WHERE space = %d", s.id), Transactional: true, + }) + } + return vectorSet(migrations...) +} + +func plan(t testing.TB, pool *sql.DB, query, probe string) string { + t.Helper() + ctx := context.Background() + tx, err := pool.BeginTx(ctx, nil) + if err != nil { + t.Fatalf("begin: %v", err) + } + defer func() { _ = tx.Rollback() }() + if _, err := tx.ExecContext(ctx, "SET LOCAL enable_seqscan = off"); err != nil { + t.Fatalf("SET LOCAL enable_seqscan: %v", err) + } + rows, err := tx.QueryContext(ctx, "EXPLAIN "+query, probe) + if err != nil { + t.Fatalf("EXPLAIN %s: %v", query, err) + } + defer func() { _ = rows.Close() }() + var lines []string + for rows.Next() { + var line string + if err := rows.Scan(&line); err != nil { + t.Fatalf("EXPLAIN %s: %v", query, err) + } + lines = append(lines, line) + } + if err := rows.Err(); err != nil { + t.Fatalf("EXPLAIN %s: %v", query, err) + } + return strings.Join(lines, "\n") +} + +func TestLive_QueryRepeatingTheCastScansItsSpaceIndex(t *testing.T) { + spaces := spacesPerMetric() + d := pgtest.MigratedWith(t, dsnEnv, "vec", migrate.Options{Extensions: declared}, perSpaceSet(spaces)...) + for _, s := range spaces { + t.Run(s.metric.Name, func(t *testing.T) { + got := plan(t, d.Pool, s.nearestWithCast(), s.probe()) + if !strings.Contains(got, "Index Scan using "+s.index+" ") { + t.Errorf("plan of %s does not scan %s:\n%s", s.nearestWithCast(), s.index, got) + } + rows, err := d.Pool.QueryContext(context.Background(), s.nearestWithCast(), s.probe()) + if err != nil { + t.Fatalf("%s: %v", s.nearestWithCast(), err) + } + defer func() { _ = rows.Close() }() + n := 0 + for rows.Next() { + n++ + } + if err := rows.Err(); err != nil { + t.Fatalf("%s: %v", s.nearestWithCast(), err) + } + if n != 5 { + t.Errorf("%s returned %d rows, want 5", s.nearestWithCast(), n) + } + }) + } +} + +func TestLive_QueryWithoutTheCastMissesEveryIndex(t *testing.T) { + spaces := spacesPerMetric() + d := pgtest.MigratedWith(t, dsnEnv, "vec", migrate.Options{Extensions: declared}, perSpaceSet(spaces)...) + for _, s := range spaces { + t.Run(s.metric.Name, func(t *testing.T) { + got := plan(t, d.Pool, s.nearestWithoutCast(), s.probe()) + for _, other := range spaces { + if strings.Contains(got, other.index) { + t.Errorf("plan of %s uses %s:\n%s", s.nearestWithoutCast(), other.index, got) + } + } + }) + } +} + +func TestLive_InsertOfTheWrongDimensionIntoAnIndexedSpaceFails(t *testing.T) { + spaces := spacesPerMetric() + d := pgtest.MigratedWith(t, dsnEnv, "vec", migrate.Options{Extensions: declared}, perSpaceSet(spaces)...) + for _, s := range spaces { + t.Run(s.metric.Name, func(t *testing.T) { + _, err := d.Pool.ExecContext(context.Background(), + "INSERT INTO item (space, embedding) VALUES ($1, $2)", s.id, vectorLiteral(s.dims+1)) + want := fmt.Sprintf("expected %d dimensions", s.dims) + if err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("insert of %d dimensions into space %d = %v, want an error containing %q", s.dims+1, s.id, err, want) + } + }) + } +} diff --git a/postgres/pgvector/sqlint.toml b/postgres/pgvector/sqlint.toml new file mode 100644 index 0000000..32f48b4 --- /dev/null +++ b/postgres/pgvector/sqlint.toml @@ -0,0 +1,35 @@ +# See docs/features.md + +[export.native_forms] +l2_distance = '<->' +negative_inner_product = '<#>' +cosine_distance = '<=>' +l1_distance = '<\+>' +hamming_distance = '<~>' +jaccard_distance = '<%>' + +vector = '(?i)\bAS\s+vector\s*[)\[]|\bvector\s*\(\s*\d' +halfvec = '(?i)\bhalfvec\b' +sparsevec = '(?i)\bsparsevec\b' + +hnsw = '(?i)\bUSING\s+hnsw\b' +ivfflat = '(?i)\bUSING\s+ivfflat\b' + +"l2_distance()" = '(?i)\bl2_distance\s*\(' +"inner_product()" = '(?i)\binner_product\s*\(' +"cosine_distance()" = '(?i)\bcosine_distance\s*\(' +"l1_distance()" = '(?i)\bl1_distance\s*\(' +"hamming_distance()" = '(?i)\bhamming_distance\s*\(' +"jaccard_distance()" = '(?i)\bjaccard_distance\s*\(' +"vector_dims()" = '(?i)\bvector_dims\s*\(' +"vector_norm()" = '(?i)\bvector_norm\s*\(' +"l2_norm()" = '(?i)\bl2_norm\s*\(' +"l2_normalize()" = '(?i)\bl2_normalize\s*\(' +"binary_quantize()" = '(?i)\bbinary_quantize\s*\(' +"subvector()" = '(?i)\bsubvector\s*\(' +"array_to_vector()" = '(?i)\barray_to_vector\s*\(' +"array_to_halfvec()" = '(?i)\barray_to_halfvec\s*\(' +"array_to_sparsevec()" = '(?i)\barray_to_sparsevec\s*\(' + +"hnsw.*" = '(?i)\bhnsw\.\w+' +"ivfflat.*" = '(?i)\bivfflat\.\w+' diff --git a/scripts/currency.sh b/scripts/currency.sh index d2bb086..e6bc92f 100755 --- a/scripts/currency.sh +++ b/scripts/currency.sh @@ -3,7 +3,9 @@ # 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. A scan command that fails +# 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" @@ -98,6 +100,29 @@ report_outdated_dockerfile_bases() { 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) @@ -112,4 +137,5 @@ report_outdated_mise_tools report_outdated_actions report_outdated_image_lines report_outdated_dockerfile_bases +report_outdated_dockerfile_args exit "$stale" diff --git a/sqlint.toml b/sqlint.toml index 7dad523..3f390db 100644 --- a/sqlint.toml +++ b/sqlint.toml @@ -1,6 +1,7 @@ # See docs/features.md engine = "postgres" +extensions = ["github.com/standards-lab/sqlate/postgres/pgvector"] [export] patterns = "query/patterns" diff --git a/sqlint/CHANGELOG.md b/sqlint/CHANGELOG.md index 09efbd6..8b76a14 100644 --- a/sqlint/CHANGELOG.md +++ b/sqlint/CHANGELOG.md @@ -7,6 +7,8 @@ changelog covers this sub-module only; the base module keeps its own. ## [Unreleased] +## [v0.5.0] - 2026-11-24 + ### Added - An `extensions` key in `sqlint.toml` lists the modules whose exported native forms join the @@ -113,7 +115,8 @@ The first release of the linter, against `github.com/standards-lab/sqlate v0.1.0 - `cmd/sqlint`, the command: one root argument, findings as `path:line: message`, exit 1 on any finding. -[Unreleased]: https://github.com/standards-lab/sqlate/compare/sqlint/v0.4.0...HEAD +[Unreleased]: https://github.com/standards-lab/sqlate/compare/sqlint/v0.5.0...HEAD +[v0.5.0]: https://github.com/standards-lab/sqlate/compare/sqlint/v0.4.0...sqlint/v0.5.0 [v0.4.0]: https://github.com/standards-lab/sqlate/compare/sqlint/v0.3.0...sqlint/v0.4.0 [v0.3.0]: https://github.com/standards-lab/sqlate/compare/sqlint/v0.2.1...sqlint/v0.3.0 [v0.2.1]: https://github.com/standards-lab/sqlate/compare/sqlint/v0.2.0...sqlint/v0.2.1