diff --git a/.github/workflows/proxied-local-smoke.yml b/.github/workflows/proxied-local-smoke.yml index c3430d291..49d7a5128 100644 --- a/.github/workflows/proxied-local-smoke.yml +++ b/.github/workflows/proxied-local-smoke.yml @@ -30,11 +30,16 @@ on: - 'cmd/bd/proxied_integration_helpers_test.go' - 'cmd/bd/store_factory*.go' - 'cmd/bd/test_dolt_server_cgo_test.go' + - 'cmd/bd/tracker_proxy_uow_conformance_integration_test.go' - 'cmd/bd/uow_factory.go' - 'internal/configfile/**' - 'internal/doltserver/**' - 'internal/storage/dbproxy/**' - 'internal/storage/uow/**' + - 'internal/tracker/conformance/**' + - 'internal/tracker/uow_store.go' + - 'internal/tracker/engine.go' + - 'internal/tracker/store.go' - 'go.mod' - 'go.sum' - '.github/workflows/proxied-local-smoke.yml' @@ -51,11 +56,16 @@ on: - 'cmd/bd/proxied_integration_helpers_test.go' - 'cmd/bd/store_factory*.go' - 'cmd/bd/test_dolt_server_cgo_test.go' + - 'cmd/bd/tracker_proxy_uow_conformance_integration_test.go' - 'cmd/bd/uow_factory.go' - 'internal/configfile/**' - 'internal/doltserver/**' - 'internal/storage/dbproxy/**' - 'internal/storage/uow/**' + - 'internal/tracker/conformance/**' + - 'internal/tracker/uow_store.go' + - 'internal/tracker/engine.go' + - 'internal/tracker/store.go' - 'go.mod' - 'go.sum' - '.github/workflows/proxied-local-smoke.yml' @@ -114,7 +124,8 @@ jobs: TestManagedLocalProxiedDoltStatusReportsLiveTopology \ TestManagedLocalProxiedDoltStartRefusesOverLiveProxy \ TestManagedLocalProxiedDoltStartRefusesWithProxyDown \ - TestManagedLocalProxiedDoltLifecycleLeavesOtherTopologiesAlone + TestManagedLocalProxiedDoltLifecycleLeavesOtherTopologiesAlone \ + TestManagedLocalProxiedTrackerUOWConformance do if ! grep -qx "$test_name" <<<"$listed"; then echo "managed-local lifecycle test $test_name is missing; got: '$listed'" >&2 diff --git a/cmd/bd/tracker_proxy_uow_conformance_integration_test.go b/cmd/bd/tracker_proxy_uow_conformance_integration_test.go new file mode 100644 index 000000000..1361b243a --- /dev/null +++ b/cmd/bd/tracker_proxy_uow_conformance_integration_test.go @@ -0,0 +1,259 @@ +//go:build cgo && unix + +package main + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "os/exec" + "sort" + "strings" + "testing" + "time" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/storage/uow" + "github.com/steveyegge/beads/internal/tracker" + trackerconformance "github.com/steveyegge/beads/internal/tracker/conformance" + "github.com/steveyegge/beads/internal/types" +) + +// TestDirectTrackerConformance is the direct-storage leg of the same shared +// scenario used by the managed-local proxy test below. Keeping both legs on +// Run prevents the proxy assertion from becoming a one-sided contract. +func TestDirectTrackerConformance(t *testing.T) { + bd := buildBDForInitTests(t) + trackerconformance.Run(t, func(t *testing.T, f *trackerconformance.Fixture) trackerconformance.Setup { + dir, beadsDir, _ := bdInit(t, bd, "--prefix", "trkpx", "--non-interactive", "--skip-hooks", "--skip-agents") + cmd := exec.Command(bd, "config", "set", "test.project", "PROJ") + cmd.Dir, cmd.Env = dir, bdEnv(dir) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("set tracker config through bd front door: %v\n%s", err, out) + } + raw, err := newDoltStoreFromConfig(context.Background(), beadsDir) + if err != nil { + t.Fatalf("open direct tracker store: %v", err) + } + t.Cleanup(func() { _ = raw.Close() }) + store := tracker.NewStore(raw) + seedTrackerConformance(t, store) + return trackerConformanceSetup(store, func(ctx context.Context, issue *types.Issue) error { return raw.CreateIssue(ctx, issue, "conformance") }, f) + }) +} + +// TestManagedLocalProxiedTrackerUOWConformance runs the shared tracker scenario +// through a real managed-local proxy and UOW provider. The normal conformance +// fixture remains map-backed for adapter tests; this test owns the distinct +// persistence and proxy boundary risk. +func TestManagedLocalProxiedTrackerUOWConformance(t *testing.T) { + requireManagedLocalProxiedEnv(t) + bd := buildBDForInitTests(t) + + trackerconformance.Run(t, func(t *testing.T, f *trackerconformance.Fixture) trackerconformance.Setup { + p := bdManagedLocalInit(t, bd, "trkpx", 5*time.Minute) + if out, err := bdProxiedRun(t, bd, p.dir, "config", "set", "test.project", "PROJ"); err != nil { + t.Fatalf("set tracker config through bd front door: %v\n%s", err, out) + } + + provider, err := newProxiedServerUOWProvider(context.Background(), p.beadsDir, "") + if err != nil { + t.Fatalf("open managed-local proxy UOW provider: %v", err) + } + t.Cleanup(func() { _ = provider.Close(context.Background()) }) + store := tracker.NewUOWStore(provider) + seedTrackerConformance(t, store) + return trackerConformanceSetup(store, func(ctx context.Context, wisp *types.Issue) error { + if err := uow.RunTx(ctx, provider, func(ctx context.Context, uw uow.UnitOfWork) (string, error) { + _, err := uw.IssueUseCase().CreateWisp(ctx, domain.CreateIssueParams{Issue: wisp}, "conformance") + return "bd: tracker conformance wisp", err + }); err != nil { + return err + } + return nil + }, f) + }) +} + +// seedTrackerConformance plants the shared pre-pull state for both legs. +// +// It deliberately seeds NO labels. Store.CreateIssue is not label-faithful +// across the two backends: the direct store persists issue.Labels through +// PersistLabels, while the UOW store creates through +// domain.CreateIssueParams{Issue: issue} with Labels unset and the domain +// create writes labels only from params.Labels — so a seeded label would +// survive on the direct leg and vanish on the proxied one. Running the two +// legs on divergent state would let this suite report parity it never +// checked. Create-path parity is tracked in bd-p0n1; once the UOW store +// passes labels through, the seed can carry them again. +func seedTrackerConformance(t *testing.T, store tracker.Store) { + t.Helper() + ref := "https://tracker.test/EXT-1" + seed := &types.Issue{ID: "trkpx-1", Title: "local", Status: types.StatusOpen, IssueType: types.TypeTask, Priority: 2, ExternalRef: &ref, UpdatedAt: time.Date(2026, 9, 3, 0, 0, 0, 0, time.UTC)} + if err := store.CreateIssue(context.Background(), seed, "conformance"); err != nil { + t.Fatalf("seed tracker issue: %v", err) + } +} + +func trackerConformanceSetup(store tracker.Store, createWisp func(context.Context, *types.Issue) error, f *trackerconformance.Fixture) trackerconformance.Setup { + ref := "https://tracker.test/EXT-1" + f.StoreFactory = &proxyTrackerStoreFactory{store: store} + f.HTTP.Enqueue(trackerconformance.Response{Body: `[{"id":"EXT-1","identifier":"EXT-1","url":"https://tracker.test/EXT-1","title":"remote","updated_at":"2026-09-03T01:00:00Z","labels":[" bug ","","bug"]},{"id":"EXT-2","identifier":"EXT-2","url":"https://tracker.test/EXT-2","title":"dependent","updated_at":"2026-09-03T01:00:00Z"}]`}) + return trackerconformance.Setup{Engine: tracker.NewEngine(&proxyConformanceTracker{client: f.HTTP.Client()}, store, "conformance"), Store: store, + Snapshot: func(ctx context.Context) (trackerconformance.Snapshot, error) { + return proxyTrackerSnapshot(ctx, store, "test.last_sync") + }, + SeedExternalRefPlanes: func(ctx context.Context) (string, string, error) { + wisp := &types.Issue{ID: "aaa-wisp-trkpx-1", Title: "pushed wisp", Status: types.StatusOpen, IssueType: types.TypeTask, Priority: 2, Ephemeral: true, ExternalRef: &ref} + if err := createWisp(ctx, wisp); err != nil { + return "", "", err + } + otherRef := ref + "-wisp-only" + only := &types.Issue{ID: "wisp-only", Title: "wisp only", Status: types.StatusOpen, IssueType: types.TypeTask, Priority: 2, Ephemeral: true, ExternalRef: &otherRef} + return "trkpx-1", "wisp-only", createWisp(ctx, only) + }, + Expected: trackerconformance.Expected{ExternalRef: ref, ConfigKey: "test.project", MetadataKey: "test.last_sync"}, + Refusal: func(context.Context) (*tracker.SyncResult, error) { + return nil, &storage.ErrUnsupported{Op: "proxy-only operation", Backend: "conformance"} + }, + APIOnly: func(ctx context.Context, _ func() tracker.Store) error { + double := trackerconformance.NewHTTPDouble() + double.Enqueue(trackerconformance.Response{Status: http.StatusOK, Body: `{"teams":[]}`}) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://tracker.test/teams", nil) + if err != nil { + return err + } + resp, err := double.Client().Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + var body struct{ Teams []json.RawMessage } + if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { + return err + } + if body.Teams == nil || len(body.Teams) != 0 { + return fmt.Errorf("expected empty teams response, got %+v", body) + } + return nil + }, + } +} + +type proxyTrackerStoreFactory struct { + store tracker.Store +} + +func (f *proxyTrackerStoreFactory) Open() tracker.Store { return f.store } + +func proxyTrackerSnapshot(ctx context.Context, store tracker.Store, lastSyncKey string) (trackerconformance.Snapshot, error) { + // The unfiltered search includes durable issues and all wisps, including + // NoHistory rows whose Ephemeral flag may be false. + issues, err := store.SearchIssues(ctx, "", types.IssueFilter{}) + if err != nil { + return trackerconformance.Snapshot{}, err + } + config, err := store.GetAllConfig(ctx) + if err != nil { + return trackerconformance.Snapshot{}, err + } + lastSync, err := store.GetLocalMetadata(ctx, lastSyncKey) + if err != nil { + return trackerconformance.Snapshot{}, err + } + snapshot := trackerconformance.Snapshot{Issues: make(map[string]types.Issue, len(issues)), Dependencies: map[string][]string{}, Config: config, Metadata: map[string]string{lastSyncKey: lastSync}, LastSync: lastSync} + for _, issue := range issues { + if issue == nil { + continue + } + copy := *issue + copy.Labels = append([]string(nil), issue.Labels...) + if issue.ExternalRef != nil { + ref := *issue.ExternalRef + copy.ExternalRef = &ref + } + snapshot.Issues[copy.ID] = copy + // Tracker-owned metadata is enumerable from the rows in this snapshot; + // tracker.Store deliberately has no general metadata-listing API. + pushHashKey := strings.TrimSuffix(lastSyncKey, ".last_sync") + ".pushhash." + copy.ID + pushHash, err := store.GetLocalMetadata(ctx, pushHashKey) + if err != nil { + return trackerconformance.Snapshot{}, err + } + snapshot.Metadata[pushHashKey] = pushHash + deps, err := store.GetDependenciesWithMetadata(ctx, copy.ID) + if err != nil { + return trackerconformance.Snapshot{}, err + } + for _, dep := range deps { + snapshot.Dependencies[copy.ID] = append(snapshot.Dependencies[copy.ID], dep.ID) + } + sort.Strings(snapshot.Dependencies[copy.ID]) + } + return snapshot, nil +} + +type proxyConformanceTracker struct{ client *http.Client } + +func (*proxyConformanceTracker) Name() string { return "test" } +func (*proxyConformanceTracker) DisplayName() string { return "Test" } +func (*proxyConformanceTracker) ConfigPrefix() string { return "test" } +func (*proxyConformanceTracker) Init(context.Context, tracker.Store) error { return nil } +func (*proxyConformanceTracker) Validate() error { return nil } +func (*proxyConformanceTracker) Close() error { return nil } +func (t *proxyConformanceTracker) FetchIssues(ctx context.Context, _ tracker.FetchOptions) ([]tracker.TrackerIssue, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://tracker.test/issues", nil) + if err != nil { + return nil, err + } + resp, err := t.client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + var issues []tracker.TrackerIssue + err = json.NewDecoder(resp.Body).Decode(&issues) + return issues, err +} +func (*proxyConformanceTracker) FetchIssue(context.Context, string) (*tracker.TrackerIssue, error) { + return nil, nil +} +func (*proxyConformanceTracker) CreateIssue(context.Context, *types.Issue) (*tracker.TrackerIssue, error) { + return &tracker.TrackerIssue{ID: "EXT-3", Identifier: "EXT-3", URL: "https://tracker.test/EXT-3"}, nil +} +func (*proxyConformanceTracker) UpdateIssue(context.Context, string, *types.Issue) (*tracker.TrackerIssue, error) { + return &tracker.TrackerIssue{ID: "EXT-1", Identifier: "EXT-1", URL: "https://tracker.test/EXT-1"}, nil +} +func (*proxyConformanceTracker) FieldMapper() tracker.FieldMapper { return proxyConformanceMapper{} } +func (*proxyConformanceTracker) IsExternalRef(string) bool { return true } +func (*proxyConformanceTracker) ExtractIdentifier(ref string) string { + return ref[strings.LastIndex(ref, "/")+1:] +} +func (*proxyConformanceTracker) BuildExternalRef(issue *tracker.TrackerIssue) string { + return issue.URL +} + +type proxyConformanceMapper struct{} + +func (proxyConformanceMapper) PriorityToBeads(interface{}) int { return 2 } +func (proxyConformanceMapper) PriorityToTracker(int) interface{} { return 2 } +func (proxyConformanceMapper) StatusToBeads(interface{}) types.Status { return types.StatusOpen } +func (proxyConformanceMapper) StatusToTracker(types.Status) interface{} { return "open" } +func (proxyConformanceMapper) TypeToBeads(interface{}) types.IssueType { return types.TypeTask } +func (proxyConformanceMapper) TypeToTracker(types.IssueType) interface{} { return "task" } +func (proxyConformanceMapper) IssueToBeads(issue *tracker.TrackerIssue) *tracker.IssueConversion { + id := "trkpx-2" + if issue.Identifier == "EXT-1" { + id = "trkpx-1" + } + conversion := &tracker.IssueConversion{Issue: &types.Issue{ID: id, Title: issue.Title, Status: types.StatusClosed, IssueType: types.TypeTask, Priority: 2, Labels: issue.Labels}} + if issue.Identifier == "EXT-2" { + conversion.Dependencies = []tracker.DependencyInfo{{FromExternalID: "EXT-2", ToExternalID: "EXT-1", Type: "blocks", Source: tracker.DependencySourceRelation}} + } + return conversion +} +func (proxyConformanceMapper) IssueToTracker(issue *types.Issue) map[string]interface{} { + return map[string]interface{}{"title": issue.Title} +} diff --git a/internal/tracker/conformance/conformance_test.go b/internal/tracker/conformance/conformance_test.go index c2d03bbba..ac189b934 100644 --- a/internal/tracker/conformance/conformance_test.go +++ b/internal/tracker/conformance/conformance_test.go @@ -2,6 +2,8 @@ package conformance import ( "context" + "encoding/json" + "fmt" "net/http" "strings" "testing" @@ -17,19 +19,51 @@ func TestRunWithEngineAndUOWFixture(t *testing.T) { store := f.StoreFactory.Open().(*Store) store.Config["test.project"] = "PROJ" ref := "https://tracker.test/EXT-1" + // Seeded straight into the map rather than through Store.CreateIssue, + // so the create-path label blind spot Run documents does not apply and + // the pre-existing label can stay: it makes the suite's single-label + // assertion prove the update REPLACES labels instead of merging them. + // The real-backend legs cannot seed labels this way, so this is the + // one leg carrying that coverage until create-path parity lands. store.Issues["bd-1"] = &types.Issue{ID: "bd-1", Title: "local", Status: types.StatusOpen, IssueType: types.TypeTask, Priority: 2, Labels: []string{"old"}, ExternalRef: &ref, UpdatedAt: time.Date(2026, 9, 3, 0, 0, 0, 0, time.UTC)} - remote := &mockTracker{} + f.HTTP.Enqueue(Response{Status: http.StatusOK, Body: `[{"id":"EXT-1","identifier":"EXT-1","url":"https://tracker.test/EXT-1","title":"remote","updated_at":"2026-09-03T01:00:00Z","labels":[" bug ","","bug"]},{"id":"EXT-2","identifier":"EXT-2","url":"https://tracker.test/EXT-2","title":"dependent","updated_at":"2026-09-03T01:00:00Z"}]`}) + remote := &mockTracker{client: f.HTTP.Client()} return Setup{ - Engine: tracker.NewEngine(remote, store, "conformance"), - Store: store, + Engine: tracker.NewEngine(remote, store, "conformance"), + Store: store, + Snapshot: func(context.Context) (Snapshot, error) { return store.Snapshot(), nil }, + MutationCount: store.MutationCount, + SeedExternalRefPlanes: func(context.Context) (string, string, error) { + ref := "https://tracker.test/EXT-1" + store.Wisps["aaa-wisp-bd-1"] = &types.Issue{ID: "aaa-wisp-bd-1", Title: "pushed wisp", Status: types.StatusOpen, IssueType: types.TypeTask, Priority: 2, Ephemeral: true, ExternalRef: &ref} + otherRef := ref + "-wisp-only" + store.Wisps["wisp-only"] = &types.Issue{ID: "wisp-only", Title: "wisp only", Status: types.StatusOpen, IssueType: types.TypeTask, Priority: 2, Ephemeral: true, ExternalRef: &otherRef} + return "bd-1", "wisp-only", nil + }, Expected: Expected{ExternalRef: ref, ConfigKey: "test.project", MetadataKey: "test.last_sync"}, Refusal: func(context.Context) (*tracker.SyncResult, error) { return nil, &storage.ErrUnsupported{Op: "proxy-only operation", Backend: "conformance"} }, APIOnly: func(ctx context.Context, _ func() tracker.Store) error { - f.HTTP.Enqueue(Response{Status: http.StatusOK, Body: `{"teams":[]}`}) - _, err := f.HTTP.Client().Get("https://tracker.test/teams") - return err + double := NewHTTPDouble() + double.Enqueue(Response{Status: http.StatusOK, Body: `{"teams":[]}`}) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://tracker.test/teams", nil) + if err != nil { + return err + } + resp, err := double.Client().Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + var body struct{ Teams []json.RawMessage } + if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { + return err + } + if body.Teams == nil || len(body.Teams) != 0 { + return fmt.Errorf("expected empty teams response, got %+v", body) + } + return nil }, } }) @@ -68,7 +102,7 @@ func TestHTTPDoubleRecordsBodyAndTransportError(t *testing.T) { } } -type mockTracker struct{} +type mockTracker struct{ client *http.Client } func (*mockTracker) Name() string { return "test" } func (*mockTracker) DisplayName() string { return "Test" } @@ -76,8 +110,19 @@ func (*mockTracker) ConfigPrefix() string { return "test" } func (*mockTracker) Init(context.Context, tracker.Store) error { return nil } func (*mockTracker) Validate() error { return nil } func (*mockTracker) Close() error { return nil } -func (*mockTracker) FetchIssues(context.Context, tracker.FetchOptions) ([]tracker.TrackerIssue, error) { - return []tracker.TrackerIssue{{ID: "EXT-1", Identifier: "EXT-1", URL: "https://tracker.test/EXT-1", Title: "remote", UpdatedAt: time.Date(2026, 9, 3, 1, 0, 0, 0, time.UTC), Labels: []string{"bug"}}}, nil +func (t *mockTracker) FetchIssues(ctx context.Context, _ tracker.FetchOptions) ([]tracker.TrackerIssue, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://tracker.test/issues", nil) + if err != nil { + return nil, err + } + resp, err := t.client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + var issues []tracker.TrackerIssue + err = json.NewDecoder(resp.Body).Decode(&issues) + return issues, err } func (*mockTracker) FetchIssue(context.Context, string) (*tracker.TrackerIssue, error) { return nil, nil @@ -102,7 +147,15 @@ func (mockMapper) StatusToTracker(types.Status) interface{} { return "open" } func (mockMapper) TypeToBeads(interface{}) types.IssueType { return types.TypeTask } func (mockMapper) TypeToTracker(types.IssueType) interface{} { return "task" } func (mockMapper) IssueToBeads(issue *tracker.TrackerIssue) *tracker.IssueConversion { - return &tracker.IssueConversion{Issue: &types.Issue{ID: "bd-2", Title: issue.Title, Status: types.StatusOpen, IssueType: types.TypeTask, Priority: 2, Labels: issue.Labels}} + id := "bd-2" + if issue.Identifier == "EXT-1" { + id = "bd-1" + } + conversion := &tracker.IssueConversion{Issue: &types.Issue{ID: id, Title: issue.Title, Status: types.StatusClosed, IssueType: types.TypeTask, Priority: 2, Labels: issue.Labels}} + if issue.Identifier == "EXT-2" { + conversion.Dependencies = []tracker.DependencyInfo{{FromExternalID: "EXT-2", ToExternalID: "EXT-1", Type: "blocks", Source: tracker.DependencySourceRelation}} + } + return conversion } func (mockMapper) IssueToTracker(issue *types.Issue) map[string]interface{} { return map[string]interface{}{"title": issue.Title} diff --git a/internal/tracker/conformance/run.go b/internal/tracker/conformance/run.go index 895c27b4c..cf8ef3ac4 100644 --- a/internal/tracker/conformance/run.go +++ b/internal/tracker/conformance/run.go @@ -13,45 +13,54 @@ import ( // Snapshot is the normalized local state inspected by the shared suite. type Snapshot struct { - Issues map[string]types.Issue - Config map[string]string - Metadata map[string]string - LastSync string + Issues map[string]types.Issue + Dependencies map[string][]string + Config map[string]string + Metadata map[string]string + LastSync string } // Fixture contains deterministic HTTP and local-store dependencies for one -// adapter test. StoreFactory counts opens so API-only operations can prove -// that they do not initialize local persistence. +// adapter test. StoreFactory is the seam an adapter's front door uses to +// obtain a store, so a future API-only front door can be observed deciding +// not to open one. type Fixture struct { HTTP *HTTPDouble - StoreFactory *Factory + StoreFactory StoreFactory } -// Factory is a fake UOW factory. Each Open returns the same map-backed store, -// while OpenCount records initialization attempts. +// StoreFactory opens a tracker store for a front-door operation. +type StoreFactory interface { + Open() tracker.Store +} + +// Factory supplies the same map-backed store to each front-door operation. type Factory struct { Store *Store - opens int } // NewFactory returns a fixture factory with an empty store. func NewFactory() *Factory { return &Factory{Store: NewStore()} } -// Open returns the tracker store and records one UOW open. -func (f *Factory) Open() tracker.Store { f.opens++; return f.Store } - -// OpenCount reports the number of UOW opens. -func (f *Factory) OpenCount() int { return f.opens } +// Open returns the tracker store. +func (f *Factory) Open() tracker.Store { return f.Store } // Setup binds an existing tracker.Engine to fixture assertions. Refusal and // APIOnly are adapter-specific front doors; keeping them callbacks avoids // inventing a backend-neutral command API. type Setup struct { Engine *tracker.Engine - Store *Store - Expected Expected - Refusal func(context.Context) (*tracker.SyncResult, error) - APIOnly func(context.Context, func() tracker.Store) error + Store tracker.Store + Snapshot func(context.Context) (Snapshot, error) + // MutationCount detects state-identical writes when the backend exposes + // a counter. Real backends may leave it nil and compare snapshots only. + MutationCount func() int + // SeedExternalRefPlanes prepares the durable/wisp collision that proves + // durable issues win external-ref lookup. It returns the durable issue ID. + SeedExternalRefPlanes func(context.Context) (string, string, error) + Expected Expected + Refusal func(context.Context) (*tracker.SyncResult, error) + APIOnly func(context.Context, func() tracker.Store) error } // Expected identifies adapter-specific values that the generic suite must @@ -66,17 +75,17 @@ type Expected struct { func Run(t *testing.T, build func(*testing.T, *Fixture) Setup) { t.Helper() ctx := context.Background() - newSetup := func(t *testing.T) Setup { + newSetup := func(t *testing.T) (Setup, *Fixture) { fixture := &Fixture{HTTP: NewHTTPDouble(), StoreFactory: NewFactory()} setup := build(t, fixture) - if setup.Engine == nil || setup.Store == nil || setup.Refusal == nil || setup.APIOnly == nil || setup.Expected.ExternalRef == "" || setup.Expected.ConfigKey == "" || setup.Expected.MetadataKey == "" { - t.Fatal("setup must provide Engine, Store, Expected refs/config/metadata, Refusal, and APIOnly") + if setup.Engine == nil || setup.Store == nil || setup.Snapshot == nil || setup.SeedExternalRefPlanes == nil || setup.Refusal == nil || setup.APIOnly == nil || setup.Expected.ExternalRef == "" || setup.Expected.ConfigKey == "" || setup.Expected.MetadataKey == "" { + t.Fatal("setup must provide Engine, Store, Snapshot, external-ref seed, Expected refs/config/metadata, Refusal, and APIOnly") } - return setup + return setup, fixture } t.Run("pull_persists_normalized_fields_and_last_sync", func(t *testing.T) { - s := newSetup(t) + s, _ := newSetup(t) result, err := s.Engine.Sync(ctx, tracker.SyncOptions{Pull: true}) if err != nil { t.Fatalf("pull: %v", err) @@ -84,22 +93,56 @@ func Run(t *testing.T, build func(*testing.T, *Fixture) Setup) { if result == nil || !result.Success { t.Fatalf("pull result = %+v", result) } - snapshot := s.Store.Snapshot() + snapshot, err := s.Snapshot(ctx) + if err != nil { + t.Fatalf("snapshot after pull: %v", err) + } if len(snapshot.Issues) == 0 { t.Fatal("pull created no local issue") } + var pulled *types.Issue for _, issue := range snapshot.Issues { - if issue.ExternalRef == nil || *issue.ExternalRef != s.Expected.ExternalRef || len(issue.Labels) == 0 { - t.Fatalf("pull lost external ref/labels: %+v", issue) + if issue.ExternalRef != nil && *issue.ExternalRef == s.Expected.ExternalRef { + copy := issue + pulled = © + break } } + // Labels are certified on the UPDATE path only. Create-path label + // parity is a known blind spot: tracker's UOW store creates through + // domain.CreateIssueParams{Issue: issue} with Labels unset, and the + // domain create writes labels only from params.Labels, so a proxied + // create drops every label a direct create persists (bd-p0n1). + // Adopters must therefore not seed labels through Store.CreateIssue — + // doing so puts the two legs on divergent state and makes this suite + // certify a parity it never checked. + if pulled == nil || len(pulled.Labels) != 1 || pulled.Labels[0] != "bug" || pulled.Status != types.StatusClosed { + t.Fatalf("pull lost normalized fields: %+v", pulled) + } + // The pulled dependency must be visible in the same Snapshot every + // other assertion reads, so the dry-run and refusal comparisons cover + // the dependency plane too. + dependent := "" + for id, targets := range snapshot.Dependencies { + if id == pulled.ID { + continue + } + for _, target := range targets { + if target == pulled.ID { + dependent = id + } + } + } + if dependent == "" { + t.Fatalf("pull did not persist a dependency onto %s: %+v", pulled.ID, snapshot.Dependencies) + } if result.LastSync == "" || snapshot.LastSync != result.LastSync { t.Fatalf("pull last_sync result=%q snapshot=%q", result.LastSync, snapshot.LastSync) } }) t.Run("push_persists_config_and_metadata", func(t *testing.T) { - s := newSetup(t) + s, _ := newSetup(t) result, err := s.Engine.Sync(ctx, tracker.SyncOptions{Push: true}) if err != nil { t.Fatalf("push: %v", err) @@ -107,15 +150,18 @@ func Run(t *testing.T, build func(*testing.T, *Fixture) Setup) { if result == nil || !result.Success { t.Fatalf("push result = %+v", result) } - snapshot := s.Store.Snapshot() + snapshot, err := s.Snapshot(ctx) + if err != nil { + t.Fatalf("snapshot after push: %v", err) + } if snapshot.Config[s.Expected.ConfigKey] == "" || snapshot.Metadata[s.Expected.MetadataKey] == "" { t.Fatalf("push did not persist config/metadata: %+v", snapshot) } }) t.Run("dry_run_does_not_mutate", func(t *testing.T) { - s := newSetup(t) - before, writes := s.Store.Snapshot(), s.Store.MutationCount() + s, _ := newSetup(t) + assertUnchanged := noMutationCheck(t, ctx, s) for name, opts := range map[string]tracker.SyncOptions{"pull": {Pull: true, DryRun: true}, "push": {Push: true, DryRun: true}} { result, err := s.Engine.Sync(ctx, opts) if err != nil { @@ -125,14 +171,12 @@ func Run(t *testing.T, build func(*testing.T, *Fixture) Setup) { t.Fatalf("%s dry-run result = %+v", name, result) } } - if !reflect.DeepEqual(before, s.Store.Snapshot()) || writes != s.Store.MutationCount() { - t.Fatal("dry-run changed local state") - } + assertUnchanged() }) t.Run("refusal_is_explicit_and_does_not_mutate", func(t *testing.T) { - s := newSetup(t) - before, writes := s.Store.Snapshot(), s.Store.MutationCount() + s, _ := newSetup(t) + assertUnchanged := noMutationCheck(t, ctx, s) _, err := s.Refusal(ctx) if err == nil { t.Fatal("refused operation succeeded") @@ -141,62 +185,75 @@ func Run(t *testing.T, build func(*testing.T, *Fixture) Setup) { if !errors.As(err, &refusal) { t.Fatalf("refusal is not typed: %v", err) } - if !reflect.DeepEqual(before, s.Store.Snapshot()) || writes != s.Store.MutationCount() { - t.Fatal("refusal changed local state") - } + assertUnchanged() }) t.Run("external_ref_resolution_prefers_issue_plane", func(t *testing.T) { - s := newSetup(t) - // The setup seeded Expected.ExternalRef on the issues plane. Put the - // SAME ref on the wisps plane — the state a push-then-pull produces - // once a wisp has been pushed under a ref the durable bead also - // carries — and give the wisp the ID that sorts first, so a resolver - // with no plane preference returns it. - var want string - for id, issue := range s.Store.Issues { - if issue.ExternalRef != nil && *issue.ExternalRef == s.Expected.ExternalRef { - want = id - break - } - } - if want == "" { - t.Fatalf("setup seeded no issues-plane row for %q", s.Expected.ExternalRef) - } - ref := s.Expected.ExternalRef - wispID := "aaa-wisp-" + want - s.Store.Wisps[wispID] = &types.Issue{ID: wispID, Title: "pushed wisp", Status: types.StatusOpen, IssueType: types.TypeTask, Priority: 2, Ephemeral: true, ExternalRef: &ref} - - got, err := s.Store.GetIssueByExternalRef(ctx, ref) + s, _ := newSetup(t) + want, onlyID, err := s.SeedExternalRefPlanes(ctx) if err != nil { - t.Fatalf("resolve %q: %v", ref, err) + t.Fatalf("seed external-ref planes: %v", err) + } + + snapshot, err := s.Snapshot(ctx) + if err != nil { + t.Fatalf("snapshot seeded planes: %v", err) + } + if issue, ok := snapshot.Issues[onlyID]; !ok || !issue.Ephemeral { + t.Fatalf("snapshot omitted seeded wisp %q: %+v", onlyID, snapshot.Issues) + } + + got, err := s.Store.GetIssueByExternalRef(ctx, s.Expected.ExternalRef) + if err != nil { + t.Fatalf("resolve %q: %v", s.Expected.ExternalRef, err) } // Resolving to the wisp would make the pull dedup update the ephemeral // row instead of the durable bead — a silent write to the wrong issue. if got == nil || got.ID != want { - t.Fatalf("external_ref %q resolved to %v, want issues-plane %q: the issues plane must win over the wisp plane", ref, got, want) + t.Fatalf("external_ref %q resolved to %v, want issues-plane %q: the issues plane must win over the wisp plane", s.Expected.ExternalRef, got, want) } - - // And the wisp plane is still reachable when the issues plane has no - // match, so plane preference did not become plane exclusion. - otherRef := ref + "-wisp-only" - onlyID := "wisp-only" - s.Store.Wisps[onlyID] = &types.Issue{ID: onlyID, Title: "wisp only", Status: types.StatusOpen, IssueType: types.TypeTask, Priority: 2, Ephemeral: true, ExternalRef: &otherRef} - got, err = s.Store.GetIssueByExternalRef(ctx, otherRef) + got, err = s.Store.GetIssueByExternalRef(ctx, s.Expected.ExternalRef+"-wisp-only") if err != nil || got == nil || got.ID != onlyID { - t.Fatalf("wisp-only external_ref %q resolved to (%v, %v), want %q", otherRef, got, err, onlyID) + t.Fatalf("wisp-only external_ref resolved to (%v, %v), want %q", got, err, onlyID) } }) - t.Run("api_only_does_not_open_uow", func(t *testing.T) { - fixture := &Fixture{HTTP: NewHTTPDouble(), StoreFactory: NewFactory()} - s := build(t, fixture) - before := fixture.StoreFactory.OpenCount() + // The API-only front door is handed a store opener it is free to ignore. + // This is a harness-contract check, not evidence that a real command skips + // persistence: today's adopters supply synthetic callbacks that never call + // open, so asserting the open count could not fail. The adapter child work + // that drives a real front door through open is what proves the boundary. + t.Run("api_only_completes_without_store", func(t *testing.T) { + s, fixture := newSetup(t) if err := s.APIOnly(ctx, fixture.StoreFactory.Open); err != nil { t.Fatalf("api-only: %v", err) } - if got := fixture.StoreFactory.OpenCount(); got != before { - t.Fatalf("api-only opened UOW: %d -> %d", before, got) - } }) } + +// noMutationCheck captures state and, where available, the write counter. +// Checking both catches idempotent writes that a state comparison cannot see. +func noMutationCheck(t *testing.T, ctx context.Context, s Setup) func() { + t.Helper() + before, err := s.Snapshot(ctx) + if err != nil { + t.Fatalf("snapshot before operation: %v", err) + } + writes := 0 + if s.MutationCount != nil { + writes = s.MutationCount() + } + return func() { + t.Helper() + after, err := s.Snapshot(ctx) + if err != nil { + t.Fatalf("snapshot after operation: %v", err) + } + if !reflect.DeepEqual(before, after) { + t.Fatal("operation changed local state") + } + if s.MutationCount != nil && writes != s.MutationCount() { + t.Fatal("operation issued local writes") + } + } +} diff --git a/internal/tracker/conformance/store.go b/internal/tracker/conformance/store.go index 99f47b0fc..1e494d4fd 100644 --- a/internal/tracker/conformance/store.go +++ b/internal/tracker/conformance/store.go @@ -2,6 +2,7 @@ package conformance import ( "context" + "sort" "strings" "sync" @@ -25,6 +26,7 @@ type Store struct { // search silently gets wrong. Empty unless a test seeds it, so every // other assertion is unaffected. Wisps map[string]*types.Issue + Deps map[string]map[string]struct{} LastSync string Mutations int @@ -34,10 +36,19 @@ type Store struct { func (s *Store) Snapshot() Snapshot { s.mu.Lock() defer s.mu.Unlock() - out := Snapshot{Issues: make(map[string]types.Issue, len(s.Issues)), Config: cloneMap(s.Config), Metadata: cloneMap(s.Metadata), LastSync: s.LastSync} + out := Snapshot{Issues: make(map[string]types.Issue, len(s.Issues)), Dependencies: make(map[string][]string, len(s.Deps)), Config: cloneMap(s.Config), Metadata: cloneMap(s.Metadata), LastSync: s.LastSync} for id, issue := range s.Issues { out.Issues[id] = *cloneIssue(issue) } + for id, issue := range s.Wisps { + out.Issues[id] = *cloneIssue(issue) + } + for id, targets := range s.Deps { + for target := range targets { + out.Dependencies[id] = append(out.Dependencies[id], target) + } + sort.Strings(out.Dependencies[id]) + } return out } @@ -54,14 +65,37 @@ func (s *Store) ApplyIssueUpdate(ctx context.Context, id string, updates map[str s.mu.Lock() defer s.mu.Unlock() if issue := s.Issues[id]; issue != nil && labels != nil { - issue.Labels = append([]string(nil), labels...) + issue.Labels = normalizedLabels(labels) } return nil } +// normalizedLabels mirrors the engine's normalizedStringSlice: trim, drop +// empty, dedupe, sort. The sort is not cosmetic — the fake is the oracle +// adapters are judged against, and both real backends read labels back +// ORDER BY label. Without it the first order-sensitive multi-label assertion +// would pass on the real legs and fail here, or vice versa. +func normalizedLabels(labels []string) []string { + seen := make(map[string]struct{}, len(labels)) + result := make([]string, 0, len(labels)) + for _, label := range labels { + label = strings.TrimSpace(label) + if label == "" { + continue + } + if _, ok := seen[label]; ok { + continue + } + seen[label] = struct{}{} + result = append(result, label) + } + sort.Strings(result) + return result +} + // NewStore returns an empty fake tracker store. func NewStore() *Store { - return &Store{Issues: map[string]*types.Issue{}, Wisps: map[string]*types.Issue{}, Config: map[string]string{}, Metadata: map[string]string{}} + return &Store{Issues: map[string]*types.Issue{}, Wisps: map[string]*types.Issue{}, Deps: map[string]map[string]struct{}{}, Config: map[string]string{}, Metadata: map[string]string{}} } // Open returns the store as a unit-of-work target. The call is intentionally @@ -180,13 +214,20 @@ func (s *Store) UpdateIssue(_ context.Context, id string, updates map[string]int if v, ok := updates["external_ref"].(string); ok { issue.ExternalRef = &v } + if v, ok := updates["status"].(string); ok { + issue.Status = types.Status(v) + } s.Mutations++ return nil } -// AddDependency is a no-op in the minimal fixture. -func (s *Store) AddDependency(context.Context, *types.Dependency, string) error { +// AddDependency stores the dependency relation in the minimal fixture. +func (s *Store) AddDependency(_ context.Context, dep *types.Dependency, _ string) error { s.mu.Lock() + if s.Deps[dep.IssueID] == nil { + s.Deps[dep.IssueID] = map[string]struct{}{} + } + s.Deps[dep.IssueID][dep.DependsOnID] = struct{}{} s.Mutations++ s.mu.Unlock() return nil diff --git a/internal/tracker/uow_store.go b/internal/tracker/uow_store.go index de99fc453..9e1b8da6d 100644 --- a/internal/tracker/uow_store.go +++ b/internal/tracker/uow_store.go @@ -157,7 +157,7 @@ func (s *uowStore) ApplyIssueUpdate(ctx context.Context, id string, updates map[ } var setLabels *[]string if labels != nil { - copy := append([]string(nil), labels...) + copy := normalizedStringSlice(labels) setLabels = © } return uow.RunTx(ctx, s.provider, func(ctx context.Context, uw uow.UnitOfWork) (string, error) { diff --git a/internal/tracker/uow_store_engine_test.go b/internal/tracker/uow_store_engine_test.go index 6377abafb..5773aff49 100644 --- a/internal/tracker/uow_store_engine_test.go +++ b/internal/tracker/uow_store_engine_test.go @@ -3,6 +3,7 @@ package tracker import ( "context" "errors" + "reflect" "sort" "testing" @@ -13,10 +14,11 @@ import ( ) type engineUOWState struct { - issues map[string]*types.Issue - wisps map[string]*types.Issue - configs map[string]string - commits int + issues map[string]*types.Issue + wisps map[string]*types.Issue + configs map[string]string + commits int + updateSpec domain.UpdateSpec // uows counts units of work handed out by the provider, so a test can pin // how many read transactions one logical lookup is allowed to span. uows int @@ -85,6 +87,7 @@ func (u *engineIssueUC) UpdateIssue(_ context.Context, id string, fields map[str return nil } func (u *engineIssueUC) ApplyUpdate(ctx context.Context, id string, spec domain.UpdateSpec, actor string) (*types.Issue, error) { + u.s.updateSpec = spec if err := u.UpdateIssue(ctx, id, spec.Fields, actor); err != nil { return nil, err } @@ -279,3 +282,30 @@ func TestUOWStoreGetIssueByExternalRefUsesOneReadTransaction(t *testing.T) { }) } } + +func TestUOWStoreApplyIssueUpdateNormalizesLabels(t *testing.T) { + for _, tc := range []struct { + name string + labels []string + want *[]string + }{ + {name: "normalize", labels: []string{" z ", " bug ", "", "bug", "z"}, want: &[]string{"bug", "z"}}, + {name: "omitted"}, + {name: "clear", labels: []string{}, want: &[]string{}}, + {name: "all_blank", labels: []string{" ", ""}, want: &[]string{}}, + } { + t.Run(tc.name, func(t *testing.T) { + state := &engineUOWState{issues: map[string]*types.Issue{"bd-1": {ID: "bd-1"}}} + st := NewUOWStore(&engineUOWProvider{state: state}).(IssueUpdater) + if err := st.ApplyIssueUpdate(context.Background(), "bd-1", nil, tc.labels, "test"); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(state.updateSpec.SetLabels, tc.want) { + t.Fatalf("SetLabels = %v, want %v", state.updateSpec.SetLabels, tc.want) + } + if state.commits != 1 { + t.Fatalf("commits = %d, want 1", state.commits) + } + }) + } +}