* Retire the last three wisp-switch call sites, and open the label guard on the whole package (ga-2ltro.12)
ga-26w10 deleted a four-way switch over (add|remove) x (wisp|durable) from
`bd label` and lint the door shut behind it. THE SWITCH SURVIVED AT THREE MORE
SITES, and the rule that was supposed to stop the next one could not see two of
them. This retires all three and makes the rule package-wide.
`bd tag`'s proxied route (cmd/bd/mutate_proxied_server.go) reached
uw.LabelUseCase() through proxiedMutateIssue, whose callback signature hands out
a unit of work AND an isWisp boolean — an invitation to pick a plane, which the
tag callback accepted. It now builds one IssuePatch and hands it to
issueops.Lifecycle.Update. IssuePlaneOnly stays false, so the role resolves the
plane inside its own transaction; TestProxiedServerTag/tag_wisp_routes_to_wisp_labels,
which asserts at the SQL table that a wisp's label lands in wisp_labels and the
durable table stays empty, passes through the role with no branch in the
command. It went red on the pre-fix tree under the boolean flipped backwards,
which is the mutation this exists to kill and which is no longer expressible.
THE MOLECULE PORT'S LABEL WRITE IS GONE RATHER THAN RE-ROUTED, and that is the
stronger fix. molWriter had an AddLabel verb with exactly one caller —
bondProtoProtoInto, labelling a compound it had just created — and two
implementations that each resolved the plane AGAIN by a DIFFERENT predicate:
storeMolWriter deferred to the storage layer's isActiveWisp, uowMolWriter
consulted a cache filled from IssueUseCase().GetWisp. Two predicates for one
fact is how a row and its labels come apart. The label now travels in
compound.Labels, so the create that decides the row's table places the label
too, and AddLabel is deleted from the interface and both implementations. The
disagreement is unrepresentable, not merely unlikely.
Worth stating plainly for the reviewer: uowMolWriter.AddLabel's WISP branch was
unreachable. Its only caller labels a durable epic it just created, so the cache
answers false every time. That is why this site had no end-to-end mutation to
run and why the new test is a unit test with a recording writer: it pins that
the create carries the label, which is the property that makes the branch
unnecessary rather than merely unused.
`bd set-state` had the switch FOUR times — the label read, the event create, the
old-label remove and the new-label add — and a second implementation of the whole
command in cmd/bd/state_proxied_server.go that no longer exists. All three verbs
now have ONE body each, on both routes, ending at issueops.Reader.Get and
issueops.Lifecycle:
- the label READ is Reader.Get's already-hydrated, already-sorted Labels, so
there is no label-shaped read here at all — the same move ga-26w10 made for
`bd label list`;
- the dimension SWAP is one IssuePatch carrying Add and Remove together;
- the EVENT is one Lifecycle.Create with ParentID, which mints the same
hierarchical child id and writes the parent edge atomically.
FOUR DELTAS, none of them absorbed.
THE DIRECT ROUTE'S DELTA IS THE EVENT'S PLANE, AND ONLY THAT. An earlier draft
of this message claimed the direct route "read no state and wrote its label into
the wrong table" for a wisp. That was reasoned, not measured, and it is FALSE:
store.GetLabels, AddLabel and RemoveLabel all reach issueops.*InTx with an EMPTY
table name, which routes by IsActiveWispInTx, and utils.ResolvePartialID
resolves through the wisp-inclusive search. Measured at the parent commit,
`bd set-state <wisp> patrol=muted` on the direct route resolves, swaps the
label, and `bd state <wisp> patrol` reads back "muted".
What the parent DID get wrong is the EVENT. It created the state-change bead
with store.CreateIssue and no wisp flag, so an ephemeral subject got a DURABLE
event child, and the parent edge was a second unguarded write across the two
planes. Measured on both sides of this commit, same wisp, same command:
parent event ms-wisp-865.1, no `ephemeral` field -> durable
this event ms-wisp-859.1, `"ephemeral": true` -> the subject's own plane
so a wisp's state history now dies with the wisp instead of outliving it in the
durable table, and its parent edge is written inside the guarded create rather
than beside it.
That correction is the finding, not the footnote: this commit's own brief is
MEASURED, NOT REASONED ABOUT, and the sentence that broke the rule was in the
commit message. The rule covers the artifact too.
A FAILED REMOVAL NO LONGER PASSES SILENTLY — with one half still open. Both
retired routes warned and carried on when the remove failed, leaving the issue
holding two values for one dimension, which findStateLabel then resolves by
whichever the label read returns first. A store-level failure now fails the
command, because the remove and the add are one guarded update.
WHAT THAT DOES NOT CLOSE, stated because the first draft of this line
overclaimed it as "the dimension has one value or nothing was written": the
CONCURRENT swap. Two racing `bd set-state <id> dim=...` calls both read the same
old label, each patch removes a label the other already removed — a no-op, not a
conflict — and both adds land, so the dimension ends with TWO values. A patch is
atomic for ONE writer; it is not a fence. ExpectedVersion cannot supply one
either, because label writes deliberately do not remint RowVersion. The race is
pre-existing, is not made worse here, and is filed as ga-dle5g.
The proxied route LOSES ONE TRANSACTION. Its event and its label swap used to
commit together; they are now two role calls. The direct route was never atomic
at all (four unguarded writes), so this is a net gain there and a stated cost
here, and it is the same trade ga-26w10 took for the same reason. The event's
plane is the subject's own retention mode copied onto the child rather than
chosen, and it is CHECKED: a guarded create refuses a parent edge it cannot
write, so an event that disagreed with its subject's plane fails loudly instead
of landing in the wrong table.
DOLT HISTORY ATTRIBUTION MOVES, which is cosmetic and is said anyway because an
unstated delta is how the two corrections above came to be needed. The role
composes its own version-commit message, so `bd tag` and `bd set-state` write
"bd: update <id>" where they used to write "bd: tag <id>" and
"bd: set-state <id>". `bd dolt log` still names the issue; it no longer names
the verb. Nothing greps for those strings in this tree.
THE FORBIDIGO RULE IS NOW PACKAGE-WIDE ACROSS cmd/bd. It was narrowed by a
path-except to cmd/bd/label.go on the argument that holding an unmigrated
command to a rule written for a migration it had not had would be a lint waived
on sight. What that missed is that the waiver was INVISIBLE — a file outside the
exemption got no marker, no reason and no diff — so the three commands still
hand-rolling the switch looked exactly like the files with nothing to declare.
Two of them were additionally exempted by `path:`-only holes written for the
FILTER rule, which silently open every forbidigo rule for their files:
mol_port.go by the mol_ hole and export_source.go by the bulk-movement one.
EVERY HOLE IN THAT FAMILY IS `text:`-SCOPED NOW, not just those two. Scoping
only the holes that covered a violation TODAY was the same reasoning error as
the paragraphs above — it sized the guard by where the calls are rather than by
where the next one may be WRITTEN — and a review probe proved it with two dodges
that both passed: a neutrally-named helper dropped into the ado/gitlab/jira/
linear hole, and that helper handing the RAW use case back to a NEW file, which
then needs no import and never spells the accessor. Both are caught now, the
second one twice (the return type and the call), and both were re-confirmed to
PASS with the hole unscoped, so the fix is the scope and not a coincidence. The
`_test\.go` exemption stays unscoped on purpose: `run: tests: false` means
forbidigo never analyzes a test file, so scoping it would assert nothing.
MEASURED, NOT REASONED ABOUT. Before: 27 LabelUseCase call sites in 8 non-test
files. After: 15 in 6, every one carrying //nolint:forbidigo and the reason that
site is not a role's question, and they add up: five in-transaction port reads
(mol_port.go), two alternate-view reads (show_proxied_server.go), two bulk
relation loads (export_source.go), two label-vocabulary reads and two
label-propagate WRITES (label_proxied_server.go), one in-transaction command
read (close_proxied_server.go) and one dry-run preview read
(create_proxied_server.go). 5+2+2+2+2+1+1 = 15. The propagate pair are the
acknowledged carve-out and the only survivors that write; each site names its
follow-up, and propagate's is issueops.BatchApplier.ApplyBatch, blocked on a
cmd/bd accessor.
Both halves verified by mutation, one bypass each. A scratch
uw.LabelUseCase().AddLabel() planted in cmd/bd/state.go — reached through
proxiedOpenReadUOW, so the file imports neither internal/storage/uow nor
internal/storage/domain and depguard is blind to it — is caught by forbidigo. A
scratch uow import in the same file is caught by depguard, which cmd/bd/state.go
now joins: it is the second entry on that list because its three verbs really
have migrated, so the rule pins something that happened.
The depguard prose said the forbidigo rule was "scoped to this same file" and
the exclusions block said its label narrowing cost "a `text:` on ONE of the
per-path holes". Both are now what they are: package-wide, and three.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Bound the union legs, and stop letting SQL page a sort it cannot order (ga-2ltro.7)
The two residues the #5476 review deferred, and they turned out to be one rule
observed from both ends: A WINDOW IS ONLY EVER PUSHED UNDER AN ORDER THE QUERY
CAN EXPRESS.
F4 — THE LEGS CARRY THE WINDOW NOW. buildUnionSubquery emitted no bound on
either side of the UNION ALL; only the outer query had one, so both planes were
read in full to deliver a page. Measured on a seeded two-plane store, a
four-row page with twenty matching rows per plane: each leg returned 20 rows,
40 scanned to deliver 4. Each leg now carries the outer clause VERBATIM plus the
deepest row index the outer query can reach, and returns 5 — the bound plus its
probe row — for 10 scanned instead of 40.
EACH LEG IS PARENTHESIZED NOW, and that is load-bearing rather than cosmetic: a
leg carrying its own ORDER BY and LIMIT inside a bare `leg UNION ALL leg` is a
SYNTAX ERROR, the engine reading the trailing clause as the union's own. The
first cut of this change shipped without the parentheses and `bd search` failed
outright — caught by CI, not by the leg probe below, because that probe executes
each subquery STANDALONE where the same string is perfectly legal. A test that
measures the part is not evidence about the whole, so there is now a case that
runs the composed query on both twins across six shapes (ordered, offset, text
term, default order, unbounded, Go-side), and it goes red on the un-parenthesized
form with the exact engine error.
Reusing the outer ORDER BY string rather than rebuilding it is what makes the
bound safe: unionOrderBySQL names `id` and the `sort_*` aliases, both of which
every leg already projects, so one string is valid in both positions and a leg
cannot come to rest in a different order than the one the outer query is about
to cut against. The pushdown is sound because the order is TOTAL — every clause
sqlbuild renders ends in `id ASC` — so a row in the union's top-N is in its own
leg's top-N, there being nothing else it could be behind. legLimit is the bound
PLUS any offset the engine carries, because those are rows the outer query reads
and discards; an offset this package keeps for itself is already inside the
bound.
F5 — AND THE OTHER HALF IS WHY THE LEGS GET NOTHING UNDER `--sort id`. That key
is the one sqlbuild renders no ORDER BY for, so the query ran
`SELECT id, src FROM (leg UNION ALL leg) merged LIMIT n` — a LIMIT with no
ordering anywhere in the statement. A LIMIT without an ORDER BY does not return
the first n rows, it returns n rows.
MEASURED, and it is worse than "arbitrary". On a store with 12 durable and 12
ephemeral beads whose ids interleave, `--sort id --limit 5` answered
[000 002 004 006 008]: five durable rows, and not one wisp. The Go-side sort
then put them in perfect order, which is why this reads as a correct page — the
ORDER was right and the MEMBERSHIP silently excluded an entire plane.
Two changes close it, and both are needed:
- searchWindowFor pushes NO page bound for a Go-side sort, which is the same
answer internal/workapi.SQLLimit gives the reader role for the same reason.
The CAP is not waived with it: maxRows still sizes a bound, so an unordered
scan too large to hold answers ErrTooManyRows rather than reading the
workspace.
- idSrcPage.sortGoSide establishes the order before finishWindow trims. This
is the union seam's copy of issueops.sortMergedResults and exists for the
identical reason that one gives: a concatenation trimmed without a re-sort
keeps an arbitrary prefix. The id is already on the ref, so no row has to be
hydrated to be placed.
THE LIVE CALLER IS `bd query`, NOT `bd list`, and the review's note undersized
it. `bd list` is protected by workapi.SQLLimit and the wire's list endpoint pins
"created" — but workapi.BuildQueryPlan pushes SortBy and Limit straight onto the
filter for any filter-expressible query with no such guard, DefaultQueryLimit
means a limit is ALWAYS set, and "id" is in both the CLI's and the HTTP
endpoint's accepted sort keys. So `bd query '<expr>' --sort id` and
GET /v0/beads/issues/query?sort=id reached this on the DEFAULT path, on a wire
the review recorded as safe. BuildQueryPlan's own comment justifies the pushdown
by promising "the page is the first N in the requested order on every backend";
that was true of every key except the one IsGoSideSort names. Both twins are
covered — the counts twin is the one those callers reach.
TWO THINGS THIS DOES NOT FIX, named rather than left for the next reader.
The per-table seam (internal/storage/issueops) bounds each leg with
EffectiveSearchLimit under the same absent ORDER BY, so it picks an arbitrary
subset per leg before sortMergedResults runs; and sqlbuild.Less ignores sortDesc
for "id", so a reversed id page there keeps the byte-FIRST rows. sortGoSide
honors sortDesc rather than mirroring that.
Costs, stated. A caller combining `--sort id` with a small limit and no cap now
reads every matching row where it used to read limit+1. It read the wrong ones,
and the reader role has always paid this price on the same query.
Also folded in, both comment-only and both named by the review: count.go cited
`bd doctor --check=cross-table`, a selector that does not exist (the flag takes
artifacts, conventions, pollution and validate; the cross-table check runs in
the default sweep), and scanIDSrcPage claimed the shadowed durable row is
dropped "wherever it sits" when the drop only ever reached the scanned window —
a distinction this change sharpens, since the legs are now bounded.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Review Sim <ci@beads.test>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
214 lines
7.3 KiB
Go
214 lines
7.3 KiB
Go
//go:build cgo
|
|
|
|
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestProxiedServerSetState(t *testing.T) {
|
|
requireSharedProxiedServer(t)
|
|
t.Parallel()
|
|
bd := buildEmbeddedBD(t)
|
|
p := newSharedProxiedProject(t, bd, "sst")
|
|
issue := bdProxiedCreate(t, bd, p.dir, "Set-state target")
|
|
|
|
setStateJSON := func(t *testing.T, spec string, extra ...string) map[string]interface{} {
|
|
t.Helper()
|
|
args := append([]string{"set-state", issue.ID, spec, "--json"}, extra...)
|
|
out, err := bdProxiedRun(t, bd, p.dir, args...)
|
|
if err != nil {
|
|
t.Fatalf("set-state %s: %v\n%s", spec, err, out)
|
|
}
|
|
var got map[string]interface{}
|
|
if err := json.Unmarshal(out, &got); err != nil {
|
|
t.Fatalf("unmarshal: %v\n%s", err, out)
|
|
}
|
|
return got
|
|
}
|
|
|
|
t.Run("set_new_dimension", func(t *testing.T) {
|
|
got := setStateJSON(t, "patrol=active", "--reason", "starting patrol")
|
|
if got["changed"] != true {
|
|
t.Errorf("expected changed=true, got %v", got["changed"])
|
|
}
|
|
if got["old_value"] != nil {
|
|
t.Errorf("expected old_value nil for a new dimension, got %v", got["old_value"])
|
|
}
|
|
if got["new_value"] != "active" {
|
|
t.Errorf("new_value = %v, want active", got["new_value"])
|
|
}
|
|
if _, ok := got["event_id"].(string); !ok || got["event_id"] == "" {
|
|
t.Errorf("expected an event_id, got %v", got["event_id"])
|
|
}
|
|
// Label cache must reflect the new state.
|
|
db := openProxiedDB(t, p)
|
|
labels := getProxiedLabels(t, db, issue.ID)
|
|
if !containsStr(labels, "patrol:active") {
|
|
t.Errorf("expected label patrol:active, got %v", labels)
|
|
}
|
|
})
|
|
|
|
t.Run("change_swaps_label", func(t *testing.T) {
|
|
got := setStateJSON(t, "patrol=muted")
|
|
if got["changed"] != true || got["old_value"] != "active" || got["new_value"] != "muted" {
|
|
t.Errorf("unexpected change result: %v", got)
|
|
}
|
|
db := openProxiedDB(t, p)
|
|
labels := getProxiedLabels(t, db, issue.ID)
|
|
if containsStr(labels, "patrol:active") {
|
|
t.Errorf("old label patrol:active should have been removed, got %v", labels)
|
|
}
|
|
if !containsStr(labels, "patrol:muted") {
|
|
t.Errorf("expected label patrol:muted, got %v", labels)
|
|
}
|
|
})
|
|
|
|
t.Run("no_change_is_noop", func(t *testing.T) {
|
|
got := setStateJSON(t, "patrol=muted")
|
|
if got["changed"] != false {
|
|
t.Errorf("expected changed=false for identical value, got %v", got)
|
|
}
|
|
})
|
|
|
|
t.Run("event_bead_created_as_child", func(t *testing.T) {
|
|
out, err := bdProxiedRun(t, bd, p.dir, "state", "list", issue.ID, "--json")
|
|
if err != nil {
|
|
t.Fatalf("state list: %v\n%s", err, out)
|
|
}
|
|
var res struct {
|
|
States map[string]string `json:"states"`
|
|
}
|
|
if err := json.Unmarshal(out, &res); err != nil {
|
|
t.Fatalf("unmarshal: %v\n%s", err, out)
|
|
}
|
|
if res.States["patrol"] != "muted" {
|
|
t.Errorf("state list shows patrol=%q, want muted", res.States["patrol"])
|
|
}
|
|
// The set-state calls created event children under the issue.
|
|
children := bdProxiedListJSON(t, bd, p, "--parent", issue.ID, "--status", "all")
|
|
var events int
|
|
for _, c := range children {
|
|
if strings.HasPrefix(c.ID, issue.ID+".") {
|
|
events++
|
|
}
|
|
}
|
|
if events == 0 {
|
|
t.Errorf("expected event child beads under %s, got none", issue.ID)
|
|
}
|
|
})
|
|
|
|
t.Run("invalid_format", func(t *testing.T) {
|
|
out, err := bdProxiedRun(t, bd, p.dir, "set-state", issue.ID, "patrolactive")
|
|
if err == nil {
|
|
t.Fatalf("expected error for missing '=', got success: %s", out)
|
|
}
|
|
})
|
|
|
|
t.Run("multiple_dimensions", func(t *testing.T) {
|
|
m := bdProxiedCreate(t, bd, p.dir, "Multi-dimension state")
|
|
|
|
for _, spec := range []string{"phase=planning", "env=staging"} {
|
|
out, err := bdProxiedRun(t, bd, p.dir, "set-state", m.ID, spec)
|
|
if err != nil {
|
|
t.Fatalf("set-state %s: %v\n%s", spec, err, out)
|
|
}
|
|
}
|
|
|
|
out, err := bdProxiedRun(t, bd, p.dir, "state", "list", m.ID, "--json")
|
|
if err != nil {
|
|
t.Fatalf("state list: %v\n%s", err, out)
|
|
}
|
|
var res struct {
|
|
States map[string]string `json:"states"`
|
|
}
|
|
if err := json.Unmarshal(out, &res); err != nil {
|
|
t.Fatalf("unmarshal: %v\n%s", err, out)
|
|
}
|
|
if res.States["phase"] != "planning" {
|
|
t.Errorf("phase = %q, want planning (states=%v)", res.States["phase"], res.States)
|
|
}
|
|
if res.States["env"] != "staging" {
|
|
t.Errorf("env = %q, want staging (states=%v)", res.States["env"], res.States)
|
|
}
|
|
|
|
// Each distinct dimension is an independent label; both must be present.
|
|
db := openProxiedDB(t, p)
|
|
labels := getProxiedLabels(t, db, m.ID)
|
|
if !containsStr(labels, "phase:planning") || !containsStr(labels, "env:staging") {
|
|
t.Errorf("expected both phase:planning and env:staging labels, got %v", labels)
|
|
}
|
|
})
|
|
|
|
t.Run("set_state_on_wisp", func(t *testing.T) {
|
|
wisp := bdProxiedCreate(t, bd, p.dir, "Wisp set-state", "--ephemeral")
|
|
|
|
out, err := bdProxiedRun(t, bd, p.dir, "set-state", wisp.ID, "patrol=muted", "--json")
|
|
if err != nil {
|
|
t.Fatalf("set-state on wisp: %v\n%s", err, out)
|
|
}
|
|
var got map[string]interface{}
|
|
if err := json.Unmarshal(out, &got); err != nil {
|
|
t.Fatalf("unmarshal: %v\n%s", err, out)
|
|
}
|
|
if got["changed"] != true || got["new_value"] != "muted" {
|
|
t.Errorf("unexpected wisp set-state result: %v", got)
|
|
}
|
|
|
|
// Wisp state lives in wisp_labels; verify via the state reader.
|
|
val, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "state", wisp.ID, "patrol")
|
|
if err != nil {
|
|
t.Fatalf("state on wisp: %v\nstderr:\n%s", err, stderr)
|
|
}
|
|
if strings.TrimSpace(val) != "muted" {
|
|
t.Errorf("wisp state value = %q, want muted", strings.TrimSpace(val))
|
|
}
|
|
|
|
// ASSERT AT THE TABLE, not only through the reader. The reader answers
|
|
// from whichever plane the write chose, so a write and a read that get
|
|
// the same boolean backwards together still agree with each other and
|
|
// the check above passes. This is the assertion that does not: a wisp's
|
|
// state label belongs in wisp_labels and the durable table stays empty.
|
|
db := openProxiedDB(t, p)
|
|
if n := countRows(t, db, "SELECT COUNT(*) FROM wisp_labels WHERE issue_id = ? AND label = ?", wisp.ID, "patrol:muted"); n != 1 {
|
|
t.Errorf("wisp_labels rows for patrol:muted = %d, want 1", n)
|
|
}
|
|
if n := countRows(t, db, "SELECT COUNT(*) FROM labels WHERE issue_id = ?", wisp.ID); n != 0 {
|
|
t.Errorf("durable labels rows for a wisp = %d, want 0", n)
|
|
}
|
|
})
|
|
|
|
t.Run("state_change_on_wisp_swaps_in_place", func(t *testing.T) {
|
|
wisp := bdProxiedCreate(t, bd, p.dir, "Wisp set-state swap", "--ephemeral")
|
|
|
|
for _, spec := range []string{"phase=planning", "phase=running"} {
|
|
if out, err := bdProxiedRun(t, bd, p.dir, "set-state", wisp.ID, spec, "--json"); err != nil {
|
|
t.Fatalf("set-state %s on wisp: %v\n%s", spec, err, out)
|
|
}
|
|
}
|
|
|
|
// The swap is one edit: the old label must be gone and the new one
|
|
// present, both in the ephemeral plane, with nothing left durable.
|
|
db := openProxiedDB(t, p)
|
|
if n := countRows(t, db, "SELECT COUNT(*) FROM wisp_labels WHERE issue_id = ? AND label LIKE 'phase:%'", wisp.ID); n != 1 {
|
|
t.Errorf("wisp_labels phase rows = %d, want exactly 1 after a swap", n)
|
|
}
|
|
if n := countRows(t, db, "SELECT COUNT(*) FROM wisp_labels WHERE issue_id = ? AND label = ?", wisp.ID, "phase:running"); n != 1 {
|
|
t.Errorf("wisp_labels rows for phase:running = %d, want 1", n)
|
|
}
|
|
if n := countRows(t, db, "SELECT COUNT(*) FROM labels WHERE issue_id = ?", wisp.ID); n != 0 {
|
|
t.Errorf("durable labels rows for a wisp = %d, want 0", n)
|
|
}
|
|
})
|
|
}
|
|
|
|
func containsStr(ss []string, want string) bool {
|
|
for _, s := range ss {
|
|
if s == want {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|