{"record":{"id":"1c4d23ed72389f79","repo":"microsoft/aspire","slug":"couldn-t-find-required-instance-id-for-index-instanceindex","errorCode":null,"errorMessage":"Couldn't find required instance ID for index {instanceIndex} on resource {resource.Name}.","messagePattern":"Couldn't find required instance ID for index (.+?) on resource (.+?)\\.","errorType":"exception","errorClass":"DistributedApplicationException","httpStatus":null,"severity":"error","filePath":"src/Aspire.Hosting/Dcp/DcpExecutor.cs","lineNumber":1145,"sourceCode":"    /// <summary>\n    /// Gets information about the resource's DCP instance. ReplicaInstancesAnnotation is added in BeforeStartEvent.\n    /// </summary>\n    internal static DcpInstance GetDcpInstance(IResource resource, int instanceIndex)\n    {\n        if (!resource.TryGetInstances(out var instances))\n        {\n            throw new DistributedApplicationException($\"Couldn't find required {nameof(DcpInstancesAnnotation)} annotation on resource {resource.Name}.\");\n        }\n\n        foreach (var instance in instances)\n        {\n            if (instance.Index == instanceIndex)\n            {\n                return instance;\n            }\n        }\n\n        throw new DistributedApplicationException($\"Couldn't find required instance ID for index {instanceIndex} on resource {resource.Name}.\");\n    }\n\n    /// <summary>\n    /// Create a patch update using the specified resource.\n    /// A copy is taken of the resource to avoid permanently changing it.\n    /// </summary>\n    private static V1Patch CreatePatch<T>(T obj, Action<T> change) where T : CustomResource\n    {\n        // This method isn't very efficient.\n        // If mass or frequent patches are required then we may want to create patches manually.\n        var current = JsonSerializer.SerializeToNode(obj);\n\n        var copy = JsonSerializer.Deserialize<T>(current)!;\n        change(copy);\n\n        var changed = JsonSerializer.SerializeToNode(copy);\n\n        var jsonPatch = JsonPatch.Create(current, changed);","sourceCodeStart":1127,"sourceCodeEnd":1163,"githubUrl":"https://github.com/microsoft/aspire/blob/25830f84bd145686607ad00c057b3f84e2e51d43/src/Aspire.Hosting/Dcp/DcpExecutor.cs#L1127-L1163","documentation":"DcpExecutor looks up a specific replicated instance of a resource by its replica index (e.g. instance 0, 1, 2 of a scaled resource) and none of the resource's DCP replicas has that index. Aspire throws DistributedApplicationException because code downstream requires an instance at exactly that index to proceed. This is an internal consistency failure: the resource model said there should be N instances but DCP state disagrees.","triggerScenarios":"Calling DcpExecutor APIs such as GetInstanceAsync/instance lookup (used internally during endpoint allocation and restart flows) with an instanceIndex for which no replica currently exists on the resource — e.g. during scale-down races, restarts of specific replicas, or when DCP has not yet created/has already deleted that replica.","commonSituations":"Restarting a specific replica while DCP is recreating instances; race between app-model replica count changes and DCP watch events; corrupt/stale DCP state where the instance list is out of sync; bugs in replica index computation during endpoint assignment.","solutions":["Retry the operation after a short delay so DCP can finish creating the replica at that index.","Verify replica count settings on the resource (WithReplicas) match what you expect before restarting a specific instance.","Check DCP state (dcp CLI / ~/.aspine dcp logs) for missing or failed replicas.","Restart the AppHost to rebuild a consistent DCP state if the instance list appears stale."],"exampleFix":"// before: restart a replica index without checking instance count\nawait executor.StopResourceAsync(reference, ct);\n// after: guard against missing instances by enumerating instances first\nvar instances = await GetInstancesAsync(resource, ct);\nif (instances.Any(i => i.Index == instanceIndex))\n{\n    await RestartInstanceAsync(resource, instanceIndex, ct);\n}","handlingStrategy":"retry","validationCode":"var instances = await GetInstancesAsync(resource, ct);\nif (!instances.Any(i => i.Index == instanceIndex))\n{\n    // instance not ready; defer or recompute instead of proceeding\n}","typeGuard":"static bool HasInstance(IEnumerable<IAppResource> instances, int index) => instances.Any(i => i.Index == index);","tryCatchPattern":"try { var instance = GetInstanceByIndex(resource, index); }\ncatch (DistributedApplicationException ex) when (ex.Message.Contains(\"Couldn't find required instance ID\"))\n{\n    // log, wait for DCP reconciliation, retry\n}","preventionTips":["Avoid targeting replica indexes immediately after scale changes","Enumerate current instances before restarting a specific replica","Keep replica counts in the app model consistent with expected DCP state"],"tags":["dcp","replicas","instance-not-found","race-condition"],"backgroundTag":"record-not-found","analyzedSha":"25830f84bd145686607ad00c057b3f84e2e51d43","analyzedAt":"2026-09-16T11:10:06.193Z","contentChangedAt":"2026-09-16T11:10:06.193Z","schemaVersion":2},"datasetVersion":"2026-09-21T09:17:21.228Z"}