beads/cmd/bd/export_source.go
Julian Knutsen f925f3f5b0
Retire the last three wisp-switch call sites, and bound the wisp-inclusive union reads (ga-2ltro.12, ga-2ltro.7) (#5587)
* 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>
2026-08-10 17:07:59 -07:00

351 lines
14 KiB
Go

package main
import (
"context"
"errors"
"fmt"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/dberrors"
"github.com/steveyegge/beads/internal/storage/uow"
"github.com/steveyegge/beads/internal/types"
)
// exportSource abstracts the storage reads `bd export` performs, so the one
// export body (runExportFromSource) serves both storage stacks:
//
// - storeExportSource reads through the classic `store` global
// (embedded / direct / server modes), preserving the exact pre-seam
// call pattern.
// - uowExportSource reads through a proxied-server unit of work, whose
// domain use cases are plane-pinned (issues vs wisps tables) where the
// classic bulk loaders partition internally — the impl queries both
// planes with the full ID set and merges, so both modes read the same
// rows regardless of which table an issue lives in.
//
// Everything downstream of these reads is shared code; the acceptance bar for
// the seam is byte-identical JSONL output across modes.
type exportSource interface {
// GetInfraTypes returns the resolved infra-type set (config, YAML, or
// hardcoded defaults). A nil/empty result makes the caller fall back to
// domain.DefaultInfraTypes(), mirroring the pre-seam behavior.
GetInfraTypes(ctx context.Context) map[string]bool
// SearchIssues returns the full, untruncated result set for the export
// filter (Limit=0, MaxRows=0). Implementations MUST fail rather than
// return a truncated page — export is a data-integrity path.
SearchIssues(ctx context.Context, query string, filter types.IssueFilter) ([]*types.Issue, error)
// GetConfig reads one config key from the database (used for the
// export.exclude_owners owner-filter keys).
GetConfig(ctx context.Context, key string) (string, error)
// GetAllConfig reads the whole config table (used to extract kv.memory.*
// rows when memories are exported).
GetAllConfig(ctx context.Context) (map[string]string, error)
// LoadExportRelations bulk-loads labels, dependency records, comments,
// comment counts, and dependency counts for the searched issues.
LoadExportRelations(ctx context.Context, issues []*types.Issue) (exportRelations, error)
// WispPlaneIDs reports which of ids currently live in the WISPS table.
// Export uses it to stamp the explicit "wisp_plane" marker on records
// whose row flags are ambiguous: a no_history=true row is either an
// unpromoted no-history wisp (wisps table) or a promoted one (durable
// issues-table row that may still carry the stray flag), and only table
// membership can tell them apart — import routes by the marker, so
// mis-stamping a durable row would re-plane it and drop its relations
// (bd-r9uce). Implementations must classify by table membership, never
// by flags, and both modes must agree (byte-identity oracle).
WispPlaneIDs(ctx context.Context, ids []string) (map[string]bool, error)
}
// storeWispPartitioner is the optional store capability WispPlaneIDs uses in
// classic mode. Both real stores (DoltStore, EmbeddedDoltStore) implement it;
// a store that does not simply gets no plane markers, which degrades to the
// data-safe side (import then routes bare no_history rows to the durable
// plane, where nothing is ever excluded from export).
type storeWispPartitioner interface {
PartitionWispIDs(ctx context.Context, ids []string) (wispIDs, permIDs []string, err error)
}
// exportRelations carries the bulk-loaded relational data for the export set,
// keyed by issue ID.
type exportRelations struct {
labels map[string][]string
deps map[string][]*types.Dependency
comments map[string][]*types.Comment
commentCounts map[string]int
depCounts map[string]*types.DependencyCounts
}
// errExportNoStore reports a classic-source read attempted with no store
// open. Callers of exportSource.GetConfig treat any error as "key unset",
// which reproduces the pre-seam `if store == nil` early return.
var errExportNoStore = errors.New("no store available")
// storeExportSource is the classic-mode exportSource over the `store` global.
type storeExportSource struct{}
func (storeExportSource) GetInfraTypes(ctx context.Context) map[string]bool {
if store == nil {
return nil
}
return store.GetInfraTypes(ctx)
}
func (storeExportSource) SearchIssues(ctx context.Context, query string, filter types.IssueFilter) ([]*types.Issue, error) {
return store.SearchIssues(ctx, query, filter)
}
func (storeExportSource) GetConfig(ctx context.Context, key string) (string, error) {
if store == nil {
return "", errExportNoStore
}
return store.GetConfig(ctx, key)
}
func (storeExportSource) GetAllConfig(ctx context.Context) (map[string]string, error) {
return store.GetAllConfig(ctx)
}
func (storeExportSource) LoadExportRelations(ctx context.Context, issues []*types.Issue) (exportRelations, error) {
issueIDs := make([]string, len(issues))
for i, issue := range issues {
issueIDs[i] = issue.ID
}
// Individual bulk-load failures deliberately degrade to empty maps rather
// than aborting the export — unchanged from the pre-seam classic behavior.
labelsMap, _ := store.GetLabelsForIssues(ctx, issueIDs)
allDeps, _ := store.GetDependencyRecordsForIssues(ctx, issueIDs)
commentsMap, _ := store.GetCommentsForIssues(ctx, issueIDs)
commentCounts, _ := store.GetCommentCounts(ctx, issueIDs)
depCounts, _ := store.GetDependencyCounts(ctx, issueIDs)
return exportRelations{
labels: labelsMap,
deps: allDeps,
comments: commentsMap,
commentCounts: commentCounts,
depCounts: depCounts,
}, nil
}
func (storeExportSource) WispPlaneIDs(ctx context.Context, ids []string) (map[string]bool, error) {
if len(ids) == 0 || store == nil {
return nil, nil
}
// The store global is decorator-wrapped (telemetry, hook firing); walk
// Unwrap() down to the store that carries the partition capability.
s := store
var p storeWispPartitioner
for {
if partitioner, ok := s.(storeWispPartitioner); ok {
p = partitioner
break
}
u, ok := s.(interface{ Unwrap() storage.DoltStorage })
if !ok {
return nil, nil
}
s = u.Unwrap()
if s == nil {
return nil, nil
}
}
wispIDs, _, err := p.PartitionWispIDs(ctx, ids)
if err != nil {
return nil, err
}
set := make(map[string]bool, len(wispIDs))
for _, id := range wispIDs {
set[id] = true
}
return set, nil
}
// uowExportSource is the proxied-server exportSource over a unit of work. All
// reads run inside the single read transaction runExport opened, so the
// export is one consistent snapshot.
type uowExportSource struct {
uw uow.UnitOfWork
}
func (s *uowExportSource) GetInfraTypes(ctx context.Context) map[string]bool {
infra, err := s.uw.ConfigUseCase().GetInfraTypes(ctx)
if err != nil {
// Match the classic source's error-free signature: an unreadable
// config degrades to the caller's DefaultInfraTypes() fallback.
return nil
}
return infra
}
func (s *uowExportSource) SearchIssues(ctx context.Context, query string, filter types.IssueFilter) ([]*types.Issue, error) {
page, err := s.uw.IssueUseCase().SearchIssues(ctx, query, filter)
if err != nil {
return nil, err
}
// Export builds its filter with Limit=0/MaxRows=0, so the whole result
// arrives as one page and HasMore can only be true if a limit creeps back
// in. Guard anyway: an export must fail loudly, never truncate silently
// (domain.SearchPage carries no continuation cursor to loop with).
if page.HasMore {
return nil, fmt.Errorf("issue search returned a truncated page (limit=%d); export must never truncate", filter.Limit)
}
return page.Items, nil
}
func (s *uowExportSource) GetConfig(ctx context.Context, key string) (string, error) {
return s.uw.ConfigUseCase().GetConfig(ctx, key)
}
func (s *uowExportSource) GetAllConfig(ctx context.Context) (map[string]string, error) {
return s.uw.ConfigUseCase().GetAllConfig(ctx)
}
// LoadExportRelations reproduces the classic bulk loaders over the
// plane-pinned domain use cases:
//
// - Labels, comments, and comment counts: the classic loaders partition IDs
// by wisps-table membership (issueops.PartitionWispIDsInTx). Row flags are
// NOT a substitute for that partition — a promoted no-history wisp is a
// durable issues-table row that (as wild data from the pre-bd-r9uce
// promote) still carries NoHistory=true — so both
// planes are queried with the FULL ID set and merged. The planes are
// ID-disjoint (GH#4455 cross-table guard), so at most one plane returns
// rows for any id and the merge cannot collide.
// - Dependency records: domain GetIssueDependencyRecords already partitions
// internally (same issueops helper), so one call covers both planes.
// - Dependency counts: classic GetDependencyCountsInTx queries BOTH dep
// tables for EVERY id and sums (a wisp blocking a durable issue
// contributes to the durable issue's dependent_count), so both planes are
// queried for the full ID set and summed here too.
//
// Wisp-plane reads tolerate a rig without the wisp tables (IsTableNotExist),
// mirroring the dependency-counts leg.
func (s *uowExportSource) LoadExportRelations(ctx context.Context, issues []*types.Issue) (exportRelations, error) {
rel := exportRelations{
labels: map[string][]string{},
deps: map[string][]*types.Dependency{},
comments: map[string][]*types.Comment{},
commentCounts: map[string]int{},
depCounts: map[string]*types.DependencyCounts{},
}
allIDs := make([]string, 0, len(issues))
for _, issue := range issues {
allIDs = append(allIDs, issue.ID)
}
if len(allIDs) == 0 {
return rel, nil
}
// BATCH READS, and the batch is what keeps them here. Export hydrates every
// relation of N issues at once — labels, comments, dependencies, counts,
// both planes — and no role answers "the labels of these N ids": Reader.Get
// is one detail view per call, so a role-routed export would be N round
// trips over a whole workspace. A bulk relation reader is the follow-up
// (ga-2ltro.12). Every LabelUseCase call in this file is one of these.
labels, err := s.uw.LabelUseCase().GetLabelsForIssues(ctx, allIDs) //nolint:forbidigo // bulk relation load; no role answers labels-for-N-ids
if err != nil {
return exportRelations{}, fmt.Errorf("load labels: %w", err)
}
mergeExportMap(rel.labels, labels)
comments, err := s.uw.CommentUseCase().GetCommentsForIssues(ctx, allIDs)
if err != nil {
return exportRelations{}, fmt.Errorf("load comments: %w", err)
}
mergeExportMap(rel.comments, comments)
counts, err := s.uw.CommentUseCase().GetCommentCounts(ctx, allIDs)
if err != nil {
return exportRelations{}, fmt.Errorf("load comment counts: %w", err)
}
mergeExportMap(rel.commentCounts, counts)
wispLabels, err := s.uw.LabelUseCase().GetLabelsForWisps(ctx, allIDs) //nolint:forbidigo // bulk relation load; see GetLabelsForIssues above
if err != nil {
if !dberrors.IsTableNotExist(err) {
return exportRelations{}, fmt.Errorf("load wisp labels: %w", err)
}
} else {
mergeExportMap(rel.labels, wispLabels)
}
wispComments, err := s.uw.CommentUseCase().GetCommentsForWisps(ctx, allIDs)
if err != nil {
if !dberrors.IsTableNotExist(err) {
return exportRelations{}, fmt.Errorf("load wisp comments: %w", err)
}
} else {
mergeExportMap(rel.comments, wispComments)
}
wispCounts, err := s.uw.CommentUseCase().GetWispCommentCounts(ctx, allIDs)
if err != nil {
if !dberrors.IsTableNotExist(err) {
return exportRelations{}, fmt.Errorf("load wisp comment counts: %w", err)
}
} else {
mergeExportMap(rel.commentCounts, wispCounts)
}
deps, err := s.uw.DependencyUseCase().GetIssueDependencyRecords(ctx, allIDs)
if err != nil {
return exportRelations{}, fmt.Errorf("load dependency records: %w", err)
}
rel.deps = deps
depCounts, err := s.uw.DependencyUseCase().CountsByIssueIDs(ctx, allIDs)
if err != nil {
return exportRelations{}, fmt.Errorf("load dependency counts: %w", err)
}
rel.depCounts = depCounts
wispDepCounts, err := s.uw.DependencyUseCase().CountsByWispIDs(ctx, allIDs)
if err != nil {
// A rig without the wisp tables simply has no wisp-plane edges.
if !dberrors.IsTableNotExist(err) {
return exportRelations{}, fmt.Errorf("load wisp dependency counts: %w", err)
}
} else {
for id, wc := range wispDepCounts {
if wc == nil || (wc.DependencyCount == 0 && wc.DependentCount == 0) {
continue
}
c := rel.depCounts[id]
if c == nil {
c = &types.DependencyCounts{}
rel.depCounts[id] = c
}
c.DependencyCount += wc.DependencyCount
c.DependentCount += wc.DependentCount
}
}
return rel, nil
}
// WispPlaneIDs classifies by wisps-table membership through the plane-pinned
// GetWispsByIDs read (row flags are NOT a substitute — see the exportSource
// interface comment). A rig without the wisp tables has no wisp-plane rows,
// mirroring the tolerance of the wisp-plane legs in LoadExportRelations.
func (s *uowExportSource) WispPlaneIDs(ctx context.Context, ids []string) (map[string]bool, error) {
if len(ids) == 0 {
return nil, nil
}
wisps, err := s.uw.IssueUseCase().GetWispsByIDs(ctx, ids)
if err != nil {
if dberrors.IsTableNotExist(err) {
return nil, nil
}
return nil, fmt.Errorf("wisp plane membership: %w", err)
}
set := make(map[string]bool, len(wisps))
for _, w := range wisps {
set[w.ID] = true
}
return set, nil
}
// mergeExportMap copies src entries into dst. The label/comment planes are
// disjoint by ID (an issue lives in exactly one of issues/wisps), so a plain
// overwrite-merge reassembles the classic partitioned loaders' single map.
func mergeExportMap[V any](dst, src map[string]V) {
for k, v := range src {
dst[k] = v
}
}