Skip to content

feat!: v0.1.0 API — explicit contexts, ErrNotFound, namespaces, batching - #8

Merged
necrophidia merged 10 commits into
mainfrom
v0.1.0-api-hardening
Sep 21, 2026
Merged

necrophidia merged 10 commits into
mainfrom
v0.1.0-api-hardening

Conversation

@necrophidia

@necrophidia necrophidia commented Sep 21, 2026 •

Copy link
Copy Markdown
Member

Reworks dsx for v0.1.0: the contract is now visible in the signatures rather than in the doc comments, and the package has tests for the first time.

Breaking, but mechanical — the compiler finds every call site except the ErrNotFound change, which compiles cleanly and behaves differently. The README carries a full before/after migration table.

Why

Two independent review passes over this branch (security + correctness, three rounds) turned up bugs beyond the API rework. Five were pre-existing and shipped in v0.0.x:

Bug Effect
OpNotIn was "not in"; Datastore spells it "not-in" the operator has never worked
OpIn rejected typed slices []string{...} — the example in our own README — was refused; only []any worked
KeysOnly().Select() returned zero rows, nil error indistinguishable from "no matches"; Datastore skips entity loading for a keys-only query and Select discarded the keys
Upsert(ctx, "", &u) an empty name makes an incomplete key, which Datastore commits as an auto-ID insert — a new duplicate entity on every call, unreachable by name
Count with a rejected filter or out-of-range limit RunAggregationQuery doesn't surface the client's internal query error the way run() does, so the bound was silently dropped and the count taken over more rows than asked for

Plus: GetMulti / UpsertMulti / InsertMultiWithAutoKey never chunked to Datastore's limits, and InsertMultiWithAutoKey discarded the keys of already-committed batches on a later failure — orphaning rows whose server-allocated IDs the caller could never learn.

What changed

API

  • Context moves to the call that performs I/O: Query[T](db, kind) then Select(ctx) / Upsert(ctx, ...) / Delete(ctx). Package helpers take ctx first.
  • Get and GetByKey return ErrNotFound instead of (nil, nil).
  • Connect takes options (WithNamespace, WithCredentialsJSON, WithClientOptions).
  • The package-level Logger / SetLogger are gone. Errors are wrapped with the operation and kind; the caller logs them once, with its own fields. The underlying Datastore and gRPC errors stay reachable via errors.Is / errors.As.
  • ProjectId() / DatabaseId() are now ProjectID() / DatabaseID(). Go capitalises initialisms, and these were the only exported names in the package that didn't; renaming an exported symbol is only cheap in a release that already breaks every call site.
  • Builder methods never return an error — the first problem is recorded and returned by the terminal call. Err() exposes it earlier.
  • New: namespaces (per connection, per request via DB.WithNamespace, per query), and a SelectKeys(ctx) terminal.

Correctness

  • Batch reads, writes and deletes chunk automatically (500 mutations / 1000 lookups).
  • Query-based Delete streams keys, so memory is constant regardless of how many entities match.
  • An empty or incomplete key, and an unknown or out-of-range filter/limit/offset, now fail closed on every path — previously several of these failed open.

Tests (0% → 96.3%)

An in-process fake Datastore gRPC server over bufconn, rather than the emulator: no Docker, runs in CI unchanged, and it asserts what a wrapper library actually does — the shape of the request it builds. Writing these is what found the OpIn and chunking bugs; an operator probe found OpNotIn.

Release workflow

The old job only ever bumped the patch version, so this rewrite would have shipped as v0.0.6. Fixing that took three rounds — at one point the override matched [major] as a substring and our own commit prose describing that marker would have tagged v1.0.0. A tag on proxy.golang.org is immutable, so the logic now lives in .github/scripts/next-version.sh with a 23-case regression suite that CI runs on every PR.

Merging this produces v0.1.0 under squash, merge-commit, or rebase — verified against real clones.

Verification

Check Result
go build, go vet, gofmt -l clean
go vet on 386 / arm / amd64 / arm64 clean
go test -race -count=2, -shuffle=on pass, no flakes
Coverage 96.3%
golangci-lint (20 linters incl. modernize) 0 issues
high-signal set (gocritic,errorlint,gosec,perfsprint,…) 0 issues
go mod tidy no churn — grpc indirect→direct, test-only, same version
shellcheck both scripts clean
next-version_test.sh 23/23

Security pass over the API diff found nothing at ≥8 confidence. It verified tenant isolation empirically — asserting PartitionId.NamespaceId on the wire for all 13 operations, including the non-obvious case where WithNamespace follows a key filter. Credentials never reach an error or a log.

Deliberately not done

  • GetMulti keeps its best-effort zero-value semantics for missing entities; erroring would hurt the common case. Documented, pointing at GetByKey.

Blast radius

Every call site breaks — including db.ProjectId() / db.DatabaseId(), which the compiler will flag. No data migration and no rollout ordering. Upsert with an empty key name now errors where it previously wrote a hidden entity — that is the fix, but any service relying on it will start failing.

🤖 Generated with Claude Code

Phillip Leonardo and others added 8 commits September 21, 2026 16:46
Reworks the public API so that the contract is visible in the signatures
rather than in the doc comments.

BREAKING CHANGES
- Context moves from the builder to the calls that perform I/O:
  Query[T](db, kind) and Select(ctx)/Get(ctx)/Upsert(ctx, ...)/Delete(ctx).
  Package helpers take ctx first, per Go convention.
- Get and GetByKey return ErrNotFound instead of (nil, nil). A missing
  entity was previously indistinguishable from a successful empty result,
  so every caller had to remember a nil check.
- Connect takes options: WithCredentialsJSON, WithNamespace,
  WithClientOptions. The old fourth string parameter left no room to add
  a namespace without another breaking change.
- The package-level Logger and SetLogger are removed. A library should
  not log; errors are now wrapped with the operation and kind, so the
  caller reports them once with its own logger. The underlying Datastore
  and gRPC errors stay reachable through errors.Is/errors.As.
- Pagination misuse reports ErrPaginationConflict rather than an
  unmatchable errors.New, and is detected when the conflicting builder
  method is called, not only at the terminal call.

Fixes
- OpIn and OpNotIn now accept any slice. The documented
  WithFilter("Status", OpIn, []string{...}) was rejected by Datastore,
  which only accepts []any, so the example in the README never worked.
- UpsertMulti, InsertMultiWithAutoKey and GetMulti now chunk to
  Datastore's limits (500 mutations per commit, 1000 keys per lookup).
  They previously sent everything in one request and failed above those
  limits while documenting the caller should split.
- Query-based Delete streams keys from the keys-only query instead of
  loading every match into memory before chunking, so memory use is
  constant regardless of how many entities match.

Adds
- Namespace support: per connection (WithNamespace), per request
  (DB.WithNamespace, a copy sharing the client) and per query
  (QueryBuilder.WithNamespace). It applies to queries and to the keys
  the builder writes, deletes and filters on.
- Deferred build errors. Builder methods record the first problem and
  the terminal call returns it, so a chain stays readable; key filters
  resolve at build time so WithNamespace works anywhere in the chain.
  QueryBuilder.Err() exposes it earlier.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The package had no tests. Rather than depend on the emulator and Docker,
the harness implements the Datastore gRPC service over bufconn and points
a real datastore.Client at it through the real Connect path. That runs
anywhere with no external services and, more importantly, lets the tests
assert the thing a wrapper library actually does: the shape of the
request it builds.

Covers query construction (filters, membership, ordering, limit, offset,
projection, distinct, ancestor, keys-only), namespace propagation to
queries and keys, ErrNotFound, deferred builder errors, pagination
conflicts, cursor round-trips, transactions, error wrapping, and the
batch sizes of every chunked operation.

Writing these found two bugs, fixed in the previous commit: OpIn rejected
ordinary typed slices, and batch operations never chunked.

grpc moves from an indirect to a direct dependency; it is used only by
the tests, and the version is unchanged.

Coverage: 96.2% of statements.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Every example used the old signatures. Adds a before/after migration
table covering each breaking change, documents namespaces, batching and
the sentinel errors, and drops the custom-logging section along with the
logger. The "use WithLimit(1) with Get()" tip is gone because Get now
limits the query itself.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The PR job built and linted but never ran a test, since there were none.
It now runs go test -race with coverage.

The release job only ever bumped the patch version, so a breaking change
would have shipped as a patch release. It now reads [major] or [minor]
from the merged commit message, defaulting to patch.

Enables the modernize, errorlint, perfsprint, prealloc, nilerr and
related linters in .golangci.yml so CI checks what is checked locally.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Correctness
- OpNotIn was defined as "not in" where the Datastore client spells the
  operator "not-in", so every WithFilter(field, OpNotIn, ...) failed. The
  operator has never worked. Found by the security pass probing all eight
  operators against the wire; the new table test covers each one.
- An unknown FilterOperator is now rejected by the builder. Count is the
  dangerous case: RunAggregationQuery does not surface the client's
  internal query error the way run() does, so a filter the client refused
  was silently dropped and the count taken over more rows than asked for.
  It now fails closed, like Select and Delete already did.
- KeysOnly() followed by Select() returned zero entities and a nil error,
  because Datastore skips entity loading for a keys-only query and Select
  discards the keys GetAll returns. A caller could not tell that from "no
  rows matched", and the README advertised it. Replaced with a
  SelectKeys(ctx) terminal that returns the keys.
- InsertMultiWithAutoKey discarded the keys of batches that had already
  committed when a later batch failed. Those entities are durably written
  with server-allocated IDs the caller then had no way to learn. It now
  returns the partial keys alongside the error.
- A typed-nil *datastore.Key or an empty key name in a key filter built an
  incomplete key and silently matched nothing, rather than reporting the
  mistake the way every other bad value does. Both are rejected now.

Determinism and resource use
- UpsertMulti ranged over its map, so batch boundaries - and therefore the
  subset applied when a commit fails - varied per run, and the [%d:%d]
  indices in the error named positions in a randomly ordered slice. Keys
  are now sorted, and the error names the first and last key of the batch.
- SelectWithCursor preallocated the caller's full limit before any row
  arrived, so a limit taken from a request parameter allocated that many
  elements regardless of how many entities matched. Capped at 1024.

Docs
- WithAncestorKey is the one key-carrying input that keeps the namespace
  it was given. The README claimed the namespace applied to every key the
  builder touches; it now states the rule precisely and the ancestor
  example sets the namespace.
- Records the OpNotIn, unknown-operator and cursor-decode behaviour
  changes in the migration notes.

Release workflow
- The bump level was read from [major]/[minor] markers that nothing in
  this repo writes, so this breaking rewrite would have been tagged as
  v0.0.6 - contradicting the README's own migration section. It now reads
  the conventional-commit subject this repo actually uses, maps breaking
  changes to the minor position below v1.0.0, and keeps the markers as an
  explicit override. The convention is documented in the README.
- The newest tag is picked by scanning for an exact vMAJOR.MINOR.PATCH
  rather than trusting the first glob match, so a prerelease tag cannot
  reset the version to v0.0.0, and the tag list is no longer piped to
  head, which under pipefail would fail the step once git is SIGPIPE'd.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Release workflow — two ways this shipped the wrong version
- The explicit override matched a bare marker anywhere in the commit
  message, and two commits on this branch *describe* that marker in their
  prose. GitHub's default squash body concatenates the branch's commit
  messages, so merging this pull request would have tagged v1.0.0 for a
  v0.x library. Verified against the real history before fixing. A module
  proxy tag is immutable, so that one could not have been undone. The
  override is now a whole-line trailer, which prose cannot satisfy.
- The bump was read from the tip commit only, so a merge commit or a
  squash with GitHub's auto-generated title produced a patch bump for a
  breaking change. It now reads every commit since the last release tag,
  and treats the "* subject" lines of a squash body as subjects. All four
  merge strategies were simulated against a real clone and now agree on
  v0.1.0.

Correctness
- Upsert and UpsertMulti accepted an empty key name, which becomes an
  incomplete key, which Datastore commits as an auto-ID insert: a new
  duplicate entity on every call, unreachable by name and invisible to
  GetByKey. Every other entry point already failed closed on this; these
  two were the ones that write durable data. Both now reject it.
- An out-of-range limit or offset sets the Datastore client's internal
  query error and leaves the bound unset. Select surfaces that error but
  RunAggregationQuery does not, so Count silently counted over more rows
  than the caller asked for — the same fail-open as the unknown-operator
  case fixed in the previous commit, reached through a limit parsed from
  a request parameter. Both are range-checked in the builder now.
- A caller-built incomplete key was still accepted in a key filter, alone
  or inside an OpIn slice, and reached the wire as a key value with an
  empty path element. Rejected, matching the empty-string spelling.

Docs
- SelectKeys holds every matching key in memory, unlike the Delete beside
  it, which streams. Says so now, in the doc comment and the README.
- Two comments still spelled the operator "not in", which was the bug the
  previous commit fixed.
- The README stated the namespace rule twice and documented the retired
  marker scheme.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…ested script

Release versioning had now taken three rounds of defects while living as
bash embedded in YAML, where nothing could exercise it. The logic moves to
.github/scripts/next-version.sh with a regression suite beside it that
builds throwaway repositories and asserts the computed version for 23
scenarios, and the PR workflow runs both it and shellcheck. A wrong tag on
the module proxy is immutable, so this is the one part of the change that
cannot be fixed after the fact.

The defects it fixes, all found by executing the script rather than
reading it:
- Harvesting "* subject" lines from a squash body ran over every commit in
  the range, so an ordinary markdown bullet in any commit body could pick
  the release level - the same defect as the prose-matched marker fixed in
  the previous commit, reintroduced by its own fix. Bullets are now read
  only when the range is a single commit, which is what a squash produces.
- A CRLF commit message left a trailing CR that defeated the whole-line
  match on the Release-As trailer, silently discarding an explicit
  instruction. The merge UI submits textarea content without git's message
  cleanup, so this is a real path. CR is stripped at the source.
- BREAKING-CHANGE:, which Conventional Commits treats as a synonym for
  BREAKING CHANGE:, was not recognised, so a breaking change shipped as a
  patch.
- Re-running the workflow with no commits since the last tag computed and
  pushed another patch tag over nothing. It now reports that there is
  nothing to release and skips the tagging step.

Go
- The test for the out-of-range limit guard used math.MaxInt32 + 1 as an
  untyped constant, which does not compile where int is 32 bits: go vet
  and go test failed to build the package on 386, arm and mips. The bound
  is computed from a variable now, and the case skips where int is 32
  bits. Verified on 386, arm, amd64 and arm64.
- datastore.Key.Incomplete only inspects the leaf, so a key whose parent
  was incomplete passed the guard added in the previous commit and reached
  the wire, matching nothing. The whole ancestor chain is checked now, and
  WithAncestorKey - the sibling hole - rejects an incomplete key too.
- WithOffset checked its upper bound before the cursor conflict, so
  combining a cursor with an out-of-range offset no longer matched
  errors.Is(err, ErrPaginationConflict). The specific error comes first.
- WithLimit and WithOffset document their upper bound.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Go capitalises initialisms, and these two accessors were the only exported
names in the package that did not. Renaming an exported symbol forces a
change on every caller, so v0.1.0 — which already breaks every call site —
is the only cheap moment to do it.

Also renames the struct fields and the Connect parameters, which appear in
the godoc signature. revive's var-naming now reports nothing.

Migration is one line per call site and the compiler finds all of them;
the README migration table covers it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@necrophidia

Copy link
Copy Markdown
Member Author

Review — v0.1.0 API hardening

Reviewed the full diff (15 files, +3353/−580) against main, re-ran every check in the PR body, and probed the new API against the branch's own bufconn fake. The verification table holds up — I reproduced all of it, numbers below. The API shape is right, the deferred-error builder is the correct call for a fluent API, and the fake-server tests assert the thing that actually matters for a wrapper (the request that goes on the wire) rather than round-tripping through a mock.

Findings are ordered by severity. Everything marked verified I reproduced locally against pr8.

Should fix

1. Query[T](db, "") is a kindless query, so Delete(ctx) wipes the whole namespace — every kind, not just T. dsx.go:362, dsx.go:1181

datastore.NewQuery("") is a valid kindless query, and nothing on the query path rejects an empty kind. Verified with the branch's own fake — a keys-only response containing one User and one Order key:

Query[testUser](db, "").Delete(ctx)
  → err=<nil>  kindInQuery=[]  deletedKeys=[u1 o1]    # deleted an Order through a Query[testUser]

The write paths already fail closed, because the client refuses the resulting key:

Query[testUser](db, "").Upsert(ctx, "k", &u)        → dsx: upsert /k: datastore: invalid key
Query[testUser](db, "").InsertWithAutoKey(ctx, &u)  → dsx: insert-with-auto-key : datastore: invalid key

but the read paths return an empty, successful result (Select → [], nil; Count → 0, nil), so an empty kind stays invisible until the Delete lands. That is the Upsert(ctx, "", &u) bug from the table one level up — an empty string producing a valid-but-catastrophically-different operation — and it is the one place left where this release does not "fail closed on every path". An empty kind is reachable the ordinary ways: a config value that didn't load, a map lookup miss, a generic kindFor[T]() helper with no registration.

Direction: Query() records a builder error when kind == "". The deferred-error mechanism is already there, so it is three lines and no API change; every terminal then reports it. If kindless queries are ever wanted deliberately, they deserve a named constructor rather than the zero value.

2. OpIn / OpNotIn bounds are not validated locally. dsx.go:710, dsx.go:448

membershipValues checks only that the value is a slice. Verified: both an empty slice and a 31-element slice build a request and reach the server —

WithFilter("Status", OpIn, []string{})        → err=<nil>, RunQuery sent
WithFilter("Status", OpIn, [31 values])       → err=<nil>, RunQuery sent
WithFilter(FieldKey,  OpIn, []string{})       → err=<nil>, RunQuery sent

Datastore caps IN/NOT_IN at 30 values and rejects an empty list, so both come back as an INVALID_ARGUMENT worded in Datastore's terms, from a library that otherwise validates operator spelling, MaxInt32 limits, incomplete keys and empty key names locally with its own message. The empty case is the one callers hit by accident — an IN filter built from a request slice that happened to be empty — and it means "match nothing", so failing closed is also the semantically honest answer.

Minor

3. One class of client-side query error still slips past Count. dsx.go:814, dsx.go:608

The PR closes this for filter operators, and I confirmed the filter paths are now tight (WithFilter("", …) and a bad value type both fail closed on Count, Select, SelectKeys, Delete). Orders are still asymmetric — verified:

Query[testUser](db,"User").WithOrder("").Count(ctx)   → 0, nil    (aggregation sent, order dropped)
Query[testUser](db,"User").WithOrder("").Select(ctx)  → dsx: select User: datastore: empty order
Query[testUser](db,"User").WithOrder("").Delete(ctx)  → dsx: delete User: scan keys: datastore: empty order

Impact today is small — an order cannot change a COUNT — but it is the same asymmetry the release set out to close, and it means a typo'd order string is silent on the count path and fatal on the select path. A WithOrder/WithOrderDesc guard on an empty field name would finish the claim.

4. RunInTransaction drops the *datastore.Commit. dsx.go:1298

tx.Put on an incomplete key returns a PendingKey that can only be resolved through commit.Key(pendingKey), so an auto-ID insert inside a transaction is unusable through dsx — the caller has to drop to db.Client(). This is the same failure as the InsertMultiWithAutoKey fix in this PR (keys the caller can never learn), and it is pre-existing, but the signature is already breaking here, which is the only cheap moment to return the commit.

5. .golangci.yml:26-28 still excludes gosec G115, and no longer needs to. Verified: golangci-lint run --no-config --default=none --enable=gosec --max-issues-per-linter=0 --max-same-issues=0 ./... → 0 issues. The new code does its own explicit math.MaxInt32 bounds checks, which is exactly the conversion G115 audits, so the exclusion now only guarantees that the next genuine overflow lands silently. This file is rewritten by the PR, so it is the moment to drop it.

6. release.yml tags and publishes without running the suite. .github/workflows/release.yml:3-11

on: push: branches: [main] goes straight to next-version.sh → git tag → gh release create. pr.yml only guards pull requests, so a direct push to main, or a merge where the check was not required, publishes an immutable proxy.golang.org tag from code nothing verified. Given the PR body's own point about tag immutability, either needs: a build/test job here or require the PR check in branch protection.

7. A Release-As: trailer with trailing whitespace is silently ignored. .github/scripts/next-version.sh:76-80

grep -qxE 'Release-As: major' is a full-line match. Verified with a real repo: a message ending Release-As: major (one trailing space — the GitHub merge UI produces these, and the CRLF case shows the same class of input noise was already anticipated) falls through to the conventional-commit path and prints Bumping v0.0.5 -> v0.0.6 (patch). It fails in the safe direction, but silently, and the result is an immutable tag. Direction: tolerate surrounding whitespace, and warn on stderr when a ^Release-As: line is present but matches no level.

8. Write terminals silently ignore the query state on the builder. dsx.go:1007, dsx.go:1080

Verified: Query[testUser](db,"User").WithFilter("Status", OpEqual, "active").WithLimit(5).Upsert(ctx, "k", &u) issues one commit with one mutation — the filter and limit are dropped. Filters, orders, limits and cursors are meaningless for Upsert/UpsertMulti/InsertWithAutoKey, but the builder accepts them, and the chain reads like a conditional update. A doc line on the write terminals is probably the right size of fix here; splitting the writer off the query builder is a bigger change than this release needs.

9. Goroutine-safety isn't stated. DB is safe for concurrent use (it wraps a thread-safe datastore.Client and WithNamespace returns a copy); QueryBuilder is mutable and is not. Neither is in the godoc, and for a library that is the kind of thing callers guess wrong.

10. pr.yml pins golangci-lint-action@v7 with version: latest. A linter release can turn CI red on an unrelated PR; pinning to the version the repo was validated against is the usual trade.

Verified independently

Claim Result
go build, go vet, gofmt -l clean
go test -race -count=1 pass, coverage 96.3% exactly as claimed
golangci-lint with the repo config 0 issues
modernize alone 0 issues
gosec alone, no excludes 0 issues (hence finding 5)
shellcheck 0.11.0, both scripts clean (run via npx, not installed locally)
next-version_test.sh 23/23
go.mod churn exactly grpc indirect→direct, same version

Spot-checked the fixes rather than taking the table on trust: Count carries the builder's limit on the wire (nested_query.limit: 10); OpIn accepts a typed slice; SelectKeys returns keys with the right namespace; Upsert/UpsertMulti reject an empty key name; every package helper rejects an empty name too (datastore: can't get/delete the incomplete key); a nil *T in UpsertMulti yields a wrapped error, not a panic; chunk boundaries come out 500/500/200 and 1000/1000/500. The uncovered 3.7% is error branches only. Examples carry no // Output: so they compile without dialling out in CI — deliberate, worth keeping that way.

I did not re-run the security pass's 13-operation namespace sweep; the namespace tests in the branch cover the same ground and pass, including WithNamespace after a key filter.

No sign-off yet — finding 1 is the one I would want closed before merge, given the terminal it affects.

Should fix
- Query[T](db, "") built a kindless query, which matches every entity of
  every kind: Select and Count quietly returned rows from outside T, and
  Delete removed the whole namespace through a builder that names one
  type. Reproduced before fixing - a Query[testUser] deleted an Order.
  This was the last place an empty string produced a valid but
  catastrophically different operation, after the Upsert(ctx, "", ...) fix
  earlier in this branch. Query now records a builder error, so every
  terminal reports it and nothing reaches the server.
- An empty OpIn / OpNotIn slice reached the server, where Datastore
  rejects it in its own terms. A filter that can match nothing is more
  often a slice that did not get populated than a deliberate query, so it
  fails closed here now. The 30-value cap is a service limit rather than a
  permanent invariant, so it stays with Datastore and is documented rather
  than duplicated, where raising it later cannot make dsx reject a valid
  query.

Minor
- An empty order field, and an empty or absent projected field, were
  dropped silently by Count while Select failed - the same asymmetry the
  operator guard closed earlier, since RunAggregationQuery does not
  surface the client's internal query error.
- RunInTransaction returns the *datastore.Commit. Without it the
  PendingKey from an auto-ID insert inside a transaction can never be
  resolved, so that case was unusable without dropping to db.Client().
  Same failure as the InsertMultiWithAutoKey fix earlier in this branch,
  and the signature is already breaking here.
- gosec's G115 exclusion is dropped: the code now bounds-checks its
  int conversions explicitly, which is what G115 audits, so the exclusion
  only served to hide the next real overflow. gosec reports 0 issues
  without it.
- The release workflow tagged and published without running anything. A
  push to main can bypass the pull request checks, and the tag is
  immutable on proxy.golang.org, so tagging now needs a verify job that
  builds, tests, lints and runs the release suite. Write permission is
  scoped to the release job rather than the workflow.
- A Release-As trailer with surrounding whitespace was silently ignored,
  and an unreadable level said nothing at all. Whitespace is tolerated and
  an unrecognised level warns on stderr.
- golangci-lint-action is pinned to the version this repo is validated
  against; `latest` lets a linter release turn an unrelated PR red.

Docs
- DB is safe for concurrent use, QueryBuilder is not, and the write
  terminals ignore the filters, ordering and pagination on the builder
  since they address entities by key. All three are now in the godoc and
  the README rather than left for callers to guess.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@necrophidia

Copy link
Copy Markdown
Member Author

Thanks — finding 1 is a real data-loss path and I reproduced it before touching anything:

Query[testUser](db, "").Delete(ctx)
  → err=<nil>  kindInQuery=[]  DELETED KEYS: [u1 o1]

An Order deleted through a Query[testUser]. All ten findings are addressed in 329a803.

Should fix

1. Empty kind — fixed. Query() records a builder error when kind == "", so every terminal reports it and nothing reaches the server. You were right that this is the same shape as the Upsert(ctx, "", &u) bug one level up; it was the last place an empty string produced a valid-but-different operation. TestEmptyKindIsRejected covers all seven terminals and asserts zero queries, commits and aggregations.

2. Membership bounds — empty list fixed; the 30-value cap deliberately not enforced. Empty now fails closed on every path, including FieldKey, and I agree that "match nothing" makes failing closed the honest answer.

I left the upper bound to Datastore, and I think this one is a real distinction rather than inconsistency. The other local checks you list — operator spelling, MaxInt32, incomplete keys, empty key names — are permanent invariants; they cannot become wrong. The 30-value cap is a service limit, and it has already moved once (10 → 30). If Google raises it again, a hardcoded check here turns a valid query into a client-side error that the caller cannot work around except by not using dsx. A server-side INVALID_ARGUMENT naming the actual limit degrades better than a stale local one. It's documented on WithFilter instead. Happy to add it if you'd rather have the symmetry — it's a two-line change.

Minor

3. Empty order — fixed, and extended to WithProject (empty field, and no fields at all), which has the same asymmetry. Verified Count now fails where it previously returned 7, nil.

4. RunInTransaction returns the commit — fixed. (*datastore.Commit, error). You're right that this is the same class as the InsertMultiWithAutoKey fix and that this release is the only cheap moment. Added ExampleRunInTransaction_autoID showing the commit.Key(pending) resolution, plus a README section.

5. G115 — dropped. Confirmed gosec alone with no excludes reports 0 issues.

6. Release workflow — fixed. Tagging now needs: a verify job that builds, vets, tests with -race, lints, shellchecks and runs the versioning suite. Also scoped contents: write to the release job instead of the whole workflow; the verify job only needs read. Branch protection is still worth having, but the workflow no longer depends on it.

7. Trailer whitespace — fixed. ^[[:space:]]*Release-As:[[:space:]]*<level>[[:space:]]*$, and a Release-As: line whose level isn't one of the three now warns on stderr instead of silently falling through. Three cases added to the suite (trailing space, surrounding whitespace, unreadable level) — 26/26.

8, 9. Write terminals and goroutine safety — documented. Agreed that splitting the writer off the builder is bigger than this release needs. Both are now on the types in godoc, repeated on each write terminal where they'll actually be read, and in a new README section.

10. Linter pinned to v2.13.2, the version the repo is validated against.

Re-verified after the changes

Check Result
go build, go vet, gofmt -l clean
go vet on 386 / arm / amd64 / arm64 clean
go test -race -count=2 pass, coverage 96.8% (was 96.3%)
golangci-lint, repo config without the G115 exclusion 0 issues
gosec alone, no excludes 0 issues
high-signal set 0 issues
shellcheck, both scripts clean
next-version_test.sh 26/26
next-version.sh against this branch v0.1.0

One correction to the PR body you reviewed: it claimed the release "fails closed on every path", which finding 1 shows wasn't true at the time. It is now, and the README's behaviour-change list names the empty-kind and empty-clause rejections explicitly so callers aren't surprised.

@necrophidia

Copy link
Copy Markdown
Member Author

Round 2 — 329a803

Re-reviewed the fix commit against cf3638c and re-ran everything. Nine of the ten findings are closed, and I accept the pushback on the tenth. One new finding, and it is mine: the trailer fix I asked for in finding 7 reintroduced the failure it was meant to prevent.

New — fix before merge

11. The Release-As: whitespace fix made an indented trailer live again. .github/scripts/next-version.sh:76-85

^[[:space:]]*Release-As:[[:space:]]*major[[:space:]]*$ now matches a trailer that is indented, which is how anyone documents a trailer inside a commit body. Verified — the same docs commit against both versions of the script:

docs: document the release convention

To force a release level, add the trailer on its own line:

    Release-As: major

Otherwise the level comes from the commit subjects.
329a803   → Bumping v0.0.5 -> v1.0.0 (major)
cf3638c   → Bumping v0.0.5 -> v0.0.6 (patch)     # the version I reviewed

So a docs: commit explaining the release convention now cuts v1.0.0, immutably. That is the "our own commit prose describing the marker would have tagged v1.0.0" failure from the PR body, back through a different door — and my suggestion opened it, so the miss is on me: I asked for whitespace tolerance without bounding which whitespace.

Git agrees that the indented form is not a trailer: printf 'docs: x\n\n Release-As: major\n' | git interpret-trailers --parse prints nothing. Direction — anchor the start and keep the rest of the tolerance:

^Release-As:[[:space:]]*major[[:space:]]*$

Verified against the four forms: Release-As: major, Release-As: major··· and Release-As:···major all match; ····Release-As: major and a tab-indented one do not.

Two follow-ons: the warning branch at :82 wants the same anchor, or an indented mention will start warning about a trailer that was never one. And case p2 at next-version_test.sh:121-124 pins exactly the behaviour that causes this — " Release-As: minor " expecting v0.1.0 — so it should flip to asserting that an indented trailer is inert, with the docs-commit body above as the case. That keeps the suite honest about the distinction rather than just the character class.

This does not affect the tag for this PR: no commit in the branch carries a trailer-like line, and next-version.sh still prints v0.1.0 for it under all three merge strategies.

Nit

12. The new clause guards test for "" exactly, so whitespace still slips past Count. dsx.go:633, dsx.go:652

Verified with the fake programmed to return a count of 7:

WithOrder(" ").Count(ctx)   → 7, nil                                  # aggregation sent, order dropped
WithOrder(" ").Select(ctx)  → dsx: select User: datastore: empty order

The client trims before validating, so a whitespace-only field lands in the same asymmetry finding 3 closed for the empty string. strings.TrimSpace(field) == "" in the two order guards and in the WithProject element check closes it. Typo-grade input, entirely optional — I mention it only because the surrounding invariant is now "the builder rejects what Count would drop".

On finding 2 — agreed, no change wanted

Your distinction between a permanent invariant and a service limit is the right one, and the 10→30 precedent settles it: a hardcoded 31st-value rejection would be a dsx bug the moment Google raises the cap again, with no way for a caller to route around it. A server-side INVALID_ARGUMENT naming the real limit is the better failure. Documenting it on WithFilter is the right amount. Dropping this one.

Verified fixed

# Finding Check
1 Empty kind Query() records the error; verified all ten terminals fail closed with 0 queries, 0 commits, 0 aggregations — your TestEmptyKindIsRejected covers six, and I confirmed SelectWithCursor, UpsertMulti, InsertWithAutoKey and InsertMultiWithAutoKey behave the same through the qb.err short-circuit
2 Empty membership list fails closed on typed, []any, nil and FieldKey variants; populated slices unaffected
3 Count swallowing clause errors empty order, order-desc, projected field and no-field projection all fail closed now (modulo finding 12)
4 RunInTransaction returns (*datastore.Commit, error); migration table, README and both examples updated consistently
5 G115 exclusion gone; gosec alone → 0 issues
6 Release gate release needs: verify; verified the parsed workflow: workflow-level contents: read, contents: write scoped to the release job only
7 Trailer whitespace fixed, but see finding 11
8, 9 Write-terminal semantics, goroutine safety on both types, on each write terminal, and in a new README section
10 Linter pin v2.13.2 in both workflows

Re-ran the whole suite on 329a803: go build / go vet / gofmt -l clean; go test -race -count=2 passes at 96.8% coverage, matching your table; golangci-lint with the repo config → 0 issues; gosec with no excludes → 0 issues; shellcheck 0.11.0 on both scripts → clean; next-version_test.sh → 26/26; next-version.sh on this branch → v0.1.0.

One structural note, not a finding: verify in release.yml and build-and-lint in pr.yml are now the same seven steps in two places and will drift. A workflow_call reusable workflow would collapse them, but that is a change for a quieter PR than this one.

Finding 11 is the only thing I would hold the merge for.

11. The whitespace tolerance added in the previous commit made an indented
    Release-As: live again, which is exactly how a commit body documents
    the convention - so a docs commit explaining the trailer would have cut
    v1.0.0, immutably. Reproduced against both commits before fixing:

      329a803  docs commit with an indented trailer -> v1.0.0 (major)
      cf3638c  same commit                          -> v0.0.6 (patch)

    This is the "our own prose describing the marker tags a release"
    failure from earlier in this branch, back through a different door.
    The pattern is anchored at the start of the line now, which is also
    what git's own trailer parsing requires: `git interpret-trailers
    --parse` reads nothing from the indented form. Whitespace after the
    colon and at the end of the line is still tolerated, since that is the
    noise the merge UI actually produces.

    The warning branch is anchored the same way, so an indented mention no
    longer warns about a trailer that was never one. The test that pinned
    the offending behaviour now asserts the opposite, with the docs-commit
    body as its input, plus a tab-indented case. 28/28.

12. The clause guards compared against "" exactly, but the Datastore
    client trims before validating, so a whitespace-only order or
    projected field stayed in the asymmetry those guards closed: dropped
    silently by Count, fatal in Select. They use strings.TrimSpace now.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@necrophidia

Copy link
Copy Markdown
Member Author

Round 2 reply — ec06c1d

Both fixed. Finding 11 was a good catch and I reproduced it before touching anything — the same docs commit against both scripts:

329a803  docs commit with an indented trailer  → Bumping v0.0.5 -> v1.0.0 (major)
cf3638c  same commit                           → Bumping v0.0.5 -> v0.0.6 (patch)

11. Anchored. ^Release-As:[[:space:]]*<level>[[:space:]]*$. Your point about git interpret-trailers is the right justification and I checked it rather than taking it on trust — the indented form parses to nothing, the unindented one parses to Release-As: major. Anchoring at the start is simply agreeing with git about what a trailer is.

Verified the five forms:

Input Result
Release-As: major match
Release-As: major··· match
Release-As:···major match
····Release-As: major inert
→Release-As: major (tab) inert

The warning branch at :82 got the same anchor, as you flagged — otherwise an indented mention would start warning about a trailer that was never one.

And p2 now asserts the opposite of what it pinned: the docs-commit body from your report is the input, expecting v0.0.6, plus a tab-indented variant. The surrounding-whitespace case stays but with the trailer at column zero, so the suite distinguishes which whitespace is tolerated rather than just asserting a character class. 28/28.

On "the miss is on me" — I'd put it differently. You asked for whitespace tolerance; I implemented it unbounded and shipped it, and the test I wrote for it pinned the wrong behaviour, which is what made it look verified. The suggestion was right and the implementation was mine.

12. Fixed rather than left as a nit, since you're right that the invariant is now "the builder rejects what Count would drop" and a half-true invariant is worse than none. strings.TrimSpace in both order guards and the WithProject element check; the table gained whitespace and tab cases for all three.

Re-verified on ec06c1d

Check Result
go build, go vet, gofmt -l clean
go vet on 386 / arm / amd64 / arm64 clean
go test -race -count=2 pass, coverage 96.8%
golangci-lint, repo config 0 issues
gosec alone, no excludes 0 issues
high-signal set 0 issues
shellcheck, both scripts clean
next-version_test.sh 28/28
next-version.sh on this branch v0.1.0

On the duplicated CI steps

Agreed, and agreed it's for a quieter PR. verify and build-and-lint are the same seven steps and will drift. A workflow_call reusable workflow is the fix; I'd rather not add that indirection to a diff this size, where the release gate is the thing under review. Worth an issue so it doesn't get lost — say the word and I'll open one.

Thanks for both rounds. Finding 1 and finding 11 were each a real path to something unrecoverable, and neither was reachable from the tests I'd written.

@necrophidia

Copy link
Copy Markdown
Member Author

Opened #9 for the duplicated verify / build-and-lint steps, so it does not get lost once this merges.

It records the current state precisely — seven of the eight shared steps are byte-identical, the two differences (-coverprofile and the Coverage step) are deliberate — along with the workflow_call shape, why it is not in this PR, and acceptance criteria. The pinned linter version appearing in both files is called out as the concrete cost.

@necrophidia

Copy link
Copy Markdown
Member Author

Round 3 — ec06c1d: approved

Both findings are closed and I found nothing new. LGTM.

11 — anchored trailer. Verified against nine message shapes, not just the five in your table:

Message Result
Release-As: major v1.0.0
Release-As: major··· (trailing spaces) v1.0.0
Release-As:···major v1.0.0
CRLF trailer v1.0.0
····Release-As: major (the docs-commit body) v0.0.6 — inert
tab-indented v0.0.6 — inert
inline prose mention v0.0.6 — inert
indented example plus a real trailer below it v0.1.0 — the column-zero one wins, the indented one is ignored
column-zero Release-As: enormous v0.1.0 from the subject

The warning branch is right too: it fires for a column-zero trailer with an unreadable level, and stays silent for an indented mention and for a valid trailer — so the message means "your trailer was rejected", never "some prose looked like one".

12 — trim-checked clauses. Verified every whitespace-only form now fails closed on Count with zero aggregations sent: " ", "\t", " " on both order guards, " " as a projected field, and a non-breaking space (strings.TrimSpace covers Unicode, matching what the Datastore client trims). No over-rejection: WithProject("First Name", "Email") and ordinary orders still build and run — an inner space is a legal property name and stays one.

Re-verified on ec06c1d

go build / go vet / gofmt -l clean; go test -race -count=2 passes at 96.8%; -shuffle=on passes; golangci-lint with the repo config → 0 issues; gosec alone, no excludes → 0 issues; shellcheck 0.11.0 → clean; next-version_test.sh → 28/28; next-version.sh on this branch → v0.1.0. Every number in your table reproduces.

Case p2b uses the exact docs-commit body from the report and p2c the tab variant, so the suite now pins which whitespace is tolerated rather than a character class — that is the part that keeps this fix from regressing again.

Deliberately deferred

approved — three rounds, and the two that mattered (the kindless-query delete and the indented trailer) were each a path to something unrecoverable: a namespace wipe and an immutable wrong tag. Nothing else outstanding from my side.

@necrophidia
necrophidia merged commit f75ea2c into main Sep 21, 2026
1 check passed
@necrophidia
necrophidia deleted the v0.1.0-api-hardening branch September 21, 2026 11:22
necrophidia pushed a commit that referenced this pull request Sep 21, 2026
Review findings on #11.

1. skip was silently merge-strategy dependent. `git log -1` is the merged
   commit under a squash but not under a merge commit, where HEAD is the
   "Merge pull request" commit and carries none of the branch's trailers.
   Verified against the current script: squash skipped, merge commit
   published v0.1.1 and warned that a correctly spelled skip was an
   unreadable level. The script's own header promised the opposite.

   It now reads HEAD^..HEAD, guarded for a parentless HEAD. Verified:
   squash and merge commit both skip, a parentless HEAD skips rather than
   dying under set -e, and deferral still holds - skip, then v0.1.1, then
   v0.2.0 across three pushes.

   A rebase that leaves the trailer below the tip still releases; that is
   only fixable from the push range, which would couple the script to the
   workflow environment. It is documented and pinned instead, so the gap
   is asserted rather than silent.

2. The warning misdiagnosed a valid skip. A correctly spelled trailer that
   simply was not on the merged commits was reported as "its level is not
   major, minor, patch or skip", sending the operator to fix spelling that
   was already right. That case has its own message now.

3. Case p6 claimed "an explicit level elsewhere in the range still wins
   over skip", but its range held no other trailer - the version came from
   the tip's subject, so the name made untested behaviour look verified.
   Same shape as the p2 problem in #8. Renamed to what it tests, and the
   precedence it claimed is now a real case, in both commit orders.

39/39.

Release-As: skip

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
necrophidia added a commit that referenced this pull request Sep 21, 2026
)

* ci: add a Release-As: skip level for changes that reach no consumer

Merging a workflow or README change publishes a version byte-identical to
the last one, because every push to main releases and next-version.sh had
no way to say "this commit is not releasable" - only "there are no commits
at all". Raised in review of #10, which would have published v0.1.1
containing three workflow files and no Go.

skip is read from the merged commit only, unlike the three release levels
which are read from every commit since the last tag. That asymmetry is the
whole design, and the naive version was broken: skipping creates no tag,
so a skip found anywhere in the range is still in the range on the next
push, and every release after it skips too. Verified before fixing - one
skip commit, then a fix, then a breaking change, all three pushes returned
skip. A single skip would have disabled releases permanently.

Reading the tip makes a skip defer rather than suppress: the next push
releases normally and carries the skipped commits with it. The suite pins
both halves of that, along with skip losing to an explicit level elsewhere
in the range, surviving a squash body, and an indented one being inert.
35/35.

Release-As: skip

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix: read Release-As: skip from the merged commits, not just HEAD

Review findings on #11.

1. skip was silently merge-strategy dependent. `git log -1` is the merged
   commit under a squash but not under a merge commit, where HEAD is the
   "Merge pull request" commit and carries none of the branch's trailers.
   Verified against the current script: squash skipped, merge commit
   published v0.1.1 and warned that a correctly spelled skip was an
   unreadable level. The script's own header promised the opposite.

   It now reads HEAD^..HEAD, guarded for a parentless HEAD. Verified:
   squash and merge commit both skip, a parentless HEAD skips rather than
   dying under set -e, and deferral still holds - skip, then v0.1.1, then
   v0.2.0 across three pushes.

   A rebase that leaves the trailer below the tip still releases; that is
   only fixable from the push range, which would couple the script to the
   workflow environment. It is documented and pinned instead, so the gap
   is asserted rather than silent.

2. The warning misdiagnosed a valid skip. A correctly spelled trailer that
   simply was not on the merged commits was reported as "its level is not
   major, minor, patch or skip", sending the operator to fix spelling that
   was already right. That case has its own message now.

3. Case p6 claimed "an explicit level elsewhere in the range still wins
   over skip", but its range held no other trailer - the version came from
   the tip's subject, so the name made untested behaviour look verified.
   Same shape as the p2 problem in #8. Renamed to what it tests, and the
   precedence it claimed is now a real case, in both commit orders.

39/39.

Release-As: skip

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* ci: describe the deferral outcome instead of implying a mistake

Review follow-up on #11, non-blocking.

Every release that follows a skip logs the "skip earlier in the range"
line, because the skipped commit stays in tag..HEAD until a tag is finally
cut. In this repo that deferral is the common path, so the usual reader of
that line has done nothing wrong - but it was worded as a correction. It
now describes what happened: a skip earlier in the range does not apply to
this push, releasing normally and carrying those commits.

The range alone cannot tell a deliberate earlier skip from a rebase that
left the trailer below the tip, so one message has to serve both. A
genuinely unreadable level still gets its own corrective message.

Also records in the README that a merged branch mixing a skip with real
work skips all of it - nothing is lost, since the next release carries
those commits, but it is worth knowing before writing the trailer on a
branch that is not purely CI.

Release-As: skip

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Phillip Leonardo <phillip.leonardo@idexpress.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant