fix(linear): wire parent-child relationships to Linear's parent field (#3930)
* fix(linear): wire parent-child relationships to Linear's parent field
bd-ena: bd linear sync wasn't pushing parent-child relationships to
Linear, leaving epic trees flat (every issue parent=null on the Linear
side). Concretely on the houmanoids_www rig: a 73-issue tree push
created HOU-151..HOU-209 all with parent=null, even though the local
beads structure was correctly parent-child-linked.
Root cause: Tracker.CreateIssue and UpdateIssue never set parentId; the
GraphQL client's buildIssueCreateInput didn't accept it; the field
mapper's IssueToTracker dropped parent entirely.
Fix: post-sync reconciliation pass.
After engine.Sync completes (push, non-dry-run, success, full scope):
1. Walk local store for beads with Linear external_refs and a
parent-child dependency to a parent that also has an external_ref.
2. For each (child, parent) pair, fetch both from Linear (cached by
identifier so repeated parents cost one fetch).
3. If child's remote parent doesn't match the desired parent UUID,
issue IssueUpdate{parentId} on the child's host team-client.
Idempotent: re-running on a healthy tree produces only Skipped++ events,
no API mutations. This means a single run of `bd linear sync` will both:
(a) wire up new trees that were just pushed in the same sync, AND
(b) repair pre-existing orphan trees from before this fix landed
(HOU-164..209 on houmanoids will get parents on next sync).
Multi-team correctness: fetchIssueAcrossTeams returns the host client
alongside the issue, and the update reuses that client. Avoids a
silent fall-through to the primary team's client (clientForExternalID's
non-rate-limit error path falls back to primary, which would silently
update the wrong team's issue in a multi-team rig).
Rate-limit safety: the pass aborts immediately when Linear's circuit
breaker trips. Already-applied updates are reported in the partial
"Reconciled N parent links" line before the warning surfaces.
Scope safety: skipped on scoped syncs (--parent / --type / --exclude-
type / --issue-id) since the reconciler walks the full local tree, not
just the in-scope subset. A subsequent unscoped sync picks up the work.
Tests (internal/linear/parent_reconcile_test.go, 9 cases):
- HappyPath, IdempotentSkip, RewiresWrongParent
- FetchCaching (parent-shared-by-N children fetched once)
- MissingChildOrParent (NotFound, no errors)
- EmptyLinks, BlankIdentifiersSkipped (defensive)
- MultiTeam (cross-team probing + correct host-client routing)
- AbortsOnRateLimit (circuit breaker stops the pass cleanly)
Codex-Reviewed-By: codex-rescue (2 rounds; second round caught the
multi-team silent-fallback hazard and the scoped-sync interaction)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat(linear): dry-run preview for parent reconciler
bd-5zh: the bd-ena parent-child reconciler had no dry-run mode — every
call mutated Linear via UpdateIssue, so callers were forced to gate on
`!dryRun` at the call site. That defeats the point of
`bd linear sync --dry-run` as a pre-flight: the orphan-repair scope
(HOU-164..209 on the houmanoids_www rig) was invisible until you
committed to a wet sync.
API change: `ReconcileParents(ctx, links)` → `ReconcileParents(ctx,
links, dryRun bool)`. ParentReconcileStats gains:
- WouldUpdate int — count of mutations that WOULD fire (dry-run);
zero in wet-run
- Mutations []ParentLink — (child, parent) pairs that were applied
(wet-run, only after IssueUpdate success) or
that would apply (dry-run). Lets callers print
per-link detail without re-deriving.
When dryRun is true the per-link logic still runs through fetch,
fetch-caching, and idempotency-check — only the API mutation is skipped.
The preview is therefore trustworthy: same NotFound/Skipped behavior,
same Mutations set as wet-run for the same input (locked by
TestReconcileParents_DryRunMatchesWetRunMutationSet).
cmd/bd/linear.go:
- Drops the `!dryRun` gate; reconcile pass now runs in dry-run too.
- `reconcileLinearParents` takes new dryRun + jsonOutput params.
- In dry-run: prints `[dry-run] Would reconcile N parent links` summary
+ one `[dry-run] Would set parent of CHILD → PARENT` per Mutations
entry. Suppressed when --json is set so the JSON envelope stays clean.
- `effectivePush := push || (!push && !pull)` mirrors engine.Sync's
bidirectional default so `bd linear sync --dry-run` (no direction
flag) still previews the reconcile.
Wet-run contract tightened (codex round 1 catch): Mutations is now
appended only AFTER the UpdateIssue API call succeeds, so the list
reflects state actually propagated to Linear — not attempted writes
that failed. Locked by TestReconcileParents_WetRunFailureDoesNotRecordMutation.
Scoped-sync skip preserved (codex confirmed): a scoped sync that
silently expanded its surface in dry-run mode would surprise the user.
Tests: 9 existing tests updated to pass `false` for dryRun (no behavior
change). 5 new tests:
- DryRunNoMutations — mixed already-correct + needs-parent; verifies
WouldUpdate, Skipped, Mutations contents + ordering, zero mock.updates.
- DryRunIdempotentSkipUnchanged — all correct → zero WouldUpdate.
- DryRunMissingTargetsNotFound — unresolvable identifiers surface in
NotFound during dry-run too.
- DryRunMatchesWetRunMutationSet — symmetry property: dry-run and
wet-run produce identical Mutations sets for identical input.
- WetRunFailureDoesNotRecordMutation — issueUpdate returning
success=false produces Errors entry, NOT a Mutations entry.
Known gap: reconcile preview lines aren't surfaced in --json output
(would require Linear-specific field on shared SyncResult; deferred).
Errors still flow through SyncResult.Warnings either way.
Codex-Reviewed-By: codex-rescue (2 rounds; caught Mutations-recorded-
before-success contract bug, --json output mixing, and the
bidirectional-default gate hole)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(linear): persistent linear.exclude_types no longer disables parent reconcile
bd-9w3: on the houmanoids_www rig the post-sync parent reconciler was
silently skipped on every full sync — HOU-164..209 stayed orphaned
despite the surrounding sync running clean. Traced via debug prints:
syncIsScoped(&opts) returned true because opts.ExcludeTypes was non-
empty (the rig has persistent `linear.exclude_types = "molecule,event"`,
merged into opts by the CLI). The gate then skipped reconcile.
Fix: drop ExcludeTypes from syncIsScoped. The reconcile pass only
mutates the parent FIELD on the child issue — it never touches the
parent issue itself — so excluding "molecule" or "event" types from
push doesn't conflict with wiring up parent-child for the remaining
types. ExcludeTypes is primarily a persistent-config knob, not a
temporary user scoping intent for THIS invocation.
Kept as scoping signals (all explicit-CLI-only):
- ParentID (--parent)
- IssueIDs (--issues / --issue-id)
- TypeFilter (--type)
Tests: cmd/bd/sync_is_scoped_test.go covers 8 sub-cases including the
regression "exclude types only (persistent config)" → false, plus the
combined cases (exclude_types + parent_id → still scoped; exclude_types
+ type_filter → still scoped).
Verified on the houmanoids_www rig (via the integration sibling
binary, since the upstream binary's schema is incompatible with the
rig DB):
bd linear sync --pull --push --dry-run
→ "[dry-run] Would reconcile 62 Linear parent links"
→ HOU-164 → HOU-159, HOU-165 → HOU-205, ... Phase epics → root epic.
Mayor's bd-9w3 nudge raised an "epic-aware silent skip" hypothesis from
the bd-2og epics-as-projects design — confirmed NOT present on this
code path. The reconciler treats all bead types (including epics)
identically; the 62 planned mutations include Phase-epic → root-epic
links (HOU-202 → HOU-159, HOU-205 → HOU-159).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
54af9d68e4
commit
98f3cb43a5
4 changed files with 1149 additions and 0 deletions
192
cmd/bd/linear.go
192
cmd/bd/linear.go
|
|
@ -379,6 +379,34 @@ func runLinearSync(cmd *cobra.Command, args []string) error {
|
|||
return HandleError("%v", err)
|
||||
}
|
||||
|
||||
// Post-sync: reconcile parent-child relationships into Linear's parent
|
||||
// field. The per-issue create/update path can't always set parentId
|
||||
// (children are sometimes pushed before parents have an external_ref),
|
||||
// and previously-pushed orphan trees need a backfill. This pass is
|
||||
// idempotent — no API mutation when remote parent already matches.
|
||||
//
|
||||
// In dry-run mode the pass still runs (read-only fetches) so the user
|
||||
// gets a preview of which parents would be set; the IssueUpdate
|
||||
// mutation is skipped per-link.
|
||||
//
|
||||
// Skipped on scoped syncs (--parent / --type / --exclude-type / --since
|
||||
// / --issue-id) because the reconciler walks ALL local beads with
|
||||
// external_refs, not just the in-scope ones — a scoped sync that
|
||||
// silently mutated other parts of the tree would surprise the user.
|
||||
// A full sync still picks up the repair on the next run.
|
||||
//
|
||||
// `effectivePush` mirrors engine.Sync's bidirectional default: when
|
||||
// neither --pull nor --push is passed, the engine internally runs both
|
||||
// directions, so the reconcile pass must also fire (otherwise
|
||||
// `bd linear sync --dry-run` with no direction flag silently skips the
|
||||
// preview). We can't read opts.Push after engine.Sync because Sync
|
||||
// receives opts by value.
|
||||
effectivePush := push || (!push && !pull)
|
||||
if effectivePush && result.Success && !syncIsScoped(&opts) {
|
||||
reconcileLinearParents(ctx, lt, dryRun, jsonOutput, &result.Warnings)
|
||||
}
|
||||
|
||||
// Record successful pull timestamp
|
||||
if (pull || !push) && !dryRun {
|
||||
if beadsDir := resolveBeadsDirForStaleness(); beadsDir != "" {
|
||||
_ = linear.WriteLastPullTimestamp(beadsDir)
|
||||
|
|
@ -1173,3 +1201,167 @@ func getLinearHashLength(ctx context.Context) int {
|
|||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// syncIsScoped returns true when the user explicitly constrained THIS
|
||||
// invocation to a specific subset of beads (via --parent, --issues, or
|
||||
// --type). The parent reconcile pass is skipped on scoped syncs because
|
||||
// it walks the full local tree, which could mutate Linear-side state
|
||||
// outside the scope the user asked for.
|
||||
//
|
||||
// Notably ExcludeTypes is NOT a scoping signal: it merges with persistent
|
||||
// config (linear.exclude_types), and rigs that set it default-on (e.g.
|
||||
// "molecule,event") would otherwise have the reconcile pass permanently
|
||||
// disabled — bd-9w3 root cause. Reconcile only ever touches the parent
|
||||
// field on the child issue, so excluding types from push doesn't really
|
||||
// conflict with wiring up parent-child for the remaining types.
|
||||
//
|
||||
// TypeFilter IS kept as a scoping signal because --type is set only via
|
||||
// the CLI flag for this invocation; the user's intent to push a specific
|
||||
// subset is explicit.
|
||||
func syncIsScoped(opts *tracker.SyncOptions) bool {
|
||||
if opts == nil {
|
||||
return false
|
||||
}
|
||||
if opts.ParentID != "" || len(opts.IssueIDs) > 0 {
|
||||
return true
|
||||
}
|
||||
if len(opts.TypeFilter) > 0 {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// reconcileLinearParents runs as a post-sync pass to wire parent-child bead
|
||||
// dependencies into Linear's parent issue field. Idempotent — no API call
|
||||
// when the remote parent already matches.
|
||||
//
|
||||
// Two scenarios this fixes:
|
||||
//
|
||||
// 1. Fresh tree push: when a child is pushed before its parent in the same
|
||||
// sync, the create call has no parentId to send. After all issues have
|
||||
// external_refs, this pass closes the loop.
|
||||
// 2. Orphan repair: existing Linear issues created in earlier bd versions
|
||||
// (or by interrupted syncs) without a parent get wired up retroactively.
|
||||
//
|
||||
// In dry-run mode the read-only fetches still run and the per-link mutation
|
||||
// plan is printed as [dry-run] lines, but no IssueUpdate is issued. Lets
|
||||
// users preview the orphan-repair scope before committing to a wet sync.
|
||||
//
|
||||
// Human-readable output is suppressed when jsonOutput is true so the
|
||||
// caller's JSON serialization (in runLinearSync's output section) isn't
|
||||
// polluted with stray fmt.Printf lines. Warnings and errors still go
|
||||
// through the warnings slice, which IS surfaced in JSON output via
|
||||
// SyncResult.Warnings.
|
||||
//
|
||||
// Warnings (per-link failures, missing refs) are appended to the engine's
|
||||
// warning slice so the user sees them in the standard sync output.
|
||||
func reconcileLinearParents(ctx context.Context, lt *linear.Tracker, dryRun, jsonOutput bool, warnings *[]string) {
|
||||
if lt == nil || store == nil {
|
||||
return
|
||||
}
|
||||
links, err := buildLinearParentLinks(ctx, lt)
|
||||
if err != nil {
|
||||
*warnings = append(*warnings, fmt.Sprintf("parent reconcile: building link set failed: %v", err))
|
||||
return
|
||||
}
|
||||
if len(links) == 0 {
|
||||
return
|
||||
}
|
||||
stats, err := lt.ReconcileParents(ctx, links, dryRun)
|
||||
// Print mutation summary first; an abort (e.g. rate-limit circuit
|
||||
// breaker) may have completed some updates before bailing, and the
|
||||
// user should see that work wasn't lost. Suppress when --json is
|
||||
// requested so the JSON envelope stays clean.
|
||||
if stats != nil && !jsonOutput {
|
||||
if dryRun {
|
||||
if stats.WouldUpdate > 0 {
|
||||
fmt.Printf("[dry-run] Would reconcile %d Linear parent link%s\n",
|
||||
stats.WouldUpdate, plural(stats.WouldUpdate))
|
||||
for _, link := range stats.Mutations {
|
||||
fmt.Printf("[dry-run] Would set parent of %s → %s\n",
|
||||
link.ChildIdentifier, link.ParentIdentifier)
|
||||
}
|
||||
}
|
||||
} else if stats.Updated > 0 {
|
||||
fmt.Printf("✓ Reconciled %d Linear parent link%s\n",
|
||||
stats.Updated, plural(stats.Updated))
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
*warnings = append(*warnings, fmt.Sprintf("parent reconcile: %v", err))
|
||||
return
|
||||
}
|
||||
for _, e := range stats.Errors {
|
||||
*warnings = append(*warnings, fmt.Sprintf("parent reconcile: %v", e))
|
||||
}
|
||||
}
|
||||
|
||||
// buildLinearParentLinks enumerates local beads with a Linear external_ref
|
||||
// and a parent-child dependency to a parent that also has a Linear
|
||||
// external_ref. The result is the set of (child, parent) pairs whose
|
||||
// Linear parent field should be set.
|
||||
//
|
||||
// Beads whose parent isn't yet synced to Linear are silently skipped —
|
||||
// they'll get picked up on a subsequent sync once the parent has an
|
||||
// external_ref.
|
||||
func buildLinearParentLinks(ctx context.Context, lt *linear.Tracker) ([]linear.ParentLink, error) {
|
||||
issues, err := store.SearchIssues(ctx, "", types.IssueFilter{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// First pass: build bead_id → linear-identifier index, restricted to
|
||||
// beads whose ref looks like a Linear ref.
|
||||
idToIdent := make(map[string]string, len(issues))
|
||||
for _, issue := range issues {
|
||||
if issue.ExternalRef == nil {
|
||||
continue
|
||||
}
|
||||
ref := strings.TrimSpace(*issue.ExternalRef)
|
||||
if !lt.IsExternalRef(ref) {
|
||||
continue
|
||||
}
|
||||
ident := lt.ExtractIdentifier(ref)
|
||||
if ident == "" {
|
||||
continue
|
||||
}
|
||||
idToIdent[issue.ID] = ident
|
||||
}
|
||||
if len(idToIdent) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
// Second pass: walk each child-bead's dependencies, find the
|
||||
// parent-child edge, and emit a link if both ends are Linear-synced.
|
||||
links := make([]linear.ParentLink, 0)
|
||||
for _, issue := range issues {
|
||||
childIdent, ok := idToIdent[issue.ID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
deps, err := store.GetDependenciesWithMetadata(ctx, issue.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("loading deps for %s: %w", issue.ID, err)
|
||||
}
|
||||
for _, d := range deps {
|
||||
if d == nil || d.DependencyType != types.DepParentChild {
|
||||
continue
|
||||
}
|
||||
// child depends-on parent — the dep target's embedded Issue is the parent.
|
||||
parentIdent, ok := idToIdent[d.Issue.ID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
links = append(links, linear.ParentLink{
|
||||
ChildIdentifier: childIdent,
|
||||
ParentIdentifier: parentIdent,
|
||||
})
|
||||
}
|
||||
}
|
||||
return links, nil
|
||||
}
|
||||
|
||||
func plural(n int) string {
|
||||
if n == 1 {
|
||||
return ""
|
||||
}
|
||||
return "s"
|
||||
}
|
||||
|
|
|
|||
64
cmd/bd/sync_is_scoped_test.go
Normal file
64
cmd/bd/sync_is_scoped_test.go
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/tracker"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
// TestSyncIsScoped covers the gate that decides whether to skip the
|
||||
// post-sync parent reconcile pass. bd-9w3 root cause: ExcludeTypes is
|
||||
// almost always non-empty on real rigs (via persistent
|
||||
// linear.exclude_types config like "molecule,event"), so treating it as
|
||||
// a scoping signal silently disabled the reconcile pass entirely on
|
||||
// every full sync — orphans never got repaired.
|
||||
//
|
||||
// Contract: only flags the user EXPLICITLY passed this invocation count
|
||||
// as scoping. Persistent config exclusions don't disable reconcile.
|
||||
func TestSyncIsScoped(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
opts *tracker.SyncOptions
|
||||
want bool
|
||||
}{
|
||||
{"nil opts", nil, false},
|
||||
{"empty opts", &tracker.SyncOptions{}, false},
|
||||
{"parent id set", &tracker.SyncOptions{ParentID: "bd-foo"}, true},
|
||||
{"issue ids set", &tracker.SyncOptions{IssueIDs: []string{"bd-1", "bd-2"}}, true},
|
||||
{"type filter set", &tracker.SyncOptions{TypeFilter: []types.IssueType{types.TypeTask}}, true},
|
||||
|
||||
// bd-9w3: this is the case that was broken. A rig with persistent
|
||||
// linear.exclude_types = "molecule,event" populates opts.ExcludeTypes
|
||||
// on every sync — used to flip scoped=true and disable reconcile.
|
||||
{"exclude types only (persistent config)",
|
||||
&tracker.SyncOptions{ExcludeTypes: []types.IssueType{"molecule", "event"}}, false},
|
||||
|
||||
// Combined: exclude_types config + explicit --parent → still scoped
|
||||
// (the --parent is the actual scoping signal).
|
||||
{"exclude types + parent id",
|
||||
&tracker.SyncOptions{
|
||||
ParentID: "bd-foo",
|
||||
ExcludeTypes: []types.IssueType{"molecule"},
|
||||
}, true},
|
||||
|
||||
// Combined: exclude_types config + explicit --type → scoped
|
||||
// (the --type is the scoping signal).
|
||||
{"exclude types + type filter",
|
||||
&tracker.SyncOptions{
|
||||
TypeFilter: []types.IssueType{types.TypeFeature},
|
||||
ExcludeTypes: []types.IssueType{"molecule"},
|
||||
}, true},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := syncIsScoped(tc.opts)
|
||||
if got != tc.want {
|
||||
t.Errorf("syncIsScoped(%+v) = %v, want %v", tc.opts, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
249
internal/linear/parent_reconcile.go
Normal file
249
internal/linear/parent_reconcile.go
Normal file
|
|
@ -0,0 +1,249 @@
|
|||
package linear
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// fetchIssueAcrossTeams locates an issue by its Linear identifier across
|
||||
// all configured team clients. Single-team setups hit the primary client
|
||||
// directly; multi-team setups fall through each client in order until one
|
||||
// returns a non-nil issue. Returns (issue, hostClient, nil) on success;
|
||||
// the hostClient is the team's client that owned the issue and should be
|
||||
// reused for subsequent mutations (so the update path doesn't re-probe
|
||||
// and silently fall back to the wrong client on transient probe errors —
|
||||
// see clientForExternalID's fallback behavior in tracker.go).
|
||||
//
|
||||
// Returns (nil, nil, nil) when no team has the issue.
|
||||
func (t *Tracker) fetchIssueAcrossTeams(ctx context.Context, identifier string) (*Issue, *Client, error) {
|
||||
if identifier == "" {
|
||||
return nil, nil, nil
|
||||
}
|
||||
if len(t.teamIDs) <= 1 {
|
||||
client := t.primaryClient()
|
||||
if client == nil {
|
||||
return nil, nil, errors.New("no Linear client available")
|
||||
}
|
||||
li, err := client.FetchIssueByIdentifier(ctx, identifier)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if li == nil {
|
||||
return nil, nil, nil
|
||||
}
|
||||
return li, client, nil
|
||||
}
|
||||
// Multi-team: try each client. First non-nil result wins. Rate-limit
|
||||
// errors abort immediately (the cross-team probe shouldn't burn
|
||||
// through quota when the circuit breaker has already tripped).
|
||||
for _, teamID := range t.teamIDs {
|
||||
client := t.clients[teamID]
|
||||
if client == nil {
|
||||
continue
|
||||
}
|
||||
li, err := client.FetchIssueByIdentifier(ctx, identifier)
|
||||
if err != nil {
|
||||
if isRateLimitExhausted(err) {
|
||||
return nil, nil, err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if li != nil {
|
||||
return li, client, nil
|
||||
}
|
||||
}
|
||||
return nil, nil, nil
|
||||
}
|
||||
|
||||
// isRateLimitExhausted returns true when err (or any error it wraps)
|
||||
// signals that Linear's rate-limit circuit breaker has tripped.
|
||||
// Mirrors internal/tracker/engine.go isRateLimitExhausted, duplicated
|
||||
// here to avoid an import cycle.
|
||||
func isRateLimitExhausted(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
type rle interface{ RateLimitExhausted() bool }
|
||||
var r rle
|
||||
return errors.As(err, &r) && r.RateLimitExhausted()
|
||||
}
|
||||
|
||||
// ParentLink describes a desired parent-child relationship to wire up
|
||||
// on the Linear side. Both fields are Linear identifiers (e.g. "HOU-159")
|
||||
// — typically extracted from each bead's external_ref via
|
||||
// Tracker.ExtractIdentifier.
|
||||
type ParentLink struct {
|
||||
ChildIdentifier string
|
||||
ParentIdentifier string
|
||||
}
|
||||
|
||||
// ParentReconcileStats summarizes a ReconcileParents run.
|
||||
type ParentReconcileStats struct {
|
||||
// Updated is the count of Linear issues whose parent field was changed
|
||||
// (set, cleared, or rewired) by this pass. Zero in dry-run mode — see
|
||||
// WouldUpdate for the dry-run counterpart.
|
||||
Updated int
|
||||
// WouldUpdate is the count of mutations the pass WOULD have issued
|
||||
// in wet-run. Populated only in dry-run mode; zero in wet-run.
|
||||
WouldUpdate int
|
||||
// Mutations is the (child, parent) link list that was applied (wet-run)
|
||||
// or would have been applied (dry-run). In wet-run, an entry is appended
|
||||
// only after the IssueUpdate API call succeeds — so this list reflects
|
||||
// state actually propagated to Linear, not attempted. In dry-run, all
|
||||
// candidates that pass the idempotency check appear. Lets callers print
|
||||
// per-link detail without having to re-derive it.
|
||||
Mutations []ParentLink
|
||||
// Skipped is the count of links where Linear's parent already matched
|
||||
// the desired value — no API mutation was issued.
|
||||
Skipped int
|
||||
// NotFound is the list of identifiers (child or parent) that didn't
|
||||
// resolve to a Linear issue (typically because their bead has no
|
||||
// external_ref yet, or the Linear issue was deleted out-of-band).
|
||||
// Their links are silently skipped; the next sync will retry.
|
||||
NotFound []string
|
||||
// Errors collects per-link failures that did not abort the pass.
|
||||
Errors []error
|
||||
}
|
||||
|
||||
// ReconcileParents wires parent-child relationships from bead-side
|
||||
// dependencies to Linear's parent issue field. Used as a post-sync pass
|
||||
// to handle two cases that the per-issue create/update path can't cover:
|
||||
//
|
||||
// 1. New tree push: when a child is created before its parent's external
|
||||
// ref is known to the engine, the create call has no parentId to send.
|
||||
// This pass closes the loop after every issue in the tree has an
|
||||
// external ref.
|
||||
// 2. Orphan repair: existing Linear issues that were created (in earlier
|
||||
// bd versions or by interrupted syncs) without parentId can be wired
|
||||
// up retroactively.
|
||||
//
|
||||
// Idempotent: fetches each child's current parent and only issues
|
||||
// IssueUpdate when the remote parent differs from the desired value.
|
||||
// Each unique parent identifier is fetched once to resolve its UUID
|
||||
// (IssueUpdateInput.parentId requires the internal UUID, not the
|
||||
// human-readable identifier).
|
||||
//
|
||||
// When dryRun is true, the read-only fetches still run (so the caller
|
||||
// gets accurate Skipped / NotFound counts and a populated Mutations
|
||||
// list for preview output) but the IssueUpdate mutation is skipped.
|
||||
// Mutations that would have fired increment stats.WouldUpdate instead
|
||||
// of stats.Updated.
|
||||
//
|
||||
// Returns nil error when the pass completed (even if per-link errors
|
||||
// were collected in Stats.Errors). A non-nil error indicates a setup-level
|
||||
// failure that prevented any work from running.
|
||||
func (t *Tracker) ReconcileParents(ctx context.Context, links []ParentLink, dryRun bool) (*ParentReconcileStats, error) {
|
||||
stats := &ParentReconcileStats{}
|
||||
if len(links) == 0 {
|
||||
return stats, nil
|
||||
}
|
||||
if t.primaryClient() == nil {
|
||||
return nil, errors.New("no Linear client available")
|
||||
}
|
||||
|
||||
// Cache identifier → (issue, host client) so we don't refetch when a
|
||||
// parent is shared by many children, AND so the update path uses the
|
||||
// SAME client that successfully fetched the child (avoids re-probing
|
||||
// via clientForExternalID, which silently falls back to the primary
|
||||
// client on transient probe errors and could send the update to the
|
||||
// wrong team).
|
||||
type entry struct {
|
||||
issue *Issue
|
||||
client *Client
|
||||
}
|
||||
fetched := make(map[string]entry, len(links)*2)
|
||||
fetchIssue := func(identifier string) (entry, error) {
|
||||
if cached, ok := fetched[identifier]; ok {
|
||||
return cached, nil
|
||||
}
|
||||
issue, client, err := t.fetchIssueAcrossTeams(ctx, identifier)
|
||||
if err != nil {
|
||||
return entry{}, err
|
||||
}
|
||||
e := entry{issue: issue, client: client}
|
||||
// Cache nil too — repeated lookups are still cheap.
|
||||
fetched[identifier] = e
|
||||
return e, nil
|
||||
}
|
||||
|
||||
for _, link := range links {
|
||||
if link.ChildIdentifier == "" || link.ParentIdentifier == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
childE, err := fetchIssue(link.ChildIdentifier)
|
||||
if err != nil {
|
||||
// Rate-limit circuit breaker tripped — stop now rather than
|
||||
// hammer the API for every remaining link.
|
||||
if isRateLimitExhausted(err) {
|
||||
return stats, fmt.Errorf("fetch child %s: %w", link.ChildIdentifier, err)
|
||||
}
|
||||
stats.Errors = append(stats.Errors,
|
||||
fmt.Errorf("fetch child %s: %w", link.ChildIdentifier, err))
|
||||
continue
|
||||
}
|
||||
if childE.issue == nil {
|
||||
stats.NotFound = append(stats.NotFound, link.ChildIdentifier)
|
||||
continue
|
||||
}
|
||||
|
||||
parentE, err := fetchIssue(link.ParentIdentifier)
|
||||
if err != nil {
|
||||
if isRateLimitExhausted(err) {
|
||||
return stats, fmt.Errorf("fetch parent %s: %w", link.ParentIdentifier, err)
|
||||
}
|
||||
stats.Errors = append(stats.Errors,
|
||||
fmt.Errorf("fetch parent %s: %w", link.ParentIdentifier, err))
|
||||
continue
|
||||
}
|
||||
if parentE.issue == nil {
|
||||
stats.NotFound = append(stats.NotFound, link.ParentIdentifier)
|
||||
continue
|
||||
}
|
||||
|
||||
// Idempotency: skip if remote parent already matches by UUID.
|
||||
if childE.issue.Parent != nil && childE.issue.Parent.ID == parentE.issue.ID {
|
||||
stats.Skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
if dryRun {
|
||||
// Dry-run: record the intended mutation but skip the API call.
|
||||
// All read-only state (fetch results, idempotency check above)
|
||||
// matched wet-run, so the preview is trustworthy.
|
||||
stats.Mutations = append(stats.Mutations, link)
|
||||
stats.WouldUpdate++
|
||||
continue
|
||||
}
|
||||
|
||||
// Use the child's host client (resolved during fetch) so the
|
||||
// update goes to the correct team in multi-team setups.
|
||||
updated, err := childE.client.UpdateIssue(ctx, childE.issue.ID, map[string]interface{}{
|
||||
"parentId": parentE.issue.ID,
|
||||
})
|
||||
if err != nil {
|
||||
if isRateLimitExhausted(err) {
|
||||
return stats, fmt.Errorf("set parent of %s → %s: %w",
|
||||
link.ChildIdentifier, link.ParentIdentifier, err)
|
||||
}
|
||||
stats.Errors = append(stats.Errors,
|
||||
fmt.Errorf("set parent of %s → %s: %w",
|
||||
link.ChildIdentifier, link.ParentIdentifier, err))
|
||||
continue
|
||||
}
|
||||
// Refresh cache with the post-update issue (Linear returns the
|
||||
// updated record), so a later link that references this child
|
||||
// as a parent sees the freshest state. Host client is unchanged.
|
||||
if updated != nil {
|
||||
fetched[link.ChildIdentifier] = entry{issue: updated, client: childE.client}
|
||||
}
|
||||
// Record the mutation only AFTER the API call succeeds, so
|
||||
// Mutations reflects actual state propagated to Linear (callers
|
||||
// can trust the list for accurate post-sync reporting).
|
||||
stats.Mutations = append(stats.Mutations, link)
|
||||
stats.Updated++
|
||||
}
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
644
internal/linear/parent_reconcile_test.go
Normal file
644
internal/linear/parent_reconcile_test.go
Normal file
|
|
@ -0,0 +1,644 @@
|
|||
package linear
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// linearMockHandler is a tiny GraphQL mock that routes by query keyword.
|
||||
// Queries it understands:
|
||||
// - "IssueByIdentifier" → returns issues[identifier] (or empty nodes)
|
||||
// - "issueUpdate" → records the update and returns the (notional) issue
|
||||
//
|
||||
// All other queries return an empty data object.
|
||||
//
|
||||
// Fidelity gap (acceptable for unit tests): the real client's
|
||||
// FetchIssueByIdentifier filters by team UUID AND issue number; this mock
|
||||
// suffix-scans the `number.eq` value against issue identifiers and ignores
|
||||
// team. That's fine here because we only care about parent-reconcile
|
||||
// semantics, not the team-routing logic of FetchIssueByIdentifier itself.
|
||||
type linearMockHandler struct {
|
||||
t *testing.T
|
||||
issues map[string]*Issue // identifier → issue (for fetch)
|
||||
updates map[string]json.RawMessage // child UUID → input JSON (recorded)
|
||||
fetches map[string]int // identifier → fetch call count
|
||||
failNextRL bool // when true, next fetch returns ErrRateLimitExhausted
|
||||
rateLimited int // count of rate-limited responses returned
|
||||
}
|
||||
|
||||
func newLinearMock(t *testing.T) *linearMockHandler {
|
||||
return &linearMockHandler{
|
||||
t: t,
|
||||
issues: map[string]*Issue{},
|
||||
updates: map[string]json.RawMessage{},
|
||||
fetches: map[string]int{},
|
||||
}
|
||||
}
|
||||
|
||||
func (h *linearMockHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
var req GraphQLRequest
|
||||
if err := json.Unmarshal(body, &req); err != nil {
|
||||
h.t.Fatalf("mock: bad request JSON: %v", err)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
// If failNextRL is set, return rate-limit-exhausted on this single
|
||||
// response (header drives the circuit breaker in Execute).
|
||||
if h.failNextRL {
|
||||
h.failNextRL = false
|
||||
h.rateLimited++
|
||||
w.Header().Set("X-RateLimit-Requests-Remaining", "1") // < DefaultRateLimitFloor (100)
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{"data": map[string]interface{}{}})
|
||||
return
|
||||
}
|
||||
|
||||
switch {
|
||||
case strings.Contains(req.Query, "IssueByIdentifier"):
|
||||
// FetchIssueByIdentifier filters by team + number; the mock keys
|
||||
// directly by identifier extracted from the filter for simplicity.
|
||||
filter, _ := req.Variables["filter"].(map[string]interface{})
|
||||
number, _ := filter["number"].(map[string]interface{})
|
||||
eq, _ := number["eq"].(float64)
|
||||
// Recover identifier by scanning issues for a matching team+number.
|
||||
// In the test fixture we just embed the number in identifier "TEAM-N".
|
||||
var found *Issue
|
||||
for ident, iss := range h.issues {
|
||||
if strings.HasSuffix(ident, "-"+itoa(int(eq))) {
|
||||
h.fetches[ident]++
|
||||
found = iss
|
||||
break
|
||||
}
|
||||
}
|
||||
nodes := []interface{}{}
|
||||
if found != nil {
|
||||
b, _ := json.Marshal(found)
|
||||
var raw map[string]interface{}
|
||||
_ = json.Unmarshal(b, &raw)
|
||||
nodes = append(nodes, raw)
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"data": map[string]interface{}{
|
||||
"issues": map[string]interface{}{"nodes": nodes},
|
||||
},
|
||||
})
|
||||
return
|
||||
case strings.Contains(req.Query, "issueUpdate"):
|
||||
id, _ := req.Variables["id"].(string)
|
||||
input, _ := json.Marshal(req.Variables["input"])
|
||||
h.updates[id] = input
|
||||
// Return the (notional) updated issue. Tests don't depend on the
|
||||
// exact echo, but we round-trip the relevant fields so the cached
|
||||
// fetch is consistent if subsequent calls reference this child.
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"data": map[string]interface{}{
|
||||
"issueUpdate": map[string]interface{}{
|
||||
"success": true,
|
||||
"issue": map[string]interface{}{
|
||||
"id": id,
|
||||
"identifier": "ECHO",
|
||||
"title": "echo",
|
||||
"updatedAt": "2026-05-13T00:00:00Z",
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{"data": map[string]interface{}{}})
|
||||
}
|
||||
|
||||
func itoa(n int) string {
|
||||
// stdlib without importing strconv twice
|
||||
if n == 0 {
|
||||
return "0"
|
||||
}
|
||||
neg := false
|
||||
if n < 0 {
|
||||
neg = true
|
||||
n = -n
|
||||
}
|
||||
var b [12]byte
|
||||
i := len(b)
|
||||
for n > 0 {
|
||||
i--
|
||||
b[i] = byte('0' + n%10)
|
||||
n /= 10
|
||||
}
|
||||
if neg {
|
||||
i--
|
||||
b[i] = '-'
|
||||
}
|
||||
return string(b[i:])
|
||||
}
|
||||
|
||||
func newTestLinearTracker(t *testing.T, serverURL string) *Tracker {
|
||||
tr := &Tracker{
|
||||
teamIDs: []string{"team-uuid"},
|
||||
clients: map[string]*Client{
|
||||
"team-uuid": NewClient("test-key", "team-uuid").WithEndpoint(serverURL),
|
||||
},
|
||||
}
|
||||
return tr
|
||||
}
|
||||
|
||||
// newTestMultiTeamTracker wires a tracker with N teams, each pointed at its
|
||||
// own mock-server URL. Returns the tracker and the same teamIDs slice in
|
||||
// stable order (matching Tracker.teamIDs iteration order).
|
||||
func newTestMultiTeamTracker(t *testing.T, serverURLs []string) (*Tracker, []string) {
|
||||
teamIDs := make([]string, len(serverURLs))
|
||||
clients := make(map[string]*Client, len(serverURLs))
|
||||
for i, url := range serverURLs {
|
||||
id := "team-" + itoa(i)
|
||||
teamIDs[i] = id
|
||||
clients[id] = NewClient("test-key", id).WithEndpoint(url)
|
||||
}
|
||||
return &Tracker{teamIDs: teamIDs, clients: clients}, teamIDs
|
||||
}
|
||||
|
||||
// TestReconcileParents_HappyPath verifies that a child needing its parent
|
||||
// set produces exactly one fetch per unique identifier and one UpdateIssue
|
||||
// call carrying the parent's UUID.
|
||||
func TestReconcileParents_HappyPath(t *testing.T) {
|
||||
mock := newLinearMock(t)
|
||||
mock.issues["TEAM-1"] = &Issue{ID: "uuid-child", Identifier: "TEAM-1"} // child has no parent yet
|
||||
mock.issues["TEAM-2"] = &Issue{ID: "uuid-parent", Identifier: "TEAM-2"} // parent
|
||||
server := httptest.NewServer(mock)
|
||||
defer server.Close()
|
||||
|
||||
tr := newTestLinearTracker(t, server.URL)
|
||||
stats, err := tr.ReconcileParents(context.Background(), []ParentLink{
|
||||
{ChildIdentifier: "TEAM-1", ParentIdentifier: "TEAM-2"},
|
||||
}, false)
|
||||
if err != nil {
|
||||
t.Fatalf("ReconcileParents err: %v", err)
|
||||
}
|
||||
if stats.Updated != 1 || stats.Skipped != 0 || len(stats.Errors) != 0 {
|
||||
t.Fatalf("stats = %+v, want Updated=1 Skipped=0", stats)
|
||||
}
|
||||
if len(mock.updates) != 1 {
|
||||
t.Fatalf("expected 1 issueUpdate call, got %d", len(mock.updates))
|
||||
}
|
||||
// The update target should be the child's UUID.
|
||||
input, ok := mock.updates["uuid-child"]
|
||||
if !ok {
|
||||
t.Fatalf("expected update on uuid-child, got updates: %v", mock.updates)
|
||||
}
|
||||
if !strings.Contains(string(input), `"parentId":"uuid-parent"`) {
|
||||
t.Errorf("update input missing parent UUID: %s", input)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReconcileParents_IdempotentSkip verifies that when the child's
|
||||
// remote parent already matches, no UpdateIssue is issued.
|
||||
func TestReconcileParents_IdempotentSkip(t *testing.T) {
|
||||
mock := newLinearMock(t)
|
||||
mock.issues["TEAM-1"] = &Issue{ID: "uuid-child", Identifier: "TEAM-1",
|
||||
Parent: &Parent{ID: "uuid-parent", Identifier: "TEAM-2"}}
|
||||
mock.issues["TEAM-2"] = &Issue{ID: "uuid-parent", Identifier: "TEAM-2"}
|
||||
server := httptest.NewServer(mock)
|
||||
defer server.Close()
|
||||
|
||||
tr := newTestLinearTracker(t, server.URL)
|
||||
stats, err := tr.ReconcileParents(context.Background(), []ParentLink{
|
||||
{ChildIdentifier: "TEAM-1", ParentIdentifier: "TEAM-2"},
|
||||
}, false)
|
||||
if err != nil {
|
||||
t.Fatalf("ReconcileParents err: %v", err)
|
||||
}
|
||||
if stats.Updated != 0 || stats.Skipped != 1 {
|
||||
t.Fatalf("stats = %+v, want Updated=0 Skipped=1", stats)
|
||||
}
|
||||
if len(mock.updates) != 0 {
|
||||
t.Errorf("expected no updates (idempotent), got %d", len(mock.updates))
|
||||
}
|
||||
}
|
||||
|
||||
// TestReconcileParents_RewiresWrongParent verifies that a child currently
|
||||
// pointing at a different parent gets its parent rewired (Linear-side state
|
||||
// took precedence over local intent — bd-ena's intended behavior).
|
||||
func TestReconcileParents_RewiresWrongParent(t *testing.T) {
|
||||
mock := newLinearMock(t)
|
||||
mock.issues["TEAM-1"] = &Issue{ID: "uuid-child", Identifier: "TEAM-1",
|
||||
Parent: &Parent{ID: "uuid-WRONG-parent", Identifier: "TEAM-99"}}
|
||||
mock.issues["TEAM-2"] = &Issue{ID: "uuid-parent", Identifier: "TEAM-2"}
|
||||
server := httptest.NewServer(mock)
|
||||
defer server.Close()
|
||||
|
||||
tr := newTestLinearTracker(t, server.URL)
|
||||
stats, err := tr.ReconcileParents(context.Background(), []ParentLink{
|
||||
{ChildIdentifier: "TEAM-1", ParentIdentifier: "TEAM-2"},
|
||||
}, false)
|
||||
if err != nil {
|
||||
t.Fatalf("ReconcileParents err: %v", err)
|
||||
}
|
||||
if stats.Updated != 1 {
|
||||
t.Errorf("Updated = %d, want 1 (wrong parent should be rewired)", stats.Updated)
|
||||
}
|
||||
input := mock.updates["uuid-child"]
|
||||
if !strings.Contains(string(input), `"parentId":"uuid-parent"`) {
|
||||
t.Errorf("expected rewire to uuid-parent, got: %s", input)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReconcileParents_FetchCaching verifies that a parent referenced by
|
||||
// multiple children is fetched only once. (Cuts API calls in the common
|
||||
// case where one epic has many sub-issues.)
|
||||
func TestReconcileParents_FetchCaching(t *testing.T) {
|
||||
mock := newLinearMock(t)
|
||||
for i, ident := range []string{"TEAM-10", "TEAM-11", "TEAM-12"} {
|
||||
_ = i
|
||||
mock.issues[ident] = &Issue{ID: "uuid-" + ident, Identifier: ident}
|
||||
}
|
||||
mock.issues["TEAM-99"] = &Issue{ID: "uuid-parent", Identifier: "TEAM-99"}
|
||||
server := httptest.NewServer(mock)
|
||||
defer server.Close()
|
||||
|
||||
tr := newTestLinearTracker(t, server.URL)
|
||||
links := []ParentLink{
|
||||
{ChildIdentifier: "TEAM-10", ParentIdentifier: "TEAM-99"},
|
||||
{ChildIdentifier: "TEAM-11", ParentIdentifier: "TEAM-99"},
|
||||
{ChildIdentifier: "TEAM-12", ParentIdentifier: "TEAM-99"},
|
||||
}
|
||||
stats, err := tr.ReconcileParents(context.Background(), links, false)
|
||||
if err != nil {
|
||||
t.Fatalf("ReconcileParents err: %v", err)
|
||||
}
|
||||
if stats.Updated != 3 {
|
||||
t.Errorf("Updated = %d, want 3", stats.Updated)
|
||||
}
|
||||
if mock.fetches["TEAM-99"] != 1 {
|
||||
t.Errorf("parent fetched %d times, want 1 (caching broken)", mock.fetches["TEAM-99"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestReconcileParents_MissingChildOrParent verifies that links with
|
||||
// unresolvable identifiers go to NotFound rather than failing the pass.
|
||||
func TestReconcileParents_MissingChildOrParent(t *testing.T) {
|
||||
mock := newLinearMock(t)
|
||||
mock.issues["TEAM-1"] = &Issue{ID: "uuid-child", Identifier: "TEAM-1"}
|
||||
// TEAM-99 (parent) and TEAM-2 (child for second link) are intentionally
|
||||
// absent.
|
||||
server := httptest.NewServer(mock)
|
||||
defer server.Close()
|
||||
|
||||
tr := newTestLinearTracker(t, server.URL)
|
||||
stats, err := tr.ReconcileParents(context.Background(), []ParentLink{
|
||||
{ChildIdentifier: "TEAM-1", ParentIdentifier: "TEAM-99"}, // parent missing
|
||||
{ChildIdentifier: "TEAM-2", ParentIdentifier: "TEAM-1"}, // child missing
|
||||
}, false)
|
||||
if err != nil {
|
||||
t.Fatalf("ReconcileParents err: %v", err)
|
||||
}
|
||||
if stats.Updated != 0 {
|
||||
t.Errorf("Updated = %d, want 0", stats.Updated)
|
||||
}
|
||||
if len(stats.NotFound) != 2 {
|
||||
t.Errorf("NotFound = %v, want 2 entries", stats.NotFound)
|
||||
}
|
||||
if len(mock.updates) != 0 {
|
||||
t.Errorf("expected no updates when targets missing, got %d", len(mock.updates))
|
||||
}
|
||||
}
|
||||
|
||||
// TestReconcileParents_EmptyLinks short-circuits cleanly.
|
||||
func TestReconcileParents_EmptyLinks(t *testing.T) {
|
||||
tr := &Tracker{} // no client needed
|
||||
stats, err := tr.ReconcileParents(context.Background(), nil, false)
|
||||
if err != nil {
|
||||
t.Fatalf("ReconcileParents err: %v", err)
|
||||
}
|
||||
if stats.Updated != 0 || stats.Skipped != 0 {
|
||||
t.Errorf("stats = %+v, want zero", stats)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReconcileParents_MultiTeam verifies cross-team probing: a child
|
||||
// living on team B and a parent on team A both resolve, and the update
|
||||
// goes to the team-client that owns the child (not the primary team's
|
||||
// client). This guards against the silent-fallback bug in
|
||||
// clientForExternalID where probe failures route to the primary client.
|
||||
func TestReconcileParents_MultiTeam(t *testing.T) {
|
||||
mockA := newLinearMock(t)
|
||||
mockA.issues["TEAM-1"] = &Issue{ID: "uuid-A1-parent", Identifier: "TEAM-1"}
|
||||
srvA := httptest.NewServer(mockA)
|
||||
defer srvA.Close()
|
||||
|
||||
mockB := newLinearMock(t)
|
||||
mockB.issues["TEAM-2"] = &Issue{ID: "uuid-B2-child", Identifier: "TEAM-2"}
|
||||
srvB := httptest.NewServer(mockB)
|
||||
defer srvB.Close()
|
||||
|
||||
tr, _ := newTestMultiTeamTracker(t, []string{srvA.URL, srvB.URL})
|
||||
stats, err := tr.ReconcileParents(context.Background(), []ParentLink{
|
||||
{ChildIdentifier: "TEAM-2", ParentIdentifier: "TEAM-1"},
|
||||
}, false)
|
||||
if err != nil {
|
||||
t.Fatalf("ReconcileParents err: %v", err)
|
||||
}
|
||||
if stats.Updated != 1 {
|
||||
t.Fatalf("Updated = %d, want 1", stats.Updated)
|
||||
}
|
||||
// Update must hit team B's mock (where the child lives), not team A's.
|
||||
if _, ok := mockB.updates["uuid-B2-child"]; !ok {
|
||||
t.Errorf("expected update on team B mock for uuid-B2-child, got: %v / %v",
|
||||
mockA.updates, mockB.updates)
|
||||
}
|
||||
if len(mockA.updates) != 0 {
|
||||
t.Errorf("expected no updates on team A (parent's team), got: %v", mockA.updates)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReconcileParents_AbortsOnRateLimit verifies that hitting the rate-
|
||||
// limit circuit breaker stops the pass immediately instead of grinding
|
||||
// through the remaining links and accumulating failures.
|
||||
func TestReconcileParents_AbortsOnRateLimit(t *testing.T) {
|
||||
mock := newLinearMock(t)
|
||||
mock.issues["TEAM-1"] = &Issue{ID: "uuid-child1", Identifier: "TEAM-1"}
|
||||
mock.issues["TEAM-2"] = &Issue{ID: "uuid-child2", Identifier: "TEAM-2"}
|
||||
mock.issues["TEAM-99"] = &Issue{ID: "uuid-parent", Identifier: "TEAM-99"}
|
||||
mock.failNextRL = true // first request returns ErrRateLimitExhausted
|
||||
server := httptest.NewServer(mock)
|
||||
defer server.Close()
|
||||
|
||||
tr := newTestLinearTracker(t, server.URL)
|
||||
stats, err := tr.ReconcileParents(context.Background(), []ParentLink{
|
||||
{ChildIdentifier: "TEAM-1", ParentIdentifier: "TEAM-99"},
|
||||
{ChildIdentifier: "TEAM-2", ParentIdentifier: "TEAM-99"},
|
||||
}, false)
|
||||
if err == nil {
|
||||
t.Fatal("expected error from rate-limit abort, got nil")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "rate limit") && !strings.Contains(err.Error(), "RateLimitExhausted") {
|
||||
t.Errorf("expected rate-limit error, got: %v", err)
|
||||
}
|
||||
// Pass should bail out — at most the first child was processed; subsequent
|
||||
// links should never reach IssueUpdate.
|
||||
if len(mock.updates) > 0 {
|
||||
t.Errorf("expected 0 updates after rate-limit abort, got %d", len(mock.updates))
|
||||
}
|
||||
if stats.Updated != 0 {
|
||||
t.Errorf("Updated = %d, want 0 (no updates after abort)", stats.Updated)
|
||||
}
|
||||
if mock.rateLimited != 1 {
|
||||
t.Errorf("expected exactly 1 rate-limited response (single failure → abort), got %d", mock.rateLimited)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReconcileParents_BlankIdentifiersSkipped — defensive guard against
|
||||
// callers that build links with empty fields.
|
||||
func TestReconcileParents_BlankIdentifiersSkipped(t *testing.T) {
|
||||
mock := newLinearMock(t)
|
||||
server := httptest.NewServer(mock)
|
||||
defer server.Close()
|
||||
|
||||
tr := newTestLinearTracker(t, server.URL)
|
||||
stats, err := tr.ReconcileParents(context.Background(), []ParentLink{
|
||||
{ChildIdentifier: "", ParentIdentifier: "TEAM-2"},
|
||||
{ChildIdentifier: "TEAM-1", ParentIdentifier: ""},
|
||||
}, false)
|
||||
if err != nil {
|
||||
t.Fatalf("ReconcileParents err: %v", err)
|
||||
}
|
||||
if stats.Updated != 0 {
|
||||
t.Errorf("Updated = %d, want 0", stats.Updated)
|
||||
}
|
||||
if len(mock.updates) != 0 || len(mock.fetches) != 0 {
|
||||
t.Errorf("expected no API calls for blank links, fetches=%v updates=%v",
|
||||
mock.fetches, mock.updates)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReconcileParents_DryRunNoMutations is the bd-5zh acceptance: when
|
||||
// dryRun=true, the read-only fetches still run (Skipped, NotFound, and
|
||||
// Mutations populate correctly) but ZERO IssueUpdate calls fire. WouldUpdate
|
||||
// counts the mutations that would have been issued; Updated stays 0.
|
||||
func TestReconcileParents_DryRunNoMutations(t *testing.T) {
|
||||
mock := newLinearMock(t)
|
||||
mock.issues["TEAM-1"] = &Issue{ID: "uuid-c1", Identifier: "TEAM-1"} // needs parent
|
||||
mock.issues["TEAM-2"] = &Issue{ID: "uuid-c2", Identifier: "TEAM-2", //
|
||||
Parent: &Parent{ID: "uuid-p", Identifier: "TEAM-99"}} // already correct
|
||||
mock.issues["TEAM-3"] = &Issue{ID: "uuid-c3", Identifier: "TEAM-3"} // needs parent
|
||||
mock.issues["TEAM-99"] = &Issue{ID: "uuid-p", Identifier: "TEAM-99"}
|
||||
server := httptest.NewServer(mock)
|
||||
defer server.Close()
|
||||
|
||||
tr := newTestLinearTracker(t, server.URL)
|
||||
stats, err := tr.ReconcileParents(context.Background(), []ParentLink{
|
||||
{ChildIdentifier: "TEAM-1", ParentIdentifier: "TEAM-99"},
|
||||
{ChildIdentifier: "TEAM-2", ParentIdentifier: "TEAM-99"},
|
||||
{ChildIdentifier: "TEAM-3", ParentIdentifier: "TEAM-99"},
|
||||
}, true)
|
||||
if err != nil {
|
||||
t.Fatalf("ReconcileParents err: %v", err)
|
||||
}
|
||||
if stats.Updated != 0 {
|
||||
t.Errorf("Updated = %d, want 0 in dry-run", stats.Updated)
|
||||
}
|
||||
if stats.WouldUpdate != 2 {
|
||||
t.Errorf("WouldUpdate = %d, want 2 (TEAM-1 + TEAM-3 need parent set)", stats.WouldUpdate)
|
||||
}
|
||||
if stats.Skipped != 1 {
|
||||
t.Errorf("Skipped = %d, want 1 (TEAM-2 already correct)", stats.Skipped)
|
||||
}
|
||||
if len(mock.updates) != 0 {
|
||||
t.Errorf("dry-run must not issue IssueUpdate; got %d updates: %v", len(mock.updates), mock.updates)
|
||||
}
|
||||
if len(stats.Mutations) != 2 {
|
||||
t.Fatalf("Mutations = %v, want 2 entries", stats.Mutations)
|
||||
}
|
||||
// Mutations should carry the original identifiers in order of input.
|
||||
if stats.Mutations[0].ChildIdentifier != "TEAM-1" || stats.Mutations[0].ParentIdentifier != "TEAM-99" {
|
||||
t.Errorf("Mutations[0] = %+v, want TEAM-1 → TEAM-99", stats.Mutations[0])
|
||||
}
|
||||
if stats.Mutations[1].ChildIdentifier != "TEAM-3" || stats.Mutations[1].ParentIdentifier != "TEAM-99" {
|
||||
t.Errorf("Mutations[1] = %+v, want TEAM-3 → TEAM-99", stats.Mutations[1])
|
||||
}
|
||||
}
|
||||
|
||||
// TestReconcileParents_DryRunIdempotentSkipUnchanged verifies that when
|
||||
// every link is already correct, dry-run produces zero WouldUpdate and
|
||||
// matches wet-run's Skipped count.
|
||||
func TestReconcileParents_DryRunIdempotentSkipUnchanged(t *testing.T) {
|
||||
mock := newLinearMock(t)
|
||||
mock.issues["TEAM-1"] = &Issue{ID: "uuid-c", Identifier: "TEAM-1",
|
||||
Parent: &Parent{ID: "uuid-p", Identifier: "TEAM-2"}}
|
||||
mock.issues["TEAM-2"] = &Issue{ID: "uuid-p", Identifier: "TEAM-2"}
|
||||
server := httptest.NewServer(mock)
|
||||
defer server.Close()
|
||||
|
||||
tr := newTestLinearTracker(t, server.URL)
|
||||
stats, err := tr.ReconcileParents(context.Background(), []ParentLink{
|
||||
{ChildIdentifier: "TEAM-1", ParentIdentifier: "TEAM-2"},
|
||||
}, true)
|
||||
if err != nil {
|
||||
t.Fatalf("ReconcileParents err: %v", err)
|
||||
}
|
||||
if stats.WouldUpdate != 0 {
|
||||
t.Errorf("WouldUpdate = %d, want 0 (already correct)", stats.WouldUpdate)
|
||||
}
|
||||
if stats.Skipped != 1 {
|
||||
t.Errorf("Skipped = %d, want 1", stats.Skipped)
|
||||
}
|
||||
if len(stats.Mutations) != 0 {
|
||||
t.Errorf("Mutations = %v, want empty (no changes needed)", stats.Mutations)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReconcileParents_DryRunMissingTargetsNotFound verifies that dry-run
|
||||
// still surfaces NotFound entries for unresolvable identifiers, so the user
|
||||
// gets the same visibility into orphan targets as wet-run.
|
||||
func TestReconcileParents_DryRunMissingTargetsNotFound(t *testing.T) {
|
||||
mock := newLinearMock(t)
|
||||
mock.issues["TEAM-1"] = &Issue{ID: "uuid-c", Identifier: "TEAM-1"}
|
||||
// TEAM-99 (parent) intentionally absent.
|
||||
server := httptest.NewServer(mock)
|
||||
defer server.Close()
|
||||
|
||||
tr := newTestLinearTracker(t, server.URL)
|
||||
stats, err := tr.ReconcileParents(context.Background(), []ParentLink{
|
||||
{ChildIdentifier: "TEAM-1", ParentIdentifier: "TEAM-99"},
|
||||
}, true)
|
||||
if err != nil {
|
||||
t.Fatalf("ReconcileParents err: %v", err)
|
||||
}
|
||||
if stats.WouldUpdate != 0 || stats.Updated != 0 {
|
||||
t.Errorf("Would/Updated = %d/%d, want 0/0", stats.WouldUpdate, stats.Updated)
|
||||
}
|
||||
if len(stats.NotFound) != 1 || stats.NotFound[0] != "TEAM-99" {
|
||||
t.Errorf("NotFound = %v, want [TEAM-99]", stats.NotFound)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReconcileParents_DryRunMatchesWetRunMutationSet verifies that the
|
||||
// Mutations list is identical between dry-run and wet-run for the same
|
||||
// input. This is the property that makes dry-run a trustworthy pre-flight:
|
||||
// what you see is what you'll get.
|
||||
func TestReconcileParents_DryRunMatchesWetRunMutationSet(t *testing.T) {
|
||||
makeMock := func() *linearMockHandler {
|
||||
m := newLinearMock(t)
|
||||
m.issues["TEAM-1"] = &Issue{ID: "uuid-c1", Identifier: "TEAM-1"}
|
||||
m.issues["TEAM-2"] = &Issue{ID: "uuid-c2", Identifier: "TEAM-2"}
|
||||
m.issues["TEAM-99"] = &Issue{ID: "uuid-p", Identifier: "TEAM-99"}
|
||||
return m
|
||||
}
|
||||
links := []ParentLink{
|
||||
{ChildIdentifier: "TEAM-1", ParentIdentifier: "TEAM-99"},
|
||||
{ChildIdentifier: "TEAM-2", ParentIdentifier: "TEAM-99"},
|
||||
}
|
||||
|
||||
// Dry-run
|
||||
dryMock := makeMock()
|
||||
drySrv := httptest.NewServer(dryMock)
|
||||
defer drySrv.Close()
|
||||
dryTr := newTestLinearTracker(t, drySrv.URL)
|
||||
dryStats, err := dryTr.ReconcileParents(context.Background(), links, true)
|
||||
if err != nil {
|
||||
t.Fatalf("dry: %v", err)
|
||||
}
|
||||
|
||||
// Wet-run
|
||||
wetMock := makeMock()
|
||||
wetSrv := httptest.NewServer(wetMock)
|
||||
defer wetSrv.Close()
|
||||
wetTr := newTestLinearTracker(t, wetSrv.URL)
|
||||
wetStats, err := wetTr.ReconcileParents(context.Background(), links, false)
|
||||
if err != nil {
|
||||
t.Fatalf("wet: %v", err)
|
||||
}
|
||||
|
||||
if dryStats.WouldUpdate != wetStats.Updated {
|
||||
t.Errorf("dry WouldUpdate=%d vs wet Updated=%d (must match)",
|
||||
dryStats.WouldUpdate, wetStats.Updated)
|
||||
}
|
||||
if len(dryStats.Mutations) != len(wetStats.Mutations) {
|
||||
t.Fatalf("Mutations length differs: dry=%d wet=%d",
|
||||
len(dryStats.Mutations), len(wetStats.Mutations))
|
||||
}
|
||||
for i := range dryStats.Mutations {
|
||||
if dryStats.Mutations[i] != wetStats.Mutations[i] {
|
||||
t.Errorf("Mutations[%d] differ: dry=%+v wet=%+v",
|
||||
i, dryStats.Mutations[i], wetStats.Mutations[i])
|
||||
}
|
||||
}
|
||||
// Sanity: wet-run actually issued updates, dry-run did not.
|
||||
if len(dryMock.updates) != 0 {
|
||||
t.Errorf("dry mock saw %d updates; expected 0", len(dryMock.updates))
|
||||
}
|
||||
if len(wetMock.updates) != 2 {
|
||||
t.Errorf("wet mock saw %d updates; expected 2", len(wetMock.updates))
|
||||
}
|
||||
}
|
||||
|
||||
// TestReconcileParents_WetRunFailureDoesNotRecordMutation verifies that
|
||||
// when a wet-run UpdateIssue call fails (e.g. transient API error), the
|
||||
// failed mutation is NOT appended to stats.Mutations. The contract is
|
||||
// that Mutations reflects state actually propagated to Linear in wet-run,
|
||||
// so callers can trust it for post-sync reporting.
|
||||
func TestReconcileParents_WetRunFailureDoesNotRecordMutation(t *testing.T) {
|
||||
// Custom handler: succeeds on fetch, returns success=false on update.
|
||||
updateAttempts := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
var req GraphQLRequest
|
||||
if err := json.Unmarshal(body, &req); err != nil {
|
||||
t.Fatalf("bad request: %v", err)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
switch {
|
||||
case strings.Contains(req.Query, "IssueByIdentifier"):
|
||||
filter, _ := req.Variables["filter"].(map[string]interface{})
|
||||
number, _ := filter["number"].(map[string]interface{})
|
||||
eq, _ := number["eq"].(float64)
|
||||
id := "uuid-" + itoa(int(eq))
|
||||
ident := "TEAM-" + itoa(int(eq))
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"data": map[string]interface{}{
|
||||
"issues": map[string]interface{}{
|
||||
"nodes": []interface{}{
|
||||
map[string]interface{}{"id": id, "identifier": ident,
|
||||
"createdAt": "2026-05-22T00:00:00Z", "updatedAt": "2026-05-22T00:00:00Z"},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
case strings.Contains(req.Query, "issueUpdate"):
|
||||
updateAttempts++
|
||||
// Return success=false to surface as an error to the client.
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"data": map[string]interface{}{
|
||||
"issueUpdate": map[string]interface{}{"success": false, "issue": nil},
|
||||
},
|
||||
})
|
||||
default:
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{"data": map[string]interface{}{}})
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
tr := newTestLinearTracker(t, server.URL)
|
||||
stats, err := tr.ReconcileParents(context.Background(), []ParentLink{
|
||||
{ChildIdentifier: "TEAM-1", ParentIdentifier: "TEAM-2"},
|
||||
}, false)
|
||||
if err != nil {
|
||||
t.Fatalf("ReconcileParents: %v", err)
|
||||
}
|
||||
if updateAttempts != 1 {
|
||||
t.Errorf("expected 1 update attempt, got %d", updateAttempts)
|
||||
}
|
||||
if stats.Updated != 0 {
|
||||
t.Errorf("Updated = %d, want 0 (API call failed)", stats.Updated)
|
||||
}
|
||||
if len(stats.Mutations) != 0 {
|
||||
t.Errorf("Mutations = %v, want empty (no successful mutation)", stats.Mutations)
|
||||
}
|
||||
if len(stats.Errors) != 1 {
|
||||
t.Errorf("Errors = %v, want 1 entry", stats.Errors)
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue