From ad620529199985935a0c59e8c5715b27bd8fe39f Mon Sep 17 00:00:00 2001 From: Nathan Kester Date: Mon, 16 Nov 2026 13:10:41 -0700 Subject: [PATCH 1/3] AIC-3901 part 5: fail closed on unsafe keys and missing sync settings Co-Authored-By: Claude Opus 5.5 --- internal/sync/api/settings_write.go | 10 ++++++- internal/sync/api/settings_write_test.go | 35 +++++++++++++++++++++++ internal/sync/bootstrap/bootstrap.go | 13 +++++++-- internal/sync/bootstrap/ownership_test.go | 26 +++++++++++++++-- internal/sync/detach/detach.go | 17 ++++++++--- internal/sync/detach/ownership_test.go | 27 ++++++++++++++++- internal/sync/prompt/conflict_test.go | 11 ++++++- internal/sync/prompt/direction_test.go | 4 ++- internal/sync/prompt/ownership_test.go | 16 +++++++++++ internal/sync/prompt/state.go | 16 +++++++++-- internal/sync/resource.go | 6 ++++ 11 files changed, 167 insertions(+), 14 deletions(-) diff --git a/internal/sync/api/settings_write.go b/internal/sync/api/settings_write.go index f1d5afcf5..db83656eb 100644 --- a/internal/sync/api/settings_write.go +++ b/internal/sync/api/settings_write.go @@ -3,6 +3,7 @@ package api import ( "fmt" "net/http" + "strings" syncdomain "github.com/launchdarkly/ldcli/internal/sync" ) @@ -32,7 +33,9 @@ func (client Client) ReturnToLaunchDarkly(projectKey string, ids []syncdomain.Re } // setSyncDirection upserts one exact rule per resource, in batches of at most -// syncSettingsWriteLimit rules. It checks every resource before it writes. +// syncSettingsWriteLimit rules. It checks every resource before it writes: +// each key becomes part of a rule pattern, so a key that is not a +// LaunchDarkly key, such as *, would write a wildcard rule. func (client Client) setSyncDirection( projectKey string, ids []syncdomain.ResourceID, direction syncdomain.SyncDirection, ) error { @@ -41,6 +44,11 @@ func (client Client) setSyncDirection( if id.ProjectKey != projectKey { return fmt.Errorf("update sync settings: %s is not in project %q", id.Label(), projectKey) } + for _, key := range append([]string{id.ProjectKey}, strings.Split(id.LookupKey, "/")...) { + if !syncdomain.IsLaunchDarklyKey(key) { + return fmt.Errorf("update sync settings: %s has key %q, which is not a LaunchDarkly key", id.Label(), key) + } + } rules = append(rules, syncSettingRule{ResourceKind: id.Kind, ResourcePattern: id.LookupKey, Direction: direction}) } for start := 0; start < len(rules); start += syncSettingsWriteLimit { diff --git a/internal/sync/api/settings_write_test.go b/internal/sync/api/settings_write_test.go index cbe4cf402..eb3dfeed8 100644 --- a/internal/sync/api/settings_write_test.go +++ b/internal/sync/api/settings_write_test.go @@ -161,3 +161,38 @@ func TestSyncSettingsWritesSendCLIUserAgent(t *testing.T) { assert.Equal(t, "/api/v2/projects/project/configs/sync/settings", path) assert.Equal(t, "launchdarkly-cli/v"+version, userAgent) } + +// A key from a repo file reaches the rule pattern as is, so a pattern +// character such as * would write a wildcard rule. Every key must be a +// LaunchDarkly key, and one bad key sends nothing for the whole batch. +func TestSetSyncDirectionRejectsAKeyThatIsNotALaunchDarklyKey(t *testing.T) { + for name, bad := range map[string]struct { + projectKey string + id syncdomain.ResourceID + key string + }{ + "config key": {"project", syncdomain.VariationID("project", "*", "default"), "*"}, + "variation key": {"project", syncdomain.VariationID("project", "support", "de*"), "de*"}, + "project key": {"proj*", syncdomain.VariationID("proj*", "support", "default"), "proj*"}, + } { + for direction, write := range map[string]func(Client, string, []syncdomain.ResourceID) error{ + "claim": Client.ClaimForCode, + "return": Client.ReturnToLaunchDarkly, + } { + t.Run(name+" "+direction, func(t *testing.T) { + transport := &recordingClient{} + client := NewClient(transport, "token", "https://example.com") + ids := []syncdomain.ResourceID{bad.id} + if bad.projectKey == "project" { + ids = append([]syncdomain.ResourceID{syncdomain.VariationID("project", "support", "concise")}, ids...) + } + + err := write(client, bad.projectKey, ids) + + require.Error(t, err) + assert.Contains(t, err.Error(), fmt.Sprintf("%q", bad.key)) + assert.Empty(t, transport.Requests) + }) + } + } +} diff --git a/internal/sync/bootstrap/bootstrap.go b/internal/sync/bootstrap/bootstrap.go index 6a313b958..904d6c530 100644 --- a/internal/sync/bootstrap/bootstrap.go +++ b/internal/sync/bootstrap/bootstrap.go @@ -456,7 +456,8 @@ type ownershipDecision struct { } // decideProject reads the ownership of the new variations of one project -// and decides which ones to claim. It claims nothing. +// and decides which ones to claim. It claims nothing. A variation that the +// read answers without an entry for fails closed. func decideProject(settings Settings, projectKey string, ids []syncdomain.ResourceID) (ownershipDecision, error) { ownership, err := settings.ResolveOwnership(projectKey, ids) if err != nil { @@ -464,7 +465,15 @@ func decideProject(settings Settings, projectKey string, ids []syncdomain.Resour } var decision ownershipDecision for _, id := range ids { - switch syncdomain.DecideOwnership(id, ownership[id]) { + owner, ok := ownership[id] + if !ok { + return ownershipDecision{}, syncdomain.NewProblem( + syncdomain.ErrorSyncSettingUnavailable, + "LaunchDarkly returned no sync setting", + "Configure the resource sync setting in LaunchDarkly, then add it again.", + ).WithResource(id) + } + switch syncdomain.DecideOwnership(id, owner) { case syncdomain.OwnershipClaim: decision.claims = append(decision.claims, id) case syncdomain.OwnershipManagedInLaunchDarkly: diff --git a/internal/sync/bootstrap/ownership_test.go b/internal/sync/bootstrap/ownership_test.go index 0df3cbccb..e4aa53406 100644 --- a/internal/sync/bootstrap/ownership_test.go +++ b/internal/sync/bootstrap/ownership_test.go @@ -26,14 +26,16 @@ import ( var _ Settings = syncapi.Client{} // recordingSettings stands in for the LaunchDarkly sync settings API. It -// answers ResolveOwnership from ownership, fails the reads and claims of the -// projects in resolveErrs and claimErrs, records every claim, and records +// answers ResolveOwnership from ownership, leaves out the resources in +// omitted, fails the reads and claims of the projects in resolveErrs and +// claimErrs, records every claim, and records // whether a claimed variation's file was already on disk when it was claimed. type recordingSettings struct { root string ownership map[syncdomain.ResourceID]syncdomain.Ownership resolveErrs map[string]error claimErrs map[string]error + omitted []syncdomain.ResourceID claims []claim } @@ -57,6 +59,9 @@ func (settings *recordingSettings) ResolveOwnership( if id.ProjectKey != projectKey { return nil, fmt.Errorf("%s is not in project %q", id.LookupKey, projectKey) } + if slices.Contains(settings.omitted, id) { + continue + } // A variation without a stored rule resolves to the project default // with no matched pattern. owner, ok := settings.ownership[id] @@ -301,6 +306,23 @@ func TestRunWritesNothingWhenTheSettingsFail(t *testing.T) { run.assertNothingWritten(t) } +// A sync settings read that answers without an entry for a new variation +// fails closed: nothing is claimed or written. +func TestRunFailsClosedWhenTheSyncSettingIsMissing(t *testing.T) { + run, id, options := singleAdd(t) + run.settings.omitted = []syncdomain.ResourceID{id} + options.Yes = true + + err := Run(options) + + problem, ok := syncdomain.ProblemFrom(err) + require.True(t, ok, "want a sync problem, got %v", err) + assert.Equal(t, syncdomain.ErrorSyncSettingUnavailable, problem.Code) + assert.Equal(t, "LaunchDarkly returned no sync setting", problem.Message) + assert.Empty(t, run.settings.claims) + run.assertNothingWritten(t) +} + func TestRunWarnsAndContinuesWithYesWhenSettingsAreUnavailable(t *testing.T) { run, id, options := singleAdd(t) run.settings.resolveErrs["project"] = settingsNotFound() diff --git a/internal/sync/detach/detach.go b/internal/sync/detach/detach.go index 38587c827..a782bb080 100644 --- a/internal/sync/detach/detach.go +++ b/internal/sync/detach/detach.go @@ -253,9 +253,9 @@ func (options Options) interactive() bool { // variation in the sync settings, with one write per project. LaunchDarkly // keeps a detached tool or skill without a rule. It reads the sync settings // of every project before it writes any rule, so a project without sync -// settings, or a read that fails, leaves no rule behind. When a project has -// no sync settings, it warns, and asks whether to detach anyway unless Yes is -// set. The bool result is false when the user declines. +// settings, a read that fails, or a read without an entry for a variation, +// leaves no rule behind. When a project has no sync settings, it warns, and +// asks whether to detach anyway unless Yes is set. The bool result is false when the user declines. func returnToLaunchDarkly(options Options, selected []syncdomain.ResourceID) (bool, error) { if options.Settings == nil { return true, nil @@ -275,7 +275,7 @@ func returnToLaunchDarkly(options Options, selected []syncdomain.ResourceID) (bo var available, unavailable []string for _, projectKey := range projectKeys { - _, err := options.Settings.ResolveOwnership(projectKey, byProject[projectKey]) + ownership, err := options.Settings.ResolveOwnership(projectKey, byProject[projectKey]) switch { case syncapi.IsNotFound(err): unavailable = append(unavailable, projectKey) @@ -285,6 +285,15 @@ func returnToLaunchDarkly(options Options, selected []syncdomain.ResourceID) (bo case err != nil: return false, fmt.Errorf("read the sync settings of project %s, so %s: %w", projectKey, detachConsequence(nil), err) } + for _, id := range byProject[projectKey] { + if _, ok := ownership[id]; !ok { + return false, syncdomain.NewProblem( + syncdomain.ErrorSyncSettingUnavailable, + "LaunchDarkly returned no sync setting", + "Configure the resource sync setting in LaunchDarkly, then run detach again.", + ).WithResource(id) + } + } available = append(available, projectKey) } if len(unavailable) != 0 { diff --git a/internal/sync/detach/ownership_test.go b/internal/sync/detach/ownership_test.go index 27ade9e7f..7442d4481 100644 --- a/internal/sync/detach/ownership_test.go +++ b/internal/sync/detach/ownership_test.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "io" + "slices" "strings" "testing" "testing/iotest" @@ -19,7 +20,8 @@ import ( ) // recordingSettings stands in for the LaunchDarkly sync settings API. Every -// variation resolves to the project default with no matched rule. It fails +// variation resolves to the project default with no matched rule, except the +// ones in omitted, which the read leaves out. It fails // the reads and writes of the projects in resolveErrs and returnErrs, and // logs every read and write in order. When workspace is set, each write // records whether every variation it names still has its local file and @@ -28,6 +30,7 @@ type recordingSettings struct { workspace *archiveWorkspace resolveErrs map[string]error returnErrs map[string]error + omitted []syncdomain.ResourceID log []string calls []settingsCall } @@ -54,6 +57,9 @@ func (settings *recordingSettings) ResolveOwnership( if id.ProjectKey != projectKey { return nil, fmt.Errorf("%s is not in project %q", id.Label(), projectKey) } + if slices.Contains(settings.omitted, id) { + continue + } result[id] = syncdomain.Ownership{Direction: syncdomain.SyncDirectionServerCanonical} } return result, nil @@ -228,6 +234,25 @@ func TestRunDoesNotWriteSyncSettingsForToolsAndSkills(t *testing.T) { assert.Empty(t, settings.calls) } +// A sync settings read that answers without an entry for a selected +// variation fails closed: no return rule is written and nothing is detached. +func TestRunFailsClosedWhenTheSyncSettingIsMissing(t *testing.T) { + workspace, settings, options := singleDetach(t) + lockBefore := workspace.baselines.manifest.Clone() + settings.omitted = []syncdomain.ResourceID{syncdomain.VariationID("project", "config", "prompt")} + options.Yes = true + + err := Run(options) + + problem, ok := syncdomain.ProblemFrom(err) + require.True(t, ok, "want a sync problem, got %v", err) + assert.Equal(t, syncdomain.ErrorSyncSettingUnavailable, problem.Code) + assert.Equal(t, "LaunchDarkly returned no sync setting", problem.Message) + assert.Empty(t, settings.calls, "no return rule") + workspace.requireTracked(t, "prompt", true) + assert.Equal(t, lockBefore, workspace.baselines.manifest) +} + // A 403 describes returning ownership to LaunchDarkly, not recording code // ownership, and names the missing permission. Nothing is detached. func TestRunKeepsEverythingWhenTheSyncSettingsWriteIsForbidden(t *testing.T) { diff --git a/internal/sync/prompt/conflict_test.go b/internal/sync/prompt/conflict_test.go index cc6a7c7ba..37885f125 100644 --- a/internal/sync/prompt/conflict_test.go +++ b/internal/sync/prompt/conflict_test.go @@ -504,11 +504,20 @@ func (api *conflictAPI) MakeRequest( method string, path string, _ string, - _ url.Values, + query url.Values, body []byte, _ bool, ) ([]byte, error) { api.requests = append(api.requests, method) + if strings.HasSuffix(path, "/configs/sync/settings") && method == "GET" { + // Every resource resolves to the default setting, with no rule. + items := make([]map[string]any, 0, len(query["resources"])) + for _, resource := range query["resources"] { + kind, lookupKey, _ := strings.Cut(resource, ":") + items = append(items, map[string]any{"resourceKind": kind, "resourceLookupKey": lookupKey, "direction": "both"}) + } + return json.Marshal(map[string]any{"items": items}) + } if strings.Contains(path, "/ai-tools/") { if method == "PATCH" { var tool syncdomain.Tool diff --git a/internal/sync/prompt/direction_test.go b/internal/sync/prompt/direction_test.go index 2c4d8e3de..36aefdd8a 100644 --- a/internal/sync/prompt/direction_test.go +++ b/internal/sync/prompt/direction_test.go @@ -82,7 +82,8 @@ func TestDeletedLinkedResourceRequiresDetach(t *testing.T) { } // A create of a linked resource has nothing in LaunchDarkly for a setting -// to govern yet, so a missing setting does not block it. +// to govern yet, so a missing setting does not block it, and the create +// records code as the owner of the new variation. func TestCreateOfALinkedResourceNeedsNoSetting(t *testing.T) { local := testVariation("local") resources := []PlannedResource{{ @@ -95,6 +96,7 @@ func TestCreateOfALinkedResourceNeedsNoSetting(t *testing.T) { require.NoError(t, err) assert.Equal(t, ActionCreateServer, resources[0].Action) + assert.True(t, resources[0].claimOwnership) } func TestMissingToolSettingIsActionable(t *testing.T) { diff --git a/internal/sync/prompt/ownership_test.go b/internal/sync/prompt/ownership_test.go index c3e38f513..5a299ae47 100644 --- a/internal/sync/prompt/ownership_test.go +++ b/internal/sync/prompt/ownership_test.go @@ -234,6 +234,22 @@ func TestPushStopsWhenTheSyncSettingsFail(t *testing.T) { } } +// A sync settings read that answers without an entry for a variation (here +// the 400 for an unsupported kind) fails closed: no claim and no push. +func TestPushFailsClosedWhenTheSyncSettingIsMissing(t *testing.T) { + root, api := managedVariationWithLocalChange(t) + api.settingsReadErr = errors.New(`{"code":"invalid_request","message":"unsupported resource kind","statusCode":400}`) + + _, _, err := runPrompt(t, root, api, "--yes") + + require.Error(t, err) + assert.Contains(t, err.Error(), "LaunchDarkly returned no sync setting") + assert.Contains(t, err.Error(), string(syncdomain.ErrorSyncSettingUnavailable)) + assert.Zero(t, countRequests(api.requests, http.MethodPatch, "/configs/sync/settings"), "no claim") + assert.Zero(t, countRequests(api.requests, http.MethodPatch, "/variations/default"), "no push") + assert.Equal(t, "Baseline", api.variation.Name) +} + // Without the sync settings API, the push warns, naming the project, that // ownership is not recorded. --yes proceeds, whether the read or the claim // after the confirmation finds the API missing. diff --git a/internal/sync/prompt/state.go b/internal/sync/prompt/state.go index fa8b69a46..34c43e555 100644 --- a/internal/sync/prompt/state.go +++ b/internal/sync/prompt/state.go @@ -303,7 +303,9 @@ func applySourceDirections(client syncapi.Client, resources []PlannedResource) e // applyVariationOwnership reads the ownership of every variation row and // applies it. Without the sync settings API, the rows keep their actions and -// record that their ownership is unknown. +// record that their ownership is unknown. A variation that the API answers +// without an entry for fails closed, before anything is claimed or written, +// unless it is a create of a variation LaunchDarkly does not have yet. func applyVariationOwnership(client syncapi.Client, resources []PlannedResource) error { byProject := make(map[string][]ResourceID) for _, resource := range resources { @@ -330,7 +332,17 @@ func applyVariationOwnership(client syncapi.Client, resources []PlannedResource) enforceDirection(resource, syncdomain.SyncDirectionBoth) continue } - enforceOwnership(resource, ownership[resource.ID]) + owner, ok := ownership[resource.ID] + // A create with nothing in LaunchDarkly yet has no rule to + // read, so it goes ahead and records code as the owner. + if !ok && !(resource.Action == ActionCreateServer && !resource.hasServer()) { + return syncdomain.NewProblem( + syncdomain.ErrorSyncSettingUnavailable, + "LaunchDarkly returned no sync setting", + "Configure the resource sync setting in LaunchDarkly, then run sync again.", + ).WithResource(resource.ID) + } + enforceOwnership(resource, owner) } } } diff --git a/internal/sync/resource.go b/internal/sync/resource.go index dfe93a799..f4222b0c6 100644 --- a/internal/sync/resource.go +++ b/internal/sync/resource.go @@ -154,6 +154,12 @@ var ( windowsReservedNames = regexp.MustCompile(`^(con|prn|aux|nul|com[0-9]|lpt[0-9])$`) ) +// IsLaunchDarklyKey reports whether key matches the LaunchDarkly key pattern. +// A key that matches holds no rule pattern character such as *. +func IsLaunchDarklyKey(key string) bool { + return createKeyPattern.MatchString(key) +} + // ValidateCreate checks the key, the name, and the description of a resource // that sync creates in LaunchDarkly. func ValidateCreate(kind Kind, key, name, description string) error { From 0e0dd4b5284da2afe0c4cac1aaf660be88433302 Mon Sep 17 00:00:00 2001 From: Nathan Kester Date: Tue, 17 Nov 2026 08:37:57 -0700 Subject: [PATCH 2/3] AIC-3901 part 5: read ownership in batches; name projects already claimed The sync settings client read at most 100 resources per call, so a first pull or a detach of more than 100 variations in one project failed before doing anything. The client now reads any number, one page at a time, and push drops its own batching. A push across projects is not atomic. When a later project's claim fails, the error now names the projects already recorded as code-owned. Co-Authored-By: Claude Opus 5.5 --- internal/sync/api/settings.go | 17 +++++---- internal/sync/api/settings_test.go | 25 +++++++++++++ internal/sync/prompt/direction_test.go | 37 ++++++++++++++++++ internal/sync/prompt/state.go | 52 ++++++++++++-------------- internal/sync/prompt/sync.go | 22 ++++++++++- 5 files changed, 115 insertions(+), 38 deletions(-) diff --git a/internal/sync/api/settings.go b/internal/sync/api/settings.go index dc2fc28fa..833b8c761 100644 --- a/internal/sync/api/settings.go +++ b/internal/sync/api/settings.go @@ -44,7 +44,8 @@ func (client Client) SyncDirections( // ResolveOwnership returns the effective LaunchDarkly setting of each // resource and the stored rule pattern that matched it. A resource of a kind -// that LaunchDarkly has no setting for is left out. +// that LaunchDarkly has no setting for is left out. Any number of resources +// can be read; they are asked for one page at a time. func (client Client) ResolveOwnership( projectKey string, ids []syncdomain.ResourceID, @@ -52,9 +53,6 @@ func (client Client) ResolveOwnership( if len(ids) == 0 { return map[syncdomain.ResourceID]syncdomain.Ownership{}, nil } - if len(ids) > 100 { - return nil, fmt.Errorf("read sync settings: at most 100 resources are allowed") - } byKind := map[syncdomain.Kind][]syncdomain.ResourceID{} for _, id := range ids { if id.ProjectKey != projectKey { @@ -66,12 +64,15 @@ func (client Client) ResolveOwnership( // The endpoint rejects a request that names a kind it has no setting for, // and the rejection fails every resource of the request. Each kind travels // alone, so a tool or a skill cannot take the variations down with it. + // The endpoint accepts at most one page of resources per request. for _, kind := range slices.Sorted(maps.Keys(byKind)) { - ownership, err := client.ownershipOfKind(projectKey, byKind[kind]) - if err != nil { - return nil, err + for batch := range slices.Chunk(byKind[kind], syncSettingsPageLimit) { + ownership, err := client.ownershipOfKind(projectKey, batch) + if err != nil { + return nil, err + } + maps.Copy(result, ownership) } - maps.Copy(result, ownership) } return result, nil } diff --git a/internal/sync/api/settings_test.go b/internal/sync/api/settings_test.go index a2fe5a86a..eedd8dcd1 100644 --- a/internal/sync/api/settings_test.go +++ b/internal/sync/api/settings_test.go @@ -155,3 +155,28 @@ func TestResolveOwnershipReportsTheMatchedRule(t *testing.T) { empty: {Direction: syncdomain.SyncDirectionServerCanonical}, }, ownership) } + +// The endpoint accepts at most 100 resources per request, so a read of more +// asks for them 100 at a time and answers for all of them. +func TestResolveOwnershipOfMoreThan100ResourcesReadsThemInBatches(t *testing.T) { + ids := make([]syncdomain.ResourceID, 0, 101) + items := make([]string, 0, 101) + for index := range 101 { + key := fmt.Sprintf("support/v%03d", index) + ids = append(ids, syncdomain.VariationID("project", "support", fmt.Sprintf("v%03d", index))) + items = append(items, fmt.Sprintf(`{"resourceKind":"variation","resourceLookupKey":%q,"direction":"server_canonical"}`, key)) + } + transport := &recordingClient{Responses: [][]byte{ + []byte(`{"items": [` + strings.Join(items[:100], ",") + `], "totalCount": 100}`), + []byte(`{"items": [` + items[100] + `], "totalCount": 1}`), + }} + client := NewClient(transport, "token", "https://example.com") + + ownership, err := client.ResolveOwnership("project", ids) + + require.NoError(t, err) + assert.Len(t, ownership, 101) + require.Len(t, transport.Requests, 2) + assert.Len(t, transport.Requests[0].Query["resources"], 100) + assert.Equal(t, []string{"variation:support/v100"}, transport.Requests[1].Query["resources"]) +} diff --git a/internal/sync/prompt/direction_test.go b/internal/sync/prompt/direction_test.go index 36aefdd8a..0dc6b040c 100644 --- a/internal/sync/prompt/direction_test.go +++ b/internal/sync/prompt/direction_test.go @@ -1,9 +1,11 @@ package prompt import ( + "errors" "net/url" "os" "path/filepath" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -177,3 +179,38 @@ server.registerTool("lookup", { require.NoError(t, err) assert.NotEqual(t, full, manifest.Resources[0].Fingerprint) } + +// forbidClaimInProject refuses the sync settings write of one project with a +// 403 and accepts every other request. +type forbidClaimInProject struct{ project string } + +var _ resources.Client = forbidClaimInProject{} + +func (transport forbidClaimInProject) MakeRequest( + _, method, path, _ string, _ url.Values, _ []byte, _ bool, +) ([]byte, error) { + if method == "PATCH" && strings.Contains(path, "/projects/"+transport.project+"/") { + return nil, errors.New(`{"code":"forbidden","statusCode":403}`) + } + return []byte(`{}`), nil +} + +func (forbidClaimInProject) MakeUnauthenticatedRequest(string, string, []byte) ([]byte, error) { + return nil, nil +} + +// A push across projects is not atomic. When a later project's claim is +// forbidden, the error names the projects already recorded as code-owned. +func TestForbiddenClaimNamesTheProjectsAlreadyClaimed(t *testing.T) { + plan := Plan{Resources: []PlannedResource{ + {ID: syncdomain.VariationID("a", "support", "default"), Action: ActionUpdateServer, claimOwnership: true}, + {ID: syncdomain.VariationID("b", "support", "default"), Action: ActionUpdateServer, claimOwnership: true}, + }} + client := syncapi.NewClient(forbidClaimInProject{project: "b"}, "token", "https://example.com") + + err := claimOwnership(Options{}, client, plan) + + require.Error(t, err) + assert.Contains(t, err.Error(), `project "b", so nothing was pushed`) + assert.Contains(t, err.Error(), "project a is already recorded as code-owned") +} diff --git a/internal/sync/prompt/state.go b/internal/sync/prompt/state.go index 34c43e555..6e4b94e10 100644 --- a/internal/sync/prompt/state.go +++ b/internal/sync/prompt/state.go @@ -314,36 +314,32 @@ func applyVariationOwnership(client syncapi.Client, resources []PlannedResource) } } for projectKey, ids := range byProject { - for start := 0; start < len(ids); start += 100 { - end := min(start+100, len(ids)) - ownership, err := client.ResolveOwnership(projectKey, ids[start:end]) - unavailable := syncapi.IsNotFound(err) - if err != nil && !unavailable { - return err + ownership, err := client.ResolveOwnership(projectKey, ids) + unavailable := syncapi.IsNotFound(err) + if err != nil && !unavailable { + return err + } + for index := range resources { + resource := &resources[index] + if resource.ID.Kind != syncdomain.KindVariation || resource.ID.ProjectKey != projectKey { + continue } - for index := range resources { - resource := &resources[index] - if resource.ID.Kind != syncdomain.KindVariation || resource.ID.ProjectKey != projectKey || - !slices.Contains(ids[start:end], resource.ID) { - continue - } - if unavailable { - resource.ownershipUnavailable = true - enforceDirection(resource, syncdomain.SyncDirectionBoth) - continue - } - owner, ok := ownership[resource.ID] - // A create with nothing in LaunchDarkly yet has no rule to - // read, so it goes ahead and records code as the owner. - if !ok && !(resource.Action == ActionCreateServer && !resource.hasServer()) { - return syncdomain.NewProblem( - syncdomain.ErrorSyncSettingUnavailable, - "LaunchDarkly returned no sync setting", - "Configure the resource sync setting in LaunchDarkly, then run sync again.", - ).WithResource(resource.ID) - } - enforceOwnership(resource, owner) + if unavailable { + resource.ownershipUnavailable = true + enforceDirection(resource, syncdomain.SyncDirectionBoth) + continue + } + owner, ok := ownership[resource.ID] + // A create with nothing in LaunchDarkly yet has no rule to + // read, so it goes ahead and records code as the owner. + if !ok && !(resource.Action == ActionCreateServer && !resource.hasServer()) { + return syncdomain.NewProblem( + syncdomain.ErrorSyncSettingUnavailable, + "LaunchDarkly returned no sync setting", + "Configure the resource sync setting in LaunchDarkly, then run sync again.", + ).WithResource(resource.ID) } + enforceOwnership(resource, owner) } } return nil diff --git a/internal/sync/prompt/sync.go b/internal/sync/prompt/sync.go index 20f7518c8..130a4b96b 100644 --- a/internal/sync/prompt/sync.go +++ b/internal/sync/prompt/sync.go @@ -3,9 +3,11 @@ package prompt import ( "bytes" "errors" + "fmt" "io" "maps" "slices" + "strings" syncdomain "github.com/launchdarkly/ldcli/internal/sync" syncapi "github.com/launchdarkly/ldcli/internal/sync/api" @@ -218,6 +220,7 @@ func (runner Runner) applyPlan( // is not recorded. func claimOwnership(options Options, client syncapi.Client, plan Plan) error { claims := plan.ownershipClaims() + var claimed []string for _, projectKey := range slices.Sorted(maps.Keys(claims)) { err := client.ClaimForCode(projectKey, claims[projectKey]) if syncapi.IsNotFound(err) { @@ -225,11 +228,26 @@ func claimOwnership(options Options, client syncapi.Client, plan Plan) error { continue } if errors.Is(err, syncapi.ErrSyncSettingsForbidden) { - return syncdomain.SyncSettingsForbiddenProblem(projectKey, "record code ownership", "nothing was pushed", err) + return syncdomain.SyncSettingsForbiddenProblem(projectKey, "record code ownership", pushConsequence(claimed), err) } if err != nil { - return err + return fmt.Errorf("record code ownership in project %s, so %s: %w", projectKey, pushConsequence(claimed), err) } + claimed = append(claimed, projectKey) } return nil } + +// pushConsequence says what a failed claim leaves behind: nothing pushed, and +// the projects whose variations were already recorded as code-owned, because +// a push across projects is not atomic. +func pushConsequence(claimed []string) string { + switch len(claimed) { + case 0: + return "nothing was pushed" + case 1: + return "nothing was pushed, but project " + claimed[0] + " is already recorded as code-owned" + default: + return "nothing was pushed, but projects " + strings.Join(claimed, ", ") + " are already recorded as code-owned" + } +} From 79d27334a30de26d4f90f124a79bdf1c5b85960d Mon Sep 17 00:00:00 2001 From: Nathan Kester Date: Tue, 17 Nov 2026 09:26:31 -0700 Subject: [PATCH 3/3] AIC-3901 part 5: a link claims a variation whose content already matches A link of a variation whose content already matched LaunchDarkly only updated the manifest, so it skipped the claim and the variation stayed unowned. A linked row now claims on that path too. A plain sync that adopts matching state still claims on its next push. Co-Authored-By: Claude Opus 5.5 --- internal/sync/prompt/ownership_test.go | 14 ++++++++++++++ internal/sync/prompt/plan.go | 10 +++++++--- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/internal/sync/prompt/ownership_test.go b/internal/sync/prompt/ownership_test.go index 5a299ae47..9f37027ee 100644 --- a/internal/sync/prompt/ownership_test.go +++ b/internal/sync/prompt/ownership_test.go @@ -324,6 +324,20 @@ func TestLinkClaimsAVariationWithoutARule(t *testing.T) { assert.Equal(t, "Local prompt.", api.variation.Instructions) } +// A link makes the variation code-owned even when its content already matches +// LaunchDarkly, so nothing else is pushed. +func TestLinkClaimsAVariationWhoseContentAlreadyMatches(t *testing.T) { + root := initRepository(t) + require.NoError(t, os.WriteFile(filepath.Join(root, "prompt.md"), []byte("Help\n"), 0o644)) + api := &directAPI{variation: pointer(variation("Server"))} + + _, err := linkPrompt(t, root, api) + + require.NoError(t, err) + assert.Equal(t, []string{"variation:support/default code_canonical"}, codeClaims(api.settingsWrites)) + assert.Zero(t, countRequests(api.requests, http.MethodPatch, "/variations/default"), "no content push") +} + // A link of a variation with an explicit LaunchDarkly rule neither claims nor // pushes it, and the user learns why. func TestLinkLeavesAVariationManagedInLaunchDarkly(t *testing.T) { diff --git a/internal/sync/prompt/plan.go b/internal/sync/prompt/plan.go index 26c660e21..191d96d1b 100644 --- a/internal/sync/prompt/plan.go +++ b/internal/sync/prompt/plan.go @@ -752,12 +752,16 @@ func (plan Plan) ownershipUnrecordedProjects() []string { return projectKeys } -// ownershipClaims returns, by project, the variations that the plan pushes -// and that code does not own yet in the LaunchDarkly sync settings. +// ownershipClaims returns, by project, the variations that the plan pushes or +// links, and that code does not own yet in the LaunchDarkly sync settings. A +// link claims its variation even when the content already matches, so only +// the manifest changes. func (plan Plan) ownershipClaims() map[string][]ResourceID { claims := make(map[string][]ResourceID) for _, resource := range plan.Resources { - if resource.ID.Kind == syncdomain.KindVariation && resource.claimOwnership && resource.Action.changesServer() { + linked := resource.Source != nil && resource.Action == ActionUpdateManifest + claimed := resource.Action.changesServer() || linked + if resource.ID.Kind == syncdomain.KindVariation && resource.claimOwnership && claimed { claims[resource.ID.ProjectKey] = append(claims[resource.ID.ProjectKey], resource.ID) } }