From 0659a75b45d69a4202f9e33a71892f7eeab2423f Mon Sep 17 00:00:00 2001 From: codex Date: Wed, 21 Oct 2026 03:18:09 +0800 Subject: [PATCH] fix(cloud): keep operation recovery identity-bound --- agent/api/server.go | 74 +- agent/api/server_test.go | 211 +- agent/cmd/virt-agent/main.go | 64 +- agent/cmd/virt-agent/main_test.go | 98 +- agent/control/client.go | 32 +- agent/control/client_test.go | 57 +- agent/hypervisor/libvirt_catalog_features.go | 10 + agent/hypervisor/libvirt_operation_admin.go | 36 +- .../libvirt_operation_admin_test.go | 166 +- agent/hypervisor/types.go | 19 +- agent/operation/journal.go | 857 ++++- agent/operation/journal_test.go | 580 ++- docs/ADMIN_OPERATIONS.md | 6 +- docs/AGENT_API.md | 18 +- docs/DEPLOYMENT.md | 10 +- docs/INTEGRATION_PLAN.md | 8 +- docs/TASK_EXECUTION.md | 18 +- docs/VALIDATION.md | 23 +- gateway/README.md | 19 +- gateway/agent/completion.go | 9 +- gateway/agent/completion_test.go | 67 +- gateway/agent/registry.go | 21 +- gateway/agent/registry_test.go | 12 +- .../Cloud/CloudAdminInstanceService.php | 98 +- .../CloudAdminOperationRecoveryService.php | 212 +- .../Cloud/CloudAdminOperationsService.php | 262 +- web/app/Services/Cloud/CloudAgentClient.php | 14 + ...CloudAutomaticOperationRecoveryService.php | 1120 +++++- .../Cloud/CloudCreateFailureFinalizer.php | 92 +- .../Services/Cloud/CloudDispatchLedger.php | 105 + .../Services/Cloud/CloudInvoiceService.php | 22 +- web/app/Services/Cloud/CloudJobService.php | 2690 +++++++++++++- .../Services/Cloud/CloudLifecycleService.php | 296 +- .../Cloud/CloudOperationCompletionService.php | 925 ++++- .../Cloud/CloudOperationRecoveryIdentity.php | 1156 ++++++ .../Cloud/CloudOperationRecoveryPolicy.php | 49 + .../Cloud/CloudOperationRecoveryService.php | 590 +-- .../CloudRecoveryAggregateStateConflict.php | 8 + .../CloudRecoveryDispatchLedgerConflict.php | 8 + .../CloudRecoveryInstanceStateConflict.php | 8 + ...CloudRecoveryOperationIdentityConflict.php | 8 + .../Cloud/CloudRecoveryPayloadUnavailable.php | 8 + .../Services/Cloud/CloudRenewalService.php | 22 +- .../CloudRescueTemplateDeletionService.php | 171 +- .../CloudRescueTemplateImportService.php | 84 +- .../Cloud/CloudTemplateCatalogService.php | 1193 +++++- .../Services/Cloud/CloudUserIsoService.php | 1116 +++++- web/app/Services/Cloud/CloudWorkerService.php | 1219 +++++- web/public/cloud/admin-instances.js | 33 +- web/public/cloud/admin-operations.js | 67 +- web/public/cloud/admin.js | 13 +- web/public/cloud/app.js | 2 +- web/public/cloud/detail.js | 29 +- web/public/cloud/invoice-detail-runtime.js | 33 +- web/public/cloud/iso-images.js | 27 +- web/public/cloud/runtime.js | 15 +- web/public/cloud/task-center.js | 53 +- web/public/cloud/task-observer.js | 47 +- .../views/venix/admin/cloud/instances.tpl | 2 +- .../views/venix/admin/cloud/operations.tpl | 6 +- .../venix/admin/cloud/operations_rows.tpl | 2 +- web/resources/views/venix/admin/index.tpl | 2 +- web/resources/views/venix/layout_assets.tpl | 2 +- .../views/venix/user/task_center_drawer.tpl | 2 +- web/tests/AdminAcceptedTaskBehaviorTest.mjs | 5 +- web/tests/AdminInstanceViewTest.php | 4 +- .../AdminOperationsCancelBehaviorTest.mjs | 16 +- web/tests/AdminOperationsViewTest.php | 29 +- web/tests/AdminOverviewContractTest.php | 2 +- web/tests/CloudAdminInstanceServiceTest.php | 171 +- ...CloudAdminOperationRecoveryServiceTest.php | 242 +- web/tests/CloudAdminOperationsServiceTest.php | 224 +- web/tests/CloudAgentMutationIdentityTest.php | 650 ++++ web/tests/CloudAgentProtocolTest.php | 17 + .../CloudAggregateRecoveryConvergenceTest.php | 3279 +++++++++++++++++ ...dAutomaticOperationRecoveryServiceTest.php | 1885 +++++++++- ...oudCatalogActiveJobPointerRecoveryTest.php | 1028 ++++++ .../CloudCatalogDispatchLedgerSafetyTest.php | 585 +++ .../CloudCatalogLockOrderContractTest.php | 191 + web/tests/CloudFinancialWorkflowTest.php | 1073 +++++- web/tests/CloudFirewallWorkflowTest.php | 17 + .../CloudInstanceReadPerformanceTest.php | 5 +- web/tests/CloudInvoiceDetailContractTest.php | 6 +- web/tests/CloudInvoiceLifecycleTest.php | 38 +- .../CloudOperationCompletionContractTest.php | 46 +- .../CloudOperationRecoveryPolicyTest.php | 223 ++ .../CloudRescueTemplateRetryBoundaryTest.php | 550 +++ .../CloudResolvedTaskPresentationTest.php | 105 + web/tests/CloudRuntimeHeartbeatTest.php | 31 +- .../CloudSingleDispatchArchitectureTest.php | 44 +- web/tests/CloudSnapshotWorkflowTest.php | 32 + .../CloudSpecialTaskSingleDispatchTest.php | 6 +- web/tests/CloudTaskDeadlineFallbackTest.php | 880 +++-- web/tests/CloudTaskObserverBehaviorTest.mjs | 142 +- .../CloudTaskRecoveryPresentationTest.php | 746 ++++ web/tests/CloudTemplateCatalogTest.php | 1 + .../CloudTemplateWorkerConvergenceTest.php | 22 +- ...CloudUndispatchedFinalizerRecoveryTest.php | 365 ++ web/tests/CloudWorkerExecutionModeTest.php | 94 +- web/tests/VirtualizationAssetsTest.php | 3 +- 100 files changed, 25405 insertions(+), 1578 deletions(-) create mode 100644 web/app/Services/Cloud/CloudDispatchLedger.php create mode 100644 web/app/Services/Cloud/CloudOperationRecoveryIdentity.php create mode 100644 web/app/Services/Cloud/CloudOperationRecoveryPolicy.php create mode 100644 web/app/Services/Cloud/CloudRecoveryAggregateStateConflict.php create mode 100644 web/app/Services/Cloud/CloudRecoveryDispatchLedgerConflict.php create mode 100644 web/app/Services/Cloud/CloudRecoveryInstanceStateConflict.php create mode 100644 web/app/Services/Cloud/CloudRecoveryOperationIdentityConflict.php create mode 100644 web/app/Services/Cloud/CloudRecoveryPayloadUnavailable.php create mode 100644 web/tests/CloudAgentMutationIdentityTest.php create mode 100644 web/tests/CloudAggregateRecoveryConvergenceTest.php create mode 100644 web/tests/CloudCatalogActiveJobPointerRecoveryTest.php create mode 100644 web/tests/CloudCatalogDispatchLedgerSafetyTest.php create mode 100644 web/tests/CloudCatalogLockOrderContractTest.php create mode 100644 web/tests/CloudOperationRecoveryPolicyTest.php create mode 100644 web/tests/CloudRescueTemplateRetryBoundaryTest.php create mode 100644 web/tests/CloudTaskRecoveryPresentationTest.php create mode 100644 web/tests/CloudUndispatchedFinalizerRecoveryTest.php diff --git a/agent/api/server.go b/agent/api/server.go index d4014426..6f3c6155 100644 --- a/agent/api/server.go +++ b/agent/api/server.go @@ -109,6 +109,9 @@ type errorEnvelope struct { type operationResponse struct { OperationID string `json:"operation_id"` + Action string `json:"action"` + ResourceID string `json:"resource_id"` + RequestFingerprint string `json:"request_fingerprint"` Status operation.State `json:"status"` Replayed bool `json:"replayed"` Result json.RawMessage `json:"result,omitempty"` @@ -1045,21 +1048,47 @@ func (s *Server) routeOperations(w http.ResponseWriter, r *http.Request, segment if !requireSuperAdminInspection(w, actor, operationID) { return } - stored, err := s.Journal.Get(operationID) + stored, err := s.Journal.GetForInspection(operationID) if err != nil { writeMappedError(w, err, nil) return } - if !requireSystemRecoverySettingsRecord(w, actor, stored) { + if !requireSystemRecoveryRecord(w, actor, stored) { return } - ctx, cancel := context.WithTimeout(r.Context(), s.OperationTimeout) - defer cancel() - inspection, err := s.Hypervisor.InspectOperation(ctx, stored) + incident, incidentFound, err := s.Journal.CompletionDeliveryIncident(operationID) if err != nil { writeMappedError(w, err, nil) return } + var inspection hypervisor.OperationInspection + if incidentFound { + // Delivery corruption is already sufficient to make the panel view + // inconclusive. Do not make reporting that durable Agent incident + // depend on a live host read which may itself time out or fail. + inspection = hypervisor.OperationInspection{ + OperationStatus: stored.State, + CheckedAt: time.Now().UTC().Unix(), + } + if stored.Error != nil { + inspection.ErrorCode = stored.Error.Code + } + applyCompletionDeliveryIncident(&inspection, incident) + } else { + ctx, cancel := context.WithTimeout(r.Context(), s.OperationTimeout) + defer cancel() + inspection, err = s.Hypervisor.InspectOperation(ctx, stored) + if err != nil { + writeMappedError(w, err, nil) + return + } + } + // Identity always comes from the immutable Journal record, never from a + // hypervisor adapter or its observation of current host state. + inspection.OperationID = stored.OperationID + inspection.Action = stored.Action + inspection.ResourceID = stored.ResourceID + inspection.RequestFingerprint = stored.Fingerprint inspection.FenceState, err = s.Journal.FenceState(operationID) if err != nil { writeMappedError(w, err, nil) @@ -1079,7 +1108,7 @@ func (s *Server) routeOperations(w http.ResponseWriter, r *http.Request, segment writeMappedError(w, err, nil) return } - if !requireSystemRecoverySettingsRecord(w, actor, stored) { + if !requireSystemRecoveryRecord(w, actor, stored) { return } resolution, err := s.Journal.GetFenceResolution(operationID) @@ -1107,7 +1136,7 @@ func (s *Server) routeOperations(w http.ResponseWriter, r *http.Request, segment writeMappedError(w, err, nil) return } - if !requireSystemRecoverySettingsRecord(w, actor, stored) { + if !requireSystemRecoveryRecord(w, actor, stored) { return } request, ok := decodeRequired[operation.FenceResolutionRequest](w, body) @@ -1126,6 +1155,9 @@ func (s *Server) routeOperations(w http.ResponseWriter, r *http.Request, segment case errors.Is(err, operation.ErrFenceNotResolvable): writeError(w, http.StatusConflict, "operation_fence_not_resolvable", "operation does not hold an active effect fence", nil) return + case errors.Is(err, operation.ErrFenceIdentityConflict): + writeError(w, http.StatusConflict, "operation_identity_conflict", "fence resolution identity does not match the immutable operation", nil) + return case errors.Is(err, operation.ErrFenceResolutionConflict): writeError(w, http.StatusConflict, "operation_fence_resolution_conflict", "operation fence already has a different audit resolution", nil) return @@ -1467,6 +1499,21 @@ func (s *Server) claimAsync(operationID string) bool { return true } +func applyCompletionDeliveryIncident(inspection *hypervisor.OperationInspection, + incident operation.CompletionDeliveryIncident) { + if inspection == nil { + return + } + inspection.Outcome = hypervisor.InspectionOutcomeUncertain + inspection.SummaryCode = hypervisor.InspectionSummaryIncomplete + inspection.EffectResolution = hypervisor.InspectionEffectInconclusive + inspection.EffectProjection = nil + inspection.AbortJob = hypervisor.OperationAbortInspection{} + inspection.Cleanup = hypervisor.OperationCleanupPlan{} + inspection.CompletionDeliveryState = operation.CompletionDeliveryStateQuarantined + inspection.CompletionDeliveryErrorCode = incident.ErrorCode +} + func (s *Server) releaseAsync(operationID string) { s.asyncMu.Lock() defer s.asyncMu.Unlock() @@ -1475,7 +1522,8 @@ func (s *Server) releaseAsync(operationID string) { func operationWire(record operation.Record, replayed bool) operationResponse { return operationResponse{ - OperationID: record.OperationID, Status: record.State, Replayed: replayed, + OperationID: record.OperationID, Action: record.Action, ResourceID: record.ResourceID, + RequestFingerprint: record.Fingerprint, Status: record.State, Replayed: replayed, Result: record.Result, Error: record.Error, CauseCode: record.CauseCode, EffectMayHaveApplied: record.EffectMayHaveApplied, SafeToResubmit: record.SafeToResubmit, @@ -1612,11 +1660,11 @@ func requireSuperAdminFenceResolution(w http.ResponseWriter, actor auth.Actor, o return true } -// System recovery is intentionally a one-kind capability. Route shape and -// operation identity are necessary but not sufficient: authorization is -// completed only after reading the immutable Journal action. -func requireSystemRecoverySettingsRecord(w http.ResponseWriter, actor auth.Actor, record operation.Record) bool { - if actor.SystemRecovery && record.Action != "update-settings" { +// Route shape and operation identity are necessary but not sufficient for +// system recovery: authorization is completed only after reading the +// immutable Journal action and applying the explicit Agent action allowlist. +func requireSystemRecoveryRecord(w http.ResponseWriter, actor auth.Actor, record operation.Record) bool { + if actor.SystemRecovery && !operation.SystemRecoveryActionAllowed(record.Action) { writePreDispatchError(w, http.StatusForbidden, "forbidden", "system recovery is not enabled for this operation kind") return false } diff --git a/agent/api/server_test.go b/agent/api/server_test.go index 80b5e542..1e35ac7d 100644 --- a/agent/api/server_test.go +++ b/agent/api/server_test.go @@ -149,6 +149,28 @@ func (a *testAPI) request(t *testing.T, method, target string, body []byte, acto return response } +func requireOperationResponseIdentity(t *testing.T, response *httptest.ResponseRecorder, + operationID, action, resourceID, requestFingerprint string) operationResponse { + t.Helper() + var wire operationResponse + if err := json.Unmarshal(response.Body.Bytes(), &wire); err != nil { + t.Fatalf("decode operation response %q: %v body=%s", operationID, err, response.Body.String()) + } + if wire.OperationID != operationID || wire.Action != action || wire.ResourceID != resourceID || + wire.RequestFingerprint != requestFingerprint { + t.Fatalf("operation identity = %#v, want operation=%q action=%q resource=%q fingerprint=%q", + wire, operationID, action, resourceID, requestFingerprint) + } + var raw map[string]json.RawMessage + if err := json.Unmarshal(response.Body.Bytes(), &raw); err != nil { + t.Fatal(err) + } + if _, legacy := raw["fingerprint"]; legacy { + t.Fatalf("legacy fingerprint key leaked into operation wire: %s", response.Body.String()) + } + return wire +} + func TestOperationRecoveryMutationRoutesAreRemoved(t *testing.T) { api := newTestAPI(t) operationID := "operation-terminal-inspect" @@ -174,8 +196,18 @@ func TestOperationRecoveryMutationRoutesAreRemoved(t *testing.T) { if response := api.request(t, http.MethodGet, "/v1/operations/"+operationID, nil, actor); response.Code != http.StatusOK { t.Fatalf("operation GET = %d %s", response.Code, response.Body.String()) } - if response := api.request(t, http.MethodGet, "/v1/operations/"+operationID+"/inspect", nil, actor); response.Code != http.StatusOK { - t.Fatalf("read-only inspect = %d %s", response.Code, response.Body.String()) + inspectionResponse := api.request(t, http.MethodGet, "/v1/operations/"+operationID+"/inspect", nil, actor) + if inspectionResponse.Code != http.StatusOK { + t.Fatalf("read-only inspect = %d %s", inspectionResponse.Code, inspectionResponse.Body.String()) + } + var inspection hypervisor.OperationInspection + if err := json.Unmarshal(inspectionResponse.Body.Bytes(), &inspection); err != nil { + t.Fatal(err) + } + if inspection.Action != spec.Action || inspection.ResourceID != spec.ResourceID || + inspection.RequestFingerprint != spec.Fingerprint { + t.Fatalf("inspection identity = %#v, want action=%q resource=%q fingerprint=%q", + inspection, spec.Action, spec.ResourceID, spec.Fingerprint) } for _, suffix := range []string{"reconcile", "confirm-inspection", "abort-job", "cleanup"} { response := api.request(t, http.MethodPost, "/v1/operations/"+operationID+"/"+suffix, []byte(`{}`), actor) @@ -191,6 +223,59 @@ func TestOperationRecoveryMutationRoutesAreRemoved(t *testing.T) { } } +func TestOperationInspectionReportsCompletionDeliveryQuarantine(t *testing.T) { + api := newTestAPI(t) + operationID := "operation-delivery-quarantine" + spec := operation.Spec{ + OperationID: operationID, + ResourceID: "vm-delivery-quarantine", + Action: "delete-vm", + Fingerprint: operation.Fingerprint(http.MethodDelete, "/v1/vms/vm-delivery-quarantine", []byte(`{}`)), + Destructive: true, + } + if _, _, err := api.journal.Execute(context.Background(), spec, func(context.Context) (json.RawMessage, error) { + return json.RawMessage(`{"nested":{"root_password":"must-not-be-delivered"}}`), nil + }); err != nil { + t.Fatal(err) + } + if claimed, err := api.journal.ClaimPendingCompletions(1); err != nil || len(claimed) != 0 { + t.Fatalf("sensitive completion was not quarantined: %#v err=%v", claimed, err) + } + + actor := auth.Actor{ + UserID: 1, IsAdmin: true, IsSuperAdmin: true, CanManage: true, + OperationID: operationID, + } + response := api.request(t, http.MethodGet, "/v1/operations/"+operationID+"/inspect", nil, actor) + if response.Code != http.StatusOK { + t.Fatalf("quarantined inspection = %d %s", response.Code, response.Body.String()) + } + var inspection hypervisor.OperationInspection + if err := json.Unmarshal(response.Body.Bytes(), &inspection); err != nil { + t.Fatal(err) + } + if inspection.OperationStatus != operation.StateSucceeded || + inspection.ErrorCode != "" || + inspection.Outcome != hypervisor.InspectionOutcomeUncertain || + inspection.SummaryCode != hypervisor.InspectionSummaryIncomplete || + inspection.EffectResolution != hypervisor.InspectionEffectInconclusive || + inspection.CompletionDeliveryState != operation.CompletionDeliveryStateQuarantined || + inspection.CompletionDeliveryErrorCode != operation.CompletionDeliveryErrorReceiptInvalid || + len(inspection.EffectProjection) != 0 || inspection.AbortJob.Available || inspection.Cleanup.Available { + t.Fatalf("quarantined completion inspection = %#v", inspection) + } + api.hv.mu.Lock() + inspections := api.hv.inspections + api.hv.mu.Unlock() + if inspections != 0 { + t.Fatalf("delivery quarantine reporting depended on %d live host inspections", inspections) + } + stored, err := api.journal.Get(operationID) + if err != nil || stored.State != operation.StateSucceeded || stored.Error != nil { + t.Fatalf("delivery quarantine changed operation status: %#v err=%v", stored, err) + } +} + func TestSuperAdminFenceResolutionIsJournalOnlyAndReadBackIsStable(t *testing.T) { api := newTestAPI(t) operationID := "operation-fence-resolution" @@ -224,11 +309,34 @@ func TestSuperAdminFenceResolutionIsJournalOnlyAndReadBackIsStable(t *testing.T) ResolutionID: "0123456789abcdef0123456789abcdef", Resolution: operation.FenceResolutionNotApplied, InspectionCheckedAt: api.now.Unix(), ReasonSHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + Action: spec.Action, ResourceID: spec.ResourceID, RequestFingerprint: spec.Fingerprint, } body, err := json.Marshal(request) if err != nil { t.Fatal(err) } + missingIdentity := request + missingIdentity.RequestFingerprint = "" + missingIdentityBody, err := json.Marshal(missingIdentity) + if err != nil { + t.Fatal(err) + } + invalidIdentity := api.request(t, http.MethodPost, "/v1/operations/"+operationID+"/resolve-fence", missingIdentityBody, actor) + if invalidIdentity.Code != http.StatusBadRequest || + !bytes.Contains(invalidIdentity.Body.Bytes(), []byte(`"code":"invalid_fence_resolution"`)) { + t.Fatalf("missing fence identity = %d %s", invalidIdentity.Code, invalidIdentity.Body.String()) + } + mismatch := request + mismatch.ResourceID = "vm-other-fence-resolution" + mismatchBody, err := json.Marshal(mismatch) + if err != nil { + t.Fatal(err) + } + identityConflict := api.request(t, http.MethodPost, "/v1/operations/"+operationID+"/resolve-fence", mismatchBody, actor) + if identityConflict.Code != http.StatusConflict || + !bytes.Contains(identityConflict.Body.Bytes(), []byte(`"code":"operation_identity_conflict"`)) { + t.Fatalf("fence identity conflict = %d %s", identityConflict.Code, identityConflict.Body.String()) + } resolved := api.request(t, http.MethodPost, "/v1/operations/"+operationID+"/resolve-fence", body, actor) if resolved.Code != http.StatusOK || !bytes.Contains(resolved.Body.Bytes(), []byte(`"replayed":false`)) { t.Fatalf("resolve fence = %d %s", resolved.Code, resolved.Body.String()) @@ -258,6 +366,8 @@ func TestFenceResolutionRequiresExactActorOperationIdentity(t *testing.T) { ResolutionID: "fedcba9876543210fedcba9876543210", Resolution: operation.FenceResolutionApplied, InspectionCheckedAt: api.now.Unix(), ReasonSHA256: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + Action: "delete-vm", ResourceID: "vm-fence-identity", + RequestFingerprint: operation.Fingerprint(http.MethodDelete, "/v1/vms/vm-fence-identity", []byte(`{}`)), } body, err := json.Marshal(request) if err != nil { @@ -305,6 +415,7 @@ func TestSystemRecoveryActorCanOnlyInspectAndResolveItsExactOperation(t *testing ResolutionID: "98769876987698769876987698769876", Resolution: operation.FenceResolutionNotApplied, InspectionCheckedAt: api.now.Unix(), ReasonSHA256: "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd", + Action: spec.Action, ResourceID: spec.ResourceID, RequestFingerprint: spec.Fingerprint, } body, err := json.Marshal(request) if err != nil { @@ -326,7 +437,6 @@ func TestSystemRecoveryActorCanOnlyInspectAndResolveItsExactOperation(t *testing for _, denied := range []struct { name, operationID, resourceID, action string }{ - {"delete", "operation-system-delete-denied", "vm-system-delete-denied", "delete-vm"}, {"unknown", "operation-system-unknown-denied", "vm-system-unknown-denied", "future-unknown"}, } { t.Run("reject "+denied.name+" operation", func(t *testing.T) { @@ -373,6 +483,63 @@ func TestSystemRecoveryActorCanOnlyInspectAndResolveItsExactOperation(t *testing }) } + reviewedActions := []string{ + "power-start", "power-shutdown", "power-reboot", "power-reset", "power-destroy", + "reinstall-vm", + "enter-rescue", "force-start-rescue", "exit-rescue:connected", "exit-rescue:suspended", + "change-network", "network-suspend", "network-resume", + "apply-firewall", "delete-vm", "force-delete-vm", + "service-suspend", + "create-snapshot:0123456789abcdef0123456789abcdef:filesystem", + "create-snapshot:0123456789abcdef0123456789abcdef:crash", + "delete-snapshot:0123456789abcdef0123456789abcdef", + "restore-snapshot:0123456789abcdef0123456789abcdef", + "import-template", "update-template", "delete-template", + "import-rescue-template", "delete-rescue-template", + "import-user-iso", "delete-user-iso", + } + for index, action := range reviewedActions { + t.Run("reviewed "+action, func(t *testing.T) { + allowedOperationID := fmt.Sprintf("operation-system-reviewed-%02d", index) + allowedResourceID := fmt.Sprintf("resource-system-reviewed-%02d", index) + allowedSpec := operation.Spec{ + OperationID: allowedOperationID, + ResourceID: allowedResourceID, + Action: action, + Fingerprint: operation.Fingerprint(http.MethodPost, "/v1/test/"+allowedResourceID, []byte(`{}`)), + Destructive: true, + } + if _, _, err := api.journal.Execute(context.Background(), allowedSpec, func(context.Context) (json.RawMessage, error) { + return nil, &worker.Error{Code: "result_unconfirmed", Message: "effect may have applied", EffectMayHaveApplied: true} + }); err == nil { + t.Fatal("seed reviewed recovery failure unexpectedly succeeded") + } + allowedActor := auth.Actor{UserID: 0, SystemRecovery: true, OperationID: allowedOperationID} + if response := api.request(t, http.MethodGet, "/v1/operations/"+allowedOperationID+"/inspect", nil, allowedActor); response.Code != http.StatusOK { + t.Fatalf("reviewed system inspect = %d %s", response.Code, response.Body.String()) + } + allowedRequest := operation.FenceResolutionRequest{ + ResolutionID: fmt.Sprintf("%032x", index+1), + Resolution: operation.FenceResolutionNotApplied, + InspectionCheckedAt: api.now.Unix(), + ReasonSHA256: "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", + Action: allowedSpec.Action, + ResourceID: allowedSpec.ResourceID, + RequestFingerprint: allowedSpec.Fingerprint, + } + allowedBody, err := json.Marshal(allowedRequest) + if err != nil { + t.Fatal(err) + } + if response := api.request(t, http.MethodPost, "/v1/operations/"+allowedOperationID+"/resolve-fence", allowedBody, allowedActor); response.Code != http.StatusOK { + t.Fatalf("reviewed system resolution = %d %s", response.Code, response.Body.String()) + } + if response := api.request(t, http.MethodGet, "/v1/operations/"+allowedOperationID+"/fence-resolution", nil, allowedActor); response.Code != http.StatusOK { + t.Fatalf("reviewed system fence read = %d %s", response.Code, response.Body.String()) + } + }) + } + for _, test := range []struct { name, method, target string body []byte @@ -399,7 +566,7 @@ func TestSystemRecoveryActorCanOnlyInspectAndResolveItsExactOperation(t *testing inspections := api.hv.inspections configureCalls := api.hv.configureCalls api.hv.mu.Unlock() - if inspections != 2 || configureCalls != 0 { + if inspections != 2+len(reviewedActions) || configureCalls != 0 { t.Fatalf("system recovery escaped read-only scope: inspections=%d mutations=%d", inspections, configureCalls) } } @@ -430,6 +597,11 @@ func TestMutationUsesIsolatedExecutorExactlyOnce(t *testing.T) { if first.Code != http.StatusAccepted { t.Fatalf("first isolated response = %d %s", first.Code, first.Body.String()) } + fingerprint := operation.Fingerprint(http.MethodPost, "/v1/storage/configuration", body) + accepted := requireOperationResponseIdentity(t, first, request.OperationID, "configure-storage", "host-storage", fingerprint) + if accepted.Status != operation.StateDispatching || accepted.Replayed { + t.Fatalf("accepted operation response = %#v", accepted) + } terminal := waitForTerminal(t, api.journal, request.OperationID) if terminal.State != operation.StateSucceeded || string(terminal.Result) != `{"configured":true}` { t.Fatalf("terminal operation = %#v", terminal) @@ -438,6 +610,10 @@ func TestMutationUsesIsolatedExecutorExactlyOnce(t *testing.T) { if replay.Code != http.StatusOK { t.Fatalf("terminal replay = %d %s", replay.Code, replay.Body.String()) } + replayed := requireOperationResponseIdentity(t, replay, request.OperationID, "configure-storage", "host-storage", fingerprint) + if replayed.Status != operation.StateSucceeded || !replayed.Replayed { + t.Fatalf("replayed operation response = %#v", replayed) + } executor.mu.Lock() defer executor.mu.Unlock() if executor.calls != 1 || len(executor.requests) != 1 { @@ -468,7 +644,10 @@ func TestIsolatedMutationDeadlineCapsOnlyStorageConfiguration(t *testing.T) { func TestIsolatedMutationAdmissionIsShortAndDoesNotStartSecondWorker(t *testing.T) { api := newTestAPI(t) - api.handler.AdmissionTimeout = 30 * time.Millisecond + // Give the first request enough time to persist its independent Bolt + // journal under a loaded test host. The short timeout is the behavior under + // test only after that first worker demonstrably owns admission. + api.handler.AdmissionTimeout = time.Second executor := &blockingMutationExecutor{ started: make(chan worker.Request, 1), release: make(chan struct{}), } @@ -487,21 +666,29 @@ func TestIsolatedMutationAdmissionIsShortAndDoesNotStartSecondWorker(t *testing. return body } firstID := "operation-admission-first" - first := api.request(t, http.MethodPost, "/v1/storage/configuration", requestBody(firstID), auth.Actor{ + firstBody := requestBody(firstID) + first := api.request(t, http.MethodPost, "/v1/storage/configuration", firstBody, auth.Actor{ UserID: 1, IsAdmin: true, IsSuperAdmin: true, CanManage: true, OperationID: firstID, }) if first.Code != http.StatusAccepted { t.Fatalf("first response = %d %s", first.Code, first.Body.String()) } + firstWire := requireOperationResponseIdentity(t, first, firstID, "configure-storage", "host-storage", + operation.Fingerprint(http.MethodPost, "/v1/storage/configuration", firstBody)) + if firstWire.Status != operation.StateDispatching || firstWire.Replayed { + t.Fatalf("first accepted operation response = %#v", firstWire) + } select { case <-executor.started: case <-time.After(time.Second): t.Fatal("first worker did not start") } + api.handler.AdmissionTimeout = 30 * time.Millisecond secondID := "operation-admission-second" + secondBody := requestBody(secondID) startedAt := time.Now() - second := api.request(t, http.MethodPost, "/v1/storage/configuration", requestBody(secondID), auth.Actor{ + second := api.request(t, http.MethodPost, "/v1/storage/configuration", secondBody, auth.Actor{ UserID: 1, IsAdmin: true, IsSuperAdmin: true, CanManage: true, OperationID: secondID, }) if elapsed := time.Since(startedAt); elapsed > 500*time.Millisecond { @@ -512,6 +699,11 @@ func TestIsolatedMutationAdmissionIsShortAndDoesNotStartSecondWorker(t *testing. !bytes.Contains(second.Body.Bytes(), []byte(`"code":"operation_not_dispatched"`)) { t.Fatalf("saturated admission response = %d %s", second.Code, second.Body.String()) } + failedWire := requireOperationResponseIdentity(t, second, secondID, "configure-storage", "host-storage", + operation.Fingerprint(http.MethodPost, "/v1/storage/configuration", secondBody)) + if failedWire.Status != operation.StateFailed || failedWire.Replayed { + t.Fatalf("failed operation response = %#v", failedWire) + } if executor.calls.Load() != 1 { t.Fatalf("saturated request started a second worker; calls=%d", executor.calls.Load()) } @@ -578,6 +770,11 @@ func TestTrustedWorkerExecutesLocallyWithoutRecursiveSpawn(t *testing.T) { if response.Code != http.StatusOK { t.Fatalf("trusted worker response = %d %s", response.Code, response.Body.String()) } + succeeded := requireOperationResponseIdentity(t, response, request.OperationID, "configure-storage", "host-storage", + operation.Fingerprint(http.MethodPost, "/v1/storage/configuration", body)) + if succeeded.Status != operation.StateSucceeded || succeeded.Replayed { + t.Fatalf("successful operation response = %#v", succeeded) + } api.hv.mu.Lock() configureCalls := api.hv.configureCalls api.hv.mu.Unlock() diff --git a/agent/cmd/virt-agent/main.go b/agent/cmd/virt-agent/main.go index 9c914636..59acc378 100644 --- a/agent/cmd/virt-agent/main.go +++ b/agent/cmd/virt-agent/main.go @@ -86,21 +86,8 @@ func main() { if _, err := journal.FinalizeInterruptedOperations(interrupted); err != nil { log.Fatalf("finalize interrupted isolated mutations: %v", err) } - pendingCompletions, err := journal.PendingCompletionOperationIDs() - if err != nil { - log.Fatalf("read pending completion deliveries: %v", err) - } - pendingOperationIDs, err := executor.PendingOperationIDs() - if err != nil { - log.Fatalf("list isolated mutation state: %v", err) - } - for _, operationID := range pendingOperationIDs { - if _, retain := pendingCompletions[operationID]; retain { - continue - } - if err := executor.Cleanup(operationID); err != nil { - log.Fatalf("clean isolated mutation state %s: %v", operationID, err) - } + if err := cleanupRecoveredWorkerState(executor); err != nil { + log.Fatalf("clean imported isolated mutation state: %v", err) } authenticator, err := auth.NewWithNonceStore([]byte(cfg.AgentSecret), cfg.ClockSkew(), cfg.NonceTTL(), journal) if err != nil { @@ -192,24 +179,47 @@ type workerStateCleaner interface { Cleanup(string) error } -// workerCompletionOutbox couples receipt delivery lifecycle to disposable -// helper state. The main Journal remains the permanent tombstone; a helper's -// journal and receipt survive restarts until the panel ACKs the immutable -// completion, or until the bounded delivery window expires. +type recoveredWorkerState interface { + workerStateCleaner + PendingOperationIDs() ([]string, error) +} + +// cleanupRecoveredWorkerState removes only disposable helper directories. +// FinalizeInterruptedOperations must run first: it imports every helper +// receipt, or terminalizes a missing receipt, in the main Journal. Main +// completion receipts and their ACK-driven outbox are never deleted here. +func cleanupRecoveredWorkerState(state recoveredWorkerState) error { + operationIDs, err := state.PendingOperationIDs() + if err != nil { + return fmt.Errorf("list isolated mutation state: %w", err) + } + for _, operationID := range operationIDs { + if err := state.Cleanup(operationID); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("clean isolated mutation state %s: %w", operationID, err) + } + } + return nil +} + +// workerCompletionOutbox keeps completion delivery in the main Journal until +// the panel ACKs it. Disposable helper state is cleaned independently after +// the durable receipt is claimed, after its ACK, or during the next startup. type workerCompletionOutbox struct { journal *operation.Journal cleaner workerStateCleaner } func (o *workerCompletionOutbox) ClaimPendingCompletions(limit int, excluded []string) ([]operation.CompletionReceipt, error) { - claimed, expired, err := o.journal.ClaimPendingCompletionsWithExpiredExcluding(limit, excluded) + claimed, _, err := o.journal.ClaimPendingCompletionsWithExpiredExcluding(limit, excluded) if err != nil { return nil, err } - for _, operationID := range expired { - log.Printf("completion outbox exhausted operation_id=%s", operationID) - if err := o.cleaner.Cleanup(operationID); err != nil && !errors.Is(err, os.ErrNotExist) { - return nil, fmt.Errorf("clean expired worker state %s: %w", operationID, err) + for _, receipt := range claimed { + if cleanupErr := o.cleaner.Cleanup(receipt.OperationID); cleanupErr != nil && !errors.Is(cleanupErr, os.ErrNotExist) { + // The main Journal receipt is already durable. Disposable helper + // cleanup must neither suppress its delivery nor remove it from the + // ACK-driven outbox; startup will retry any failed cleanup. + log.Printf("clean delivered worker state operation_id=%s: %v", receipt.OperationID, cleanupErr) } } return claimed, nil @@ -221,8 +231,10 @@ func (o *workerCompletionOutbox) AcknowledgeCompletion(eventID string) error { return err } if operationID != "" { - if err := o.cleaner.Cleanup(operationID); err != nil && !errors.Is(err, os.ErrNotExist) { - return fmt.Errorf("clean acknowledged worker state %s: %w", operationID, err) + if cleanupErr := o.cleaner.Cleanup(operationID); cleanupErr != nil && !errors.Is(cleanupErr, os.ErrNotExist) { + // An ACK is authoritative delivery state. A disposable helper + // cleanup failure must not keep the receipt in the delivery loop. + log.Printf("clean acknowledged worker state operation_id=%s: %v", operationID, cleanupErr) } } return o.journal.AcknowledgeCompletion(eventID) diff --git a/agent/cmd/virt-agent/main_test.go b/agent/cmd/virt-agent/main_test.go index 00708633..8a2e1f85 100644 --- a/agent/cmd/virt-agent/main_test.go +++ b/agent/cmd/virt-agent/main_test.go @@ -1,11 +1,9 @@ package main import ( - "bytes" "context" "encoding/json" "errors" - "log" "path/filepath" "strings" "sync" @@ -21,6 +19,16 @@ type fakeWorkerStateCleaner struct { failOnce bool } +type fakeRecoveredWorkerState struct { + fakeWorkerStateCleaner + operationIDs []string + listErr error +} + +func (s *fakeRecoveredWorkerState) PendingOperationIDs() ([]string, error) { + return append([]string(nil), s.operationIDs...), s.listErr +} + func (c *fakeWorkerStateCleaner) Cleanup(operationID string) error { c.mu.Lock() defer c.mu.Unlock() @@ -53,7 +61,7 @@ func terminalOperation(t *testing.T, journal *operation.Journal, operationID str return claimed[0] } -func TestCompletionAckCleansWorkerStateAndKeepsJournalTombstone(t *testing.T) { +func TestCompletionAckDoesNotDependOnDisposableWorkerCleanup(t *testing.T) { journal, err := operation.Open(filepath.Join(t.TempDir(), "operations.db")) if err != nil { t.Fatal(err) @@ -63,14 +71,6 @@ func TestCompletionAckCleansWorkerStateAndKeepsJournalTombstone(t *testing.T) { cleaner := &fakeWorkerStateCleaner{failOnce: true} outbox := &workerCompletionOutbox{journal: journal, cleaner: cleaner} - if err := outbox.AcknowledgeCompletion(receipt.EventID); err == nil { - t.Fatal("cleanup failure consumed completion ACK") - } - if pending, err := journal.PendingCompletionOperationIDs(); err != nil { - t.Fatal(err) - } else if _, exists := pending[receipt.OperationID]; !exists { - t.Fatal("cleanup failure removed pending completion") - } if err := outbox.AcknowledgeCompletion(receipt.EventID); err != nil { t.Fatal(err) } @@ -84,12 +84,43 @@ func TestCompletionAckCleansWorkerStateAndKeepsJournalTombstone(t *testing.T) { cleaner.mu.Lock() calls := append([]string(nil), cleaner.calls...) cleaner.mu.Unlock() - if len(calls) != 2 || calls[0] != receipt.OperationID || calls[1] != receipt.OperationID { + if len(calls) != 1 || calls[0] != receipt.OperationID { t.Fatalf("cleanup calls = %#v", calls) } + if err := outbox.AcknowledgeCompletion(receipt.EventID); err != nil { + t.Fatalf("duplicate ACK was not idempotent: %v", err) + } +} + +func TestRecoveredWorkerCleanupDoesNotDeleteMainCompletion(t *testing.T) { + journal, err := operation.Open(filepath.Join(t.TempDir(), "operations.db")) + if err != nil { + t.Fatal(err) + } + defer journal.Close() + receipt := terminalOperation(t, journal, "operation-recovered-helper-cleanup") + state := &fakeRecoveredWorkerState{operationIDs: []string{receipt.OperationID}} + if err := cleanupRecoveredWorkerState(state); err != nil { + t.Fatal(err) + } + state.mu.Lock() + calls := append([]string(nil), state.calls...) + state.mu.Unlock() + if len(calls) != 1 || calls[0] != receipt.OperationID { + t.Fatalf("recovered worker cleanup calls = %#v", calls) + } + if pending, err := journal.PendingCompletionOperationIDs(); err != nil { + t.Fatal(err) + } else if _, exists := pending[receipt.OperationID]; !exists { + t.Fatal("disposable helper cleanup deleted the main completion outbox") + } + record, err := journal.Get(receipt.OperationID) + if err != nil || record.State != operation.StateSucceeded { + t.Fatalf("helper cleanup changed operation tombstone: %#v err=%v", record, err) + } } -func TestExpiredCompletionCleansWorkerStateWithoutChangingTerminalResult(t *testing.T) { +func TestCompletionRemainsDeliverableUntilAcknowledged(t *testing.T) { journal, err := operation.Open(filepath.Join(t.TempDir(), "operations.db")) if err != nil { t.Fatal(err) @@ -97,30 +128,41 @@ func TestExpiredCompletionCleansWorkerStateWithoutChangingTerminalResult(t *test defer journal.Close() now := time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC) journal.SetClockForTesting(func() time.Time { return now }) - receipt := terminalOperation(t, journal, "operation-expired-cleanup") + receipt := terminalOperation(t, journal, "operation-durable-delivery") now = now.Add(25 * time.Hour) - cleaner := &fakeWorkerStateCleaner{} + cleaner := &fakeWorkerStateCleaner{failOnce: true} outbox := &workerCompletionOutbox{journal: journal, cleaner: cleaner} - var logs bytes.Buffer - previousLogWriter := log.Writer() - log.SetOutput(&logs) - defer log.SetOutput(previousLogWriter) claimed, err := outbox.ClaimPendingCompletions(1, nil) - if err != nil || len(claimed) != 0 { - t.Fatalf("expired claim = %#v err=%v", claimed, err) + if err != nil || len(claimed) != 1 || claimed[0].EventID != receipt.EventID { + t.Fatalf("25-hour claim = %#v err=%v", claimed, err) } - record, err := journal.Get(receipt.OperationID) - if err != nil || record.State != operation.StateSucceeded || string(record.Result) != `{"deleted":true}` { - t.Fatalf("expiry changed terminal operation: %#v err=%v", record, err) + now = now.Add(365 * 24 * time.Hour) + claimed, err = outbox.ClaimPendingCompletions(1, nil) + if err != nil || len(claimed) != 1 || claimed[0].EventID != receipt.EventID { + t.Fatalf("long-lived claim = %#v err=%v", claimed, err) } cleaner.mu.Lock() calls := append([]string(nil), cleaner.calls...) cleaner.mu.Unlock() - if len(calls) != 1 || calls[0] != receipt.OperationID { - t.Fatalf("expired cleanup calls = %#v", calls) + if len(calls) != 2 || calls[0] != receipt.OperationID || calls[1] != receipt.OperationID { + t.Fatalf("delivery cleanup calls = %#v", calls) } - if !strings.Contains(logs.String(), "completion outbox exhausted operation_id="+receipt.OperationID) { - t.Fatalf("missing bounded completion expiry log: %q", logs.String()) + if pending, err := journal.PendingCompletionOperationIDs(); err != nil { + t.Fatal(err) + } else if _, exists := pending[receipt.OperationID]; !exists { + t.Fatal("disposable delivery cleanup deleted the main completion outbox") + } + if err := outbox.AcknowledgeCompletion(receipt.EventID); err != nil { + t.Fatal(err) + } + cleaner.mu.Lock() + calls = append([]string(nil), cleaner.calls...) + cleaner.mu.Unlock() + if len(calls) != 3 || calls[2] != receipt.OperationID { + t.Fatalf("ACK cleanup calls = %#v", calls) + } + if pending, err := journal.PendingCompletionOperationIDs(); err != nil || len(pending) != 0 { + t.Fatalf("ACK left completion pending: %#v err=%v", pending, err) } } diff --git a/agent/control/client.go b/agent/control/client.go index e994b0b7..fb7bf255 100644 --- a/agent/control/client.go +++ b/agent/control/client.go @@ -30,7 +30,7 @@ import ( ) const ( - ControlSubprotocol = "virt-agent-control.v2" + ControlSubprotocol = "virt-agent-control.v3" ConsoleProtocol = "virt-agent-console." controlPath = "/agent/connect" consolePath = "/agent/console" @@ -84,6 +84,9 @@ type completionMessage struct { Type string `json:"type"` ID string `json:"id"` OperationID string `json:"operation_id"` + Action string `json:"action"` + ResourceID string `json:"resource_id"` + RequestFingerprint string `json:"request_fingerprint"` Status string `json:"status"` EffectMayHaveApplied bool `json:"effect_may_have_applied"` SafeToResubmit bool `json:"safe_to_resubmit"` @@ -91,6 +94,22 @@ type completionMessage struct { Result json.RawMessage `json:"result"` } +func completionMessageFromReceipt(completion operation.CompletionReceipt) (completionMessage, error) { + if !transportIDPattern.MatchString(completion.EventID) || + !transportIDPattern.MatchString(completion.OperationID) || + !operation.ValidOperationIdentity(completion.Action, completion.ResourceID, completion.RequestFingerprint) { + return completionMessage{}, errors.New("completion receipt identity is invalid") + } + return completionMessage{ + Type: "completion", ID: completion.EventID, OperationID: completion.OperationID, + Action: completion.Action, ResourceID: completion.ResourceID, + RequestFingerprint: completion.RequestFingerprint, + Status: completion.Status, Result: completion.Result, + ErrorCode: completion.ErrorCode, EffectMayHaveApplied: completion.EffectMayHaveApplied, + SafeToResubmit: completion.SafeToResubmit, + }, nil +} + type CompletionOutbox interface { ClaimPendingCompletions(int, []string) ([]operation.CompletionReceipt, error) AcknowledgeCompletion(string) error @@ -372,13 +391,12 @@ func (c *Client) pumpCompletions(ctx context.Context, writer *connectionWriter, } if len(completions) == 1 { completion := completions[0] - window.track(completion.EventID, completion.OperationID) - message := completionMessage{ - Type: "completion", ID: completion.EventID, OperationID: completion.OperationID, - Status: completion.Status, Result: completion.Result, - ErrorCode: completion.ErrorCode, EffectMayHaveApplied: completion.EffectMayHaveApplied, - SafeToResubmit: completion.SafeToResubmit, + message, err := completionMessageFromReceipt(completion) + if err != nil { + window.abandonReservation() + return err } + window.track(completion.EventID, completion.OperationID) if err := writer.write(ctx, message); err != nil { window.release(completion.EventID) logCompletionDelivery(completionPhaseAgentSendFailed, completion.OperationID, completion.EventID) diff --git a/agent/control/client_test.go b/agent/control/client_test.go index f603442d..481eeac2 100644 --- a/agent/control/client_test.go +++ b/agent/control/client_test.go @@ -20,6 +20,7 @@ import ( "git.luoli.live/root/virt/agent/auth" consolebroker "git.luoli.live/root/virt/agent/console" + "git.luoli.live/root/virt/agent/operation" ) const controlTestSecret = "0123456789abcdef0123456789abcdef" @@ -49,16 +50,58 @@ func TestCompletionDeliveryWindowReleasesOnlyOnDisposition(t *testing.T) { } } -func TestControlSubprotocolUsesCleanBreakV2(t *testing.T) { - if ControlSubprotocol != "virt-agent-control.v2" { - t.Fatalf("control subprotocol = %q, want clean-break v2", ControlSubprotocol) +func TestCompletionMessageCarriesStrictImmutableOperationIdentity(t *testing.T) { + receipt := operation.CompletionReceipt{ + EventID: "completion_identity_123", OperationID: "operation_identity_123", + Action: "delete-vm", ResourceID: "vm-completion-identity", + RequestFingerprint: strings.Repeat("a", 64), + Status: "succeeded", Result: json.RawMessage(`{"done":true}`), + } + message, err := completionMessageFromReceipt(receipt) + if err != nil { + t.Fatal(err) + } + if message.Action != receipt.Action || message.ResourceID != receipt.ResourceID || + message.RequestFingerprint != receipt.RequestFingerprint { + t.Fatalf("completion message identity = %#v", message) + } + + tests := []struct { + name string + mutate func(*operation.CompletionReceipt) + }{ + {name: "missing action", mutate: func(value *operation.CompletionReceipt) { value.Action = "" }}, + {name: "uppercase action", mutate: func(value *operation.CompletionReceipt) { value.Action = "Delete-VM" }}, + {name: "resource path", mutate: func(value *operation.CompletionReceipt) { value.ResourceID = "vm/unsafe" }}, + {name: "missing resource", mutate: func(value *operation.CompletionReceipt) { value.ResourceID = "" }}, + {name: "uppercase fingerprint", mutate: func(value *operation.CompletionReceipt) { value.RequestFingerprint = strings.Repeat("A", 64) }}, + {name: "short fingerprint", mutate: func(value *operation.CompletionReceipt) { value.RequestFingerprint = strings.Repeat("a", 63) }}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + candidate := receipt + test.mutate(&candidate) + if _, err := completionMessageFromReceipt(candidate); err == nil { + t.Fatal("invalid immutable operation identity was accepted") + } + }) } } -func TestControlSessionRejectsLegacyV1Gateway(t *testing.T) { +func TestControlSubprotocolUsesCleanBreakV3(t *testing.T) { + if ControlSubprotocol != "virt-agent-control.v3" { + t.Fatalf("control subprotocol = %q, want clean-break v3", ControlSubprotocol) + } +} + +func TestControlSessionRejectsLegacyV2GatewayDuringHandshake(t *testing.T) { server := newTLSServer(t, http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if request.Header.Get("Sec-WebSocket-Protocol") != "virt-agent-control.v2" { + http.Error(writer, "legacy v2 control subprotocol required", http.StatusBadRequest) + return + } connection, err := websocket.Accept(writer, request, &websocket.AcceptOptions{ - Subprotocols: []string{"virt-agent-control.v1"}, CompressionMode: websocket.CompressionDisabled, + Subprotocols: []string{"virt-agent-control.v2"}, CompressionMode: websocket.CompressionDisabled, }) if err != nil { return @@ -80,8 +123,8 @@ func TestControlSessionRejectsLegacyV1Gateway(t *testing.T) { } client.httpClient = server.Client() err = client.runSession(context.Background()) - if err == nil || !strings.Contains(err.Error(), "invalid control subprotocol") { - t.Fatalf("legacy v1 gateway handshake error = %v", err) + if err == nil || !strings.Contains(err.Error(), "dial panel control channel") { + t.Fatalf("legacy v2 gateway handshake error = %v", err) } } diff --git a/agent/hypervisor/libvirt_catalog_features.go b/agent/hypervisor/libvirt_catalog_features.go index 60f7c6ff..e698bc68 100644 --- a/agent/hypervisor/libvirt_catalog_features.go +++ b/agent/hypervisor/libvirt_catalog_features.go @@ -947,6 +947,16 @@ func (l *Libvirt) reconcileCatalogOperation(ctx context.Context, record operatio } var current target switch record.Action { + case "update-template": + id, ok := strings.CutPrefix(record.ResourceID, "template:") + if !ok || !templateIDPattern.MatchString(id) { + return operation.Resolution{}, true, NewError(ErrInvalid, "invalid_operation_resource", "template operation resource is invalid", nil) + } + // The Journal intentionally does not retain the raw update request. + // A current name or revision therefore cannot prove that this exact + // operation applied; only its immutable terminal result is bound to the + // operation fingerprint. Keep an uncertain failure inconclusive. + return operation.Resolution{}, true, nil case "import-template", "delete-template": id, ok := strings.CutPrefix(record.ResourceID, "template:") if !ok || !templateIDPattern.MatchString(id) { diff --git a/agent/hypervisor/libvirt_operation_admin.go b/agent/hypervisor/libvirt_operation_admin.go index abc2692b..1515b8fa 100644 --- a/agent/hypervisor/libvirt_operation_admin.go +++ b/agent/hypervisor/libvirt_operation_admin.go @@ -62,7 +62,19 @@ func (l *Libvirt) InspectOperation(ctx context.Context, record operation.Record) return OperationInspection{}, err } if storedOperationInspectionAvailable(record) { - return inspectionFromRecord(record), nil + if record.InspectionEvidenceUnavailable { + return inconclusiveInspectionFromRecord(record), nil + } + inspection := inspectionFromRecord(record) + // A recovered successful receipt is useful for convergence only when its + // action-specific result can be reduced to the bounded public projection. + // Receipt status alone must not turn an unprojectable or damaged result + // into an "applied" verdict after Journal detail retention. + if record.InspectionReceiptRecovered && record.State == operation.StateSucceeded && + len(inspection.EffectProjection) == 0 { + return inconclusiveInspectionFromRecord(record), nil + } + return inspection, nil } if resolution, handled, err := l.reconcileStorageConfiguration(record); handled { @@ -896,7 +908,8 @@ func backupPushMatchesTarget(backupXML, targetPath string) bool { func buildOperationInspection(record operation.Record, resolution operation.Resolution, abort OperationAbortInspection, cleanup operationCleanupInspection) OperationInspection { result := OperationInspection{ - OperationID: record.OperationID, OperationStatus: record.State, + OperationID: record.OperationID, Action: record.Action, ResourceID: record.ResourceID, + RequestFingerprint: record.Fingerprint, OperationStatus: record.State, CheckedAt: time.Now().UTC().Unix(), Outcome: InspectionOutcomeUncertain, SummaryCode: InspectionSummaryIncomplete, EffectResolution: InspectionEffectInconclusive, @@ -1007,8 +1020,13 @@ func inspectionFromRecord(record operation.Record) OperationInspection { } return buildOperationInspection(record, resolution, OperationAbortInspection{}, operationCleanupInspection{}) } + return inconclusiveInspectionFromRecord(record) +} + +func inconclusiveInspectionFromRecord(record operation.Record) OperationInspection { return OperationInspection{ - OperationID: record.OperationID, OperationStatus: record.State, + OperationID: record.OperationID, Action: record.Action, ResourceID: record.ResourceID, + RequestFingerprint: record.Fingerprint, OperationStatus: record.State, CheckedAt: time.Now().UTC().Unix(), Outcome: InspectionOutcomeUncertain, SummaryCode: InspectionSummaryIncomplete, EffectResolution: InspectionEffectInconclusive, } @@ -1142,20 +1160,20 @@ func operationEffectProjection(record operation.Record, raw []byte) json.RawMess TemplateID string `json:"template_id,omitempty"` NetworkSuspended bool `json:"network_suspended"` }{value.Active, value.Staged, value.PendingManualRestart, value.TemplateID, value.NetworkSuspended} - case record.Action == "import-template": + case record.Action == "import-template" || record.Action == "update-template": var value ImageTemplate - if !decodeOperationEffectResult(raw, &value) { + if !decodeOperationEffectResult(raw, &value) || record.ResourceID != "template:"+value.ID { return nil } projection = operationCatalogImportProjection{ ID: value.ID, Name: value.Name, OSFamily: value.OSFamily, Version: value.Version, Architecture: value.Architecture, SizeBytes: value.SizeBytes, VirtualSizeBytes: value.VirtualSizeBytes, SHA256: value.SHA256, - Revision: value.Revision, CreatedAt: value.CreatedAt, + Revision: value.Revision, GenerationToken: value.GenerationToken, CreatedAt: value.CreatedAt, } case record.Action == "import-rescue-template": var value RescueTemplate - if !decodeOperationEffectResult(raw, &value) { + if !decodeOperationEffectResult(raw, &value) || record.ResourceID != "rescue-template:"+value.ID { return nil } projection = operationCatalogImportProjection{ @@ -1164,7 +1182,8 @@ func operationEffectProjection(record operation.Record, raw []byte) json.RawMess } case record.Action == "import-user-iso": var value UserISO - if !decodeOperationEffectResult(raw, &value) { + if !decodeOperationEffectResult(raw, &value) || + record.ResourceID != "user-iso:"+strconv.FormatInt(value.OwnerID, 10)+":"+value.ID { return nil } projection = operationCatalogImportProjection{ @@ -1235,6 +1254,7 @@ type operationCatalogImportProjection struct { VirtualSizeBytes uint64 `json:"virtual_size_bytes,omitempty"` SHA256 string `json:"sha256,omitempty"` Revision uint64 `json:"revision,omitempty"` + GenerationToken string `json:"generation_token,omitempty"` CreatedAt time.Time `json:"created_at"` } diff --git a/agent/hypervisor/libvirt_operation_admin_test.go b/agent/hypervisor/libvirt_operation_admin_test.go index 68640496..a468e659 100644 --- a/agent/hypervisor/libvirt_operation_admin_test.go +++ b/agent/hypervisor/libvirt_operation_admin_test.go @@ -3,11 +3,14 @@ package hypervisor import ( + "context" "encoding/json" "errors" + "path/filepath" "reflect" "strings" "testing" + "time" "git.luoli.live/root/virt/agent/operation" "libvirt.org/go/libvirt" @@ -99,7 +102,11 @@ func TestCleanupJobEvidenceRequiresIdleDomainAndBlockJobs(t *testing.T) { func TestCleanupPlanIdentifierBindsPrivateExactEvidence(t *testing.T) { record := operation.Record{ OperationID: "operation-exact-cleanup-plan", ResourceID: "123e4567-e89b-42d3-a456-426614174000", - Action: "delete-vm", Fingerprint: "request-fingerprint", State: operation.StateFailed, + Action: "delete-vm", + Fingerprint: operation.Fingerprint( + "DELETE", "/v1/vms/123e4567-e89b-42d3-a456-426614174000", []byte(`{}`), + ), + State: operation.StateFailed, EffectMayHaveApplied: true, } first := buildOperationInspection(record, operation.Resolution{}, OperationAbortInspection{}, @@ -113,7 +120,8 @@ func TestCleanupPlanIdentifierBindsPrivateExactEvidence(t *testing.T) { if err != nil { t.Fatal(err) } - if string(encoded) == "" || containsAny(string(encoded), "managed-volume:first", "request-fingerprint") { + if string(encoded) == "" || containsAny(string(encoded), "managed-volume:first") || + !strings.Contains(string(encoded), record.Fingerprint) { t.Fatalf("private cleanup evidence leaked: %s", encoded) } } @@ -149,6 +157,7 @@ func TestOperationInspectionPublishesBoundedEffectEvidence(t *testing.T) { OperationID: "operation-settings-effect-evidence", ResourceID: "123e4567-e89b-42d3-a456-426614174000", Action: "update-settings", + Fingerprint: operation.Fingerprint("POST", "/v1/vms/123e4567-e89b-42d3-a456-426614174000/settings", []byte(`{}`)), State: operation.StateFailed, EffectMayHaveApplied: true, } @@ -172,6 +181,10 @@ func TestOperationInspectionPublishesBoundedEffectEvidence(t *testing.T) { }`), } inspection := buildOperationInspection(record, resolution, OperationAbortInspection{}, operationCleanupInspection{}) + if inspection.Action != record.Action || inspection.ResourceID != record.ResourceID || + inspection.RequestFingerprint != record.Fingerprint { + t.Fatalf("inspection omitted immutable operation identity: %#v", inspection) + } if inspection.EffectResolution != InspectionEffectApplied { t.Fatalf("effect resolution = %q, want %q", inspection.EffectResolution, InspectionEffectApplied) } @@ -226,6 +239,155 @@ func TestOperationInspectionPublishesBoundedEffectEvidence(t *testing.T) { } } +func TestReceiptBackedTombstoneInspectionRequiresProjectableEvidence(t *testing.T) { + journal, err := operation.Open(filepath.Join(t.TempDir(), "operations.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = journal.Close() }) + now := time.Date(2026, 10, 20, 12, 0, 0, 0, time.UTC) + journal.SetClockForTesting(func() time.Time { return now }) + resourceID := "123e4567-e89b-42d3-a456-426614174000" + spec := operation.Spec{ + OperationID: "operation-pruned-settings-receipt", + ResourceID: resourceID, + Action: "update-settings", + Fingerprint: operation.Fingerprint("POST", "/v1/vms/"+resourceID+"/settings", []byte(`{}`)), + Destructive: true, + } + result := json.RawMessage(`{ + "uuid":"123e4567-e89b-42d3-a456-426614174000", + "name":"vm-safe", + "status":"running", + "hostname":"safe.example", + "settings_changed":true, + "internal_note":"must-not-leak" + }`) + if _, _, err := journal.Execute(context.Background(), spec, func(context.Context) (json.RawMessage, error) { + return result, nil + }); err != nil { + t.Fatal(err) + } + claimed, err := journal.ClaimPendingCompletions(1) + if err != nil || len(claimed) != 1 { + t.Fatalf("completion claim = %#v err=%v", claimed, err) + } + if err := journal.AcknowledgeCompletion(claimed[0].EventID); err != nil { + t.Fatal(err) + } + now = now.Add(91 * 24 * time.Hour) + if accepted, err := journal.UseNonce("nonce-project-pruned-receipt", now, now.Add(time.Minute)); err != nil || !accepted { + t.Fatalf("trigger detail pruning accepted=%v err=%v", accepted, err) + } + record, err := journal.GetForInspection(spec.OperationID) + if err != nil || !record.Tombstone || !record.InspectionReceiptRecovered || + record.InspectionEvidenceUnavailable { + t.Fatalf("receipt-backed record = %#v err=%v", record, err) + } + inspection, err := (&Libvirt{}).InspectOperation(context.Background(), record) + if err != nil || inspection.Outcome != InspectionOutcomeSucceeded || + inspection.EffectResolution != InspectionEffectApplied || len(inspection.EffectProjection) == 0 { + t.Fatalf("receipt-backed tombstone inspection = %#v err=%v", inspection, err) + } + encoded, err := json.Marshal(inspection) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(encoded), "must-not-leak") || strings.Contains(string(encoded), "internal_note") || + !strings.Contains(string(inspection.EffectProjection), `"settings_changed":true`) { + t.Fatalf("unsafe or incomplete receipt projection: %s", encoded) + } + + t.Run("tampered receipt marker", func(t *testing.T) { + tampered := record + tampered.Result = nil + tampered.InspectionReceiptRecovered = false + tampered.InspectionEvidenceUnavailable = true + inspection, err := (&Libvirt{}).InspectOperation(context.Background(), tampered) + if err != nil || inspection.Outcome != InspectionOutcomeUncertain || + inspection.SummaryCode != InspectionSummaryIncomplete || + inspection.EffectResolution != InspectionEffectInconclusive || len(inspection.EffectProjection) != 0 { + t.Fatalf("tampered receipt inspection = %#v err=%v", inspection, err) + } + }) + + t.Run("unprojectable recovered result", func(t *testing.T) { + unprojectable := record + unprojectable.Result = json.RawMessage(`{"uuid":"123e4567-e89b-42d3-a456-426614174999","settings_changed":true}`) + inspection, err := (&Libvirt{}).InspectOperation(context.Background(), unprojectable) + if err != nil || inspection.Outcome != InspectionOutcomeUncertain || + inspection.SummaryCode != InspectionSummaryIncomplete || + inspection.EffectResolution != InspectionEffectInconclusive || len(inspection.EffectProjection) != 0 { + t.Fatalf("unprojectable receipt inspection = %#v err=%v", inspection, err) + } + }) +} + +func TestTemplateOperationProjectionPreservesFinalizerIdentity(t *testing.T) { + raw := []byte(`{ + "id":"template-safe", + "name":"Debian 13", + "os_family":"linux", + "version":"13", + "architecture":"amd64", + "size_bytes":1048576, + "virtual_size_bytes":2147483648, + "sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "revision":7, + "generation_token":"0123456789abcdef0123456789abcdef", + "created_at":"2026-10-20T01:00:00Z", + "source_token":"must-not-leak" + }`) + for _, action := range []string{"import-template", "update-template"} { + t.Run(action, func(t *testing.T) { + inspection := inspectionFromRecord(operation.Record{ + OperationID: "operation-template-projection-" + strings.ReplaceAll(action, "-", ""), + ResourceID: "template:template-safe", + Action: action, + State: operation.StateSucceeded, + Result: raw, + }) + var projection struct { + ID string `json:"id"` + Name string `json:"name"` + Revision uint64 `json:"revision"` + GenerationToken string `json:"generation_token"` + } + if err := json.Unmarshal(inspection.EffectProjection, &projection); err != nil { + t.Fatalf("decode template projection: %v (%s)", err, inspection.EffectProjection) + } + if projection.ID != "template-safe" || projection.Name != "Debian 13" || projection.Revision != 7 || + projection.GenerationToken != "0123456789abcdef0123456789abcdef" { + t.Fatalf("template projection omitted finalizer identity: %#v", projection) + } + if strings.Contains(string(inspection.EffectProjection), "must-not-leak") || + strings.Contains(string(inspection.EffectProjection), "source_token") { + t.Fatalf("template projection leaked source credential: %s", inspection.EffectProjection) + } + }) + } + + mismatched := operationEffectProjection(operation.Record{ + ResourceID: "template:different", Action: "import-template", + }, raw) + if len(mismatched) != 0 { + t.Fatalf("template identity mismatch produced projection: %s", mismatched) + } +} + +func TestUncertainTemplateUpdateDoesNotUseCurrentCatalogStateAsOperationEvidence(t *testing.T) { + resolution, handled, err := (&Libvirt{}).reconcileCatalogOperation(context.Background(), operation.Record{ + OperationID: "operation-template-update-inspect", + ResourceID: "template:template-safe", + Action: "update-template", + State: operation.StateFailed, + EffectMayHaveApplied: true, + }) + if err != nil || !handled || resolution.Resolved { + t.Fatalf("template update inspection = %#v handled=%v err=%v", resolution, handled, err) + } +} + func TestOperationInspectionDoesNotPromoteTargetStateToExactEffect(t *testing.T) { for name, record := range map[string]operation.Record{ "power target state": { diff --git a/agent/hypervisor/types.go b/agent/hypervisor/types.go index 20be5d60..bb33f836 100644 --- a/agent/hypervisor/types.go +++ b/agent/hypervisor/types.go @@ -569,13 +569,18 @@ const ( // contains a raw Journal result, libvirt handles, XML, host paths, raw errors, // credentials, keys, NoCloud seed contents, or user-data. type OperationInspection struct { - OperationID string `json:"operation_id"` - OperationStatus operation.State `json:"operation_status"` - CheckedAt int64 `json:"checked_at"` - Outcome string `json:"outcome"` - SummaryCode string `json:"summary_code"` - ErrorCode string `json:"error_code,omitempty"` - EffectResolution string `json:"effect_resolution"` + OperationID string `json:"operation_id"` + Action string `json:"action"` + ResourceID string `json:"resource_id"` + RequestFingerprint string `json:"request_fingerprint"` + OperationStatus operation.State `json:"operation_status"` + CheckedAt int64 `json:"checked_at"` + Outcome string `json:"outcome"` + SummaryCode string `json:"summary_code"` + ErrorCode string `json:"error_code,omitempty"` + CompletionDeliveryState string `json:"completion_delivery_state,omitempty"` + CompletionDeliveryErrorCode string `json:"completion_delivery_error_code,omitempty"` + EffectResolution string `json:"effect_resolution"` // FenceState and FenceResolutionRequired are derived from the immutable // Journal record, not the live target state. State preserves whether a // fence is absent, active, or already resolved; callers must never treat an diff --git a/agent/operation/journal.go b/agent/operation/journal.go index eabef9f5..eb1ca91f 100644 --- a/agent/operation/journal.go +++ b/agent/operation/journal.go @@ -10,6 +10,7 @@ import ( "encoding/json" "errors" "fmt" + "log" "os" "path/filepath" "regexp" @@ -41,40 +42,49 @@ const ( ) var ( - ErrNotFound = errors.New("operation not found") - ErrFingerprint = errors.New("operation_id payload conflict") - ErrOperationStarting = errors.New("operation dispatch is already starting") - ErrBusy = errors.New("operation execution capacity is exhausted") - ErrResourceBlocked = errors.New("resource has an unresolved operation") - ErrInvalidSupersession = errors.New("operation cannot supersede the requested predecessor") - ErrInspectionInconclusive = errors.New("read-only inspection did not confirm a terminal outcome") - ErrExecutionNotReaped = errors.New("isolated mutation process did not exit after forced termination") - ErrFenceNotResolvable = errors.New("operation does not hold an effect fence") - ErrFenceResolutionConflict = errors.New("operation effect fence already has a different resolution") - ErrFenceInspectionStale = errors.New("operation effect fence resolution requires a fresh inspection") - operationIDPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{8,80}$`) - hexDigestPattern = regexp.MustCompile(`^[0-9a-f]{64}$`) - noncePattern = regexp.MustCompile(`^[A-Za-z0-9_-]{16,128}$`) - networkSourcePattern = regexp.MustCompile(`^[A-Za-z0-9_.:-]{1,128}$`) - causeCodePattern = regexp.MustCompile(`^[a-z][a-z0-9]*(_[a-z0-9]+)*$`) - canonicalUUIDPattern = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`) - resourcePartPattern = regexp.MustCompile(`^[A-Za-z0-9_.:-]{1,192}$`) - resourceKindPattern = regexp.MustCompile(`^[a-z][a-z0-9_-]{0,63}$`) - fenceResolutionIDPattern = regexp.MustCompile(`^[a-f0-9]{32}$`) - - metadataBucket = []byte("metadata") - operationsBucket = []byte("operations") - inflightBucket = []byte("inflight") - resourceBlockersBucket = []byte("resource_blockers") - operationExpiryBucket = []byte("operation_expiry") - completionReceiptsBucket = []byte("completion_receipts") - completionOutboxBucket = []byte("completion_outbox") - fenceResolutionsBucket = []byte("fence_resolutions") - fenceResolutionIDsBucket = []byte("fence_resolution_ids") - noncesBucket = []byte("nonces") - nonceExpiryBucket = []byte("nonce_expiry") - schemaVersionKey = []byte("schema_version") - schemaVersion = []byte("6") + ErrNotFound = errors.New("operation not found") + ErrFingerprint = errors.New("operation_id payload conflict") + ErrOperationStarting = errors.New("operation dispatch is already starting") + ErrBusy = errors.New("operation execution capacity is exhausted") + ErrResourceBlocked = errors.New("resource has an unresolved operation") + ErrInvalidSupersession = errors.New("operation cannot supersede the requested predecessor") + ErrInspectionInconclusive = errors.New("read-only inspection did not confirm a terminal outcome") + ErrExecutionNotReaped = errors.New("isolated mutation process did not exit after forced termination") + ErrFenceNotResolvable = errors.New("operation does not hold an effect fence") + ErrFenceIdentityConflict = errors.New("fence resolution identity does not match operation") + ErrFenceResolutionConflict = errors.New("operation effect fence already has a different resolution") + ErrFenceInspectionStale = errors.New("operation effect fence resolution requires a fresh inspection") + operationIDPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{8,80}$`) + operationActionPattern = regexp.MustCompile(`^[a-z][a-z0-9]*(?:[-:][a-z0-9]+)*$`) + operationResourceIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.:-]*$`) + hexDigestPattern = regexp.MustCompile(`^[0-9a-f]{64}$`) + noncePattern = regexp.MustCompile(`^[A-Za-z0-9_-]{16,128}$`) + networkSourcePattern = regexp.MustCompile(`^[A-Za-z0-9_.:-]{1,128}$`) + causeCodePattern = regexp.MustCompile(`^[a-z][a-z0-9]*(_[a-z0-9]+)*$`) + canonicalUUIDPattern = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`) + resourcePartPattern = regexp.MustCompile(`^[A-Za-z0-9_.:-]{1,192}$`) + resourceKindPattern = regexp.MustCompile(`^[a-z][a-z0-9_-]{0,63}$`) + fenceResolutionIDPattern = regexp.MustCompile(`^[a-f0-9]{32}$`) + completionSensitiveKeyPattern = regexp.MustCompile(`(?i)password|secret|(?:public|private).?key|ssh.?key|passphrase|credential|(?:(?:access|refresh|auth|api|bearer|session|source).?token)|^token$`) + snapshotRecoveryActionPattern = regexp.MustCompile( + `^(?:create-snapshot:[a-f0-9]{32}:(?:filesystem|crash)|(?:delete|restore)-snapshot:[a-f0-9]{32})$`, + ) + + metadataBucket = []byte("metadata") + operationsBucket = []byte("operations") + inflightBucket = []byte("inflight") + resourceBlockersBucket = []byte("resource_blockers") + operationExpiryBucket = []byte("operation_expiry") + completionReceiptsBucket = []byte("completion_receipts") + completionOutboxBucket = []byte("completion_outbox") + completionQuarantineBucket = []byte("completion_quarantine") + completionQuarantineOperationsBucket = []byte("completion_quarantine_operations") + fenceResolutionsBucket = []byte("fence_resolutions") + fenceResolutionIDsBucket = []byte("fence_resolution_ids") + noncesBucket = []byte("nonces") + nonceExpiryBucket = []byte("nonce_expiry") + schemaVersionKey = []byte("schema_version") + schemaVersion = []byte("6") ) // ExpectedState is the non-secret, durable evidence contract used after a @@ -144,6 +154,12 @@ type Record struct { // SupersedesOperationID is only valid for an explicitly acknowledged // force-delete-vm successor of one matching graceful/force_required record. SupersedesOperationID string `json:"-"` + // InspectionReceiptRecovered and InspectionEvidenceUnavailable are + // ephemeral read-path markers. They are never persisted or exposed by the + // Agent API; the hypervisor inspector uses them to distinguish strictly + // validated completion evidence from a missing or inconsistent receipt. + InspectionReceiptRecovered bool `json:"-"` + InspectionEvidenceUnavailable bool `json:"-"` } type Spec struct { @@ -158,22 +174,65 @@ type Spec struct { SupersedesOperationID string } +// SystemRecoveryActionAllowed is the deny-by-default capability boundary for +// the panel's read-only inspector and Journal-only fence resolver. Adding a +// new mutation route does not implicitly grant system recovery access: every +// leaf action must be reviewed and added here explicitly. +func SystemRecoveryActionAllowed(action string) bool { + switch action { + case "power-start", "power-shutdown", "power-reboot", "power-reset", "power-destroy", + "reinstall-vm", + "enter-rescue", "force-start-rescue", "exit-rescue:connected", "exit-rescue:suspended", + "change-network", "network-suspend", "network-resume", + "update-settings", "apply-firewall", + "delete-vm", "force-delete-vm", + "service-suspend", + "import-template", "update-template", "delete-template", + "import-rescue-template", "delete-rescue-template", + "import-user-iso", "delete-user-iso": + return true + default: + return snapshotRecoveryActionPattern.MatchString(action) + } +} + +// ValidOperationIdentity validates the immutable non-secret identity copied +// from a Journal record into inspections and completion deliveries. +func ValidOperationIdentity(action, resourceID, requestFingerprint string) bool { + return len(action) <= 128 && operationActionPattern.MatchString(action) && + len(resourceID) <= 255 && operationResourceIDPattern.MatchString(resourceID) && + hexDigestPattern.MatchString(requestFingerprint) +} + +const ( + completionDeliveryInterval = 30 * time.Second + completionPanelMaximumBody = 1 << 20 + fenceInspectionMaximumAge = 2 * time.Minute + fenceInspectionFutureSkew = 5 * time.Second +) + const ( - completionDeliveryMaxAttempts = uint32(12) - completionDeliveryLifetime = 24 * time.Hour - completionDeliveryInterval = 30 * time.Second - fenceInspectionMaximumAge = 2 * time.Minute - fenceInspectionFutureSkew = 5 * time.Second + CompletionDeliveryStateQuarantined = "quarantined" + + CompletionDeliveryErrorOutboxInvalid = "completion_outbox_invalid" + CompletionDeliveryErrorReceiptMissing = "completion_receipt_missing" + CompletionDeliveryErrorReceiptInvalid = "completion_receipt_invalid" + CompletionDeliveryErrorOperationMissing = "completion_operation_missing" + CompletionDeliveryErrorOperationInvalid = "completion_operation_invalid" + CompletionDeliveryErrorIdentityMismatch = "completion_identity_mismatch" ) var workerReapDeadline = 3 * time.Second // CompletionReceipt is immutable once an operation first reaches a terminal -// state. Delivery attempts are kept in a separate bounded outbox record so an -// ACK can never rewrite the operation or its receipt. +// state. Delivery timing is kept in a separate outbox record so an ACK can +// never rewrite the operation or its receipt. type CompletionReceipt struct { EventID string `json:"id"` OperationID string `json:"operation_id"` + Action string `json:"action"` + ResourceID string `json:"resource_id"` + RequestFingerprint string `json:"request_fingerprint"` Status string `json:"status"` Result json.RawMessage `json:"result"` ErrorCode string `json:"error_code,omitempty"` @@ -216,6 +275,9 @@ type FenceResolutionRequest struct { Resolution string `json:"resolution"` InspectionCheckedAt int64 `json:"inspection_checked_at"` ReasonSHA256 string `json:"reason_sha256"` + Action string `json:"action"` + ResourceID string `json:"resource_id"` + RequestFingerprint string `json:"request_fingerprint"` } // InterruptedReceipt is the non-secret terminal result recovered from an @@ -233,9 +295,20 @@ type InterruptedReceipt struct { type completionOutboxRecord struct { OperationID string `json:"operation_id"` - Attempts uint32 `json:"attempts"` NextAttemptAt time.Time `json:"next_attempt_at"` - ExpiresAt time.Time `json:"expires_at"` +} + +// CompletionDeliveryIncident is durable, non-secret audit metadata for one +// outbox entry that could not be reconstructed into the immutable completion +// wire contract. The receipt and outbox bytes remain untouched. A later claim +// revalidates them and removes this incident automatically after repair. +type CompletionDeliveryIncident struct { + EventID string `json:"event_id,omitempty"` + EventKeySHA256 string `json:"event_key_sha256"` + OperationID string `json:"operation_id,omitempty"` + ErrorCode string `json:"error_code"` + EvidenceSHA256 string `json:"evidence_sha256"` + FirstObservedAt time.Time `json:"first_observed_at"` } type Result struct { @@ -480,6 +553,87 @@ func (j *Journal) Get(operationID string) (Record, error) { return cloneRecord(record), err } +// GetForInspection returns the immutable Journal record and, when retention +// has removed its result (or the terminal result was empty), reconstructs only +// an in-memory copy from the operation's immutable completion receipt. Receipt +// anomalies are represented on the returned copy so inspection can stay +// inconclusive; this method never rewrites the Journal, receipt, or outbox. +func (j *Journal) GetForInspection(operationID string) (Record, error) { + var record Record + err := j.db.View(func(tx *bolt.Tx) error { + operations := tx.Bucket(operationsBucket) + if operations == nil { + return errors.New("operation bucket is unavailable") + } + value := operations.Get([]byte(operationID)) + if value == nil { + return ErrNotFound + } + decoded, err := decodeRecord(value) + if err != nil { + return err + } + record = decoded + if !terminalState(record.State) || (!record.Tombstone && len(record.Result) != 0) { + return nil + } + + // Treat every receipt anomaly as incomplete evidence. The caller still + // receives the immutable operation identity and terminal status, but no + // receipt bytes are trusted or persisted back into the Journal. + record.InspectionEvidenceUnavailable = true + receipts := tx.Bucket(completionReceiptsBucket) + if receipts == nil { + return nil + } + eventID := completionEventID(operationID) + encoded := receipts.Get([]byte(eventID)) + if encoded == nil { + return nil + } + var receipt CompletionReceipt + if err := json.Unmarshal(encoded, &receipt); err != nil || + !completionReceiptMatchesRecordForInspection(eventID, operationID, receipt, record) { + return nil + } + record.Result = append(json.RawMessage(nil), receipt.Result...) + record.InspectionReceiptRecovered = true + record.InspectionEvidenceUnavailable = false + return nil + }) + return cloneRecord(record), err +} + +func completionReceiptMatchesRecordForInspection(eventID, requestedOperationID string, + receipt CompletionReceipt, record Record) bool { + if record.OperationID != requestedOperationID || eventID != completionEventID(requestedOperationID) || + receipt.EventID != eventID || receipt.OperationID != requestedOperationID || + !ValidOperationIdentity(record.Action, record.ResourceID, record.Fingerprint) || + !ValidOperationIdentity(receipt.Action, receipt.ResourceID, receipt.RequestFingerprint) || + receipt.Action != record.Action || receipt.ResourceID != record.ResourceID || + receipt.RequestFingerprint != record.Fingerprint || + receipt.EffectMayHaveApplied != record.EffectMayHaveApplied || + receipt.SafeToResubmit != record.SafeToResubmit || + len(receipt.Result) == 0 || !json.Valid(receipt.Result) { + return false + } + + recordErrorCode := "" + if record.Error != nil { + recordErrorCode = record.Error.Code + } + switch record.State { + case StateSucceeded: + return receipt.Status == "succeeded" && receipt.ErrorCode == "" && + recordErrorCode == "" && !receipt.EffectMayHaveApplied && !receipt.SafeToResubmit + case StateFailed: + return receipt.Status == "failed" && receipt.ErrorCode != "" && + validCauseCode(receipt.ErrorCode) && receipt.ErrorCode == recordErrorCode + default: + return false + } +} + func ValidateFenceResolutionRequest(request FenceResolutionRequest) error { if !fenceResolutionIDPattern.MatchString(request.ResolutionID) { return errors.New("resolution_id must be 32 lowercase hexadecimal characters") @@ -493,6 +647,9 @@ func ValidateFenceResolutionRequest(request FenceResolutionRequest) error { if !hexDigestPattern.MatchString(request.ReasonSHA256) { return errors.New("reason_sha256 must be a 64-character lowercase SHA-256 digest") } + if !ValidOperationIdentity(request.Action, request.ResourceID, request.RequestFingerprint) { + return errors.New("fence resolution operation identity is invalid") + } return nil } @@ -610,18 +767,28 @@ func (j *Journal) ResolveResourceFence(operationID string, resolvedBy int64, if operations == nil || blockers == nil || resolutions == nil || resolutionIDs == nil { return errors.New("operation fence buckets are unavailable") } - if encoded := resolutions.Get([]byte(operationID)); encoded != nil { - encodedRecord := operations.Get([]byte(operationID)) - if encodedRecord == nil { - return ErrNotFound - } - record, err := decodeRecord(encodedRecord) - if err != nil { - return err - } - if resolvedBy == 0 && record.Action != "update-settings" { - return ErrFenceNotResolvable + encodedRecord := operations.Get([]byte(operationID)) + if encodedRecord == nil { + checkedAt := time.Unix(request.InspectionCheckedAt, 0).UTC() + if checkedAt.Before(now.Add(-fenceInspectionMaximumAge)) || checkedAt.After(now.Add(fenceInspectionFutureSkew)) { + return ErrFenceInspectionStale } + return ErrNotFound + } + record, err := decodeRecord(encodedRecord) + if err != nil { + return err + } + if !fenceResolutionIdentityMatches(request, record) { + return ErrFenceIdentityConflict + } + // The zero audit actor is a deliberately narrow internal capability. + // Only explicitly reviewed automatic recovery actions may use it; + // human administrators retain their positive audited identity. + if resolvedBy == 0 && !SystemRecoveryActionAllowed(record.Action) { + return ErrFenceNotResolvable + } + if encoded := resolutions.Get([]byte(operationID)); encoded != nil { if err := json.Unmarshal(encoded, &resolution); err != nil || resolution.OperationID != operationID { return fmt.Errorf("decode fence resolution %q", operationID) } @@ -640,20 +807,6 @@ func (j *Journal) ResolveResourceFence(operationID string, resolvedBy int64, if checkedAt.Before(now.Add(-fenceInspectionMaximumAge)) || checkedAt.After(now.Add(fenceInspectionFutureSkew)) { return ErrFenceInspectionStale } - encodedRecord := operations.Get([]byte(operationID)) - if encodedRecord == nil { - return ErrNotFound - } - record, err := decodeRecord(encodedRecord) - if err != nil { - return err - } - // The zero audit actor is a deliberately narrow internal capability. - // Only the currently registered automatic settings finalizer may use - // it; human administrators retain their positive audited identity. - if resolvedBy == 0 && record.Action != "update-settings" { - return ErrFenceNotResolvable - } if !blocksResources(record) { return ErrFenceNotResolvable } @@ -691,27 +844,31 @@ func (j *Journal) ResolveResourceFence(operationID string, resolvedBy int64, return resolution, replayed, err } -// ClaimPendingCompletions returns a bounded batch and durably charges one -// delivery attempt for every returned event. Expired or exhausted events are -// removed from the outbox; their immutable receipts remain available for -// diagnostics and duplicate ACKs remain harmless. +func fenceResolutionIdentityMatches(request FenceResolutionRequest, record Record) bool { + return request.Action == record.Action && request.ResourceID == record.ResourceID && + request.RequestFingerprint == record.Fingerprint +} + +// ClaimPendingCompletions returns a bounded batch and durably schedules every +// returned event's next delivery. A completion remains in the outbox until an +// ACK removes it; delivery age and attempt count never discard it. func (j *Journal) ClaimPendingCompletions(limit int) ([]CompletionReceipt, error) { claimed, _, err := j.ClaimPendingCompletionsWithExpired(limit) return claimed, err } -// ClaimPendingCompletionsWithExpired additionally returns the operation IDs -// whose bounded delivery window ended during this claim. The Agent uses those -// IDs only to remove disposable worker directories; operation tombstones and -// immutable completion receipts remain in the main journal. +// ClaimPendingCompletionsWithExpired retains its historical return shape for +// callers compiled against the bounded-outbox API. Completion delivery no +// longer expires, so the second result is always empty. func (j *Journal) ClaimPendingCompletionsWithExpired(limit int) ([]CompletionReceipt, []string, error) { return j.ClaimPendingCompletionsWithExpiredExcluding(limit, nil) } // ClaimPendingCompletionsWithExpiredExcluding leaves events already in the // current control session's ACK window untouched. An in-flight receipt cannot -// consume another durable attempt merely because its resend time arrived -// while the Gateway was still processing the first delivery. +// move its durable resend time merely because that time arrived while the +// Gateway was still processing the first delivery. The historical "expired" +// result is retained for API compatibility and is always empty. func (j *Journal) ClaimPendingCompletionsWithExpiredExcluding(limit int, excluded []string) ([]CompletionReceipt, []string, error) { if limit < 1 || limit > 128 { return nil, nil, errors.New("completion claim limit must be between 1 and 128") @@ -724,43 +881,134 @@ func (j *Journal) ClaimPendingCompletionsWithExpiredExcluding(limit int, exclude excludedEvents[eventID] = struct{}{} } claimed := make([]CompletionReceipt, 0, limit) - expired := make([]string, 0) + newIncidents := make([]CompletionDeliveryIncident, 0, 1) err := j.db.Update(func(tx *bolt.Tx) error { + operations := tx.Bucket(operationsBucket) receipts := tx.Bucket(completionReceiptsBucket) outbox := tx.Bucket(completionOutboxBucket) - if receipts == nil || outbox == nil { + quarantine := tx.Bucket(completionQuarantineBucket) + quarantineOperations := tx.Bucket(completionQuarantineOperationsBucket) + if operations == nil || receipts == nil || outbox == nil || quarantine == nil || quarantineOperations == nil { return errors.New("completion buckets are unavailable") } now := j.currentTime() cursor := outbox.Cursor() for key, encoded := cursor.First(); key != nil && len(claimed) < limit; key, encoded = cursor.Next() { + receiptEncoded := receipts.Get(key) + operationID := completionIncidentOperationID(key, encoded, receiptEncoded) var pending completionOutboxRecord - if err := json.Unmarshal(encoded, &pending); err != nil || pending.OperationID == "" || - pending.NextAttemptAt.IsZero() || pending.ExpiresAt.IsZero() { - return fmt.Errorf("decode completion outbox event %q", key) - } - if _, excluded := excludedEvents[string(key)]; excluded { + // Older records may contain attempts and expires_at fields. JSON + // decoding deliberately ignores them so an upgrade resumes delivery + // even when the legacy deadline or attempt cap was already reached. + if err := json.Unmarshal(encoded, &pending); err != nil || + !validCompletionEventID(string(key)) || + !operationIDPattern.MatchString(pending.OperationID) || + string(key) != completionEventID(pending.OperationID) || pending.NextAttemptAt.IsZero() { + incident, changed, incidentErr := quarantineCompletionDelivery( + quarantine, quarantineOperations, key, operationID, + CompletionDeliveryErrorOutboxInvalid, now, encoded, receiptEncoded, + ) + if incidentErr != nil { + return incidentErr + } + if changed { + newIncidents = append(newIncidents, incident) + } continue } - if !now.Before(pending.ExpiresAt) || pending.Attempts >= completionDeliveryMaxAttempts { - expired = append(expired, pending.OperationID) - if err := cursor.Delete(); err != nil { - return err - } + operationID = pending.OperationID + if _, excluded := excludedEvents[string(key)]; excluded { continue } if now.Before(pending.NextAttemptAt) { continue } - receiptEncoded := receipts.Get(key) if receiptEncoded == nil { - return fmt.Errorf("completion outbox references missing receipt %q", key) + incident, changed, incidentErr := quarantineCompletionDelivery( + quarantine, quarantineOperations, key, operationID, + CompletionDeliveryErrorReceiptMissing, now, encoded, + ) + if incidentErr != nil { + return incidentErr + } + if changed { + newIncidents = append(newIncidents, incident) + } + continue } var receipt CompletionReceipt if err := json.Unmarshal(receiptEncoded, &receipt); err != nil || receipt.EventID != string(key) || receipt.OperationID != pending.OperationID { - return fmt.Errorf("decode completion receipt %q", key) + incident, changed, incidentErr := quarantineCompletionDelivery( + quarantine, quarantineOperations, key, operationID, + CompletionDeliveryErrorReceiptInvalid, now, encoded, receiptEncoded, + ) + if incidentErr != nil { + return incidentErr + } + if changed { + newIncidents = append(newIncidents, incident) + } + continue + } + recordEncoded := operations.Get([]byte(pending.OperationID)) + if recordEncoded == nil { + incident, changed, incidentErr := quarantineCompletionDelivery( + quarantine, quarantineOperations, key, operationID, + CompletionDeliveryErrorOperationMissing, now, encoded, receiptEncoded, + ) + if incidentErr != nil { + return incidentErr + } + if changed { + newIncidents = append(newIncidents, incident) + } + continue + } + record, err := decodeRecord(recordEncoded) + if err != nil { + incident, changed, incidentErr := quarantineCompletionDelivery( + quarantine, quarantineOperations, key, operationID, + CompletionDeliveryErrorOperationInvalid, now, encoded, receiptEncoded, recordEncoded, + ) + if incidentErr != nil { + return incidentErr + } + if changed { + newIncidents = append(newIncidents, incident) + } + continue + } + if err := bindCompletionReceiptIdentity(&receipt, record); err != nil { + incident, changed, incidentErr := quarantineCompletionDelivery( + quarantine, quarantineOperations, key, operationID, + CompletionDeliveryErrorIdentityMismatch, now, encoded, receiptEncoded, recordEncoded, + ) + if incidentErr != nil { + return incidentErr + } + if changed { + newIncidents = append(newIncidents, incident) + } + continue + } + if !completionReceiptMatchesRecord(receipt, record) { + incident, changed, incidentErr := quarantineCompletionDelivery( + quarantine, quarantineOperations, key, operationID, + CompletionDeliveryErrorReceiptInvalid, now, encoded, receiptEncoded, recordEncoded, + ) + if incidentErr != nil { + return incidentErr + } + if changed { + newIncidents = append(newIncidents, incident) + } + continue + } + if err := clearCompletionDeliveryIncident( + quarantine, quarantineOperations, key, + ); err != nil { + return err } - pending.Attempts++ pending.NextAttemptAt = now.Add(completionDeliveryInterval) updated, err := json.Marshal(pending) if err != nil { @@ -774,12 +1022,398 @@ func (j *Journal) ClaimPendingCompletionsWithExpiredExcluding(limit int, exclude } return nil }) - return claimed, expired, err + if err == nil { + for _, incident := range newIncidents { + log.Printf( + "completion_delivery phase=quarantined operation_id=%s event_id=%s event_key_sha256=%s error_code=%s", + incident.OperationID, incident.EventID, incident.EventKeySHA256, incident.ErrorCode, + ) + } + } + return claimed, []string{}, err +} + +func bindCompletionReceiptIdentity(receipt *CompletionReceipt, record Record) error { + if receipt == nil || !ValidOperationIdentity(record.Action, record.ResourceID, record.Fingerprint) { + return errors.New("Journal operation identity is invalid") + } + if receipt.Action == "" && receipt.ResourceID == "" && receipt.RequestFingerprint == "" { + // Compatibility for immutable receipts created before operation identity + // was added to the wire contract. The returned copy is enriched from the + // same immutable Journal record; the stored receipt bytes are untouched. + receipt.Action = record.Action + receipt.ResourceID = record.ResourceID + receipt.RequestFingerprint = record.Fingerprint + return nil + } + if !ValidOperationIdentity(receipt.Action, receipt.ResourceID, receipt.RequestFingerprint) || + receipt.Action != record.Action || receipt.ResourceID != record.ResourceID || + receipt.RequestFingerprint != record.Fingerprint { + return errors.New("completion identity does not match Journal operation") + } + return nil +} + +func completionIncidentOperationID(eventKey, outboxEncoded, receiptEncoded []byte) string { + // Prefer an internally consistent immutable receipt over the mutable retry + // marker. This still recovers the affected operation when only the outbox + // bytes or key were damaged, without letting an arbitrary operation_id in a + // malformed receipt surface on the administrator inspection path. + var receiptIdentity struct { + EventID string `json:"id"` + OperationID string `json:"operation_id"` + } + receiptIdentityValid := json.Unmarshal(receiptEncoded, &receiptIdentity) == nil && + operationIDPattern.MatchString(receiptIdentity.OperationID) && + receiptIdentity.EventID == completionEventID(receiptIdentity.OperationID) + + var pendingIdentity struct { + OperationID string `json:"operation_id"` + } + pendingIdentityValid := json.Unmarshal(outboxEncoded, &pendingIdentity) == nil && + operationIDPattern.MatchString(pendingIdentity.OperationID) + + if receiptIdentityValid && receiptIdentity.EventID == string(eventKey) { + return receiptIdentity.OperationID + } + if pendingIdentityValid && completionEventID(pendingIdentity.OperationID) == string(eventKey) { + return pendingIdentity.OperationID + } + if receiptIdentityValid { + return receiptIdentity.OperationID + } + if pendingIdentityValid { + return pendingIdentity.OperationID + } + + // A valid event key alone is not reversible to an operation ID. It remains + // part of the durable evidence digest for an unassociated Agent incident. + return "" +} + +func validCompletionDeliveryErrorCode(code string) bool { + switch code { + case CompletionDeliveryErrorOutboxInvalid, + CompletionDeliveryErrorReceiptMissing, + CompletionDeliveryErrorReceiptInvalid, + CompletionDeliveryErrorOperationMissing, + CompletionDeliveryErrorOperationInvalid, + CompletionDeliveryErrorIdentityMismatch: + return true + default: + return false + } +} + +func completionDeliveryDigest(eventKey []byte, errorCode string, evidence ...[]byte) string { + hash := sha256.New() + writePart := func(value []byte) { + var size [8]byte + binary.BigEndian.PutUint64(size[:], uint64(len(value))) + _, _ = hash.Write(size[:]) + _, _ = hash.Write(value) + } + writePart([]byte("completion-delivery-incident-v1")) + writePart(eventKey) + writePart([]byte(errorCode)) + for _, value := range evidence { + writePart(value) + } + return hex.EncodeToString(hash.Sum(nil)) +} + +func quarantineCompletionDelivery(quarantine, operationIndex *bolt.Bucket, eventKey []byte, + operationID, errorCode string, observedAt time.Time, evidence ...[]byte) (CompletionDeliveryIncident, bool, error) { + if quarantine == nil || operationIndex == nil { + return CompletionDeliveryIncident{}, false, errors.New("completion quarantine buckets are unavailable") + } + if !validCompletionDeliveryErrorCode(errorCode) { + return CompletionDeliveryIncident{}, false, errors.New("invalid completion delivery incident code") + } + if !operationIDPattern.MatchString(operationID) { + operationID = "" + } + observedAt = observedAt.UTC() + if observedAt.IsZero() { + return CompletionDeliveryIncident{}, false, errors.New("completion delivery incident time is invalid") + } + eventID := "" + if validCompletionEventID(string(eventKey)) { + eventID = string(eventKey) + } + eventKeySum := sha256.Sum256(eventKey) + incident := CompletionDeliveryIncident{ + EventID: eventID, + EventKeySHA256: hex.EncodeToString(eventKeySum[:]), + OperationID: operationID, + ErrorCode: errorCode, + EvidenceSHA256: completionDeliveryDigest(eventKey, errorCode, evidence...), + FirstObservedAt: observedAt, + } + + changed := true + if encoded := quarantine.Get(eventKey); encoded != nil { + var existing CompletionDeliveryIncident + if json.Unmarshal(encoded, &existing) == nil && + existing.EventID == incident.EventID && + existing.EventKeySHA256 == incident.EventKeySHA256 && + existing.OperationID == incident.OperationID && + existing.ErrorCode == incident.ErrorCode && + existing.EvidenceSHA256 == incident.EvidenceSHA256 && + !existing.FirstObservedAt.IsZero() { + incident.FirstObservedAt = existing.FirstObservedAt.UTC() + changed = false + } + } + + // Remove every stale reverse-index entry for this raw event key. This also + // repairs an index left behind by corrupt incident JSON or by a changed + // best-effort operation association. + indexCursor := operationIndex.Cursor() + for key, value := indexCursor.First(); key != nil; key, value = indexCursor.Next() { + if bytes.Equal(value, eventKey) && (operationID == "" || string(key) != operationID) { + if err := indexCursor.Delete(); err != nil { + return CompletionDeliveryIncident{}, false, err + } + } + } + + encoded, err := json.Marshal(incident) + if err != nil { + return CompletionDeliveryIncident{}, false, err + } + if err := quarantine.Put(eventKey, encoded); err != nil { + return CompletionDeliveryIncident{}, false, err + } + if operationID != "" { + indexed := operationIndex.Get([]byte(operationID)) + if !bytes.Equal(indexed, eventKey) { + changed = true + } + if err := operationIndex.Put([]byte(operationID), eventKey); err != nil { + return CompletionDeliveryIncident{}, false, err + } + } + return incident, changed, nil +} + +func clearCompletionDeliveryIncident(quarantine, operationIndex *bolt.Bucket, eventKey []byte) error { + if quarantine == nil || operationIndex == nil { + return errors.New("completion quarantine buckets are unavailable") + } + if err := quarantine.Delete(eventKey); err != nil { + return err + } + cursor := operationIndex.Cursor() + for key, value := cursor.First(); key != nil; key, value = cursor.Next() { + if bytes.Equal(value, eventKey) { + if err := cursor.Delete(); err != nil { + return err + } + } + } + return nil +} + +// CompletionDeliveryIncident returns a persistent delivery-only incident for +// administrator inspection. It never changes the immutable operation status, +// receipt, or outbox entry. +func (j *Journal) CompletionDeliveryIncident(operationID string) (CompletionDeliveryIncident, bool, error) { + if !operationIDPattern.MatchString(operationID) { + return CompletionDeliveryIncident{}, false, ErrNotFound + } + var incident CompletionDeliveryIncident + found := false + err := j.db.View(func(tx *bolt.Tx) error { + quarantine := tx.Bucket(completionQuarantineBucket) + operationIndex := tx.Bucket(completionQuarantineOperationsBucket) + if quarantine == nil || operationIndex == nil { + return errors.New("completion quarantine buckets are unavailable") + } + eventKey := operationIndex.Get([]byte(operationID)) + derivedAssociation := false + if eventKey == nil { + // The event ID is a deterministic digest of the operation ID. If both + // the outbox and immutable receipt JSON are damaged, quarantine cannot + // recover an operation ID to populate the reverse index. The exact + // deterministic key still safely associates that detected corruption + // with this requested operation without scanning either bucket. + eventKey = []byte(completionEventID(operationID)) + if quarantine.Get(eventKey) == nil { + return nil + } + derivedAssociation = true + } + encoded := quarantine.Get(eventKey) + if encoded == nil { + return errors.New("completion quarantine operation index is inconsistent") + } + if err := json.Unmarshal(encoded, &incident); err != nil { + return fmt.Errorf("decode completion delivery incident: %w", err) + } + eventKeySum := sha256.Sum256(eventKey) + operationMatches := incident.OperationID == operationID || + (derivedAssociation && incident.OperationID == "" && + incident.EventID == string(eventKey)) + if !operationMatches || + !validCompletionDeliveryErrorCode(incident.ErrorCode) || + !hexDigestPattern.MatchString(incident.EventKeySHA256) || + incident.EventKeySHA256 != hex.EncodeToString(eventKeySum[:]) || + !hexDigestPattern.MatchString(incident.EvidenceSHA256) || + incident.FirstObservedAt.IsZero() || + (incident.EventID != "" && (incident.EventID != string(eventKey) || !validCompletionEventID(incident.EventID))) { + return errors.New("completion delivery incident is invalid") + } + if derivedAssociation { + // Bind only the returned copy. Repairing the receipt/outbox must still + // clear the original quarantine entry through its immutable event key; + // inspection must never rewrite corruption evidence. + incident.OperationID = operationID + } + found = true + return nil + }) + return incident, found, err +} + +func completionReceiptMatchesRecord(receipt CompletionReceipt, record Record) bool { + if receipt.EventID != completionEventID(record.OperationID) || + receipt.OperationID != record.OperationID || + !ValidOperationIdentity(receipt.Action, receipt.ResourceID, receipt.RequestFingerprint) || + receipt.Action != record.Action || receipt.ResourceID != record.ResourceID || + receipt.RequestFingerprint != record.Fingerprint || + receipt.EffectMayHaveApplied != record.EffectMayHaveApplied || + receipt.SafeToResubmit != record.SafeToResubmit || + !completionResultSafe(receipt.Result) || !completionDeliveryFitsPanelLimit(receipt) { + return false + } + + recordErrorCode := "" + if record.Error != nil { + recordErrorCode = record.Error.Code + } + switch record.State { + case StateSucceeded: + if receipt.Status != "succeeded" || receipt.ErrorCode != "" || recordErrorCode != "" || + receipt.EffectMayHaveApplied || receipt.SafeToResubmit { + return false + } + case StateFailed: + if receipt.Status != "failed" || receipt.ErrorCode == "" || + !validCauseCode(receipt.ErrorCode) || receipt.ErrorCode != recordErrorCode || + (receipt.EffectMayHaveApplied && receipt.SafeToResubmit) { + return false + } + default: + return false + } + + // Retention intentionally removes the Journal result while preserving the + // immutable receipt. All other records must still carry the exact JSON value + // that was copied into that receipt at terminalization. + if record.Tombstone { + return true + } + return completionResultsEqual(receipt.Result, record.Result) +} + +func completionDeliveryFitsPanelLimit(receipt CompletionReceipt) bool { + // The Gateway adds agent_id before POSTing to PHP. Marshal the exact public + // envelope with the longest valid agent ID so every claimed receipt is + // guaranteed to fit the panel's authenticated 1 MiB request limit. + encoded, err := json.Marshal(struct { + Type string `json:"type"` + ID string `json:"id"` + AgentID string `json:"agent_id"` + OperationID string `json:"operation_id"` + Action string `json:"action"` + ResourceID string `json:"resource_id"` + RequestFingerprint string `json:"request_fingerprint"` + Status string `json:"status"` + EffectMayHaveApplied bool `json:"effect_may_have_applied"` + SafeToResubmit bool `json:"safe_to_resubmit"` + ErrorCode string `json:"error_code"` + Result json.RawMessage `json:"result"` + }{ + Type: "completion", ID: receipt.EventID, AgentID: "9999999999999999999", + OperationID: receipt.OperationID, Action: receipt.Action, ResourceID: receipt.ResourceID, + RequestFingerprint: receipt.RequestFingerprint, Status: receipt.Status, + EffectMayHaveApplied: receipt.EffectMayHaveApplied, SafeToResubmit: receipt.SafeToResubmit, + ErrorCode: receipt.ErrorCode, Result: receipt.Result, + }) + return err == nil && len(encoded) <= completionPanelMaximumBody +} + +func completionResultsEqual(receipt, record json.RawMessage) bool { + if len(record) == 0 { + return bytes.Equal(bytes.TrimSpace(receipt), []byte("null")) + } + if !json.Valid(receipt) || !json.Valid(record) { + return false + } + var compactReceipt bytes.Buffer + var compactRecord bytes.Buffer + if json.Compact(&compactReceipt, receipt) != nil || json.Compact(&compactRecord, record) != nil { + return false + } + return bytes.Equal(compactReceipt.Bytes(), compactRecord.Bytes()) +} + +func completionResultSafe(raw json.RawMessage) bool { + if len(raw) == 0 || !json.Valid(raw) { + return false + } + var value any + if err := json.Unmarshal(raw, &value); err != nil { + return false + } + if value == nil { + return true + } + switch value.(type) { + case map[string]any, []any: + return completionResultValueSafe(value, 0) + default: + return false + } +} + +func completionResultValueSafe(value any, depth int) bool { + if depth > 16 { + return false + } + switch typed := value.(type) { + case map[string]any: + for key, nested := range typed { + if completionSensitiveKeyPattern.MatchString(key) { + return false + } + if _, ok := nested.(map[string]any); ok && !completionResultValueSafe(nested, depth+1) { + return false + } + if _, ok := nested.([]any); ok && !completionResultValueSafe(nested, depth+1) { + return false + } + } + case []any: + for _, nested := range typed { + if _, ok := nested.(map[string]any); ok && !completionResultValueSafe(nested, depth+1) { + return false + } + if _, ok := nested.([]any); ok && !completionResultValueSafe(nested, depth+1) { + return false + } + } + default: + return false + } + return true } // CompletionOperationID resolves a still-pending delivery marker without -// changing it. It lets the Agent remove disposable worker state before -// durably consuming an ACK, so a cleanup failure can be retried safely. +// changing it. It lets the Agent clean disposable worker state independently +// before durably consuming an ACK; the lookup never changes the receipt or +// its delivery marker. func (j *Journal) CompletionOperationID(eventID string) (string, error) { if !validCompletionEventID(eventID) { return "", errors.New("invalid completion event ID") @@ -804,8 +1438,9 @@ func (j *Journal) CompletionOperationID(eventID string) (string, error) { return operationID, err } -// PendingCompletionOperationIDs returns the worker directories that must be -// retained across restart until their terminal receipt is ACKed or expires. +// PendingCompletionOperationIDs returns operation IDs whose terminal receipt +// still awaits an ACK. Disposable worker directories are no longer coupled to +// this set once their result has been imported into the main Journal. func (j *Journal) PendingCompletionOperationIDs() (map[string]struct{}, error) { operationIDs := make(map[string]struct{}) err := j.db.View(func(tx *bolt.Tx) error { @@ -958,6 +1593,9 @@ func syncCompletionReceipt(receipts, outbox *bolt.Bucket, previous, current Reco if !terminalState(current.State) || terminalState(previous.State) { return nil } + if !ValidOperationIdentity(current.Action, current.ResourceID, current.Fingerprint) { + return errors.New("terminal operation identity is invalid") + } eventID := completionEventID(current.OperationID) key := []byte(eventID) if receipts.Get(key) != nil { @@ -971,7 +1609,9 @@ func syncCompletionReceipt(receipts, outbox *bolt.Bucket, previous, current Reco errorCode = current.Error.Code } receipt := CompletionReceipt{ - EventID: eventID, OperationID: current.OperationID, Status: status, + EventID: eventID, OperationID: current.OperationID, + Action: current.Action, ResourceID: current.ResourceID, RequestFingerprint: current.Fingerprint, + Status: status, Result: append(json.RawMessage(nil), current.Result...), ErrorCode: errorCode, EffectMayHaveApplied: current.EffectMayHaveApplied, SafeToResubmit: current.SafeToResubmit, CreatedAt: current.UpdatedAt.UTC(), @@ -985,7 +1625,6 @@ func syncCompletionReceipt(receipts, outbox *bolt.Bucket, previous, current Reco } pending, err := json.Marshal(completionOutboxRecord{ OperationID: current.OperationID, NextAttemptAt: current.UpdatedAt.UTC(), - ExpiresAt: current.UpdatedAt.UTC().Add(completionDeliveryLifetime), }) if err != nil { return err @@ -1346,6 +1985,12 @@ func (j *Journal) initialize() error { if err != nil { return fmt.Errorf("create completion outbox bucket: %w", err) } + if _, err := tx.CreateBucketIfNotExists(completionQuarantineBucket); err != nil { + return fmt.Errorf("create completion quarantine bucket: %w", err) + } + if _, err := tx.CreateBucketIfNotExists(completionQuarantineOperationsBucket); err != nil { + return fmt.Errorf("create completion quarantine operation index: %w", err) + } if _, err := tx.CreateBucketIfNotExists(fenceResolutionsBucket); err != nil { return fmt.Errorf("create fence resolution bucket: %w", err) } @@ -2210,14 +2855,8 @@ func validateSpec(spec Spec) error { if !operationIDPattern.MatchString(spec.OperationID) { return errors.New("operation_id must be 8-80 URL-safe characters") } - if strings.TrimSpace(spec.Action) == "" || len(spec.Action) > 128 { - return errors.New("action must contain 1-128 characters") - } - if len(spec.ResourceID) > 255 { - return errors.New("resource_id is too long") - } - if !hexDigestPattern.MatchString(spec.Fingerprint) { - return errors.New("fingerprint must be lowercase SHA-256 hex") + if !ValidOperationIdentity(spec.Action, spec.ResourceID, spec.Fingerprint) { + return errors.New("operation action, resource_id, or request fingerprint is invalid") } if _, err := normalizeLockKeys(spec.LockKeys); err != nil { return err diff --git a/agent/operation/journal_test.go b/agent/operation/journal_test.go index 6aa60de7..83a03568 100644 --- a/agent/operation/journal_test.go +++ b/agent/operation/journal_test.go @@ -548,7 +548,9 @@ func TestCompletionReceiptIsImmutableAndAckOnlyClearsOutbox(t *testing.T) { t.Fatalf("completion claim = %#v err=%v", claimed, err) } receipt := claimed[0] - if receipt.Status != "succeeded" || receipt.Result == nil || string(receipt.Result) != `{"deleted":true}` { + if receipt.Status != "succeeded" || receipt.Result == nil || string(receipt.Result) != `{"deleted":true}` || + receipt.Action != spec.Action || receipt.ResourceID != spec.ResourceID || + receipt.RequestFingerprint != spec.Fingerprint { t.Fatalf("completion receipt = %#v", receipt) } if err := j.AcknowledgeCompletion(receipt.EventID); err != nil { @@ -572,27 +574,507 @@ func TestCompletionReceiptIsImmutableAndAckOnlyClearsOutbox(t *testing.T) { } } -func TestCompletionOutboxHasFiniteAttemptsAndBackoff(t *testing.T) { +func TestInspectionRecoversAckedCompletionReceiptAfterDetailPrune(t *testing.T) { + j, spec, eventID, want := pruneAckedSettingsOperation(t) + + plain, err := j.Get(spec.OperationID) + if err != nil || !plain.Tombstone || len(plain.Result) != 0 { + t.Fatalf("pruned Journal record = %#v err=%v", plain, err) + } + var persistedBefore []byte + if err := j.db.View(func(tx *bolt.Tx) error { + persistedBefore = append([]byte(nil), tx.Bucket(operationsBucket).Get([]byte(spec.OperationID))...) + return nil + }); err != nil { + t.Fatal(err) + } + + inspected, err := j.GetForInspection(spec.OperationID) + if err != nil || !inspected.Tombstone || !inspected.InspectionReceiptRecovered || + inspected.InspectionEvidenceUnavailable || string(inspected.Result) != string(want) { + t.Fatalf("receipt-backed inspection record = %#v err=%v", inspected, err) + } + if pending, err := j.ClaimPendingCompletions(1); err != nil || len(pending) != 0 { + t.Fatalf("rejected/ACKed completion returned to outbox: %#v err=%v", pending, err) + } + var persistedAfter, receipt []byte + if err := j.db.View(func(tx *bolt.Tx) error { + persistedAfter = append([]byte(nil), tx.Bucket(operationsBucket).Get([]byte(spec.OperationID))...) + receipt = append([]byte(nil), tx.Bucket(completionReceiptsBucket).Get([]byte(eventID))...) + return nil + }); err != nil { + t.Fatal(err) + } + if !bytes.Equal(persistedBefore, persistedAfter) || len(receipt) == 0 { + t.Fatal("inspection rewrote the Journal or lost the immutable receipt") + } + again, err := j.Get(spec.OperationID) + if err != nil || len(again.Result) != 0 || again.InspectionReceiptRecovered || + again.InspectionEvidenceUnavailable { + t.Fatalf("in-memory recovery leaked into persistent Journal read: %#v err=%v", again, err) + } +} + +func TestInspectionRejectsTamperedCompletionReceipt(t *testing.T) { + tests := map[string]func(*CompletionReceipt){ + "event id": func(receipt *CompletionReceipt) { + receipt.EventID = completionEventID("operation-different-event") + }, + "operation id": func(receipt *CompletionReceipt) { + receipt.OperationID = "operation-different-identity" + }, + "action": func(receipt *CompletionReceipt) { + receipt.Action = "change-network" + }, + "resource id": func(receipt *CompletionReceipt) { + receipt.ResourceID = "123e4567-e89b-42d3-a456-426614174999" + }, + "request fingerprint": func(receipt *CompletionReceipt) { + receipt.RequestFingerprint = strings.Repeat("a", 64) + }, + "status": func(receipt *CompletionReceipt) { + receipt.Status = "failed" + }, + "effect": func(receipt *CompletionReceipt) { + receipt.EffectMayHaveApplied = true + }, + "safe to resubmit": func(receipt *CompletionReceipt) { + receipt.SafeToResubmit = true + }, + "error": func(receipt *CompletionReceipt) { + receipt.ErrorCode = "operation_failed" + }, + } + for name, tamper := range tests { + t.Run(name, func(t *testing.T) { + j, spec, eventID, _ := pruneAckedSettingsOperation(t) + if err := j.db.Update(func(tx *bolt.Tx) error { + receipts := tx.Bucket(completionReceiptsBucket) + var receipt CompletionReceipt + if err := json.Unmarshal(receipts.Get([]byte(eventID)), &receipt); err != nil { + return err + } + tamper(&receipt) + encoded, err := json.Marshal(receipt) + if err != nil { + return err + } + return receipts.Put([]byte(eventID), encoded) + }); err != nil { + t.Fatal(err) + } + + inspected, err := j.GetForInspection(spec.OperationID) + if err != nil || inspected.InspectionReceiptRecovered || + !inspected.InspectionEvidenceUnavailable || len(inspected.Result) != 0 { + t.Fatalf("tampered receipt inspection record = %#v err=%v", inspected, err) + } + }) + } +} + +func pruneAckedSettingsOperation(t *testing.T) (*Journal, Spec, string, json.RawMessage) { + t.Helper() + j := openTestJournal(t) + now := time.Date(2026, 10, 20, 10, 0, 0, 0, time.UTC) + j.SetClockForTesting(func() time.Time { return now }) + resourceID := "123e4567-e89b-42d3-a456-426614174000" + spec := Spec{ + OperationID: "operation-settings-receipt-prune", + ResourceID: resourceID, + Action: "update-settings", + Fingerprint: Fingerprint("POST", "/v1/vms/"+resourceID+"/settings", []byte(`{"hostname":"safe.example"}`)), + Destructive: true, + } + want := json.RawMessage(`{"uuid":"123e4567-e89b-42d3-a456-426614174000","name":"vm-safe","status":"running","hostname":"safe.example","settings_changed":true,"internal_note":"must-not-leak"}`) + if _, _, err := j.Execute(context.Background(), spec, func(context.Context) (json.RawMessage, error) { + return want, nil + }); err != nil { + t.Fatal(err) + } + claimed, err := j.ClaimPendingCompletions(1) + if err != nil || len(claimed) != 1 { + t.Fatalf("completion claim = %#v err=%v", claimed, err) + } + eventID := completionEventID(spec.OperationID) + if claimed[0].EventID != eventID { + t.Fatalf("completion event ID = %q, want %q", claimed[0].EventID, eventID) + } + // The Agent intentionally cannot distinguish an applied/late completion + // from a Gateway "rejected" disposition: all produce the same ACK. + if err := j.AcknowledgeCompletion(eventID); err != nil { + t.Fatal(err) + } + now = now.Add(operationDetailRetention + time.Hour) + if accepted, err := j.UseNonce("nonce-prune-acked-receipt", now, now.Add(time.Minute)); err != nil || !accepted { + t.Fatalf("trigger operation pruning accepted=%v err=%v", accepted, err) + } + return j, spec, eventID, want +} + +func TestCompletionOutboxRetriesLegacyExpiredRecordUntilACK(t *testing.T) { j := openTestJournal(t) now := time.Date(2026, 10, 19, 1, 0, 0, 0, time.UTC) j.SetClockForTesting(func() time.Time { return now }) - if _, _, err := j.Execute(context.Background(), testSpec("operation-bounded-outbox", "vm-outbox"), func(context.Context) (json.RawMessage, error) { + spec := testSpec("operation-durable-outbox", "vm-outbox") + if _, _, err := j.Execute(context.Background(), spec, func(context.Context) (json.RawMessage, error) { return nil, testFailure{code: "injected_failure", message: "injected", effect: false, safe: true} }); err == nil { t.Fatal("injected failure unexpectedly succeeded") } - for attempt := uint32(0); attempt < completionDeliveryMaxAttempts; attempt++ { - claimed, err := j.ClaimPendingCompletions(1) - if err != nil || len(claimed) != 1 { - t.Fatalf("attempt %d claim = %#v err=%v", attempt+1, claimed, err) + eventID := completionEventID(spec.OperationID) + err := j.db.Update(func(tx *bolt.Tx) error { + receipts := tx.Bucket(completionReceiptsBucket) + var legacyReceipt map[string]json.RawMessage + if unmarshalErr := json.Unmarshal(receipts.Get([]byte(eventID)), &legacyReceipt); unmarshalErr != nil { + return unmarshalErr + } + delete(legacyReceipt, "action") + delete(legacyReceipt, "resource_id") + delete(legacyReceipt, "request_fingerprint") + legacyReceiptEncoded, marshalErr := json.Marshal(legacyReceipt) + if marshalErr != nil { + return marshalErr + } + if putErr := receipts.Put([]byte(eventID), legacyReceiptEncoded); putErr != nil { + return putErr + } + legacy, marshalErr := json.Marshal(struct { + OperationID string `json:"operation_id"` + Attempts uint32 `json:"attempts"` + NextAttemptAt time.Time `json:"next_attempt_at"` + ExpiresAt time.Time `json:"expires_at"` + }{ + OperationID: spec.OperationID, Attempts: 12, + NextAttemptAt: now, ExpiresAt: now.Add(24 * time.Hour), + }) + if marshalErr != nil { + return marshalErr + } + return tx.Bucket(completionOutboxBucket).Put([]byte(eventID), legacy) + }) + if err != nil { + t.Fatal(err) + } + + now = now.Add(25 * time.Hour) + claimed, expired, err := j.ClaimPendingCompletionsWithExpired(1) + if err != nil || len(claimed) != 1 || claimed[0].EventID != eventID || len(expired) != 0 { + t.Fatalf("legacy expired claim = %#v expired=%#v err=%v", claimed, expired, err) + } + if claimed[0].Action != spec.Action || claimed[0].ResourceID != spec.ResourceID || + claimed[0].RequestFingerprint != spec.Fingerprint { + t.Fatalf("legacy receipt identity was not enriched from Journal: %#v", claimed[0]) + } + if err := j.db.View(func(tx *bolt.Tx) error { + var persisted map[string]json.RawMessage + if unmarshalErr := json.Unmarshal(tx.Bucket(completionReceiptsBucket).Get([]byte(eventID)), &persisted); unmarshalErr != nil { + return unmarshalErr } - if immediate, err := j.ClaimPendingCompletions(1); err != nil || len(immediate) != 0 { - t.Fatalf("attempt %d ignored backoff: %#v err=%v", attempt+1, immediate, err) + if _, exists := persisted["action"]; exists { + return errors.New("legacy immutable receipt was rewritten") } - now = now.Add(completionDeliveryInterval) + return nil + }); err != nil { + t.Fatal(err) } - if exhausted, err := j.ClaimPendingCompletions(1); err != nil || len(exhausted) != 0 { - t.Fatalf("exhausted outbox = %#v err=%v", exhausted, err) + if immediate, err := j.ClaimPendingCompletions(1); err != nil || len(immediate) != 0 { + t.Fatalf("claim ignored delivery interval: %#v err=%v", immediate, err) + } + + now = now.Add(365 * 24 * time.Hour) + claimed, expired, err = j.ClaimPendingCompletionsWithExpired(1) + if err != nil || len(claimed) != 1 || claimed[0].EventID != eventID || len(expired) != 0 { + t.Fatalf("long-lived claim = %#v expired=%#v err=%v", claimed, expired, err) + } + if err := j.AcknowledgeCompletion(eventID); err != nil { + t.Fatal(err) + } + now = now.Add(completionDeliveryInterval) + if afterACK, err := j.ClaimPendingCompletions(1); err != nil || len(afterACK) != 0 { + t.Fatalf("ACK did not remove outbox event: %#v err=%v", afterACK, err) + } +} + +func TestCompletionOutboxQuarantinesPoisonAndContinuesDelivery(t *testing.T) { + tests := []struct { + name string + errorCode string + poison func(*bolt.Bucket, []byte, []byte) error + }{ + { + name: "identity mismatch", + errorCode: "completion_identity_mismatch", + poison: func(receipts *bolt.Bucket, key, original []byte) error { + var receipt CompletionReceipt + if err := json.Unmarshal(original, &receipt); err != nil { + return err + } + receipt.Action = "power-start" + encoded, err := json.Marshal(receipt) + if err != nil { + return err + } + return receipts.Put(key, encoded) + }, + }, + { + name: "invalid receipt JSON", + errorCode: "completion_receipt_invalid", + poison: func(receipts *bolt.Bucket, key, _ []byte) error { + return receipts.Put(key, []byte(`{"id":`)) + }, + }, + { + name: "missing receipt", + errorCode: "completion_receipt_missing", + poison: func(receipts *bolt.Bucket, key, _ []byte) error { + return receipts.Delete(key) + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "operations.db") + j, err := Open(path) + if err != nil { + t.Fatal(err) + } + now := time.Date(2026, 10, 19, 1, 15, 0, 0, time.UTC) + j.SetClockForTesting(func() time.Time { return now }) + + first := testSpec("operation-poison-first", "vm-poison-first") + second := testSpec("operation-poison-second", "vm-poison-second") + poisonSpec, healthySpec := first, second + if completionEventID(poisonSpec.OperationID) > completionEventID(healthySpec.OperationID) { + poisonSpec, healthySpec = healthySpec, poisonSpec + } + for _, spec := range []Spec{poisonSpec, healthySpec} { + if _, _, err := j.Execute(context.Background(), spec, func(context.Context) (json.RawMessage, error) { + return json.RawMessage(`{"done":true}`), nil + }); err != nil { + t.Fatal(err) + } + } + + poisonEventID := completionEventID(poisonSpec.OperationID) + healthyEventID := completionEventID(healthySpec.OperationID) + var originalReceipt, poisonedReceipt []byte + if err := j.db.Update(func(tx *bolt.Tx) error { + receipts := tx.Bucket(completionReceiptsBucket) + outbox := tx.Bucket(completionOutboxBucket) + originalReceipt = append([]byte(nil), receipts.Get([]byte(poisonEventID))...) + if len(originalReceipt) == 0 || len(outbox.Get([]byte(poisonEventID))) == 0 { + return errors.New("poison fixture is missing durable completion state") + } + if err := test.poison(receipts, []byte(poisonEventID), originalReceipt); err != nil { + return err + } + poisonedReceipt = append([]byte(nil), receipts.Get([]byte(poisonEventID))...) + return nil + }); err != nil { + t.Fatal(err) + } + + claimed, err := j.ClaimPendingCompletions(1) + if err != nil || len(claimed) != 1 || claimed[0].EventID != healthyEventID { + t.Fatalf("claim after poison = %#v err=%v", claimed, err) + } + incident, found, err := j.CompletionDeliveryIncident(poisonSpec.OperationID) + if err != nil || !found || incident.OperationID != poisonSpec.OperationID || + incident.EventID != poisonEventID || incident.ErrorCode != test.errorCode || + incident.FirstObservedAt.IsZero() || !hexDigestPattern.MatchString(incident.EvidenceSHA256) { + t.Fatalf("completion incident = %#v found=%v err=%v", incident, found, err) + } + if err := j.db.View(func(tx *bolt.Tx) error { + if len(tx.Bucket(completionOutboxBucket).Get([]byte(poisonEventID))) == 0 { + return errors.New("poison completion outbox entry was deleted") + } + if !bytes.Equal(tx.Bucket(completionReceiptsBucket).Get([]byte(poisonEventID)), poisonedReceipt) { + return errors.New("poison completion receipt was rewritten or deleted") + } + return nil + }); err != nil { + t.Fatal(err) + } + + if err := j.Close(); err != nil { + t.Fatal(err) + } + j, err = Open(path) + if err != nil { + t.Fatal(err) + } + defer j.Close() + j.SetClockForTesting(func() time.Time { return now }) + persisted, found, err := j.CompletionDeliveryIncident(poisonSpec.OperationID) + if err != nil || !found || persisted.OperationID != incident.OperationID || persisted.EventID != incident.EventID || + persisted.ErrorCode != incident.ErrorCode || persisted.EvidenceSHA256 != incident.EvidenceSHA256 || + !persisted.FirstObservedAt.Equal(incident.FirstObservedAt) { + t.Fatalf("persisted completion incident = %#v found=%v err=%v; want %#v", persisted, found, err, incident) + } + + if err := j.db.Update(func(tx *bolt.Tx) error { + return tx.Bucket(completionReceiptsBucket).Put([]byte(poisonEventID), originalReceipt) + }); err != nil { + t.Fatal(err) + } + now = now.Add(completionDeliveryInterval) + claimed, err = j.ClaimPendingCompletions(1) + if err != nil || len(claimed) != 1 || claimed[0].EventID != poisonEventID { + t.Fatalf("claim after repairing poison = %#v err=%v", claimed, err) + } + if incident, found, err := j.CompletionDeliveryIncident(poisonSpec.OperationID); err != nil || found { + t.Fatalf("repaired completion remains quarantined: %#v found=%v err=%v", incident, found, err) + } + }) + } +} + +func TestCompletionQuarantineAssociatesDeterministicEventAfterDoubleCorruption(t *testing.T) { + j := openTestJournal(t) + now := time.Date(2026, 10, 19, 1, 20, 0, 0, time.UTC) + j.SetClockForTesting(func() time.Time { return now }) + spec := testSpec("operation-double-corruption", "vm-double-corruption") + if _, _, err := j.Execute(context.Background(), spec, func(context.Context) (json.RawMessage, error) { + return json.RawMessage(`{"done":true}`), nil + }); err != nil { + t.Fatal(err) + } + + eventID := completionEventID(spec.OperationID) + var originalOutbox, originalReceipt []byte + if err := j.db.Update(func(tx *bolt.Tx) error { + outbox := tx.Bucket(completionOutboxBucket) + receipts := tx.Bucket(completionReceiptsBucket) + originalOutbox = append([]byte(nil), outbox.Get([]byte(eventID))...) + originalReceipt = append([]byte(nil), receipts.Get([]byte(eventID))...) + if len(originalOutbox) == 0 || len(originalReceipt) == 0 { + return errors.New("double-corruption fixture is missing completion state") + } + if err := outbox.Put([]byte(eventID), []byte(`{"operation_id":`)); err != nil { + return err + } + return receipts.Put([]byte(eventID), []byte(`{"id":`)) + }); err != nil { + t.Fatal(err) + } + + if claimed, err := j.ClaimPendingCompletions(1); err != nil || len(claimed) != 0 { + t.Fatalf("double-corrupt completion was delivered: %#v err=%v", claimed, err) + } + incident, found, err := j.CompletionDeliveryIncident(spec.OperationID) + if err != nil || !found || incident.OperationID != spec.OperationID || + incident.EventID != eventID || incident.ErrorCode != CompletionDeliveryErrorOutboxInvalid { + t.Fatalf("derived double-corruption incident = %#v found=%v err=%v", incident, found, err) + } + if err := j.db.View(func(tx *bolt.Tx) error { + encoded := tx.Bucket(completionQuarantineBucket).Get([]byte(eventID)) + var persisted CompletionDeliveryIncident + if json.Unmarshal(encoded, &persisted) != nil || persisted.OperationID != "" { + return errors.New("derived incident lookup rewrote quarantine evidence") + } + if tx.Bucket(completionQuarantineOperationsBucket).Get([]byte(spec.OperationID)) != nil { + return errors.New("derived incident lookup invented a reverse index") + } + return nil + }); err != nil { + t.Fatal(err) + } + + if err := j.db.Update(func(tx *bolt.Tx) error { + if err := tx.Bucket(completionOutboxBucket).Put([]byte(eventID), originalOutbox); err != nil { + return err + } + return tx.Bucket(completionReceiptsBucket).Put([]byte(eventID), originalReceipt) + }); err != nil { + t.Fatal(err) + } + now = now.Add(completionDeliveryInterval) + claimed, err := j.ClaimPendingCompletions(1) + if err != nil || len(claimed) != 1 || claimed[0].EventID != eventID { + t.Fatalf("repaired double-corrupt completion = %#v err=%v", claimed, err) + } + if incident, found, err := j.CompletionDeliveryIncident(spec.OperationID); err != nil || found { + t.Fatalf("repaired double-corrupt incident remains: %#v found=%v err=%v", incident, found, err) + } +} + +func TestCompletionOutboxQuarantinesUndeliverableResultAndContinuesDelivery(t *testing.T) { + tests := []struct { + name string + result json.RawMessage + }{ + { + name: "recursive sensitive key", + result: json.RawMessage(`{"safe":{"nested":{"root_password":"must-not-leak"}}}`), + }, + { + name: "scalar result", + result: json.RawMessage(`"unexpected"`), + }, + { + name: "result exceeds safe recursion depth", + result: json.RawMessage( + strings.Repeat(`{"nested":`, 18) + `true` + strings.Repeat(`}`, 18), + ), + }, + { + name: "result makes completion HTTP body exceed one MiB", + result: json.RawMessage( + `{"data":"` + strings.Repeat("x", 1<<20) + `"}`, + ), + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + j := openTestJournal(t) + now := time.Date(2026, 10, 19, 1, 25, 0, 0, time.UTC) + j.SetClockForTesting(func() time.Time { return now }) + + first := testSpec("operation-result-poison-first", "vm-result-poison-first") + second := testSpec("operation-result-poison-second", "vm-result-poison-second") + poisonSpec, healthySpec := first, second + if completionEventID(poisonSpec.OperationID) > completionEventID(healthySpec.OperationID) { + poisonSpec, healthySpec = healthySpec, poisonSpec + } + if _, _, err := j.Execute(context.Background(), poisonSpec, func(context.Context) (json.RawMessage, error) { + return test.result, nil + }); err != nil { + t.Fatal(err) + } + if _, _, err := j.Execute(context.Background(), healthySpec, func(context.Context) (json.RawMessage, error) { + return json.RawMessage(`{"done":true}`), nil + }); err != nil { + t.Fatal(err) + } + + poisonEventID := completionEventID(poisonSpec.OperationID) + healthyEventID := completionEventID(healthySpec.OperationID) + claimed, err := j.ClaimPendingCompletions(1) + if err != nil || len(claimed) != 1 || claimed[0].EventID != healthyEventID { + t.Fatalf("claim after undeliverable result = %#v err=%v", claimed, err) + } + incident, found, err := j.CompletionDeliveryIncident(poisonSpec.OperationID) + if err != nil || !found || incident.OperationID != poisonSpec.OperationID || + incident.EventID != poisonEventID || incident.ErrorCode != "completion_receipt_invalid" || + incident.FirstObservedAt.IsZero() || !hexDigestPattern.MatchString(incident.EvidenceSHA256) { + t.Fatalf("undeliverable result incident = %#v found=%v err=%v", incident, found, err) + } + if err := j.db.View(func(tx *bolt.Tx) error { + if len(tx.Bucket(completionOutboxBucket).Get([]byte(poisonEventID))) == 0 { + return errors.New("undeliverable completion outbox entry was deleted") + } + if len(tx.Bucket(completionReceiptsBucket).Get([]byte(poisonEventID))) == 0 { + return errors.New("undeliverable completion receipt was deleted") + } + return nil + }); err != nil { + t.Fatal(err) + } + }) } } @@ -655,6 +1137,20 @@ func TestFenceResolutionIsAuditedIdempotentAndDoesNotRewriteTerminalEvidence(t * ResolutionID: "0123456789abcdef0123456789abcdef", Resolution: FenceResolutionNotApplied, InspectionCheckedAt: now.Unix(), ReasonSHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + Action: spec.Action, ResourceID: spec.ResourceID, RequestFingerprint: spec.Fingerprint, + } + missingIdentity := request + missingIdentity.RequestFingerprint = "" + if _, _, err := j.ResolveResourceFence(spec.OperationID, 42, missingIdentity); err == nil { + t.Fatal("fence resolution accepted a missing operation identity") + } + mismatchedIdentity := request + mismatchedIdentity.ResourceID = "vm-other-effect-fence" + if _, _, err := j.ResolveResourceFence(spec.OperationID, 42, mismatchedIdentity); !errors.Is(err, ErrFenceIdentityConflict) { + t.Fatalf("mismatched fence identity err=%v", err) + } + if state, err := j.FenceState(spec.OperationID); err != nil || state != FenceStateActive { + t.Fatalf("identity conflict released fence state=%q err=%v", state, err) } resolution, replayed, err := j.ResolveResourceFence(spec.OperationID, 42, request) if err != nil || replayed || resolution.OperationID != spec.OperationID || resolution.ResolvedBy != 42 { @@ -737,6 +1233,7 @@ func TestExpiredUnresolvedFenceRetainsPruneIndexUntilLateResolution(t *testing.T ResolutionID: "abcdefabcdefabcdefabcdefabcdefab", Resolution: FenceResolutionNotApplied, InspectionCheckedAt: now.Unix(), ReasonSHA256: "abababababababababababababababababababababababababababababababab", + Action: spec.Action, ResourceID: spec.ResourceID, RequestFingerprint: spec.Fingerprint, } if _, replayed, err := j.ResolveResourceFence(spec.OperationID, 42, request); err != nil || replayed { t.Fatalf("late fence resolution replayed=%v err=%v", replayed, err) @@ -758,6 +1255,8 @@ func TestFenceResolutionRequiresFreshInspectionAndActiveBlocker(t *testing.T) { ResolutionID: "fedcba9876543210fedcba9876543210", Resolution: FenceResolutionApplied, InspectionCheckedAt: now.Add(-3 * time.Minute).Unix(), ReasonSHA256: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + Action: "delete-vm", ResourceID: "vm-no-fence", + RequestFingerprint: Fingerprint("DELETE", "/v1/vms/vm-no-fence", []byte(`{}`)), } if _, _, err := j.ResolveResourceFence("operation-no-fence", 7, request); !errors.Is(err, ErrFenceInspectionStale) { t.Fatalf("stale inspection err=%v", err) @@ -766,11 +1265,15 @@ func TestFenceResolutionRequiresFreshInspectionAndActiveBlocker(t *testing.T) { if _, _, err := j.ResolveResourceFence("operation-no-fence", 7, request); !errors.Is(err, ErrNotFound) { t.Fatalf("missing operation err=%v", err) } - if _, _, err := j.Execute(context.Background(), testSpec("operation-clean-result", "vm-clean"), func(context.Context) (json.RawMessage, error) { + cleanSpec := testSpec("operation-clean-result", "vm-clean") + if _, _, err := j.Execute(context.Background(), cleanSpec, func(context.Context) (json.RawMessage, error) { return nil, testFailure{code: "clean_failure", message: "not applied", effect: false, safe: true} }); err == nil { t.Fatal("seed clean failure unexpectedly succeeded") } + request.Action = cleanSpec.Action + request.ResourceID = cleanSpec.ResourceID + request.RequestFingerprint = cleanSpec.Fingerprint if _, _, err := j.ResolveResourceFence("operation-clean-result", 7, request); !errors.Is(err, ErrFenceNotResolvable) { t.Fatalf("non-effectful failure err=%v", err) } @@ -793,8 +1296,8 @@ func TestSystemFenceResolutionUsesZeroAuditActorButRejectsNegativeActors(t *test now := time.Date(2026, 10, 19, 3, 30, 0, 0, time.UTC) j.SetClockForTesting(func() time.Time { return now }) spec := testSpec("operation-system-fence", "vm-system-fence") - spec.Action = "update-settings" - spec.Fingerprint = Fingerprint("POST", "/v1/vms/vm-system-fence/settings", []byte(`{}`)) + spec.Action = "delete-vm" + spec.Fingerprint = Fingerprint("DELETE", "/v1/vms/vm-system-fence", []byte(`{}`)) if _, _, err := j.Execute(context.Background(), spec, func(context.Context) (json.RawMessage, error) { return nil, testFailure{code: "result_unconfirmed", message: "effect may have applied", effect: true} }); err == nil { @@ -804,6 +1307,7 @@ func TestSystemFenceResolutionUsesZeroAuditActorButRejectsNegativeActors(t *test ResolutionID: "01230123012301230123012301230123", Resolution: FenceResolutionApplied, InspectionCheckedAt: now.Unix(), ReasonSHA256: "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + Action: spec.Action, ResourceID: spec.ResourceID, RequestFingerprint: spec.Fingerprint, } resolved, replayed, err := j.ResolveResourceFence(spec.OperationID, 0, request) if err != nil || replayed || resolved.ResolvedBy != 0 { @@ -811,14 +1315,19 @@ func TestSystemFenceResolutionUsesZeroAuditActorButRejectsNegativeActors(t *test } disallowed := testSpec("operation-system-delete-fence", "vm-system-delete-fence") + disallowed.Action = "future-unknown" + disallowed.Fingerprint = Fingerprint("POST", "/v1/future/vm-system-delete-fence", []byte(`{}`)) if _, _, err := j.Execute(context.Background(), disallowed, func(context.Context) (json.RawMessage, error) { return nil, testFailure{code: "result_unconfirmed", message: "effect may have applied", effect: true} }); err == nil { t.Fatal("seed system-disallowed failure unexpectedly succeeded") } request.ResolutionID = "23012301230123012301230123012301" + request.Action = disallowed.Action + request.ResourceID = disallowed.ResourceID + request.RequestFingerprint = disallowed.Fingerprint if _, _, err := j.ResolveResourceFence(disallowed.OperationID, 0, request); !errors.Is(err, ErrFenceNotResolvable) { - t.Fatalf("system actor resolved non-settings fence: %v", err) + t.Fatalf("system actor resolved unknown-action fence: %v", err) } var successorCalls atomic.Int32 successor := testSpec("operation-after-system-delete-fence", disallowed.ResourceID) @@ -841,6 +1350,45 @@ func TestSystemFenceResolutionUsesZeroAuditActorButRejectsNegativeActors(t *test } } +func TestSystemRecoveryActionAllowlistIsExplicit(t *testing.T) { + allowed := []string{ + "power-start", "power-shutdown", "power-reboot", "power-reset", "power-destroy", + "reinstall-vm", + "enter-rescue", "force-start-rescue", "exit-rescue:connected", "exit-rescue:suspended", + "change-network", "network-suspend", "network-resume", + "update-settings", "apply-firewall", + "delete-vm", "force-delete-vm", + "service-suspend", + "create-snapshot:0123456789abcdef0123456789abcdef:filesystem", + "create-snapshot:0123456789abcdef0123456789abcdef:crash", + "delete-snapshot:0123456789abcdef0123456789abcdef", + "restore-snapshot:0123456789abcdef0123456789abcdef", + "import-template", "update-template", "delete-template", + "import-rescue-template", "delete-rescue-template", + "import-user-iso", "delete-user-iso", + } + for _, action := range allowed { + if !SystemRecoveryActionAllowed(action) { + t.Errorf("reviewed action %q was rejected", action) + } + } + + denied := []string{ + "", "create-vm", "configure-storage", "service-resume", "future-unknown", "power-future", + "exit-rescue:future", + "create-snapshot:0123456789abcdef0123456789abcdef:future", + "create-snapshot:0123456789ABCDEF0123456789ABCDEF:filesystem", + "delete-snapshot:0123456789abcdef0123456789abcde", + "restore-snapshot:0123456789abcdef0123456789abcdef:extra", + "import-template:future", + } + for _, action := range denied { + if SystemRecoveryActionAllowed(action) { + t.Errorf("unreviewed action %q was accepted", action) + } + } +} + func TestSuccessfulForceSuccessorOnlyRemovesPredecessorBlockerIndex(t *testing.T) { j := openTestJournal(t) predecessor := testSpec("operation-graceful-predecessor", "vm-force-successor") diff --git a/docs/ADMIN_OPERATIONS.md b/docs/ADMIN_OPERATIONS.md index 158fc04f..3ae5bc1c 100644 --- a/docs/ADMIN_OPERATIONS.md +++ b/docs/ADMIN_OPERATIONS.md @@ -6,10 +6,10 @@ - 提交接口只在任务已经持久化后返回 HTTP `202 Accepted`。这表示“任务已接收”,不表示宿主机操作成功。 - 每个任务最多派发一次。派发前拒绝、派发后断线、Agent 超时、worker 退出和回执截止都会在固定期限内落为 `failed`,不会重新排队。 -- 终态只有 `succeeded`、`failed`,一旦写入便不可改变。晚到回执不能翻转任务、退款或重放资源变更;当前仅 `instance_settings` 的精确成功回执或明确无副作用的失败回执,可通过种类专用终结器收敛 PHP 账本并解除 effect fence,原任务仍保持 `failed`。 +- 终态只有 `succeeded`、`failed`,一旦写入便不可改变。晚到回执不能翻转任务、退款或重放资源变更;策略表覆盖的实例电源、重装/救援、公网 IP、实例设置、快照、防火墙、删除/强制删除、生命周期网络、模板与 ISO 叶子任务,可以用精确回执或 operation-bound 只读证据通过种类专用终结器收敛 PHP 账本并解除 effect fence,原任务仍保持 `failed`。 - `effect_may_have_applied=true` 表示底层副作用可能已经发生。任务本身仍然已经结束;破坏性操作的相关资源继续被安全栅栏保护,新的冲突请求会立即返回错误,不会排队等待。固定存储池配置是非破坏性的例外:保留失败证据但不保留跨任务栅栏,可按已定义 pool 的同一路径,或只修正尚未定义的角色后显式创建新任务。 - 普通用户和管理员界面均不提供任务重试按钮。需要再次执行时,必须先完成只读核验和人工处置,再创建一个经过重新授权的新任务。 -- 只有具备种类专用业务账本终结器的失败任务才能解除栅栏。实例设置可消费同一 Agent operation 的不可变成功回执;开通只允许用新鲜缺失证据确认 `not_applied`,并原子退款与释放资源;支付根据签名回调或管理员已在外部平台核验的证据收敛本地账本。其他类型当前拒绝假解锁,但任务本身已是终态失败,不会继续占用 worker 或重试。 +- 只有具备种类专用业务账本终结器的失败任务才能解除栅栏。上述策略类型会一直保留在低频恢复队列,不受六小时、十二次或其他累计预算限制。Agent 离线、回执错误、操作身份冲突、密文损坏和实例/账本状态矛盾都只会保留安全栅栏并显示具体异常,修复根因后同一 operation 继续核对。开通只允许用新鲜缺失证据确认 `not_applied`,并原子退款与释放资源;支付根据签名回调或管理员已在外部平台核验的证据收敛本地账本。 ## 管理操作 @@ -30,7 +30,7 @@ POST /api/v1/admin/operations/jobs/{id}/force-delete 2. `resolve-effect` 只允许超级管理员在完成新鲜证据核验后使用。开通路径可向 Agent 写入一次不调用 libvirt 的审计栅栏元数据,然后在 PHP 同一事务完成退款和资源释放;响应丢失时只做一次只读核验,不重发写请求。支付路径不联系 Agent 或重新向渠道下单。原任务始终保持 `failed`。 3. `force-delete` 是单独授权的新破坏性任务。它需要既有正常删除任务已经明确返回 `force_required`,并要求超级管理员再次确认数据丢失风险;它不能由超时、失联或仅看到 Domain 仍在运行自动产生。 -已经删除的通用旧恢复入口——重放 mutation、确认旧检查结果、中止 libvirt job、自动清理残留——不得重新加入路由或前端。内部只读恢复只对具有种类专用账本终结器的 `instance_settings` 开放,且只能写 Agent 栅栏审计元数据;原任务仍作为不可变审计记录保留。 +已经删除的通用旧恢复入口——重放 mutation、确认旧检查结果、中止 libvirt job、自动清理残留——不得重新加入路由或前端。内部只读恢复只对显式策略表中、具有种类专用账本终结器的 Agent 叶子任务开放,且只能写与原操作三元身份精确匹配的 Agent 栅栏审计元数据;原任务仍作为不可变审计记录保留。 ## 运行状态 diff --git a/docs/AGENT_API.md b/docs/AGENT_API.md index 12bcf014..3de5163f 100644 --- a/docs/AGENT_API.md +++ b/docs/AGENT_API.md @@ -4,7 +4,7 @@ ## 传输 -- Agent 使用数字 `agent_id` 与独立 `agent_secret` 主动连接 `WSS /agent/connect`,子协议固定为 `virt-agent-control.v2`。v2 包含不可变完成回执;Agent 与 Gateway 不提供 v1 兼容或协商降级,任一侧版本不一致必须在握手阶段失败。Gateway 必须通过 PHP 内部接口认证连接。 +- Agent 使用数字 `agent_id` 与独立 `agent_secret` 主动连接 `WSS /agent/connect`,子协议固定为 `virt-agent-control.v3`。v3 的不可变完成回执必须携带操作三元身份;Agent 与 Gateway 不提供 v1/v2 兼容或协商降级,任一侧版本不一致必须在握手阶段失败。Gateway 必须通过 PHP 内部接口认证连接。 - PHP 把已签名的内层 API 请求发送到 Gateway 字面 loopback 的 `POST /internal/agent/request`。Gateway 不改写 method、request target、body 或内层认证头。 - 控制请求帧为 `request`,即时响应帧为 `response`;帧 ID 只负责当前连接的配对,不是业务幂等键。 - mutation 的即时响应只说明 Agent 已接收或已明确拒绝。Agent 在独立 helper 中执行一次,并通过单独的 `completion` 帧发送不可变终态回执。 @@ -36,7 +36,7 @@ actor 普通字段如下;只读请求可省略 `operation_id`,mutation 必 } ``` -面板内部的超时设置恢复可以使用一个保留 actor,它没有人类管理员权限,并且严格绑定一个 operation: +面板内部对已派发、已失败但影响未知的允许类型进行恢复核对时,可以使用一个保留 actor。它没有人类管理员权限,并且严格绑定一个 operation: ```json { @@ -49,7 +49,7 @@ actor 普通字段如下;只读请求可省略 `operation_id`,mutation 必 } ``` -该 actor 只能访问同一 `operation_id` 的 `GET inspect`、`GET fence-resolution` 和 `POST resolve-fence`;不能访问健康、能力、资源列表、原始 Journal 或任何 libvirt/catalog/storage mutation。`resolve-fence` 只持久化该 operation 的审计结论并移除其 admission 索引,不调用 libvirt,也不继续或重放原操作。 +该 actor 只能访问同一 `operation_id` 的 `GET inspect`、`GET fence-resolution` 和 `POST resolve-fence`,而且 Agent 还会按显式 action allowlist 再次授权;不能访问健康、能力、资源列表、原始 Journal 或任何 libvirt/catalog/storage mutation。`inspect`、完成回执和 `resolve-fence` 都必须同时匹配不可变的 `action + resource_id + request_fingerprint`。`resolve-fence` 只持久化该 operation 的审计结论并移除其 admission 索引,不调用 libvirt,也不继续或重放原操作。 canonical bytes 为六段原值用一个 LF 连接,末尾没有 LF: @@ -73,6 +73,9 @@ PHP 在提交给 Gateway 前已经持久化任务、请求指纹、唯一 `opera ```json { "operation_id": "0123456789abcdef0123456789abcdef", + "action": "power-reboot", + "resource_id": "123e4567-e89b-42d3-a456-426614174000", + "request_fingerprint": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", "status": "dispatching", "replayed": false, "retryable": false @@ -88,6 +91,9 @@ helper 结束后 Agent 写入唯一完成记录,并通过 WSS 发送: "type": "completion", "id": "immutable-event-id", "operation_id": "0123456789abcdef0123456789abcdef", + "action": "power-reboot", + "resource_id": "123e4567-e89b-42d3-a456-426614174000", + "request_fingerprint": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", "status": "failed", "effect_may_have_applied": true, "safe_to_resubmit": false, @@ -98,9 +104,9 @@ helper 结束后 Agent 写入唯一完成记录,并通过 WSS 发送: Gateway 只接受当前已认证 session 的事件,并自行注入该连接的 `agent_id`,用 Gateway-PHP 密钥签名后 POST `/api/internal/cloud/operation-completion`。PHP 按 agent、operation、事件 ID 和正文摘要幂等接收;成功处理后 Gateway 返回 `completion_ack`。ACK 只删除 Agent outbox,不能删除 Journal tombstone。 -Agent 与 Gateway 必须来自同一发布版本。健康检查和 capabilities 只验证经当前控制连接转发的 Agent API,不能替代 v2 握手;旧 Gateway 不允许以“健康但不能处理 completion”的形式继续承载任务。 +Agent 与 Gateway 必须来自同一发布版本。健康检查和 capabilities 只验证经当前控制连接转发的 Agent API,不能替代 v3 握手;旧 Gateway 不允许以“健康但不能处理 completion”的形式继续承载任务。 -回执只允许 `succeeded|failed`。成功必须没有错误码,且两个风险布尔值均为 false;失败必须有稳定错误码,`effect_may_have_applied=true` 时 `safe_to_resubmit` 必须为 false。相同事件可以在固定次数和绝对截止时间内重复投递,超过任一界限就停止。晚到回执不能翻转 PHP 终态或重放 mutation;当且仅当任务类型已登记幂等业务终结器时,精确同源回执才能在保留原 `failed` 审计记录的同时收敛 PHP 账本与 effect fence。 +回执只允许 `succeeded|failed`。成功必须没有错误码,且两个风险布尔值均为 false;失败必须有稳定错误码,`effect_may_have_applied=true` 时 `safe_to_resubmit` 必须为 false。相同事件在获得匹配 ACK 前按低频间隔持续投递;旧 outbox 中的 attempts 和 expires 字段不再淘汰回执。晚到回执不能翻转 PHP 终态或重放 mutation;当且仅当任务类型已登记幂等业务终结器时,精确同源回执才能在保留原 `failed` 审计记录的同时收敛 PHP 账本与 effect fence。 Go context 无法可靠中止已进入 CGo/libvirt 的调用。父 Agent 到达绝对截止后终止整个 helper 进程组并执行有界 `Wait`;未确认 helper 已退出时保留 durable execution fence。Agent 重启发现“已启动但没有完整回执”的 operation 时直接终态失败并保留栅栏,不再次执行。 @@ -171,7 +177,7 @@ Go context 无法可靠中止已进入 CGo/libvirt 的调用。父 Agent 到达 | GET/POST | `/v1/user-isos?owner_id=...` | 列出 / 导入用户 ISO | | DELETE | `/v1/user-isos/{id}?owner_id=...` | 删除用户 ISO | -不存在 mutation `reconcile`、`confirm-inspection`、`abort-job` 或 `cleanup` endpoint。`inspect` 不取得 mutation admission,不写 Journal,不继续原目标,也不能调用任何 libvirt 变更。不可变 Journal 成功或明确无副作用失败可以提供精确结论;已失败且影响未知的实例设置只有在 Domain metadata 与 NoCloud seed 都匹配同一 transition ID 时才是 `applied`,两者都确认未提交时才是 `not_applied`。电源、网络链路或服务的“当前状态刚好符合目标”不是原 operation 的强证据,必须保持 `inconclusive`。 +不存在 mutation `reconcile`、`confirm-inspection`、`abort-job` 或 `cleanup` endpoint。`inspect` 不取得 mutation admission,不写 Journal,不继续原目标,也不能调用任何 libvirt 变更。不可变 Journal 成功或明确无副作用失败可以为策略表中的任何类型提供精确结论;其他已失败且影响未知的类型只有在该 action 的专用投影证据完整匹配时才能输出 `applied/not_applied`,否则保持 `partial/inconclusive`。例如实例设置只有在 Domain metadata 与 NoCloud seed 都匹配同一 transition ID 时才是 `applied`,两者都确认未提交时才是 `not_applied`。电源、网络链路或服务的“当前状态刚好符合目标”不是原 operation 的强证据,必须保持 `inconclusive`。 ## 关键资源语义 diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index ddf8e942..a9ce5ec3 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -127,7 +127,7 @@ Agent 的 capabilities 响应仍使用 `network_selectors` 字段,但它是自 Agent 的 systemd 单元保持 `ProtectSystem=strict`。`journal_path` 必须位于已授权的 `/var/lib/virt-agent`;若确需另一个状态目录,应由运维通过 systemd drop-in 精确增加对应 `ReadWritePaths`。存储池内容仍只由独立的 libvirt/QEMU 服务通过 `qemu:///system` 管理,不能把受管存储池目录授权给 Agent。删除回查需要清理域定义消失后残留的 UUID 专属 VARS 文件,因此样例 unit 仅额外授权标准 `/var/lib/libvirt/qemu/nvram`;若 `nvram_directory` 使用其他路径,必须在 drop-in 中用该实际目录替换,并保持授权范围只覆盖 NVRAM 目录。capabilities 只确认该目录存在,不冒充对 systemd mount namespace 写权限的验证;正式上线仍须用授权的创建/删除验收确认权限。 -`journal_path` 是当前版本专用的 bbolt 数据库,不是可编辑 JSON;同目录的 `.traffic.json` 是流量状态,两者都要纳入一致性备份。Agent 会拒绝旧 schema,不执行升级或回填;全新安装必须使用空状态目录。Journal 在变更跨越派发边界前写入 operation tombstone,随后只允许这一次 worker 执行。Agent 重启若发现已启动但没有完整回执的 operation,会直接写入终态失败和执行栅栏,不会重新调用 libvirt。operation ID、指纹、资源、动作和终态永久保留用于防重放;完成回执的网络重发有固定次数和绝对截止时间,不会重新执行 mutation。 +`journal_path` 是当前版本专用的 bbolt 数据库,不是可编辑 JSON;同目录的 `.traffic.json` 是流量状态,两者都要纳入一致性备份。Agent 会拒绝旧 schema,不执行升级或回填;全新安装必须使用空状态目录。Journal 在变更跨越派发边界前写入 operation tombstone,随后只允许这一次 worker 执行。Agent 重启若发现已启动但没有完整回执的 operation,会直接写入终态失败和执行栅栏,不会重新调用 libvirt。operation ID、指纹、资源、动作和终态永久保留用于防重放;完成回执在收到精确 ACK 前按固定低频间隔持续重发,不会重新执行 mutation。 每个变更由独立 helper 进程打开自己的 libvirt 连接。父 Agent 到达绝对截止后终止整个 helper 进程组并执行有界 `Wait`;正常确认 helper 已退出后释放运行时 admission。若回收仍无法确认,Journal 会把任务终态化并释放进程内 admission:虚拟机和磁盘等破坏性操作继续由持久执行栅栏拒绝同资源的新 mutation;固定存储配置则由 helper 持有的宿主机非阻塞文件锁拒绝并发,旧进程真实退出时由内核自动释放。两类任务都不会长期保持运行中,固定存储任务也不会因旧失败留下永久栅栏。 @@ -160,7 +160,7 @@ systemctl enable --now virt-cloud-worker.service \ virt-cloud-policy-worker@1.service virt-cloud-policy-worker@2.service ``` -普通 worker 负责购买、创建、重装、邮件和最终删除;至少两个策略 worker 处理到期断网、网络恢复与删除前策略;lifecycle 生成续费账单并推进账期、流量、宽限和删除状态。`virt-cloud-recovery-worker.service` 是必需的独立实例设置恢复进程,只做 operation-bound inspection/栅栏审计或持久晚到回执的 PHP 收敛,不投递邮件,也绝不重放原设置 mutation。它与普通队列隔离,避免某个离线 Agent 的核对占住正常 worker。 +普通 worker 负责购买、创建、重装、邮件和最终删除;至少两个策略 worker 处理到期断网、网络恢复与删除前策略;lifecycle 生成续费账单并推进账期、流量、宽限和删除状态。`virt-cloud-recovery-worker.service` 是必需的独立 operation 恢复进程,覆盖策略表中的实例电源、重装/救援、公网 IP、实例设置、快照、防火墙、删除、生命周期网络、模板与 ISO Agent 叶子任务。它只做 operation-bound inspection/栅栏审计、持久晚到回执的 PHP 收敛或聚合父任务的本地汇总,不投递邮件,也绝不重放原 mutation。离线、身份冲突或账本异常按固定低频间隔持续核对,没有次数或总时长上限。它与普通队列隔离,避免某个离线 Agent 的核对占住正常 worker。 在面板机器构建并安装 Agent Gateway: @@ -176,7 +176,7 @@ install -o apache -g apache -m 0600 \ cp /home/virt-cloud/deploy/virt-cloud-agent-gateway.service /etc/systemd/system/ ``` -Agent 与 Gateway 控制子协议固定为 `virt-agent-control.v2`,不提供 v1 兼容或降级。每次发布必须先准备同一提交构建的 Agent 和 Gateway 二进制,再在同一发布窗口替换并重启两端。混用新旧二进制必须在 WSS 握手阶段失败,不允许出现“健康检查成功但丢弃完成回执”。 +Agent 与 Gateway 控制子协议固定为 `virt-agent-control.v3`,不提供 v1/v2 兼容或降级。每次发布必须先准备同一提交的 PHP 面板源码、Agent 和 Gateway 二进制,再在同一发布窗口更新三端并重启两个 Go 服务。混用新旧 Agent/Gateway 必须在 WSS 握手阶段失败;新 PHP 也会拒绝缺少 v3 操作身份的旧完成回执,不允许出现“健康检查成功但丢弃完成回执”。 启动前先编辑 Gateway runtime JSON,把 `REPLACE_ME` 占位符换成安全随机密钥,并在 PHP `config.php` 中配置完全一致的 `cloud_agent_gateway_secret`;`cloud_agent_gateway_url` 必须严格为 `http://127.0.0.1:8001/internal/agent/request`。占位符短于 32 字节,保留它会使服务拒绝启动。然后才启动: @@ -327,7 +327,7 @@ location = /agent/console { - 分别注入派发前拒绝、派发后断线、helper 超时、Agent 重启、Gateway 重启、PHP worker 重启和完成回执丢失;所有任务都必须在固定截止内进入 `succeeded` 或 `failed`,不能重新派发。 - 在明确授权的非生产宿主机重启实际启用的 `virtqemud` 或 `libvirtd`,确认 Agent 能恢复连接并重新注册 lifecycle、`JOB_COMPLETED` 和 close callback,但不会扫描或执行历史 mutation。重启 Agent 后,已启动而未留下完整回执的 operation 必须终态失败并保留 durable fence。 - 杀死超时 helper 后确认整个进程组已回收;只有 `Wait` 成功才释放资源 admission。不能回收时,新冲突请求必须立即被执行栅栏拒绝。 -- 重复、乱序和晚到完成回执不能改变终态或触发 mutation;允许类型的精确同源回执最多幂等收敛 PHP 副作用账本与 effect fence。回执发送超过固定次数或绝对截止后必须停止。 +- 重复、乱序和晚到完成回执不能改变终态或触发 mutation;允许类型的精确同源回执最多幂等收敛 PHP 副作用账本与 effect fence。回执在精确 ACK 前按固定低频间隔持续投递,旧 attempts/expires 不得使其永久退出 outbox。 - 并发购买不超卖 CPU/内存/磁盘/IP;同一 VM 变更串行。 - RX+TX 额度用尽只断网;下一账期恢复;最终到期只断网;三天宽限结束后删除定义与面板受管磁盘。 - MariaDB、Redis、SMTP、支付回调、大文件上传和 PHP-FPM 重启。 @@ -346,4 +346,4 @@ journalctl -u virt-cloud-agent-gateway.service -n 200 --no-pager 先区分 PHP 任务尚未派发、Gateway 未运行、Agent 出站 WSS 认证/网络失败、已派发但回执丢失、libvirt 明确失败和业务库提交失败。权限位与所有者不是应用层合规检查项;遇到启动错误应读取具体的“不可读、JSON 无效或字段无效”诊断,而不是盲目放宽权限。 -任何破坏性任务在派发后超时都会立即显示终态失败,同时保留原 `operation_id`、reservation、IP、账单和安全栅栏。可以进行独立只读检查,但不要重放旧任务、直接改库释放、自动退款或再次毁盘;人工收敛后只能通过审计的 effect resolution 解除栅栏。 +任何破坏性任务在派发后超时都会立即显示终态失败,同时保留原 `operation_id`、reservation、IP、账单和安全栅栏。独立 recovery worker 会持续执行只读核对并仅凭 operation-bound 证据收敛;不要重放旧任务、直接改库释放、自动退款或再次毁盘。异常时先修复页面所示的网络、身份、密文或账本根因,后续轮次会继续核对,只有审计的 effect resolution 提交后才解除栅栏。 diff --git a/docs/INTEGRATION_PLAN.md b/docs/INTEGRATION_PLAN.md index a5cbae1b..3a481272 100644 --- a/docs/INTEGRATION_PLAN.md +++ b/docs/INTEGRATION_PLAN.md @@ -69,9 +69,9 @@ Unix 时间戳 2. PHP worker 只领取 `dispatch_attempts=0` 且未超过绝对派发截止的任务。领取事务把计数原子改为 1,再向已绑定 Agent 派发一次;任何错误都直接终态失败,不能 requeue。 3. Agent 先取得 `domain`、`volume`、`nwfilter`、`catalog` 或 `storage-config` 资源准入,再原子写入派发边界。每个 mutation 由同一二进制的隐藏 worker 模式在独立子进程中执行,worker 使用自己的 libvirt 连接;主 Agent 不在进程内直接等待不可取消的 CGo 调用。 4. 主 Agent 对 worker 使用绝对截止、进程组 TERM/KILL 和有界 `Wait`。只有确认 worker 已退出后才释放运行时资源锁。截止、崩溃或重启直接持久化 `failed/result_unconfirmed`,不扫描、不续作、不重新调用原 mutation。 -5. Agent 通过完成 outbox 投递不可变回执。相同 `event_id` 可在固定次数和固定年龄内重复投递;PHP 按事件 ID、operation ID 与正文摘要幂等 ACK。回执传输截止后停止,不能形成无限请求。 -6. PHP 任务的公开终态只有 `succeeded` 和 `failed`。`receipt_deadline_at` 到期时直接失败;晚到回执不能翻转终态。策略表允许的 `instance_settings` 精确成功/无副作用失败回执,或同一 Agent operation 的新鲜只读双标记证据,可以幂等收敛 PHP 账本与内部 effect fence,但不会重放 mutation 或改写原任务结果。 -7. 失败且 `effect_may_have_applied=true` 时,任务已经结束,但破坏性操作对应的资源进入安全锁定。冲突请求立即失败而不是等待;系统不自动退款、释放 reservation 或再次执行。超级管理员完成独立只读检查及宿主机人工收敛后,只能通过审计动作解除资源锁,不能改变原任务结果。固定存储池配置不删除、不迁移也不改绑数据,因此失败只终止原 operation,不保留跨任务栅栏;后续只能按已定义 pool 的同一路径,或只修正尚未定义的角色后显式创建新任务,并继续由 `storage-config` 运行时准入及宿主机非阻塞文件锁串行。 +5. Agent 通过完成 outbox 投递不可变回执。相同 `event_id` 在收到精确 ACK 前按固定低频间隔持续投递;PHP 按事件 ID、operation ID、不可变操作身份与正文摘要幂等 ACK。历史 attempts/expires 只是兼容数据,不再淘汰未确认回执;低频退避防止空转,且投递回执永远不重放 mutation。 +6. PHP 任务的公开终态只有 `succeeded` 和 `failed`。`receipt_deadline_at` 到期时直接失败;晚到回执不能翻转终态。恢复策略表内的 22 类 Agent 叶子任务可消费精确成功/无副作用失败回执,或同一 Agent operation 的新鲜、种类专用只读证据,幂等收敛 PHP 账本与内部 effect fence,但不会重放 mutation 或改写原任务结果。模板与用户 ISO 的聚合父任务只从这些叶子任务的已知效果持续汇总。 +7. 失败且 `effect_may_have_applied=true` 时,任务已经结束,但破坏性操作对应的资源进入安全锁定。冲突请求立即失败而不是等待;在精确效果结论提交前,系统不退款、不释放 reservation、也不再次执行原操作。独立 recovery worker 会按固定低频间隔持续消费不可变回执或执行只读 inspection;Agent 离线、回执/身份冲突、密文损坏和账本状态矛盾都保留队列与具体异常,不受次数或总时长上限影响。管理员可以检查并修复根因,但只有 operation-bound 证据收敛后才解除资源锁。固定存储池配置不删除、不迁移也不改绑数据,因此失败只终止原 operation,不保留跨任务栅栏;后续只能按已定义 pool 的同一路径,或只修正尚未定义的角色后显式创建新任务,并继续由 `storage-config` 运行时准入及宿主机非阻塞文件锁串行。 同一 `operation_id` 和同一指纹只返回已存在的任务或终态;同一标识绑定不同请求必须拒绝。这个防重放规则不构成重试许可。 @@ -93,7 +93,7 @@ Agent 在连接前注册并持续运行 libvirt event loop;每个连接 genera PHP 的容量策略、reservation 和具体 IP 账本是调度事实源。Agent 仅执行已签名的目标网络配置并做宿主机最终校验,不通过全量扫描改变可售库存。 -每个支付周期拥有独立流量额度。RX 与 TX 都计费;额度耗尽或最终到期只持久断开网络,不改变 VM 电源。下一已付费周期开始后更新基线并恢复网络。未支付续费进入三天宽限,结束后才删除域定义及面板管理的磁盘。删除在回执截止前无法取得确定结果时,任务立即终态失败并保留账本占用;管理员完成宿主机人工收敛和审计解除前不得退款、释放或再次删除。 +每个支付周期拥有独立流量额度。RX 与 TX 都计费;额度耗尽或最终到期只持久断开网络,不改变 VM 电源。下一已付费周期开始后更新基线并恢复网络。未支付续费进入三天宽限,结束后才删除域定义及面板管理的磁盘。删除在回执截止前无法取得确定结果时,任务立即终态失败并保留账本占用;recovery worker 会持续核对同一 operation,只有确认效果并完成账本收敛后才释放,期间不得退款、释放或再次删除。 ## 控制台 diff --git a/docs/TASK_EXECUTION.md b/docs/TASK_EXECUTION.md index cf4336b6..7efbe4a1 100644 --- a/docs/TASK_EXECUTION.md +++ b/docs/TASK_EXECUTION.md @@ -26,9 +26,9 @@ accepted ──单次领取──> dispatching ──Agent 已接收──> awai └──> failed ``` -每个任务最多跨越一次派发边界。`dispatch_attempts` 的数据库约束为 `0..1`;worker、进程重启、租约过期、Gateway 断线和 HTTP 超时都不得把任务重新放回派发队列。绝对截止时间在任何层都不能因重新读取、页面刷新或服务重启而重置。 +每个任务最多跨越一次派发边界。`dispatch_attempts` 的数据库约束为 `0..1`;运行时只把 `0` 视为确定未派发、只把 `1` 视为合法已派发。若旧数据库、人工修库或损坏数据产生其他值,面板必须以 `recovery_dispatch_ledger_conflict` fail-closed:不采信或 ACK 回执、不访问 Agent 栅栏、不退款、不释放资源、不授权后续破坏性操作,并保留恢复密文和资源锁。页面显示具体异常,恢复 worker 按低频持续保留该任务。管理员必须依据真实派发记录把计数修复为 `1` 或 `0`;修改计数不会立即解锁,sticky repair incident 仍由后台重新验证不可变终态。修为 `1` 时,同一 operation 和同一不可变回执/只读证据继续收敛;修为 `0` 时只重跑 PHP 本地未派发终结器,绝不联系 Agent;若既有成功终态却被修为 `0`,系统将明确报告状态矛盾并继续锁定。任何路径都不重放 mutation。worker、进程重启、租约过期、Gateway 断线和 HTTP 超时都不得把任务重新放回派发队列。绝对截止时间在任何层都不能因重新读取、页面刷新或服务重启而重置。 -任务一旦终态即不可变。晚到的宿主机回执不能把 `failed` 改成 `succeeded`,也不能重写原任务的错误、结果、终态时间或完成事件编号。只有列入种类策略表、且具备幂等业务账本终结器的精确同源回执,才可以在不重放 mutation 的前提下收敛其副作用账本;当前 `instance_settings` 接受精确成功回执为 `applied`,也接受明确 `effect_may_have_applied=false` 的精确失败回执为 `not_applied`。两者都不会重放,且原任务仍为 `failed`。 +任务一旦终态即不可变。晚到的宿主机回执不能把 `failed` 改成 `succeeded`,派发账本异常也不能把既有 `succeeded` 改成 `failed`;两者都不能重写原任务的错误、结果、终态时间或完成事件编号。恢复异常通过独立的 `finalization_incident`、效果结论和资源锁表达,页面不能仅因原终态为成功就显示普通成功。只有列入种类策略表、且具备幂等业务账本终结器的精确同源回执,才可以在不重放 mutation 的前提下收敛其副作用账本。策略表覆盖实例电源、重装、救援、更换网络、实例设置、快照、防火墙、删除/强制删除、生命周期网络控制,以及模板、救援模板和用户 ISO 的 Agent 叶子任务;聚合父任务只根据子任务重新汇总。精确成功回执收敛为 `applied`,明确 `effect_may_have_applied=false` 的精确失败回执收敛为 `not_applied`。两者都不会重放,且原任务终态保持不变。 ## Agent 执行边界 @@ -45,11 +45,11 @@ Go context 不能可靠中止已经进入 CGo/libvirt 的调用,因此每个 ## 回执传输 -完成回执是不可变事件,不是新的变更请求。Agent 可以在有界次数和绝对截止时间内重复投递同一 `event_id`;PHP 以 `event_id`、`operation_id` 和正文摘要幂等接收。回执到达或超过投递截止后,Agent 必须停止发送。 +完成回执是不可变事件,不是新的变更请求。Agent 持续投递同一 `event_id`,直到 PHP 返回 ACK;重启、旧 outbox 中保存的尝试次数或历史过期时间都不能淘汰未确认回执。PHP 以 `event_id`、`operation_id` 和正文摘要幂等接收。ACK 只删除投递 outbox,不删除主 Journal 记录。 -PHP 的 `receipt_deadline_at` 到期时直接把任务终态化为失败。之后收到相同回执不能更新任务结果;不支持恢复的类型只返回晚到 ACK。对策略表允许的 `instance_settings`,精确匹配 `agent_id + operation_id + event_id + 正文摘要` 的成功回执会先以原加密请求收敛 PHP 凭据/主机名账本,再提交 `effect_resolution=applied`;明确无副作用的失败回执则收敛为 `not_applied`。该回执路径只使用 PHP 已持久化事件,不联系 Agent;任务结论与事件 ACK 在同一事务提交,结论提交后立即清除恢复密文。如果进程在事件提交后或预提交后崩溃,专用 recovery worker 会从 terminal job 出发,以已有 `(host_id,operation_id)` 唯一索引精确读取 `received` 事件,重算正文摘要后继续 PHP 提交;精确事件可以越过旧 inspection 的 `available_at` 退避及 `recovery_limit_reached/recovery_state_invalid` 普通领取排除而进入证据核验,但仍尊重当前租约。它只有在既有 prepared 证据同方向、同关键 operation hash 且明确不带活动 Agent fence 时才可继续纯 PHP 收敛;方向、哈希、栅栏语义或恢复状态冲突时,必须原子记录 `recovery_evidence_conflict`、终结该事件并保留 blocker/escrow,不能无限重试或覆盖旧证据。传输摘要有效但缺少 `instance_settings` 必需成功证明的回执立即记为 `recovery_receipt_invalid` 人工事件;密钥、本地账本或数据库异常则保持 `received` 并低频重试,修复后可继续收敛,但从 `received_at` 起最多 21600 秒,超限记为 `recovery_receipt_limit_reached` 并保留 blocker/escrow 供人工处置。它不扫描事件全表,也不依赖 Agent 再次投递。相同回执重传只返回幂等 ACK;不同正文复用事件 ID 或 operation ID 必须拒绝并记录安全日志。 +PHP 的 `receipt_deadline_at` 到期时直接把任务终态化为失败。之后收到相同回执不能更新原任务终态;除开通任务的精确成功回执专用路径外,不支持恢复的类型只返回晚到 ACK。对策略表允许的任务,精确匹配 `agent_id + operation_id + event_id + 正文摘要` 的成功回执会先以原加密请求收敛对应 PHP 业务账本,再提交 `effect_resolution=applied`;明确无副作用的失败回执则收敛为 `not_applied`。开通任务不进入通用 inspection、fence 或 mutation replay;只有已持久化且身份完全匹配的成功回执,才能在重新验证未退款订单、已支付开通发票、库存、IP、placement、服务周期和凭据 escrow 后原子补完本地账本。该回执路径只使用 PHP 已持久化事件,不联系 Agent;任务效果结论与事件 ACK 在同一事务提交,结论提交后立即清除恢复密文。如果进程在事件提交后或预提交后崩溃,专用 recovery worker 会从 terminal job 出发,以已有 `(host_id,operation_id)` 唯一索引精确读取 `received` 事件,重算正文摘要后继续 PHP 提交。它只有在既有 prepared 证据同方向、同完整 operation hash 且栅栏语义一致时才可继续收敛;方向、哈希、ID、栅栏语义、密文或账本状态冲突时,必须记录具体 `recovery_*` 异常并保留 blocker/escrow。异常事件可以被隔离,但任务仍按固定低频退避留在恢复队列,修复数据、身份、网络或 Agent 后继续核对;不存在 6 小时、12 次或其他永久退出上限。它不扫描事件全表,也不依赖 Agent 再次投递。相同回执重传只返回幂等 ACK;不同正文复用事件 ID 或 operation ID 必须拒绝并记录安全日志。 -任何回执或 inspection 改变 PHP 账本前,都必须使用同一套规则重新验证加密请求的 method、target、owner、body、settings fields 和 credential DTO;可解密但不完整的 escrow 不得以空账本假收敛。关键 operation hash 只绑定原请求实际消费的稳定字段,因此密码/公钥回执附带的当前 hostname 不会与已准备证据发生假冲突。如果恢复必须写 Agent 栅栏审计结论,该有界网络写入与随后的 PHP effect commit 必须在同一 job-row 锁下串行,写前再次验证租约、incident 和优先回执,防止陈旧 worker 在冲突证据落盘后解除 Agent fence。 +任何回执或 inspection 改变 PHP 账本前,都必须重新验证加密请求、任务/宿主机/资源身份,以及该种类终结器会消费的请求与结果字段;可解密但不完整的 escrow 不得以空账本假收敛。prepared 证据绑定规范化后的完整 operation;重试次数只属于调度状态,不参与 immutable operation hash,也不能破坏 prepare 后的崩溃续跑。如果恢复必须写 Agent 栅栏审计结论,该有界网络写入与随后的 PHP effect commit 必须在同一 job-row 锁下串行,写前再次验证租约、incident 和优先回执,防止陈旧 worker 在冲突证据落盘后解除 Agent fence。 `host_storage_configure` 使用更短且固定的专用边界:60 秒内必须跨越派发边界,Agent helper 最多执行 120 秒,PHP 最多等待终态回执 180 秒,浏览器 GET 观察最多 300 秒并在停止前做一次本地状态刷新。存储配置读取本身会先收敛已经越过绝对截止的关联任务;该过程只消费已持久化回执或写失败终态,不联系 Agent、不发送 PUT,也不重放 mutation。为使升级时已经存在的任务同样有界,存储任务的有效截止取数据库旧值与这些专用期限中的较早值。 @@ -61,14 +61,14 @@ PHP 的 `receipt_deadline_at` 到期时直接把任务终态化为失败。之 - 同一 VM、卷、网络过滤器、地址或账单的冲突变更立即返回明确错误,不进入等待队列; - 不自动退款、不释放 reservation、不再次删除磁盘; - 管理员可以执行独立的只读检查,但检查不会翻转原任务终态,也不会续作原 mutation; -- `instance_settings` 可以自动消费同一 operation 的不可变证据:晚到终态回执是纯 PHP 收敛;没有回执时,由独立的 `cloudWorker --recovery-only` 进程每轮最多领取一项,精确 `received` 事件优先,其余任务按 `available_at,id` 排序。普通/策略 worker 从不联系恢复目标,因此离线宿主的 30~120 秒核对不会阻塞正常派发。恢复使用绑定 operation ID 的 system-recovery actor 调用 Agent 只读 `inspect`,且只接受新鲜的双标记 `applied/not_applied` 证据。它先预提交 PHP 账本并继续保留 blocker;只有活动失败栅栏才写入一次 operation-bound 审计结论,再提交 `effect_resolution`。原设置 mutation 永不调用。`partial/inconclusive` 或 Agent 离线会保留 blocker 并持久低频退避;pending inspection 与 prepare 后 crash-resume 各有独立的 12 次或 21600 秒上限,任一先到即停止网络请求、保留恢复 escrow 并记录 `recovery_limit_reached`。之后到达的精确同 operation/hash/方向且与既有无栅栏 prepared 证据兼容的回执仍可纯 PHP 收敛并清除 incident;任何有效但相互矛盾的持久证据都转为一次性人工 incident,不猜测解锁; +- 策略表中的 Agent 叶子任务可以自动消费同一 operation 的不可变证据:晚到终态回执是纯 PHP 收敛;没有回执时,由独立的 `cloudWorker --recovery-only` 进程每轮最多领取一项,精确 `received` 事件优先,其余任务按 `available_at,id` 排序。普通/策略 worker 从不联系恢复目标,因此离线宿主的核对不会阻塞正常派发。恢复使用绑定 operation ID 的 system-recovery actor 调用 Agent 只读 `inspect`,且只接受新鲜、种类专用、资源身份一致的 `applied/not_applied` 证据。它先预提交 PHP 账本并继续保留 blocker;只有活动失败栅栏才写入一次 operation-bound Journal 审计结论,再提交 `effect_resolution`。原 mutation 永不调用。`partial/inconclusive`、Agent 离线、ID 冲突、无效回执、密文损坏或账本/实例状态矛盾都会保留 blocker,向页面公开具体异常,并按固定低频退避持续重检;没有次数和总时长上限。修复根因后,同一 operation 可继续自动收敛并清除 incident;相互矛盾的持久证据不得被覆盖或猜测解锁; - 超级管理员只能对已有种类专用原子终结器的任务提交审计结论。开通任务仅支持由新鲜宿主机缺失证据确认 `not_applied`,并在同一事务退款、释放库存/IP/预留后再解栅栏;支付任务只根据签名回调或外部支付平台审计证据收敛本地账本,不重新下单; - 没有专用终结器的类型必须拒绝“只改任务字段”的假解锁。它们的原任务仍已终态失败,但资金或资源保持 fenced,直到实现并验收对应的业务账本终结器; - 需要修复时创建一个经过人工判断的新操作,而不是复用或重放原任务。 固定存储池配置是非破坏性的窄例外:失败回执仍如实保留 `effect_may_have_applied`,原 operation ID 仍永久终止且不能重放,但它不形成跨任务资源栅栏。存储配置只做单调补全,已定义的固定 pool 不因后续失败而被 destroy、undefine 或回滚。管理员可以按已定义的同一路径,或只修正尚未定义的角色后显式创建新任务;新 operation 仍通过 `storage-config` 运行时准入和宿主机非阻塞文件锁串行,并且只核验或补全固定池,不改绑、迁移或删除数据。旧 helper 尚未退出时,新任务必须立即失败而不是等待,且不得自动重试或留下新的永久栅栏。 -如果业务账本终结器本身因损坏数据或数据库异常失败,公开任务仍必须落为 `failed`,并写入 `finalization_incident`。只有已注册自动终结器的 `instance_settings` 才在 `effect_resolution=unknown` 期间保留能通过当前密钥验证的密封请求作为隐藏恢复 escrow;其他种类即使效果未知或出现 finalization incident 也立即脱敏。一旦确认 `applied/not_applied`,设置 escrow 也立即改写为脱敏审计载荷;无法验证的密文直接清除。除上述固定存储池配置例外外,资金与资源栅栏继续保留,并向管理端显示需要修复账本的事件。它绝不会为了让任务看起来成功而猜测退款、释放或重放 mutation。 +如果业务账本终结器本身因损坏数据或数据库异常失败,公开任务仍必须落为 `failed`,并写入 `finalization_incident`。所有已注册自动终结器的策略种类在 incident 未清除期间都保留原始密封请求作为隐藏恢复 escrow;这既包括已派发且效果仍为 `unknown` 的任务,也包括 `dispatch_attempts=0`、宿主机效果已确定为 `not_applied`、但 PHP 业务账本回滚尚未提交的任务。后者由 recovery-only worker 只重跑同一种类的 PHP 终结器,不进行 Agent 检查或 mutation;成功后原子清除 incident、将 escrow 改写为脱敏审计载荷,并保留原终态审计字段。失败时按固定低频继续尝试,不能热循环。无法验证或不完整的密文不能假收敛、清空原密文或把任务永久移出恢复队列,而应显示 `recovery_payload_unavailable` 并等待密钥/数据修复。除上述固定存储池配置例外外,资金与资源栅栏继续保留。恢复器绝不会为了让任务看起来成功而猜测退款、释放或重放 mutation。 这一区分同时满足可用性和安全性:用户不会看到永久运行的任务,worker 不会永久占用槽位,而未知破坏性副作用也不会被自动重复执行。 @@ -82,7 +82,9 @@ PHP 的 `receipt_deadline_at` 到期时直接把任务终态化为失败。之 - 在派发前失败、派发后超时、worker 崩溃、Agent 崩溃、Gateway 断线和 PHP 重启场景中,任务都在固定截止内进入终态。 - 截止后执行槽、资源锁、WSS pending map、数据库租约和浏览器 busy 状态全部释放。 - 终态回执重复、乱序或晚到不能改变已终态任务,也不能触发 mutation;允许类型的精确晚到回执只能幂等收敛副作用账本与 effect fence。 -- 公共任务 API 和任务中心不把 `partial/inconclusive` 暴露为新任务状态,也不存在自动重试 mutation 语义;资源账本可以保留内部安全栅栏状态,任务始终显示原来的失败终态。`instance_settings` 的证据驱动收敛不是任务重试,也不会重新执行宿主机变更。 +- 非法派发计数及其修复后的 sticky incident 在后台复核完成前始终阻断同资源操作;既有成功终态保持成功审计,但 UI 必须显示恢复异常而不能触发普通成功回调。 +- `dispatch_attempts=0` 的本地终结器异常只重试 PHP 业务账本,第二次 tick 不重复已提交副作用;无效回执、密文或身份冲突的 receipt-priority 路径必须遵守低频退避,不能形成 hot loop。 +- 公共任务 API 和任务中心不把 `partial/inconclusive` 暴露为新任务状态,也不存在自动重试 mutation 语义;资源账本可以保留内部安全栅栏状态,任务始终显示原来的失败终态。策略种类的证据驱动收敛不是任务重试,也不会重新执行宿主机变更;页面必须同时说明正在持续核对及当前具体异常。 - 真实非生产 libvirt 宿主机必须验证:被终止 worker 不残留、后续独立任务仍可执行,以及 reboot/reset/shutdown 的成功判定来自明确证据而非仅观察“仍在运行”。 ## 设计依据 diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 92ca017e..601a8cf7 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -41,13 +41,14 @@ jq empty deploy/*.json.example - HTTP mutation 在数据库任务提交后立即返回 `202`、`task_id`、`status_url`,不等待宿主机完成。 - 相同幂等键和相同指纹只返回原任务;不同指纹复用键被拒绝。 - `dispatch_attempts` 永远不超过 1;租约过期、worker/Agent/Gateway 重启和 HTTP 超时都不会把 mutation 放回队列。 +- 运行时故障注入 `dispatch_attempts=-1/2`(以及可模拟时的 NULL/非整数)必须 fail-closed:任务和聚合父任务继续阻断,回执保持 `received` 且不 ACK,Agent 调用次数为 0,恢复密文不清除,用户与管理员页面显示 `recovery_dispatch_ledger_conflict`。修回 `1` 后同一回执或只读证据可继续收敛;修复前不得手工解栅栏、退款、强制删除或提交重叠模板/ISO/救援目录操作。 - 进行中 DTO 只有 `completed:false`;完成 DTO 只有 `completed:true` 与 `succeeded|failed`。 - GET 列表、详情、任务观察、管理员检查和健康检查都不会修改任务或联系 mutation 端点。 - 显式 `/tasks/read` 只更新可见的已完成任务;读取失败不自动重试。 -- 终态不可变;重复、乱序和晚到回执不能改变任务或触发 mutation。`instance_settings` 的精确晚到成功/无副作用失败回执只允许幂等收敛账本和 effect fence;不同 event、operation 或正文必须拒绝。 +- 终态不可变;重复、乱序和晚到回执不能改变任务或触发 mutation。策略表中所有 Agent 叶子任务的精确晚到成功/无副作用失败回执只允许幂等收敛账本和 effect fence;不同 event、operation 或正文必须拒绝,并保留任务供后续只读恢复。 - Agent 完成事件严格绑定当前 WSS 会话的 `agent_id`、`operation_id` 和正文摘要;事件 ID 或 operation ID 携带不同正文必须拒绝。 -- Agent 与 Gateway 只接受 `virt-agent-control.v2`;任一侧使用旧控制协议时握手必须失败,不能通过健康检查后再丢弃完成回执。 -- 回执传输只有固定次数与绝对截止时间,ACK 只删除 outbox,不删除主 Journal tombstone。 +- Agent 与 Gateway 只接受 `virt-agent-control.v3`;任一侧使用旧 v1/v2 控制协议时握手必须失败,不能通过健康检查后再丢弃完成回执。 +- 回执传输在收到 ACK 前持续进行;旧 attempts/expires 元数据不能淘汰 outbox。ACK 只删除 outbox,不删除主 Journal tombstone。 ## 3. 底层执行与故障注入 @@ -60,16 +61,16 @@ jq empty deploy/*.json.example 5. helper 超时:父进程 TERM/KILL 整个进程组并执行有界 `Wait`;确认回收后才释放 admission。 6. helper 无法回收:任务仍终态失败;VM、磁盘等破坏性操作的执行栅栏继续立即拒绝相同资源的新 mutation。固定存储池配置保留失败证据但不得形成跨任务栅栏。 7. Agent/Gateway/PHP worker 分别重启:任务不重派,数据库租约和浏览器 busy 状态均在固定截止内释放。 -8. 完成 endpoint 连续失败:同一个不可变事件最多发送配置中的固定次数,并在绝对截止后停止。 +8. 完成 endpoint 连续失败:同一个不可变事件持续低频重投;Agent 重启后仍保留,只有收到匹配 ACK 才删除 outbox。 9. 存储配置专用边界:派发 60 秒、helper 120 秒、回执 180 秒;旧记录即使保存了更长通用截止,也按较早的有效截止失败并允许新的独立 operation。 -10. 实例设置恢复: - - 晚到成功与明确无副作用失败回执分别收敛 `applied/not_applied`;无回执时用新鲜 Agent inspection 双标记做同样收敛。任务必须保持原 `failed`、原错误、结果、终态时间和 `completion_event_id`。 +10. 策略种类恢复(实例电源、重装、救援、网络/设置、快照、防火墙、删除、生命周期网络控制、模板、救援模板和用户 ISO): + - 晚到成功与明确无副作用失败回执分别收敛 `applied/not_applied`;无回执时用新鲜、种类专用、operation-bound 的 Agent inspection 做同样收敛。任务必须保持原 `failed`、原错误、结果、终态时间和 `completion_event_id`。 - 精确持久回执可以在接收入口同步做纯 PHP 收敛;只有需联系 Agent 的 inspection/fence 恢复才能由独立 `--recovery-only` worker 执行。普通/策略 worker 不得联系恢复目标;recovery worker 每轮最多公平处理一项。 - - PHP 先预提交账本并继续保持 blocker。活动失败栅栏的 Agent 审计写入必须和 PHP effect commit 在同一 job-row 锁下串行,且写前重验租约、incident 和 `received` 事件;原设置 mutation 调用次数仍为 1。 - - `partial/inconclusive` 与 Agent 离线必须持久低频退避。pending inspection 与 prepared crash-resume 各自最多 12 次或 21600 秒;耗尽后停止网络请求、保留 blocker/escrow 并记录 incident。 - - 测试必须覆盖第 12 次 pending 刚完成 prepare 时重置独立预算、fence POST 响应丢失后 GET 恢复、prepared 阶段耗尽、精确晚到回执覆盖匹配且无活栅栏的 exhausted prepared intent,以及 event 持久化后/prepare 后崩溃且无 Agent 重投时的续跑。任务 effect commit 与事件 `applied` ACK 必须同事务提交。 - - received event 必须从 terminal job 做 `(host_id,operation_id)` 相关索引查询并重算 `payload_sha256`。无效摘要直接拒绝;方向、关键 operation hash 或 fence 语义冲突时原子落为 `recovery_evidence_conflict`,保留 blocker/escrow/prepared 证据并不再领取。关键 operation hash 只包含原请求真正消费的设置字段,密码/公钥操作回执附带的当前 hostname 不得造成假冲突。 - - kind-specific 成功证明缺失时立即落为 `recovery_receipt_invalid`。加密请求、本地账本或数据库异常允许修复后重试,但从 `received_at` 起不得超过 21600 秒,退避也不得越过截止;耗尽后终结为 `recovery_receipt_limit_reached` 且不再自动领取。 + - PHP 先预提交账本并继续保持 blocker。活动失败栅栏的 Agent 审计写入必须和 PHP effect commit 在同一 job-row 锁下串行,且写前重验租约、incident 和 `received` 事件;原 mutation 调用次数仍只能为 0 或 1。 + - `partial/inconclusive`、Agent 离线、认证失败、operation/ID 冲突、无效回执、密文损坏、账本或实例状态矛盾都必须持久低频退避;不得因 6 小时、12 次、历史 attempts/expires 或任何累计预算停止领取。 + - 测试必须覆盖超过 12 次和超过 21600 秒后继续 inspection、fence POST 响应丢失后 GET 恢复、prepared crash-resume、精确晚到回执覆盖匹配且无活栅栏的 prepared intent,以及 event 持久化后/prepare 后崩溃且无 Agent 重投时的续跑。任务 effect commit 与事件 `applied` ACK 必须同事务提交。 + - received event 必须从 terminal job 做 `(host_id,operation_id)` 相关索引查询并重算 `payload_sha256`。无效摘要直接拒绝;方向、完整 operation hash 或 fence 语义冲突时原子落为 `recovery_evidence_conflict`,保留 blocker/escrow/prepared 证据;隔离该异常事件后,job 仍必须按退避再次领取,不能覆盖冲突证据。 + - kind-specific 成功证明缺失时记录 `recovery_receipt_invalid`;加密请求、本地账本、数据库或资源状态异常记录对应 `recovery_*` 代码。所有异常都必须在任务中心/管理页面显示具体中文说明,并在根因修复后继续同一 operation 的安全收敛。 测试必须覆盖不相交资源并行、相同资源拒绝、存储配置运行时串行但终态失败后允许新 operation、旧存储 blocker 派生索引的原子清理、存储配置非阻塞进程锁的 busy/释放行为、角色中途失败后同路径新任务单调补全且不回滚、重 I/O 容量限制、nonce 防重放、operation 指纹冲突、Journal schema 不匹配拒绝启动,以及 `.traffic.json` 跨 helper 进程的文件锁。 diff --git a/gateway/README.md b/gateway/README.md index a45f6ba4..4698bce1 100644 --- a/gateway/README.md +++ b/gateway/README.md @@ -51,7 +51,7 @@ The gateway listens only on `127.0.0.1:8001`. The public reverse proxy exposes not expose `POST /internal/agent/request`. An Agent opens `/agent/connect` with `X-Virt-Agent-ID`, `Authorization: Bearer -`, and the exact `virt-agent-control.v2` subprotocol. The +`, and the exact `virt-agent-control.v3` subprotocol. The gateway validates those credentials through the fixed loopback PHP endpoint `/api/internal/cloud/agent-auth`. It retains the presented secret only in that live session's memory and revalidates it before every ordinary dispatch or @@ -60,10 +60,10 @@ signed request envelope to the loopback-only `/internal/agent/request`; the gateway sends it to the live Agent and returns the Agent's exact HTTP status and JSON body. Control frames are bounded JSON text frames: -The v2 subprotocol is a clean break that includes immutable completion frames. -There is no v1 negotiation or compatibility mode: an old Agent or Gateway must -fail the WebSocket handshake instead of appearing healthy while dropping a -terminal receipt. Deploy the Agent and Gateway binaries from the same release. +The v3 subprotocol is a clean break that includes immutable completion frames. +There is no v1 or v2 negotiation or compatibility mode: an old Agent or Gateway +must fail the WebSocket handshake instead of appearing healthy while dropping +a terminal receipt. Deploy the Agent and Gateway binaries from the same release. ```json {"type":"request","id":"...","method":"POST","request_target":"/v1/...","body":"{...}","headers":{"X-Virt-Actor":"..."}} @@ -74,15 +74,16 @@ Failures proven to occur before the host's durable operation journal carry the exact error field `"dispatch_state":"not_dispatched"`. Mutation requests are never automatically requeued, including when that marker is present; callers must create a new operation explicitly. Terminal completion receipts use a -separate bounded delivery outbox and an eight-event ACK-driven window. The +separate durable delivery outbox and an eight-event ACK-driven window. The Gateway stops reading additional completion events while that window is full; it never silently drops an event. It returns `completion_ack` only after PHP responds with strict JSON `{"accepted":true,"disposition":"applied|late|rejected"}`. `received`, malformed JSON, unknown fields, trailing data, a non-JSON content type, or a delivery error produces `completion_retry` instead, leaving the -durable event pending for its bounded retry interval. Events may be -retransmitted only until their attempt limit or absolute expiry. Gateway or -Agent nonce replay errors deliberately omit the marker because the first +durable event pending for a later retry. Delivery age and attempt count never +discard a completion event: the Agent keeps retransmitting it at a bounded +rate until PHP returns an exact terminal ACK. Gateway or Agent nonce replay +errors deliberately omit the marker because the first request may already have been dispatched. Resolving an effect fence is a separate, explicit super-administrator action: diff --git a/gateway/agent/completion.go b/gateway/agent/completion.go index d0fdab7c..8aba5df0 100644 --- a/gateway/agent/completion.go +++ b/gateway/agent/completion.go @@ -29,7 +29,7 @@ type completionAcceptance struct { } // HTTPCompletionSink performs exactly one bounded delivery attempt. Retry -// policy belongs to the Agent's durable, attempt-limited outbox. +// policy belongs to the Agent's durable, ACK-driven outbox. type HTTPCompletionSink struct { endpoint string secret []byte @@ -72,6 +72,9 @@ func (s *HTTPCompletionSink) Deliver(ctx context.Context, agentID string, comple ID string `json:"id"` AgentID string `json:"agent_id"` OperationID string `json:"operation_id"` + Action string `json:"action"` + ResourceID string `json:"resource_id"` + RequestFingerprint string `json:"request_fingerprint"` Status string `json:"status"` EffectMayHaveApplied bool `json:"effect_may_have_applied"` SafeToResubmit bool `json:"safe_to_resubmit"` @@ -79,7 +82,9 @@ func (s *HTTPCompletionSink) Deliver(ctx context.Context, agentID string, comple Result json.RawMessage `json:"result"` }{ Type: "completion", ID: completion.ID, AgentID: agentID, OperationID: completion.OperationID, - Status: completion.Status, EffectMayHaveApplied: completion.EffectMayHaveApplied, + Action: completion.Action, ResourceID: completion.ResourceID, + RequestFingerprint: completion.RequestFingerprint, + Status: completion.Status, EffectMayHaveApplied: completion.EffectMayHaveApplied, SafeToResubmit: completion.SafeToResubmit, ErrorCode: completion.ErrorCode, Result: completion.Result, }) diff --git a/gateway/agent/completion_test.go b/gateway/agent/completion_test.go index c73dd6b5..dbf46e90 100644 --- a/gateway/agent/completion_test.go +++ b/gateway/agent/completion_test.go @@ -50,7 +50,9 @@ func TestHTTPCompletionSinkUsesExactPanelContractAndGatewayIdentity(t *testing.T })} completion := Completion{ Type: "completion", ID: "completion_event_123", OperationID: "operation_terminal_123", - Status: "failed", ErrorCode: "result_unconfirmed", Result: json.RawMessage("null"), + Action: "delete-vm", ResourceID: "vm-completion-123", + RequestFingerprint: strings.Repeat("a", 64), + Status: "failed", ErrorCode: "result_unconfirmed", Result: json.RawMessage("null"), EffectMayHaveApplied: true, } if err := sink.Deliver(context.Background(), "42", completion); err != nil { @@ -63,7 +65,10 @@ func TestHTTPCompletionSinkUsesExactPanelContractAndGatewayIdentity(t *testing.T if err := json.Unmarshal(capturedBody, &payload); err != nil { t.Fatal(err) } - wantKeys := []string{"type", "id", "agent_id", "operation_id", "status", "effect_may_have_applied", "safe_to_resubmit", "error_code", "result"} + wantKeys := []string{ + "type", "id", "agent_id", "operation_id", "action", "resource_id", "request_fingerprint", + "status", "effect_may_have_applied", "safe_to_resubmit", "error_code", "result", + } if len(payload) != len(wantKeys) { t.Fatalf("completion keys = %#v body=%s", payload, capturedBody) } @@ -73,7 +78,10 @@ func TestHTTPCompletionSinkUsesExactPanelContractAndGatewayIdentity(t *testing.T } } if string(payload["type"]) != `"completion"` || string(payload["id"]) != `"completion_event_123"` || - string(payload["agent_id"]) != `"42"` || string(payload["result"]) != "null" { + string(payload["agent_id"]) != `"42"` || string(payload["action"]) != `"delete-vm"` || + string(payload["resource_id"]) != `"vm-completion-123"` || + string(payload["request_fingerprint"]) != `"`+strings.Repeat("a", 64)+`"` || + string(payload["result"]) != "null" { t.Fatalf("completion payload = %s", capturedBody) } if _, legacy := payload["event_id"]; legacy { @@ -93,7 +101,9 @@ func TestHTTPCompletionSinkUsesExactPanelContractAndGatewayIdentity(t *testing.T func TestHTTPCompletionSinkRequiresExactTerminalAcceptance(t *testing.T) { completion := Completion{ Type: "completion", ID: "completion_event_strict", OperationID: "operation_terminal_strict", - Status: "succeeded", Result: json.RawMessage(`{"done":true}`), + Action: "delete-vm", ResourceID: "vm-completion-strict", + RequestFingerprint: strings.Repeat("b", 64), + Status: "succeeded", Result: json.RawMessage(`{"done":true}`), } tests := []struct { name string @@ -171,7 +181,9 @@ func TestCompletionDeliveryACKsOnlyTerminalPanelAcceptance(t *testing.T) { } completion := Completion{ Type: "completion", ID: "completion_disposition_123", OperationID: "operation_disposition_123", - Status: "succeeded", Result: json.RawMessage(`{"done":true}`), + Action: "delete-vm", ResourceID: "vm-completion-disposition", + RequestFingerprint: strings.Repeat("c", 64), + Status: "succeeded", Result: json.RawMessage(`{"done":true}`), } registry.deliverCompletion(context.Background(), current, completion) select { @@ -202,7 +214,9 @@ func TestRegistryBindsCompletionToAuthenticatedSessionAgent(t *testing.T) { } completion := Completion{ Type: "completion", ID: "completion_event_456", OperationID: "operation_terminal_456", - Status: "succeeded", Result: json.RawMessage(`{"accepted":true}`), + Action: "delete-vm", ResourceID: "vm-completion-456", + RequestFingerprint: strings.Repeat("d", 64), + Status: "succeeded", Result: json.RawMessage(`{"accepted":true}`), } registry.deliverCompletion(context.Background(), current, completion) select { @@ -238,7 +252,9 @@ func TestCompletionDeliveryAppliesBackpressureInsteadOfDropping(t *testing.T) { } completion := Completion{ Type: "completion", ID: "completion_backpressure_123", OperationID: "operation_backpressure_123", - Status: "succeeded", Result: json.RawMessage(`{"accepted":true}`), + Action: "delete-vm", ResourceID: "vm-completion-backpressure", + RequestFingerprint: strings.Repeat("e", 64), + Status: "succeeded", Result: json.RawMessage(`{"accepted":true}`), } returned := make(chan struct{}) go func() { @@ -266,7 +282,9 @@ func TestCompletionDeliveryAppliesBackpressureInsteadOfDropping(t *testing.T) { func TestCompletionValidationRequiresExplicitNullResult(t *testing.T) { valid := Completion{ Type: "completion", ID: "completion_event_789", OperationID: "operation_terminal_789", - Status: "failed", ErrorCode: "operation_failed", Result: json.RawMessage("null"), + Action: "delete-vm", ResourceID: "vm-completion-789", + RequestFingerprint: strings.Repeat("f", 64), + Status: "failed", ErrorCode: "operation_failed", Result: json.RawMessage("null"), } if err := validateCompletion(valid); err != nil { t.Fatalf("explicit null result rejected: %v", err) @@ -278,6 +296,39 @@ func TestCompletionValidationRequiresExplicitNullResult(t *testing.T) { } } +func TestCompletionValidationRequiresStrictImmutableOperationIdentity(t *testing.T) { + valid := Completion{ + Type: "completion", ID: "completion_identity_123", OperationID: "operation_identity_123", + Action: "create-snapshot:0123456789abcdef0123456789abcdef:filesystem", + ResourceID: "template:debian-13", RequestFingerprint: strings.Repeat("a", 64), + Status: "succeeded", Result: json.RawMessage(`{"done":true}`), + } + if err := validateCompletion(valid); err != nil { + t.Fatalf("valid immutable identity rejected: %v", err) + } + + tests := []struct { + name string + mutate func(*Completion) + }{ + {name: "missing action", mutate: func(value *Completion) { value.Action = "" }}, + {name: "uppercase action", mutate: func(value *Completion) { value.Action = "Delete-VM" }}, + {name: "resource path", mutate: func(value *Completion) { value.ResourceID = "vm/unsafe" }}, + {name: "missing resource", mutate: func(value *Completion) { value.ResourceID = "" }}, + {name: "uppercase fingerprint", mutate: func(value *Completion) { value.RequestFingerprint = strings.Repeat("A", 64) }}, + {name: "short fingerprint", mutate: func(value *Completion) { value.RequestFingerprint = strings.Repeat("a", 63) }}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + candidate := valid + test.mutate(&candidate) + if err := validateCompletion(candidate); err == nil { + t.Fatal("invalid immutable operation identity was accepted") + } + }) + } +} + func TestGatewayCompletionDeliveryLogContainsOnlyStableMetadata(t *testing.T) { logger := log.Default() previousWriter, previousFlags, previousPrefix := logger.Writer(), logger.Flags(), logger.Prefix() diff --git a/gateway/agent/registry.go b/gateway/agent/registry.go index eb4727af..1fd6d34e 100644 --- a/gateway/agent/registry.go +++ b/gateway/agent/registry.go @@ -24,7 +24,7 @@ const ( ControlPath = "/agent/connect" ConsolePath = "/agent/console" InternalRequestPath = "/internal/agent/request" - ControlSubprotocol = "virt-agent-control.v2" + ControlSubprotocol = "virt-agent-control.v3" ConsoleSubprotocolPrefix = "virt-agent-console." maxControlFrame = 4 << 20 maxInternalRequest = 4 << 20 @@ -53,10 +53,13 @@ var ( ) var ( - agentIDPattern = regexp.MustCompile(`^[1-9][0-9]{0,18}$`) - requestIDPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{8,80}$`) - tokenPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{32,256}$`) - stableCodePattern = regexp.MustCompile(`^[a-z][a-z0-9]*(_[a-z0-9]+)*$`) + agentIDPattern = regexp.MustCompile(`^[1-9][0-9]{0,18}$`) + requestIDPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{8,80}$`) + tokenPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{32,256}$`) + stableCodePattern = regexp.MustCompile(`^[a-z][a-z0-9]*(_[a-z0-9]+)*$`) + operationActionPattern = regexp.MustCompile(`^[a-z][a-z0-9]*(?:[-:][a-z0-9]+)*$`) + operationResourceIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.:-]*$`) + requestFingerprintPattern = regexp.MustCompile(`^[0-9a-f]{64}$`) ) type wireRequest struct { @@ -79,6 +82,9 @@ type Completion struct { Type string `json:"type"` ID string `json:"id"` OperationID string `json:"operation_id"` + Action string `json:"action"` + ResourceID string `json:"resource_id"` + RequestFingerprint string `json:"request_fingerprint"` Status string `json:"status"` EffectMayHaveApplied bool `json:"effect_may_have_applied"` SafeToResubmit bool `json:"safe_to_resubmit"` @@ -656,7 +662,10 @@ func (s *session) readLoop(ctx context.Context, registry *Registry) { func validateCompletion(completion Completion) error { if completion.Type != "completion" || !requestIDPattern.MatchString(completion.ID) || - !requestIDPattern.MatchString(completion.OperationID) || len(completion.Result) == 0 || + !requestIDPattern.MatchString(completion.OperationID) || + len(completion.Action) > 128 || !operationActionPattern.MatchString(completion.Action) || + len(completion.ResourceID) > 255 || !operationResourceIDPattern.MatchString(completion.ResourceID) || + !requestFingerprintPattern.MatchString(completion.RequestFingerprint) || len(completion.Result) == 0 || !json.Valid(completion.Result) || (completion.Status != "succeeded" && completion.Status != "failed") || (completion.EffectMayHaveApplied && completion.SafeToResubmit) { return errors.New("invalid completion event") diff --git a/gateway/agent/registry_test.go b/gateway/agent/registry_test.go index 64f284a9..53535b32 100644 --- a/gateway/agent/registry_test.go +++ b/gateway/agent/registry_test.go @@ -127,17 +127,23 @@ func dialControl(t *testing.T, registry *Registry, serverURL, agentID string) *w return conn } -func TestControlRejectsLegacyV1Subprotocol(t *testing.T) { +func TestControlSubprotocolUsesCleanBreakV3(t *testing.T) { + if ControlSubprotocol != "virt-agent-control.v3" { + t.Fatalf("control subprotocol = %q, want clean-break v3", ControlSubprotocol) + } +} + +func TestControlRejectsLegacyV2SubprotocolDuringHandshake(t *testing.T) { registry := &Registry{} request := httptest.NewRequest(http.MethodGet, "http://gateway.invalid"+ControlPath, nil) - request.Header.Set("Sec-WebSocket-Protocol", "virt-agent-control.v1") + request.Header.Set("Sec-WebSocket-Protocol", "virt-agent-control.v2") request.Header.Set("X-Virt-Agent-ID", "12") request.Header.Set("Authorization", "Bearer "+strings.Repeat("a", 32)) response := httptest.NewRecorder() registry.ServeControl(response, request) if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), "subprotocol required") { - t.Fatalf("legacy v1 handshake status=%d body=%q", response.Code, response.Body.String()) + t.Fatalf("legacy v2 handshake status=%d body=%q", response.Code, response.Body.String()) } } diff --git a/web/app/Services/Cloud/CloudAdminInstanceService.php b/web/app/Services/Cloud/CloudAdminInstanceService.php index 5b9ef363..26709851 100644 --- a/web/app/Services/Cloud/CloudAdminInstanceService.php +++ b/web/app/Services/Cloud/CloudAdminInstanceService.php @@ -319,10 +319,12 @@ final class CloudAdminInstanceService { return 'EXISTS (SELECT 1 FROM cloud_jobs attention_job WHERE ' . self::jobRelationSql('attention_job') - . " AND attention_job.phase = 'terminal' " + . " AND ((attention_job.phase = 'terminal' " . "AND attention_job.outcome = 'failed' " . "AND (attention_job.updated_at >= ? OR " - . "attention_job.effect_resolution = 'unknown'))"; + . "attention_job.effect_resolution = 'unknown')) OR " + . self::recoveryIncidentSql('attention_job') . ' OR ' + . self::terminalStateConflictSql('attention_job') . '))'; } /** A terminal failure may keep a safety fence, but it is never active work. */ @@ -334,7 +336,78 @@ final class CloudAdminInstanceService . $alias . ".error_code = 'force_required' OR (" . $alias . ".effect_resolution = 'unknown' AND (" . $alias . '.effect_may_have_applied = 1 OR ' - . $alias . '.safe_to_resubmit = 0)))))'; + . $alias . '.safe_to_resubmit = 0)))) OR ' + . self::recoveryIncidentSql($alias) . ' OR ' + . self::terminalStateConflictSql($alias) . ')'; + } + + private static function recoveryIncidentSql(string $alias): string + { + $supported = self::sqlList(CloudOperationRecoveryPolicy::kinds()); + $repair = self::sqlList(CloudDispatchLedger::repairIncidentCodes()); + $aggregateKinds = self::sqlList(CloudJobService::aggregateKinds()); + $agent = '(' . $alias . ".execution_mode = 'agent' AND (" + . '(' . $alias . '.dispatch_attempts IS NULL OR ' + . $alias . '.dispatch_attempts NOT IN (0, 1)) OR (' + . $alias . ".phase = 'terminal' AND " + . $alias . '.finalization_incident = 1 AND (' + . $alias . '.finalization_error_code IN (' . $repair . ') OR (' + . $alias . ".outcome = 'failed' AND " + . $alias . ".status = 'failed' AND " + . $alias . '.dispatch_attempts = 0 AND ' + . $alias . '.kind IN (' . $supported . ')) OR (' + . $alias . '.dispatch_attempts IN (0, 1) AND ' + . $alias . '.effect_resolution IN (\'applied\', \'not_applied\') ' + . 'AND ' . $alias . '.kind IN (' . $supported . '))))))'; + $aggregateIncident = '(' . $alias . ".phase = 'terminal' AND " + . $alias . '.parent_job_id IS NULL AND ' + . $alias . '.finalization_incident = 1 AND ' + . '(' . $alias . ".execution_mode = 'aggregate' OR " + . $alias . '.kind IN (' . $aggregateKinds . ') OR ' + . $alias . '.finalization_error_code = ' + . "'recovery_aggregate_state_conflict'))"; + return '(' . $agent . ' OR ' + . CloudJobService::aggregateLocalStateConflictSql($alias) + . ' OR ' . $aggregateIncident . ')'; + } + + private static function terminalStateConflictSql(string $alias): string + { + return CloudJobService::terminalRecoveryStateConflictSql($alias); + } + + /** Keep raw attention/filter SQL aligned with the task DTO check. */ + private static function invalidResolvedTerminalTupleSql( + string $alias + ): string { + return '(' . $alias + . ".effect_resolution IN ('applied', 'not_applied') AND NOT ((" + . "COALESCE(" . $alias . ".outcome, '') = 'succeeded' AND " + . "COALESCE(" . $alias . ".status, '') = 'succeeded' AND " + . $alias . ".effect_resolution = 'applied' AND " + . 'COALESCE(' . $alias . '.effect_may_have_applied, -1) = 0 AND ' + . 'COALESCE(' . $alias . '.safe_to_resubmit, -1) = 0 AND ' + . 'COALESCE(' . $alias . '.terminal_at, 0) > 0 AND ' + . $alias . '.error_code IS NULL) OR (' + . "COALESCE(" . $alias . ".outcome, '') = 'failed' AND " + . "COALESCE(" . $alias . ".status, '') = 'failed' AND " + . 'COALESCE(' . $alias . '.terminal_at, 0) > 0 AND ' + . 'COALESCE(' . $alias . '.effect_may_have_applied, -1) IN (0, 1) AND ' + . 'COALESCE(' . $alias . '.safe_to_resubmit, -1) IN (0, 1) AND ((' + . $alias . '.effect_may_have_applied = 1 AND ' + . $alias . '.safe_to_resubmit = 0) OR (' + . $alias . '.effect_may_have_applied = 0 AND ' + . $alias . ".effect_resolution = 'not_applied')))))"; + } + + /** @param list $values */ + private static function sqlList(array $values): string + { + return implode(', ', array_map( + static fn (string $value): string => "'" + . str_replace("'", "''", $value) . "'", + $values + )); } private static function activeJobs($records): array @@ -351,10 +424,18 @@ final class CloudAdminInstanceService private static function jobColumns(): array { - return ['id', 'kind', 'phase', 'outcome', 'status', 'attempts', - 'error_code', 'result_json', 'sealed_payload', + return ['id', 'operation_id', 'request_idempotency_key', + 'request_fingerprint', 'parent_job_id', 'order_id', 'invoice_id', + 'instance_id', 'snapshot_id', 'user_id', 'host_id', + 'kind', 'execution_mode', + 'phase', 'outcome', 'status', 'attempts', 'dispatch_attempts', + 'dispatch_deadline_at', 'dispatch_started_at', + 'agent_accepted_at', 'dispatched_at', 'receipt_deadline_at', + 'completion_event_id', 'error_code', 'result_json', 'sealed_payload', 'effect_may_have_applied', 'safe_to_resubmit', - 'effect_resolution', 'terminal_at', 'created_at', 'updated_at']; + 'effect_resolution', 'finalization_incident', + 'finalization_error_code', 'available_at', + 'terminal_at', 'created_at', 'updated_at']; } private static function jobRow($job): array @@ -365,7 +446,9 @@ final class CloudAdminInstanceService $status = $completed && in_array((string) $job->outcome, ['succeeded', 'failed'], true) ? (string) $job->outcome : 'active'; - $blocksMutation = !$completed || ($status === 'failed' + $recovery = CloudJobService::recoveryPresentation($job, true); + $blocksMutation = !$completed || $recovery !== null + || ($status === 'failed' && ((string) $job->error_code === 'force_required' || ((string) $job->effect_resolution === 'unknown' && ((bool) $job->effect_may_have_applied @@ -379,6 +462,7 @@ final class CloudAdminInstanceService 'safe_to_resubmit' => $job->safe_to_resubmit === null ? null : (bool) $job->safe_to_resubmit, 'effect_resolution' => (string) $job->effect_resolution, + 'recovery' => $recovery, 'attempts' => max(0, (int) $job->attempts), 'error' => CloudOperationErrorCatalog::adminSummary( (string) $job->kind, $status, $job->error_code, diff --git a/web/app/Services/Cloud/CloudAdminOperationRecoveryService.php b/web/app/Services/Cloud/CloudAdminOperationRecoveryService.php index 89ad8143..fc31fab0 100644 --- a/web/app/Services/Cloud/CloudAdminOperationRecoveryService.php +++ b/web/app/Services/Cloud/CloudAdminOperationRecoveryService.php @@ -19,12 +19,28 @@ final class CloudAdminOperationRecoveryService 'applied', 'not_applied', 'partial', 'inconclusive', ]; private const INSPECTION_FIELDS = [ - 'operation_id', 'operation_status', 'checked_at', 'outcome', + 'operation_id', 'action', 'resource_id', 'request_fingerprint', + 'operation_status', 'checked_at', 'outcome', 'summary_code', 'error_code', 'effect_resolution', 'fence_state', 'fence_resolution_required', + 'completion_delivery_state', 'completion_delivery_error_code', 'effect_projection', 'abort_job', 'cleanup', ]; + private const COMPLETION_DELIVERY_ERRORS = [ + 'completion_outbox_invalid' => + 'Agent 完成回执队列状态损坏,当前结果不能采信', + 'completion_receipt_missing' => + 'Agent 完成回执内容缺失,当前结果不能采信', + 'completion_receipt_invalid' => + 'Agent 完成回执内容无效,当前结果不能采信', + 'completion_operation_missing' => + 'Agent 完成回执缺少对应的原操作记录,当前结果不能采信', + 'completion_operation_invalid' => + 'Agent 完成回执对应的原操作记录无效,当前结果不能采信', + 'completion_identity_mismatch' => + 'Agent 完成回执身份与原操作记录不匹配,当前结果不能采信', + ]; private const MAX_INSPECTION_BYTES = 96 * 1024; private const MAX_PROJECTION_BYTES = 64 * 1024; private const MAX_PROJECTION_NODES = 1024; @@ -88,6 +104,7 @@ final class CloudAdminOperationRecoveryService 'virtual_size_bytes' => 'integer', 'sha256' => 'string', 'revision' => 'integer', + 'generation_token' => 'string', 'created_at' => 'string', ]; private const CATALOG_DELETE_PROJECTION = [ @@ -145,12 +162,14 @@ final class CloudAdminOperationRecoveryService $error->agentHttpStatus ); } - return self::inspection( + $inspection = self::inspection( $value, (string) $job->operation_id, (string) $job->kind, false ); + self::assertInspectionIdentity($job, $inspection); + return $inspection; } /** @@ -165,9 +184,9 @@ final class CloudAdminOperationRecoveryService [$job, $client] = self::jobContext( $id, 30.0, - 'instance_settings' + CloudOperationRecoveryPolicy::kinds() ); - if ((string) $job->kind !== 'instance_settings' + if (!CloudOperationRecoveryPolicy::supports((string) $job->kind) || (string) $job->execution_mode !== 'agent' || (string) $job->phase !== 'terminal' || (string) $job->outcome !== 'failed' @@ -215,13 +234,24 @@ final class CloudAdminOperationRecoveryService || mb_strlen($reason) < 20 || mb_strlen($reason) > 500) { throw new CloudError('自动恢复结论或审计说明无效', 400); } + self::assertCompletionDeliveryUsable($inspection); [$job, $client] = self::jobContext( $id, 30.0, - 'instance_settings' + CloudOperationRecoveryPolicy::kinds() ); $checkedAt = $inspection['checked_at'] ?? null; - if ((string) $job->kind !== 'instance_settings' + $identity = CloudOperationRecoveryIdentity::expected( + $job, + $resolution === 'applied' + ); + CloudOperationRecoveryIdentity::assertMatches($identity, [ + 'action' => $inspection['action'] ?? null, + 'resource_id' => $inspection['resource_id'] ?? null, + 'request_fingerprint' => + $inspection['request_fingerprint'] ?? null, + ]); + if (!CloudOperationRecoveryPolicy::supports((string) $job->kind) || (string) $job->execution_mode !== 'agent' || (string) $job->phase !== 'terminal' || (string) $job->outcome !== 'failed' @@ -262,7 +292,8 @@ final class CloudAdminOperationRecoveryService $resolution, $reason, $checkedAt, - null + null, + $identity ); } @@ -285,9 +316,9 @@ final class CloudAdminOperationRecoveryService [$job, $client] = self::jobContext( $id, 30.0, - 'instance_settings' + CloudOperationRecoveryPolicy::kinds() ); - if ((string) $job->kind !== 'instance_settings' + if (!CloudOperationRecoveryPolicy::supports((string) $job->kind) || (string) $job->execution_mode !== 'agent' || (string) $job->phase !== 'terminal' || (string) $job->outcome !== 'failed' @@ -301,6 +332,13 @@ final class CloudAdminOperationRecoveryService )) { throw new CloudError('任务尚未完成可验证的账本预提交', 409); } + // A prepared escrow persists the identity validated before the PHP + // finalizer changed any catalog or instance ledger rows. Verify that + // immutable binding before accepting an existing Agent fence verdict. + CloudOperationRecoveryIdentity::expected( + $job, + $resolution === 'applied' + ); $value = $client->systemRecoveryRequest( 'GET', self::agentPath($job, '/fence-resolution'), @@ -349,6 +387,7 @@ final class CloudAdminOperationRecoveryService || mb_strlen($reason) < 20 || mb_strlen($reason) > 500) { throw new CloudError('影响结论或审计说明无效', 400); } + self::assertCompletionDeliveryUsable($inspection); [$job, $client] = self::context($actor, $id, 30.0); $checkedAt = $inspection['checked_at'] ?? null; if (($inspection['operation_id'] ?? null) @@ -359,6 +398,7 @@ final class CloudAdminOperationRecoveryService } $current = CloudJob::where('id', (int) $job->id) ->where('operation_id', (string) $job->operation_id) + ->where('dispatch_attempts', 1) ->where('phase', 'terminal')->where('outcome', 'failed') ->where('effect_resolution', 'unknown') ->where('effect_may_have_applied', 1)->first(); @@ -384,6 +424,16 @@ final class CloudAdminOperationRecoveryService $resolution, $inspection ); + $identity = CloudOperationRecoveryIdentity::expected( + $current, + $resolution === 'applied' + ); + CloudOperationRecoveryIdentity::assertMatches($identity, [ + 'action' => $inspection['action'] ?? null, + 'resource_id' => $inspection['resource_id'] ?? null, + 'request_fingerprint' => + $inspection['request_fingerprint'] ?? null, + ]); $agentActor = $actor; $agentActor['operation_id'] = (string) $job->operation_id; @@ -393,7 +443,8 @@ final class CloudAdminOperationRecoveryService $resolution, $reason, $checkedAt, - $agentActor + $agentActor, + $identity ); } @@ -444,29 +495,57 @@ final class CloudAdminOperationRecoveryService private static function jobContext( string $id, float $timeoutSeconds, - ?string $requiredKind = null + ?array $requiredKinds = null ): array { if (preg_match('/^[1-9][0-9]{0,17}$/D', $id) !== 1) { throw new CloudError('编号无效', 400); } $job = CloudJob::query()->select([ - 'id', 'operation_id', 'host_id', 'kind', 'execution_mode', - 'phase', 'outcome', 'status', 'dispatch_attempts', + 'id', 'operation_id', 'request_idempotency_key', + 'request_fingerprint', 'host_id', 'kind', 'execution_mode', + 'phase', 'outcome', 'status', 'attempts', 'dispatch_attempts', + 'dispatch_deadline_at', 'dispatch_started_at', + 'agent_accepted_at', 'receipt_deadline_at', + 'completion_event_id', 'terminal_at', 'error_code', 'effect_may_have_applied', 'safe_to_resubmit', 'effect_resolution', 'effect_resolution_reason', 'dispatched_at', + 'finalization_incident', 'finalization_error_code', 'result_json', + 'sealed_payload', 'instance_id', 'snapshot_id', 'parent_job_id', + 'user_id', 'order_id', ])->where('id', (int) $id)->first(); if ($job === null) { throw new CloudError('任务不存在', 404); } - if ($requiredKind !== null - && (string) $job->kind !== $requiredKind) { + if ($requiredKinds !== null + && !in_array((string) $job->kind, $requiredKinds, true)) { throw new CloudError('任务类型不支持自动效果恢复', 409); } + if ((string) $job->execution_mode !== 'agent' + || CloudJobService::isAggregateKind((string) $job->kind)) { + throw new CloudError( + '任务执行模式账本异常,只能由 PHP 本地恢复核对', + 409 + ); + } + if (CloudJobService::hasTerminalRecoveryStateConflict($job) + || ((string) $job->phase === 'terminal' + && (bool) $job->finalization_incident + && (in_array( + (string) $job->effect_resolution, + ['applied', 'not_applied'], + true + ) || CloudDispatchLedger::hasRepairIncident($job)))) { + throw new CloudError( + '任务终态、派发信封或恢复账本尚未安全收敛,只能由 PHP 本地恢复核对', + 409 + ); + } if (preg_match('/^[a-f0-9]{32}$/D', (string) $job->operation_id) !== 1 || (int) $job->host_id < 1) { throw new CloudError('任务缺少可检查的 Agent 操作标识', 409); } + CloudDispatchLedger::assertDispatched($job); if ($job->dispatched_at === null || (int) $job->dispatched_at < 1) { throw new CloudError('任务没有跨越 Agent 派发边界', 409); } @@ -484,16 +563,43 @@ final class CloudAdminOperationRecoveryService private static function automaticPreparedReason(string $reason): bool { return preg_match( - '/^(?:automatic_recovery:v1:[1-9][0-9]{0,10}:([1-9]|1[0-2]):)?prepared:automatic_(?:applied|not_applied)_(?:succeeded|failed)_(?:fence|nofence):[a-f0-9]{64}:[a-f0-9]{64}$/D', + '/^(?:automatic_recovery:v1:[1-9][0-9]{0,10}:[1-9][0-9]{0,9}:)?prepared:automatic_(?:applied|not_applied)_(?:succeeded|failed)_(?:fence|nofence):[a-f0-9]{64}:[a-f0-9]{64}$/D', $reason ) === 1; } - /** - * Convert the fixed Agent inspection schema without exposing action - * tokens. Human DTOs retain only the effect classification; the internal - * recovery DTO may additionally carry a kind-scoped safe projection. - */ + private static function assertCompletionDeliveryUsable( + array $inspection + ): void { + if (($inspection['completion_delivery_state'] ?? null) + === 'quarantined') { + throw new CloudError( + 'Agent 完成回执处于隔离状态,修复回执证据前不能确认操作影响', + 409 + ); + } + } + + private static function assertInspectionIdentity( + CloudJob $job, + array $inspection + ): void { + if (!CloudOperationRecoveryIdentity::supports((string) $job->kind)) { + return; + } + $identity = CloudOperationRecoveryIdentity::expected( + $job, + ($inspection['effect_resolution'] ?? null) === 'applied' + ); + CloudOperationRecoveryIdentity::assertMatches($identity, [ + 'action' => $inspection['action'] ?? null, + 'resource_id' => $inspection['resource_id'] ?? null, + 'request_fingerprint' => + $inspection['request_fingerprint'] ?? null, + ]); + } + + /** Convert the fixed Agent inspection schema into a bounded DTO. */ private static function inspection( array $value, string $operationId, @@ -517,10 +623,40 @@ final class CloudAdminOperationRecoveryService $fenceState = $value['fence_state'] ?? null; $fenceResolutionRequired = $value['fence_resolution_required'] ?? null; + $hasCompletionDeliveryState = array_key_exists( + 'completion_delivery_state', + $value + ); + $hasCompletionDeliveryError = array_key_exists( + 'completion_delivery_error_code', + $value + ); + $completionDeliveryState = + $value['completion_delivery_state'] ?? null; + $completionDeliveryErrorCode = + $value['completion_delivery_error_code'] ?? null; + $identity = [ + 'action' => $value['action'] ?? null, + 'resource_id' => $value['resource_id'] ?? null, + 'request_fingerprint' => $value['request_fingerprint'] ?? null, + ]; if (array_is_list($value) || strlen($encoded) > self::MAX_INSPECTION_BYTES || array_diff(array_keys($value), self::INSPECTION_FIELDS) !== [] || ($value['operation_id'] ?? null) !== $operationId + || !is_string($identity['action']) + || strlen($identity['action']) > 128 + || preg_match( + '/^[a-z][a-z0-9]*(?:[-:][a-z0-9]+)*$/D', + $identity['action'] + ) !== 1 + || !is_string($identity['resource_id']) + || strlen($identity['resource_id']) > 255 + || preg_match('/^[A-Za-z0-9][A-Za-z0-9_.:-]*$/D', + $identity['resource_id']) !== 1 + || !is_string($identity['request_fingerprint']) + || preg_match('/^[a-f0-9]{64}$/D', + $identity['request_fingerprint']) !== 1 || !is_string($status) || !in_array($status, self::OPERATION_STATUSES, true) || !is_string($outcome) @@ -536,6 +672,14 @@ final class CloudAdminOperationRecoveryService ['not_required', 'active', 'resolved'], true) || !is_bool($fenceResolutionRequired) || $fenceResolutionRequired !== ($fenceState === 'active') + || $hasCompletionDeliveryState !== $hasCompletionDeliveryError + || ($hasCompletionDeliveryState + && ($completionDeliveryState !== 'quarantined' + || !is_string($completionDeliveryErrorCode) + || !array_key_exists( + $completionDeliveryErrorCode, + self::COMPLETION_DELIVERY_ERRORS + ))) || ($status === 'succeeded' && $fenceState !== 'not_required') || ($status === 'failed' && $effectResolution === 'applied' @@ -567,6 +711,9 @@ final class CloudAdminOperationRecoveryService } $dto = [ 'operation_id' => $operationId, + 'action' => $identity['action'], + 'resource_id' => $identity['resource_id'], + 'request_fingerprint' => $identity['request_fingerprint'], 'journal_status' => $status, 'checked_at' => $checkedAt, 'outcome' => self::OUTCOMES[$outcome], @@ -576,6 +723,16 @@ final class CloudAdminOperationRecoveryService 'summary_code' => $summaryCode, 'summary' => self::SUMMARY_LABELS[$summaryCode], ]; + if ($hasCompletionDeliveryState) { + $dto['completion_delivery_state'] = + $completionDeliveryState; + $dto['completion_delivery_error_code'] = + $completionDeliveryErrorCode; + $dto['completion_delivery_error'] = + self::COMPLETION_DELIVERY_ERRORS[ + $completionDeliveryErrorCode + ]; + } if ($errorCode !== null) { $dto['error_code'] = $errorCode; $dto['error'] = self::INSPECTION_ERROR_LABELS[$errorCode] @@ -745,7 +902,8 @@ final class CloudAdminOperationRecoveryService ]; } if (in_array($kind, [ - 'template_import_replica', 'rescue_template_import', + 'template_import_replica', 'template_metadata_replica', + 'rescue_template_import', 'user_iso_import_replica', ], true)) { return self::CATALOG_IMPORT_PROJECTION; @@ -790,6 +948,9 @@ final class CloudAdminOperationRecoveryService 'rescue' => ['active', 'staged', 'network_suspended'], 'template_import_replica', 'rescue_template_import', 'user_iso_import_replica' => ['id', 'created_at'], + 'template_metadata_replica' => [ + 'id', 'name', 'revision', 'generation_token', + ], 'template_delete_replica', 'rescue_template_delete', 'user_iso_delete_replica' => [ 'resource_type', 'id', 'deleted', @@ -925,7 +1086,8 @@ final class CloudAdminOperationRecoveryService string $resolution, string $reason, int $checkedAt, - ?array $actor + ?array $actor, + array $identity ): array { $operationId = (string) $job->operation_id; $system = $actor === null; @@ -977,6 +1139,10 @@ final class CloudAdminOperationRecoveryService 'resolution' => $resolution, 'inspection_checked_at' => $checkedAt, 'reason_sha256' => $reasonDigest, + 'action' => $identity['action'] ?? null, + 'resource_id' => $identity['resource_id'] ?? null, + 'request_fingerprint' => + $identity['request_fingerprint'] ?? null, ]; try { return self::matchingFenceResolution( diff --git a/web/app/Services/Cloud/CloudAdminOperationsService.php b/web/app/Services/Cloud/CloudAdminOperationsService.php index 3304c8d6..8e718497 100644 --- a/web/app/Services/Cloud/CloudAdminOperationsService.php +++ b/web/app/Services/Cloud/CloudAdminOperationsService.php @@ -25,12 +25,15 @@ final class CloudAdminOperationsService $filters = self::filters($input); $query = self::query(); self::applyFilters($query, $filters); + $recoverySql = self::recoveryPendingSql('cloud_jobs'); $summaryRow = (clone $query)->selectRaw( "COUNT(*) AS total, " . "COALESCE(SUM(CASE WHEN cloud_jobs.phase <> 'terminal' THEN 1 ELSE 0 END), 0) AS active, " . "COALESCE(SUM(CASE WHEN cloud_jobs.phase = 'terminal' AND cloud_jobs.outcome = 'succeeded' THEN 1 ELSE 0 END), 0) AS succeeded, " . "COALESCE(SUM(CASE WHEN cloud_jobs.phase = 'terminal' AND cloud_jobs.outcome = 'failed' THEN 1 ELSE 0 END), 0) AS failed, " - . "COALESCE(SUM(CASE WHEN cloud_jobs.phase = 'terminal' AND cloud_jobs.outcome = 'failed' AND cloud_jobs.effect_resolution = 'unknown' AND cloud_jobs.kind <> 'host_storage_configure' THEN 1 ELSE 0 END), 0) AS unresolved_effect" + . "COALESCE(SUM(CASE WHEN ((cloud_jobs.phase = 'terminal' AND cloud_jobs.outcome = 'failed' AND cloud_jobs.effect_resolution = 'unknown' AND cloud_jobs.kind <> 'host_storage_configure') OR " + . $recoverySql + . ') THEN 1 ELSE 0 END), 0) AS unresolved_effect' )->first(); $summary = []; foreach (['total', 'active', 'succeeded', 'failed', @@ -88,20 +91,26 @@ final class CloudAdminOperationsService if ($job === null) { throw new CloudError('任务不存在', 404); } + $row = self::row($job, self::canManage($actor)); + $recovering = ($row['recovery']['pending'] ?? false) === true; $storageConfiguration = (string) $job->kind === 'host_storage_configure'; $effectNote = $storageConfiguration ? '存储配置失败不会保留跨任务资源栅栏;旧 operation ID 仍永久终止且绝不重放,管理员可按已有固定池的同一路径用新 operation ID 显式提交独立任务。' - : '副作用可能已发生时,资源安全栅栏保持生效;只有超级管理员完成新鲜只读检查并记录审计结论后,才会显式解除面板与 Agent 栅栏。'; + : ($recovering + ? '恢复异常尚未安全收敛时,资源安全栅栏保持生效;系统校验原任务证据并安全收敛面板账本后会自动解除栅栏。' + : '副作用可能已发生时,资源安全栅栏保持生效;只有超级管理员完成新鲜只读检查并记录审计结论后,才会显式解除面板与 Agent 栅栏。'); $ledgerNote = $storageConfiguration ? '新的存储配置任务只会核验或补全路径一致的固定池;不会更换已有池路径,也不会迁移或删除数据。' - : '其他类型若还没有专用业务账本终结器,系统会拒绝假解锁;任务已终态失败,资源栅栏保持安全锁定。'; + : ($recovering + ? (string) $row['recovery']['message'] + : '其他类型若还没有专用业务账本终结器,系统会拒绝假解锁;任务已终态失败,资源栅栏保持安全锁定。'); return [ - 'job' => self::row($job, self::canManage($actor)), + 'job' => $row, 'generated_at' => time(), 'notes' => [ '任务状态来自数据库,不会因打开页面而联系 Agent。', - '任务最多派发一次;失败后不会自动核对、重新排队或重放宿主机操作。', + '任务原操作最多派发一次;恢复流程只读取原回执和宿主机证据,绝不会重放原操作。', '宿主机只读检查不改变任务终态,也不执行清理或续作。', $effectNote, '开通任务只有在宿主机明确确认虚拟机和管理资源均不存在时,才能按未应用原子退款并释放库存、公网 IP 与资源预留;只读检查不能把开通任务确认成已应用。', @@ -312,13 +321,16 @@ final class CloudAdminOperationsService { $columns = []; foreach ([ - 'id', 'operation_id', 'user_id', 'host_id', 'kind', - 'execution_mode', 'invoice_id', 'phase', + 'id', 'operation_id', 'request_idempotency_key', + 'request_fingerprint', 'user_id', 'host_id', 'kind', + 'parent_job_id', 'execution_mode', 'invoice_id', 'phase', + 'order_id', 'instance_id', 'snapshot_id', 'outcome', 'status', 'attempts', 'dispatch_attempts', 'error_code', - 'dispatched_at', 'dispatch_deadline_at', 'receipt_deadline_at', + 'dispatched_at', 'dispatch_deadline_at', 'dispatch_started_at', + 'agent_accepted_at', 'receipt_deadline_at', 'completion_event_id', 'terminal_at', 'effect_may_have_applied', 'safe_to_resubmit', 'effect_resolution', 'effect_resolved_at', 'effect_resolved_by', - 'finalization_incident', 'finalization_error_code', + 'finalization_incident', 'finalization_error_code', 'result_json', 'lease_until', 'available_at', 'created_at', 'updated_at', ] as $column) { $columns[] = 'cloud_jobs.' . $column; @@ -351,8 +363,14 @@ final class CloudAdminOperationsService private static function applyFilters($query, array $filters): void { if ($filters['status'] === 'attention') { - $query->where('cloud_jobs.phase', 'terminal') - ->where('cloud_jobs.outcome', 'failed'); + $query->where(static function ($attention): void { + $attention->where(static function ($failed): void { + $failed->where('cloud_jobs.phase', 'terminal') + ->where('cloud_jobs.outcome', 'failed'); + })->orWhereRaw( + self::recoveryPendingSql('cloud_jobs') + ); + }); } elseif ($filters['status'] === 'active') { $query->where('cloud_jobs.phase', '<>', 'terminal'); } elseif ($filters['status'] !== 'all') { @@ -417,6 +435,21 @@ final class CloudAdminOperationsService [$canForceDelete, $forceDeleteReason] = self::forceDeleteable( $job, $canManage ); + $recovery = CloudJobService::recoveryPresentation($job, true); + $localFinalizerRecovery = self::isLocalFinalizerRecovery($job); + $repairIncident = CloudDispatchLedger::hasRepairIncident($job); + $finalizationErrorCode = (bool) $job->finalization_incident + ? (string) $job->finalization_error_code : null; + if (is_string($finalizationErrorCode) + && str_starts_with($finalizationErrorCode, 'recovery_')) { + $finalizationErrorCode = $recovery['code'] + ?? 'recovery_pending'; + } elseif (is_string($finalizationErrorCode)) { + $finalizationErrorCode = + CloudOperationErrorCatalog::agentCauseCode( + $finalizationErrorCode + ) ?? 'finalization_failed'; + } return [ 'id' => (string) $job->id, 'operation_id' => preg_match('/^[a-f0-9]{32}$/D', @@ -437,7 +470,12 @@ final class CloudAdminOperationsService 'resolve_effect_reason' => $resolveReason, 'can_force_delete' => $canForceDelete, 'force_delete_reason' => $forceDeleteReason, - 'dispatch_attempts' => max(0, (int) $job->dispatch_attempts), + 'dispatch_attempts' => $job->dispatch_attempts === null + ? null : CloudDispatchLedger::attempts($job), + 'dispatch_state' => CloudDispatchLedger::isInvalid($job) + ? 'invalid' + : (CloudDispatchLedger::isDispatched($job) + ? 'dispatched' : 'not_dispatched'), 'effect_may_have_applied' => $job->effect_may_have_applied === null ? null : (bool) $job->effect_may_have_applied, 'safe_to_resubmit' => $job->safe_to_resubmit === null @@ -447,8 +485,8 @@ final class CloudAdminOperationsService 'effect_resolved_by' => $job->effect_resolved_by === null ? null : (string) $job->effect_resolved_by, 'finalization_incident' => (bool) $job->finalization_incident, - 'finalization_error_code' => (bool) $job->finalization_incident - ? (string) $job->finalization_error_code : null, + 'finalization_error_code' => $finalizationErrorCode, + 'recovery' => $recovery, 'error_code' => CloudOperationErrorCatalog::publicCode( $job->error_code ), @@ -499,12 +537,15 @@ final class CloudAdminOperationsService 'display' => [ 'kind' => $labels['kind_label'], 'action' => $labels['action_label'], - 'status' => self::STATUSES[$status], - 'effect' => (string) $job->effect_resolution === 'unknown' - ? ((string) $job->kind === 'host_storage_configure' - ? '部分固定存储池可能已应用;旧任务已终止且不阻断新的独立任务' - : '副作用状态未知;任务已失败,资源已安全锁定') - : '无任务级安全栅栏', + 'status' => $recovery !== null + ? '恢复处理中' : self::STATUSES[$status], + 'effect' => self::effectDisplay( + $job, + $status, + $recovery, + $localFinalizerRecovery, + $repairIncident + ), ], ]; } @@ -518,6 +559,41 @@ final class CloudAdminOperationsService if ((string) $job->kind === 'payment_create') { return [false, '支付任务不使用宿主机 Agent 检查']; } + if (CloudJobService::isAggregateKind((string) ($job->kind ?? '')) + || (string) ($job->execution_mode ?? '') === 'aggregate') { + return [false, '汇总任务只核对 PHP 账本,不联系宿主机 Agent']; + } + if (CloudOperationRecoveryPolicy::supports( + (string) ($job->kind ?? '') + ) && (string) ($job->execution_mode ?? '') !== 'agent') { + return [false, + '任务执行模式账本异常;仅由 PHP 本地恢复核对,不能联系 Agent']; + } + if (CloudJobService::hasTerminalRecoveryStateConflict($job)) { + return [false, + '任务终态或派发信封矛盾;仅由 PHP 本地恢复核对,不能联系 Agent']; + } + if ((string) ($job->phase ?? '') === 'terminal' + && (bool) ($job->finalization_incident ?? false) + && in_array( + (string) ($job->effect_resolution ?? ''), + ['applied', 'not_applied'], + true + )) { + return [false, + '任务终态后的恢复账本仍在收敛;不会再次联系 Agent']; + } + if (CloudDispatchLedger::isInvalid($job)) { + return [false, + '任务单次派发计数账本异常;修复为合法值后才能读取宿主机状态']; + } + if (CloudDispatchLedger::hasRepairIncident($job)) { + return [false, + '任务恢复账本异常尚未收敛;保持原终态和资源锁,完成后才能读取宿主机状态']; + } + if (!CloudDispatchLedger::isDispatched($job)) { + return [false, '任务没有跨越 Agent 派发边界']; + } if ((int) $job->host_id < 1 || preg_match('/^[a-f0-9]{32}$/D', (string) $job->operation_id) !== 1) { @@ -535,12 +611,21 @@ final class CloudAdminOperationsService if (!$canManage) { return [false, '只有超级管理员可以记录影响结论']; } + if (CloudDispatchLedger::isInvalid($job) + || CloudDispatchLedger::hasRepairIncident($job)) { + return [false, + '任务恢复账本异常尚未收敛;资源保持锁定,不能人工覆盖原任务结论']; + } if ((string) $job->phase !== 'terminal' || (string) $job->outcome !== 'failed' || (string) $job->effect_resolution !== 'unknown' || !(bool) $job->effect_may_have_applied) { return [false, '任务不处于副作用未知的终态失败']; } + if ((string) $job->execution_mode === 'agent' + && !CloudDispatchLedger::isDispatched($job)) { + return [false, '任务没有合法的 Agent 派发记录']; + } if ((string) $job->kind === 'create') { return [true, '仅可在宿主机确认虚拟机及管理资源均不存在后选择未应用并退款;不能用只读检查确认已应用']; @@ -567,11 +652,20 @@ final class CloudAdminOperationsService ['delete', 'expiry_delete', 'service_suspend'], true)) { return [false, '当前任务不是可升级的删除任务']; } + if (CloudDispatchLedger::isInvalid($job) + || (bool) ($job->finalization_incident ?? false) + || CloudJobService::hasTerminalRecoveryStateConflict($job)) { + return [false, + '原删除任务的恢复账本异常尚未收敛;不能创建强制删除任务']; + } if ((string) $job->phase !== 'terminal' || (string) $job->outcome !== 'failed' || (string) $job->error_code !== 'force_required') { return [false, '原删除任务没有明确返回 force_required']; } + if (!CloudDispatchLedger::isDispatched($job)) { + return [false, '原删除任务没有合法的 Agent 派发记录']; + } if ($job->dispatched_at === null || (int) $job->dispatched_at < 1) { return [false, '原删除任务没有跨越 Agent 派发边界']; } @@ -582,4 +676,132 @@ final class CloudAdminOperationsService { return $value !== null && (int) $value > 0 ? (int) $value : null; } + + private static function recoveryIncidentSql(string $alias): string + { + $supported = self::sqlList(CloudOperationRecoveryPolicy::kinds()); + $repair = self::sqlList(CloudDispatchLedger::repairIncidentCodes()); + $aggregateKinds = self::sqlList(CloudJobService::aggregateKinds()); + $agent = '(' . $alias . ".execution_mode = 'agent' AND (" + . '(' . $alias . '.dispatch_attempts IS NULL OR ' + . $alias . '.dispatch_attempts NOT IN (0, 1)) OR (' + . $alias . ".phase = 'terminal' AND " + . $alias . '.finalization_incident = 1 AND (' + . $alias . '.finalization_error_code IN (' . $repair . ') OR (' + . $alias . ".outcome = 'failed' AND " + . $alias . ".status = 'failed' AND " + . $alias . '.dispatch_attempts = 0 AND ' + . $alias . '.kind IN (' . $supported . ')) OR (' + . $alias . '.dispatch_attempts IN (0, 1) AND ' + . $alias . '.effect_resolution IN (\'applied\', \'not_applied\') ' + . 'AND ' . $alias . '.kind IN (' . $supported . '))))))'; + $aggregateIncident = '(' . $alias . ".phase = 'terminal' AND " + . $alias . '.parent_job_id IS NULL AND ' + . $alias . '.finalization_incident = 1 AND ' + . '(' . $alias . ".execution_mode = 'aggregate' OR " + . $alias . '.kind IN (' . $aggregateKinds . ') OR ' + . $alias . '.finalization_error_code = ' + . "'recovery_aggregate_state_conflict'))"; + return '(' . $agent . ' OR ' + . CloudJobService::aggregateLocalStateConflictSql($alias) + . ' OR ' . $aggregateIncident . ')'; + } + + private static function recoveryPendingSql(string $alias): string + { + return '(' . self::recoveryIncidentSql($alias) . ' OR ' + . self::terminalStateConflictSql($alias) . ')'; + } + + private static function terminalStateConflictSql(string $alias): string + { + return CloudJobService::terminalRecoveryStateConflictSql($alias); + } + + /** Keep raw inventory counts aligned with CloudJobService's DTO check. */ + private static function invalidResolvedTerminalTupleSql( + string $alias + ): string { + return '(' . $alias + . ".effect_resolution IN ('applied', 'not_applied') AND NOT ((" + . "COALESCE(" . $alias . ".outcome, '') = 'succeeded' AND " + . "COALESCE(" . $alias . ".status, '') = 'succeeded' AND " + . $alias . ".effect_resolution = 'applied' AND " + . 'COALESCE(' . $alias . '.effect_may_have_applied, -1) = 0 AND ' + . 'COALESCE(' . $alias . '.safe_to_resubmit, -1) = 0 AND ' + . 'COALESCE(' . $alias . '.terminal_at, 0) > 0 AND ' + . $alias . '.error_code IS NULL) OR (' + . "COALESCE(" . $alias . ".outcome, '') = 'failed' AND " + . "COALESCE(" . $alias . ".status, '') = 'failed' AND " + . 'COALESCE(' . $alias . '.terminal_at, 0) > 0 AND ' + . 'COALESCE(' . $alias . '.effect_may_have_applied, -1) IN (0, 1) AND ' + . 'COALESCE(' . $alias . '.safe_to_resubmit, -1) IN (0, 1) AND ((' + . $alias . '.effect_may_have_applied = 1 AND ' + . $alias . '.safe_to_resubmit = 0) OR (' + . $alias . '.effect_may_have_applied = 0 AND ' + . $alias . ".effect_resolution = 'not_applied')))))"; + } + + /** @param list $values */ + private static function sqlList(array $values): string + { + return implode(', ', array_map( + static fn (string $value): string => "'" + . str_replace("'", "''", $value) . "'", + $values + )); + } + + private static function isLocalFinalizerRecovery(object $job): bool + { + return (string) ($job->execution_mode ?? '') === 'agent' + && (string) ($job->phase ?? '') === 'terminal' + && (string) ($job->outcome ?? '') === 'failed' + && (string) ($job->status ?? '') === 'failed' + && CloudDispatchLedger::isNeverDispatched($job) + && (bool) ($job->finalization_incident ?? false) + && !CloudDispatchLedger::hasRepairIncident($job) + && CloudOperationRecoveryPolicy::supports( + (string) ($job->kind ?? '') + ); + } + + private static function effectDisplay( + object $job, + string $status, + ?array $recovery, + bool $localFinalizerRecovery, + bool $repairIncident + ): string { + if (CloudDispatchLedger::isInvalid($job)) { + return '单次派发计数账本异常;任务终态保持不变,资源安全锁定,等待修复并校验'; + } + if ($repairIncident) { + return '原任务终态保持不变;恢复账本尚未安全收敛,资源保持锁定'; + } + if ($localFinalizerRecovery) { + return '原操作确认未派发;PHP 业务账本收尾异常,资源保持锁定并在本地持续恢复,不会联系 Agent'; + } + if ($recovery !== null + && (string) ($job->effect_resolution ?? '') !== 'unknown') { + return '任务终态或派发账本证据矛盾;资源保持安全锁定,仅在 PHP 本地持续核对,不会联系 Agent'; + } + if ($status === 'failed' + && (bool) $job->effect_may_have_applied + && in_array((string) $job->effect_resolution, + ['applied', 'not_applied'], true)) { + return (string) $job->effect_resolution === 'applied' + ? '系统已确认操作已应用;任务仍保留失败审计,资源锁已解除' + : '系统已确认操作未应用;任务仍保留失败审计,资源锁已解除'; + } + if ((string) $job->effect_resolution === 'unknown') { + if ((string) $job->kind === 'host_storage_configure') { + return '部分固定存储池可能已应用;旧任务已终止且不阻断新的独立任务'; + } + return $recovery !== null + ? '副作用状态未知;资源保持安全锁定,系统仍会继续自动核对' + : '副作用状态未知;任务已失败,资源已安全锁定'; + } + return '无任务级安全栅栏'; + } } diff --git a/web/app/Services/Cloud/CloudAgentClient.php b/web/app/Services/Cloud/CloudAgentClient.php index c8bd4bf8..5e87e9a6 100644 --- a/web/app/Services/Cloud/CloudAgentClient.php +++ b/web/app/Services/Cloud/CloudAgentClient.php @@ -370,6 +370,20 @@ final class CloudAgentClient 'replayed' => false, 'retryable' => ($error['retryable'] ?? false) === true, ]; + // The embedded value is the raw immutable Journal record. Normalize + // its field name to the public operation response shape so the worker + // can authenticate a 409 replay/conflict exactly like a 2xx response. + foreach (['action', 'resource_id'] as $identityField) { + if (array_key_exists($identityField, $record)) { + $operation[$identityField] = $record[$identityField]; + } + } + if (array_key_exists('request_fingerprint', $record)) { + $operation['request_fingerprint'] = + $record['request_fingerprint']; + } elseif (array_key_exists('fingerprint', $record)) { + $operation['request_fingerprint'] = $record['fingerprint']; + } if (array_key_exists('result', $record)) { $operation['result'] = $record['result']; } diff --git a/web/app/Services/Cloud/CloudAutomaticOperationRecoveryService.php b/web/app/Services/Cloud/CloudAutomaticOperationRecoveryService.php index 27abdb41..fc1aff02 100644 --- a/web/app/Services/Cloud/CloudAutomaticOperationRecoveryService.php +++ b/web/app/Services/Cloud/CloudAutomaticOperationRecoveryService.php @@ -4,9 +4,11 @@ namespace App\Services\Cloud; use App\Models\CloudAgentCompletionEvent; use App\Models\CloudJob; +use App\Models\CloudTemplate; +use App\Models\CloudUserIso; /** - * Safely converges one timed-out settings operation from read-only evidence. + * Safely converges one timed-out Agent operation from read-only evidence. * * This coordinator never calls the original VM mutation endpoint. Its only * Agent write is the operation-bound journal fence resolution, after PHP has @@ -18,30 +20,101 @@ final class CloudAutomaticOperationRecoveryService // fence read, one write, and lost-response verification). private const CLAIM_SECONDS = 180; private const RETRY_SECONDS = 300; - private const INCONCLUSIVE_RETRY_SECONDS = 600; private const INSPECTION_MAX_AGE_SECONDS = 120; - private const MAX_ATTEMPTS = 12; - private const MAX_AGE_SECONDS = 21600; - private const LIMIT_ERROR = 'recovery_limit_reached'; - private const EVIDENCE_CONFLICT_ERROR = 'recovery_evidence_conflict'; - private const RECEIPT_INVALID_ERROR = 'recovery_receipt_invalid'; - private const RECEIPT_LIMIT_ERROR = 'recovery_receipt_limit_reached'; - - /** Claim and inspect at most one terminal unknown-effect task. */ + + /** Claim and inspect at most one unknown-effect or corrupt-ledger task. */ public function tick(): bool { - $claimed = $this->claim(); + // A durable completion receipt is the strongest available evidence + // and may be the only proof left for a create operation. Consume one + // before the legacy aggregate sweep: a permanently waiting aggregate + // must not starve an exact receipt (and therefore Agent outbox ACKs). + $claimed = $this->claim(true); + if ($claimed === null) { + $claimed = $this->claim(false); + } + // Ordinary leaf convergence outranks periodic catalog projection + // auditing. Healthy published aggregates rotate available_at after + // every audit, so neither path can hot-loop or starve the other. + if ($claimed === null + && CloudJobService::reconcileOneLegacyAggregateEffect()) { + return true; + } if ($claimed === null) { return false; } $job = $claimed['job']; + if (CloudDispatchLedger::isInvalid($job)) { + // A corrupt generation counter is neither proof that the request + // stayed local nor a valid dispatched generation. Keep the job in + // the recovery queue, retain any immutable receipt, and wait for + // an operator to repair the counter to exactly one. + CloudOperationCompletionService::deferDispatchLedgerConflict( + $job + ); + return true; + } + if ($claimed['mode'] === 'dispatch_repair') { + $this->resumeDispatchLedgerRepair($job); + return true; + } + if (in_array($claimed['mode'], [ + 'invalid_envelope', 'invalid_state', 'resolved_incident', + 'aggregate_state', 'invalid_identity', + 'dispatch_repair_invalid_envelope', + 'dispatch_repair_invalid_identity', + ], true)) { + $incidentCode = strtolower(trim( + (string) ($job->finalization_error_code ?? '') + )); + $releaseCode = 'recovery_instance_state_conflict'; + if ($claimed['mode'] === 'invalid_identity') { + $releaseCode = 'recovery_operation_identity_conflict'; + } elseif ($claimed['mode'] + === 'dispatch_repair_invalid_identity') { + $releaseCode = + 'recovery_dispatch_repair_operation_identity_conflict'; + } elseif ($claimed['mode'] + === 'dispatch_repair_invalid_envelope') { + $releaseCode = + 'recovery_dispatch_repair_instance_state_conflict'; + } elseif ($claimed['mode'] === 'resolved_incident' + && preg_match( + '/^recovery_[a-z0-9_]{1,55}$/D', + $incidentCode + ) === 1) { + $releaseCode = $incidentCode; + } elseif (in_array($claimed['mode'], [ + 'aggregate_state', 'invalid_state', + ], true) && ((string) $job->execution_mode === 'aggregate' + || CloudJobService::isAggregateKind((string) $job->kind))) { + $releaseCode = 'recovery_aggregate_state_conflict'; + } + $this->releaseLocalClaim($job, $releaseCode); + return true; + } + if ($claimed['mode'] === 'local_finalizer') { + try { + (new CloudWorkerService())->retryUndispatchedFinalization( + (int) $job->id, + (string) $job->lease_token + ); + } catch (\Throwable $error) { + $this->releaseLocalClaim( + $job, + self::recoveryErrorCode($error) + ); + } + return true; + } if ($claimed['event'] !== null) { try { $this->settleReceivedEvent($job, $claimed['event']); } catch (\Throwable $error) { $this->releaseReceivedEventClaim( $job, - self::receiptRetryDelay($claimed['event']) + self::receiptRetryDelay($claimed['event']), + self::recoveryErrorCode($error) ); error_log(sprintf( 'cloud received completion recovery pending job_id=%d kind=%s error=%s', @@ -54,15 +127,23 @@ final class CloudAutomaticOperationRecoveryService } try { - $delay = $this->recover($job); - if ($delay !== null) { - $this->releaseForRetry($job, $delay); + $pending = $this->recover($job); + if ($pending !== null) { + $this->releaseForRetry( + $job, + $pending['delay'], + $pending['error_code'] + ); } } catch (\Throwable $error) { // Agent downtime, stale evidence, malformed host state and a PHP // crash-window retry all remain fenced. A later worker performs a // new read-only inspection; the original mutation is never sent. - $this->releaseForRetry($job, self::RETRY_SECONDS); + $this->releaseForRetry( + $job, + self::RETRY_SECONDS, + self::recoveryErrorCode($error) + ); error_log(sprintf( 'cloud automatic operation recovery pending job_id=%d kind=%s error=%s', (int) $job->id, @@ -79,7 +160,25 @@ final class CloudAutomaticOperationRecoveryService ): void { if (!CloudOperationCompletionService::isExactStoredEvent($event)) { CloudOperationCompletionService::mark($event, 'rejected'); - $this->releaseReceivedEventClaim($job, 0); + $this->releaseReceivedEventClaim( + $job, + self::RETRY_SECONDS, + 'recovery_receipt_invalid' + ); + return; + } + $expectedIdentity = CloudOperationRecoveryIdentity::expected( + $job, + (string) $event->outcome === 'succeeded' + ); + if (!CloudOperationRecoveryIdentity::same( + $expectedIdentity, + CloudOperationCompletionService::identity($event) + )) { + CloudOperationCompletionService::isolateIdentityMismatch( + $job, + $event + ); return; } $disposition = CloudOperationRecoveryService::settleLateReceipt( @@ -99,28 +198,35 @@ final class CloudAutomaticOperationRecoveryService private static function receiptRetryDelay( CloudAgentCompletionEvent $event ): int { - $remaining = (int) $event->received_at - + self::MAX_AGE_SECONDS - time(); - return max(1, min(self::RETRY_SECONDS, $remaining)); + return self::RETRY_SECONDS; } private function releaseReceivedEventClaim( CloudJob $claimed, - int $delay + int $delay, + ?string $errorCode = null ): void { $now = time(); CloudJob::where('id', (int) $claimed->id) ->where('effect_resolution', 'unknown') ->where('lease_token', (string) $claimed->lease_token) - ->update([ + ->update(array_filter([ 'lease_token' => null, // Receipt evidence bypasses an older inspection backoff, so // use the lease clock as the retry gate if local settlement // itself fails. This prevents a received event hot loop. 'lease_until' => $delay > 0 ? $now + $delay : 0, 'available_at' => $delay > 0 ? $now + $delay : 0, + 'finalization_incident' => $errorCode === null ? null : 1, + 'finalization_error_code' => $errorCode, + 'read_at' => $errorCode === null ? null : null, 'updated_at' => $now, - ]); + ], static fn ($value, $key): bool => $errorCode !== null + || !in_array($key, [ + 'finalization_incident', + 'finalization_error_code', + 'read_at', + ], true), ARRAY_FILTER_USE_BOTH)); } /** @@ -128,14 +234,253 @@ final class CloudAutomaticOperationRecoveryService * an otherwise exhausted job eligible, but is loaded only by its indexed * host+operation key; the event table is never scanned by disposition. * - * @return array{job:CloudJob,event:?CloudAgentCompletionEvent}|null + * @return array{job:CloudJob,event:?CloudAgentCompletionEvent,mode:string}|null */ - private function claim(): ?array + private function claim(bool $receivedOnly): ?array { return (new CloudJob())->getConnection()->transaction( - static function (): ?array { + static function () use ($receivedOnly): ?array { $now = time(); - $job = CloudJob::where('kind', 'instance_settings') + $job = null; + $mode = 'agent'; + if (!$receivedOnly) { + // Recover historical fail-open rows regardless of their + // apparent terminal outcome. A corrupt non-zero dispatch + // counter invalidates both "succeeded" and "not applied" + // projections until an operator repairs it to exactly 1. + // They are claimed only on the ordinary pass so a damaged + // row cannot starve a newly received immutable receipt. + $job = CloudJob::query() + ->where('execution_mode', 'agent') + ->whereIn('phase', [ + 'accepted', + 'dispatching', + 'awaiting_receipt', + 'terminal', + ]) + ->where(static function ($invalid): void { + $invalid->whereNull('dispatch_attempts') + ->orWhereNotIn( + 'dispatch_attempts', + [0, 1] + ); + }) + ->where('available_at', '<=', $now) + ->where('lease_until', '<=', $now) + ->orderBy('available_at') + ->orderBy('id') + ->lockForUpdate() + ->first(); + } + if ($job === null && !$receivedOnly) { + // A valid zero counter proves that no Agent mutation was + // sent. Retry only PHP's kind-specific not-applied ledger + // finalizer; never inspect or contact the host. + $job = CloudJob::query() + ->where('execution_mode', 'agent') + ->where('phase', 'terminal') + ->where('outcome', 'failed') + ->where('status', 'failed') + ->where('dispatch_attempts', 0) + ->where('finalization_incident', 1) + ->where(static function ($incident): void { + $incident->whereNull('finalization_error_code') + ->orWhereNotIn( + 'finalization_error_code', + CloudDispatchLedger::repairIncidentCodes() + ); + }) + ->whereIn( + 'kind', + CloudOperationRecoveryPolicy::kinds() + )->where('available_at', '<=', $now) + ->where('lease_until', '<=', $now) + ->orderBy('available_at') + ->orderBy('id') + ->lockForUpdate() + ->first(); + if ($job !== null) { + $mode = 'local_finalizer'; + } + } + if ($job === null) { + // A terminal row whose invalid counter was repaired keeps + // a sticky blocker until its immutable state is checked. + $repair = CloudJob::query() + ->where('execution_mode', 'agent') + ->where('phase', 'terminal') + ->where('finalization_incident', 1) + ->whereIn( + 'finalization_error_code', + CloudDispatchLedger::repairIncidentCodes() + )->whereIn('dispatch_attempts', [0, 1]) + ->where('lease_until', '<=', $now); + if ($receivedOnly) { + $repair->whereExists( + static function ($events): void { + self::receivedEventExists($events); + } + ); + } else { + $repair->where('available_at', '<=', $now); + } + $job = $repair->orderBy('available_at') + ->orderBy('id')->lockForUpdate()->first(); + if ($job !== null) { + $mode = 'dispatch_repair'; + } + } + if ($job === null && !$receivedOnly) { + // A terminal row may have a final effect and still carry a + // failed PHP projection/finalizer incident. It is already + // resolved on the host, so only retain the local incident + // with backoff; never inspect or mutate Agent state. + $job = CloudJob::query() + ->where('execution_mode', 'agent') + ->where('phase', 'terminal') + ->whereIn('dispatch_attempts', [0, 1]) + ->whereIn( + 'effect_resolution', + ['applied', 'not_applied'] + )->where('finalization_incident', 1) + ->where(static function ($incident): void { + $incident->whereNull('finalization_error_code') + ->orWhereNotIn( + 'finalization_error_code', + CloudDispatchLedger::repairIncidentCodes() + ); + })->whereIn( + 'kind', + CloudOperationRecoveryPolicy::kinds() + )->where('available_at', '<=', $now) + ->where('lease_until', '<=', $now) + ->orderBy('available_at') + ->orderBy('id') + ->lockForUpdate() + ->first(); + if ($job !== null) { + $mode = 'resolved_incident'; + } + } + if ($job === null && !$receivedOnly) { + // A published effect with a contradictory immutable + // terminal tuple is a PHP-ledger conflict. Keep it in a + // local-only retry loop; never ask the Agent to reinterpret + // or repeat the already concluded mutation. + $job = CloudJob::query() + ->where('phase', 'terminal') + ->whereIn( + 'kind', + CloudOperationRecoveryPolicy::kinds() + )->where(static function ($invalid): void { + CloudJobService::applyInvalidResolvedTerminalTuple( + $invalid + ); + })->where('available_at', '<=', $now) + ->where('lease_until', '<=', $now) + ->orderBy('available_at') + ->orderBy('id') + ->lockForUpdate() + ->first(); + if ($job !== null) { + $mode = 'invalid_state'; + } + } + if ($job === null && !$receivedOnly) { + // A valid dispatched generation with a damaged immutable + // envelope must not disappear from the recovery queue. + // This mode records the concrete conflict without making + // any Agent request. + $job = CloudJob::query() + ->where('execution_mode', 'agent') + ->where('phase', 'terminal') + ->where('outcome', 'failed') + ->where('status', 'failed') + ->where('dispatch_attempts', 1) + ->where('effect_may_have_applied', 1) + ->where('safe_to_resubmit', 0) + ->where('effect_resolution', 'unknown') + ->whereIn( + 'kind', + CloudOperationRecoveryPolicy::kinds() + )->where(static function ($repair): void { + $repair->where('finalization_incident', 0) + ->orWhereNull('finalization_error_code') + ->orWhereNotIn( + 'finalization_error_code', + CloudDispatchLedger::repairIncidentCodes() + ); + })->where(static function ($broken): void { + $broken->whereNull('host_id') + ->orWhere('host_id', '<=', 0) + ->orWhereNull('operation_id') + ->orWhereRaw('LENGTH(operation_id) <> 32') + ->orWhereNull('dispatched_at') + ->orWhere('dispatched_at', '<=', 0); + })->where('available_at', '<=', $now) + ->where('lease_until', '<=', $now) + ->orderBy('available_at') + ->orderBy('id') + ->lockForUpdate() + ->first(); + if ($job !== null) { + $mode = 'invalid_envelope'; + } + } + if ($job === null && !$receivedOnly) { + // A terminal unknown-effect row has exactly one trustworthy + // safety tuple. Contradictory historical/data-damaged rows + // stay in a PHP-only incident loop and never contact Agent. + $job = CloudJob::query() + ->where('phase', 'terminal') + ->where('effect_resolution', 'unknown') + ->where(static function ($scope): void { + $scope->where(static function ($leaf): void { + $leaf->whereIn('dispatch_attempts', [0, 1]) + ->whereIn( + 'kind', + CloudOperationRecoveryPolicy::kinds() + ); + })->orWhere( + static function ($aggregate): void { + $aggregate->where( + 'execution_mode', + 'aggregate' + )->whereNull('parent_job_id') + ->whereIn( + 'kind', + CloudJobService::aggregateKinds() + ); + } + ); + })->where(static function ($invalid): void { + $invalid->where(static function ($mode): void { + $mode->whereIn( + 'kind', + CloudOperationRecoveryPolicy::kinds() + )->where(static function ($broken): void { + $broken->whereNull('execution_mode') + ->orWhere( + 'execution_mode', + '<>', + 'agent' + ); + }); + })->orWhere(static function ($tuple): void { + self::applyInvalidTerminalTuple($tuple); + }); + })->where('available_at', '<=', $now) + ->where('lease_until', '<=', $now) + ->orderBy('available_at') + ->orderBy('id') + ->lockForUpdate() + ->first(); + if ($job !== null) { + $mode = 'invalid_state'; + } + } + if ($job === null) { + $job = CloudJob::query() ->where('execution_mode', 'agent') ->where('phase', 'terminal') ->where('outcome', 'failed') @@ -144,51 +489,70 @@ final class CloudAutomaticOperationRecoveryService ->where('effect_may_have_applied', 1) ->where('safe_to_resubmit', 0) ->where('effect_resolution', 'unknown') + ->where(static function ($repair): void { + $repair->where('finalization_incident', 0) + ->orWhereNull('finalization_error_code') + ->orWhereNotIn( + 'finalization_error_code', + CloudDispatchLedger::repairIncidentCodes() + ); + }) ->whereNotNull('operation_id') - ->whereNotNull('instance_id') ->whereNotNull('host_id') ->whereNotNull('dispatched_at') - ->where(static function ($eligible) use ($now): void { + ->where(static function ($eligible) use ( + $now, + $receivedOnly + ): void { $eligible->where( - static function ($ordinary) use ($now): void { - $ordinary->where( - 'available_at', - '<=', - $now + static function ($policy) use ( + $now, + $receivedOnly + ): void { + $policy->whereIn( + 'kind', + CloudOperationRecoveryPolicy::kinds() )->where( - static function ($allowed): void { - $allowed->whereNull( - 'finalization_error_code' - )->orWhereNotIn( - 'finalization_error_code', - [ - self::LIMIT_ERROR, - 'recovery_state_invalid', - self::EVIDENCE_CONFLICT_ERROR, - self::RECEIPT_INVALID_ERROR, - self::RECEIPT_LIMIT_ERROR, - ] + static function ($ready) use ( + $now, + $receivedOnly + ): void { + if ($receivedOnly) { + $ready->whereExists( + static function ( + $events + ): void { + self::receivedEventExists( + $events + ); + } + ); + return; + } + $ready->where('available_at', '<=', $now) + ->orWhereExists( + static function ($events): void { + self::receivedEventExists( + $events + ); + } ); } ); } - )->orWhereExists( - static function ($events): void { - $events->selectRaw('1') - ->from( - 'cloud_agent_completion_events as recovery_events' - ) - ->whereColumn( - 'recovery_events.host_id', - 'cloud_jobs.host_id' - ) - ->whereColumn( - 'recovery_events.operation_id', - 'cloud_jobs.operation_id' - ) - ->where( - 'recovery_events.disposition', - 'received' + )->orWhere( + static function ($create): void { + // Create keeps its specialised financial + // finalizer. It is recoverable here only from + // a durable exact completion receipt; it must + // never enter generic inspection or replay. + $create->where('kind', 'create') + ->whereExists( + static function ($events): void { + self::receivedCreateSuccessEventExists( + $events + ); + } ); } ); @@ -202,9 +566,86 @@ final class CloudAutomaticOperationRecoveryService ->orderBy('id') ->lockForUpdate() ->first(); + } if ($job === null) { return null; } + // SQL only finds a bounded candidate. Revalidate the complete + // immutable Agent envelope on the hydrated row before loading + // a receipt or allowing any Agent/fence path. A damaged field + // is a local ledger incident; immutable evidence stays queued. + $envelopeConflict = + CloudJobService::hasAgentRecoveryEnvelopeConflict($job); + if ($envelopeConflict) { + $identityConflict = CloudJobService:: + hasAgentRecoveryIdentityConflict($job); + if ($mode === 'dispatch_repair') { + $mode = $identityConflict + ? 'dispatch_repair_invalid_identity' + : 'dispatch_repair_invalid_envelope'; + } else { + $mode = $identityConflict + ? 'invalid_identity' : 'invalid_envelope'; + } + } + if (!$envelopeConflict + && (string) $job->phase === 'terminal' + && (CloudTemplate::where( + 'active_job_id', + (int) $job->id + )->exists() || CloudUserIso::where( + 'active_job_id', + (int) $job->id + )->exists())) { + $job->lease_token = bin2hex(random_bytes(16)); + $job->lease_until = $now + self::CLAIM_SECONDS; + $job->save(); + return [ + 'job' => $job, + 'event' => null, + 'mode' => 'aggregate_state', + ]; + } + if (CloudDispatchLedger::isInvalid($job)) { + // Do not inspect or consume a receipt while the dispatch + // generation is corrupt. Lease only long enough to hand + // the row to the fail-closed normalizer after commit. + $job->lease_token = bin2hex(random_bytes(16)); + $job->lease_until = $now + self::CLAIM_SECONDS; + $job->save(); + return [ + 'job' => $job, + 'event' => null, + 'mode' => 'invalid', + ]; + } + if ($mode === 'local_finalizer' + || $mode === 'invalid_envelope' + || $mode === 'invalid_state' + || $mode === 'resolved_incident' + || $mode === 'aggregate_state' + || $mode === 'invalid_identity' + || $mode === 'dispatch_repair_invalid_envelope' + || $mode === 'dispatch_repair_invalid_identity' + || $mode === 'dispatch_repair') { + $event = null; + if ($mode === 'dispatch_repair' + && is_string($job->completion_event_id) + && $job->completion_event_id !== '') { + $event = CloudAgentCompletionEvent::where( + 'event_id', + (string) $job->completion_event_id + )->lockForUpdate()->first(); + } + $job->lease_token = bin2hex(random_bytes(16)); + $job->lease_until = $now + self::CLAIM_SECONDS; + $job->save(); + return [ + 'job' => $job, + 'event' => $event, + 'mode' => $mode, + ]; + } $event = CloudAgentCompletionEvent::where( 'host_id', (int) $job->host_id @@ -212,66 +653,106 @@ final class CloudAutomaticOperationRecoveryService 'operation_id', (string) $job->operation_id )->where('disposition', 'received') + ->when( + (string) $job->kind === 'create', + static fn ($events) => $events->where( + 'outcome', + 'succeeded' + ) + ) ->lockForUpdate() ->first(); if ($event !== null) { $job->lease_token = bin2hex(random_bytes(16)); $job->lease_until = $now + self::CLAIM_SECONDS; $job->save(); - return ['job' => $job, 'event' => $event]; - } - if (in_array( - (string) ($job->finalization_error_code ?? ''), - [ - self::LIMIT_ERROR, - 'recovery_state_invalid', - self::EVIDENCE_CONFLICT_ERROR, - self::RECEIPT_INVALID_ERROR, - self::RECEIPT_LIMIT_ERROR, - ], - true - )) { - return null; + return [ + 'job' => $job, + 'event' => $event, + 'mode' => 'agent', + ]; } $attempt = self::nextAttemptMarker( (string) $job->effect_resolution_reason, $now ); - if ($attempt === null) { - $job->finalization_incident = 1; - $job->finalization_error_code = self::LIMIT_ERROR; - $job->lease_token = null; - $job->lease_until = 0; - $job->available_at = 0; - $job->updated_at = $now; - $job->save(); - return null; - } if ($attempt === false) { $job->finalization_incident = 1; $job->finalization_error_code = 'recovery_state_invalid'; - $job->lease_token = null; - $job->lease_until = 0; - $job->available_at = 0; - $job->updated_at = $now; - $job->save(); - return null; + $job->read_at = null; + } else { + $job->effect_resolution_reason = $attempt; + if (in_array( + (string) ($job->finalization_error_code ?? ''), + [ + 'recovery_limit_reached', + 'recovery_receipt_limit_reached', + ], + true + )) { + $job->finalization_incident = 0; + $job->finalization_error_code = null; + $job->read_at = null; + } } - $job->effect_resolution_reason = $attempt; $job->lease_token = bin2hex(random_bytes(16)); $job->lease_until = $now + self::CLAIM_SECONDS; $job->save(); - return ['job' => $job, 'event' => null]; + return [ + 'job' => $job, + 'event' => null, + 'mode' => 'agent', + ]; }, 3 ); } + /** Add the negation of the canonical failed/effectful/non-retryable tuple. */ + private static function applyInvalidTerminalTuple($invalid): void + { + $invalid->where(static function ($tuple): void { + $tuple->whereNull('outcome') + ->orWhere('outcome', '<>', 'failed') + ->orWhereNull('status') + ->orWhere('status', '<>', 'failed') + ->orWhereNull('effect_may_have_applied') + ->orWhere('effect_may_have_applied', '<>', 1) + ->orWhereNull('safe_to_resubmit') + ->orWhere('safe_to_resubmit', '<>', 0); + })->orWhere(static function ($neverDispatched): void { + $neverDispatched->where('dispatch_attempts', 0) + ->where('finalization_incident', 0); + }); + } + + private static function receivedEventExists($events): void + { + $events->selectRaw('1') + ->from('cloud_agent_completion_events as recovery_events') + ->whereColumn( + 'recovery_events.host_id', + 'cloud_jobs.host_id' + ) + ->whereColumn( + 'recovery_events.operation_id', + 'cloud_jobs.operation_id' + ) + ->where('recovery_events.disposition', 'received'); + } + + private static function receivedCreateSuccessEventExists($events): void + { + self::receivedEventExists($events); + $events->where('recovery_events.outcome', 'succeeded'); + } + /** - * @return int|null Retry delay, or null after a committed resolution. + * @return array{delay:int,error_code:string}|null Retry state, or null + * after a committed resolution. */ - private function recover(CloudJob $claimed): ?int + private function recover(CloudJob $claimed): ?array { $job = CloudJob::find((int) $claimed->id); if ($job === null @@ -282,7 +763,7 @@ final class CloudAutomaticOperationRecoveryService )) { throw new CloudError('自动核对租约已失效', 409); } - $context = CloudWorkerService::settingsRecoveryContext($job); + $context = self::recoveryContext($job); // A late immutable completion receipt is a PHP-local two-phase // recovery. If the accepting request crashed after prepare, rebuild @@ -357,16 +838,29 @@ final class CloudAutomaticOperationRecoveryService ); self::assertFreshInspection($job, $inspection); + // A poisoned completion outbox means the Agent cannot prove that its + // immutable result was delivered intact. Even if the journal's local + // projection says applied/not-applied, that projection must remain + // inconclusive until the outbox/receipt record is repaired. + $deliveryIncident = self::completionDeliveryIncident($inspection); + if ($deliveryIncident !== null) { + return self::pending($deliveryIncident); + } + // A resolved Agent fence proves that some coordinator already wrote // an immutable verdict; it does not prove that PHP prepared the same // verdict. Only the prepared-intent resume path above may consume it. if (($inspection['fence_state'] ?? null) === 'resolved') { - return self::INCONCLUSIVE_RETRY_SECONDS; + return self::pending('recovery_evidence_conflict'); } $resolution = (string) ($inspection['effect_resolution'] ?? ''); if (in_array($resolution, ['partial', 'inconclusive'], true)) { - return self::INCONCLUSIVE_RETRY_SECONDS; + return self::pending( + $resolution === 'partial' + ? 'recovery_evidence_partial' + : 'recovery_evidence_inconclusive' + ); } if (!in_array($resolution, ['applied', 'not_applied'], true)) { throw new CloudError('宿主机效果核对结论无效', 409); @@ -446,25 +940,88 @@ final class CloudAutomaticOperationRecoveryService string $reason, array $inspection ): void { + // Snapshot the immutable parent link before opening the locking + // transaction. Aggregate paths take parent -> catalog -> leaf so the + // nested commitPrepared() transaction can safely reacquire that same + // canonical lock sequence. + $aggregateParentId = (int) (CloudJob::where( + 'id', + (int) $claimed->id + )->value('parent_job_id') ?? 0); (new CloudJob())->getConnection()->transaction( static function () use ( $claimed, $prepared, $reason, - $inspection + $inspection, + $aggregateParentId ): void { - $job = CloudJob::where('id', (int) $claimed->id) - ->where( - 'lease_token', - (string) $claimed->lease_token - )->where('lease_until', '>', time()) - ->lockForUpdate()->first(); + $aggregateChildren = null; + if ($aggregateParentId > 0) { + $aggregateParent = CloudJob::where( + 'id', + $aggregateParentId + ) + ->lockForUpdate()->first(); + if ($aggregateParent === null) { + throw new CloudRecoveryAggregateStateConflict( + '任务的汇总父任务不存在', + 409 + ); + } + if ((string) $aggregateParent->execution_mode + !== 'aggregate' + || CloudJobService::hasAggregateLocalStateConflict( + $aggregateParent + )) { + throw new CloudRecoveryAggregateStateConflict( + '任务的汇总父任务账本状态异常', + 409 + ); + } + CloudTemplateCatalogService::lockAggregateCatalogLocked( + $aggregateParent + ); + CloudUserIsoService::lockAggregateCatalogLocked( + $aggregateParent + ); + $aggregateChildren = CloudJob::where( + 'parent_job_id', + $aggregateParentId + )->orderBy('id')->lockForUpdate()->get(); + $job = $aggregateChildren->first( + static fn (CloudJob $child): bool => + (int) $child->id === (int) $claimed->id + ); + } else { + $job = CloudJob::where('id', (int) $claimed->id) + ->lockForUpdate()->first(); + } if ($job === null + || !hash_equals( + (string) ($job->lease_token ?? ''), + (string) $claimed->lease_token + ) + || (int) $job->lease_until <= time() || (string) $job->effect_resolution !== 'unknown' || !$prepared['fence_resolution_required']) { throw new CloudError('自动核对租约已失效', 409); } - $context = CloudWorkerService::settingsRecoveryContext($job); + if ((int) ($job->parent_job_id ?? 0) + !== $aggregateParentId) { + throw new CloudRecoveryAggregateStateConflict( + '任务的汇总父级关系在栅栏提交期间发生变化', + 409 + ); + } + if ($aggregateParentId > 0) { + CloudJobService::assertAggregateChildRelationshipLocked( + $aggregateParent, + $job, + $aggregateChildren + ); + } + $context = self::recoveryContext($job); $current = self::preparedAutomaticIntent($job, $context); if ($current === null || $current['resolution'] !== $prepared['resolution'] @@ -490,19 +1047,6 @@ final class CloudAutomaticOperationRecoveryService if ($pending !== null) { throw new CloudError('晚到完成回执正在等待优先收敛', 409); } - if (in_array( - (string) ($job->finalization_error_code ?? ''), - [ - self::LIMIT_ERROR, - 'recovery_state_invalid', - self::EVIDENCE_CONFLICT_ERROR, - self::RECEIPT_INVALID_ERROR, - self::RECEIPT_LIMIT_ERROR, - ], - true - )) { - throw new CloudError('自动核对事件尚未处置', 409); - } CloudAdminOperationRecoveryService::resolveFenceForRecovery( (string) $job->id, $prepared['resolution'], @@ -528,6 +1072,40 @@ final class CloudAutomaticOperationRecoveryService || $checkedAt > $now + 5) { throw new CloudError('宿主机只读核对证据已失效', 409); } + $expected = CloudOperationRecoveryIdentity::expected( + $job, + ($inspection['effect_resolution'] ?? null) === 'applied' + ); + CloudOperationRecoveryIdentity::assertMatches($expected, [ + 'action' => $inspection['action'] ?? null, + 'resource_id' => $inspection['resource_id'] ?? null, + 'request_fingerprint' => + $inspection['request_fingerprint'] ?? null, + ]); + } + + private static function completionDeliveryIncident( + array $inspection + ): ?string { + if (($inspection['completion_delivery_state'] ?? null) + !== 'quarantined') { + return null; + } + return match ($inspection['completion_delivery_error_code'] ?? null) { + 'completion_outbox_invalid' => + 'recovery_completion_outbox_invalid', + 'completion_receipt_missing' => + 'recovery_completion_receipt_missing', + 'completion_receipt_invalid' => + 'recovery_completion_receipt_invalid', + 'completion_operation_missing' => + 'recovery_completion_operation_missing', + 'completion_operation_invalid' => + 'recovery_completion_operation_invalid', + 'completion_identity_mismatch' => + 'recovery_completion_identity_mismatch', + default => 'recovery_evidence_invalid', + }; } private static function operationFromInspection( @@ -562,63 +1140,57 @@ final class CloudAutomaticOperationRecoveryService || !is_string($errorCode) || preg_match('/^[a-z][a-z0-9_]{0,63}$/D', $errorCode) !== 1 - || ($fenceResolutionRequired - && $errorCode !== 'settings_not_committed') || array_key_exists('effect_projection', $inspection)) { throw new CloudError('宿主机未生效证据不完整', 409); } return [ 'operation_id' => (string) $job->operation_id, + 'action' => (string) $inspection['action'], + 'resource_id' => (string) $inspection['resource_id'], + 'request_fingerprint' => + (string) $inspection['request_fingerprint'], 'status' => 'failed', 'effect_may_have_applied' => false, 'safe_to_resubmit' => false, - 'error_code' => 'settings_not_committed', + 'error_code' => $errorCode, 'result' => [], ]; } $projection = $inspection['effect_projection'] ?? null; - $allowedProjection = [ - 'uuid', 'name', 'status', 'vcpu', 'memory_mib', 'disk_gib', - 'bandwidth_mbps', 'hostname', 'public_ip_cidr', - 'public_pool_key', 'public_pool_cidr', 'gateway', 'dns_servers', - 'network', 'template_id', 'machine', 'firmware', 'secure_boot', - 'settings_changed', 'network_changed', 'reinstall_committed', - 'cleanup_pending', - ]; if (($inspection['outcome'] ?? null) !== 'succeeded' || ($inspection['summary_code'] ?? null) !== 'operation_succeeded' || array_key_exists('error_code', $inspection) - || !is_array($projection) || array_is_list($projection) - || array_diff(array_keys($projection), $allowedProjection) !== [] - || ($projection['uuid'] ?? null) - !== (string) $context['instance']->uuid - || ($projection['settings_changed'] ?? null) !== true) { + || !is_array($projection) || array_is_list($projection)) { throw new CloudError('宿主机已生效证据不完整', 409); } - if (array_key_exists('hostname', $context['body']) - && ($projection['hostname'] ?? null) - !== $context['body']['hostname']) { - throw new CloudError('宿主机主机名证据与请求不匹配', 409); - } - $result = [ - 'uuid' => (string) $context['instance']->uuid, - 'settings_changed' => true, - ]; - if (array_key_exists('hostname', $context['body'])) { - $result['hostname'] = $context['body']['hostname']; + if ((string) $job->kind === 'instance_settings') { + if (($projection['uuid'] ?? null) + !== (string) $context['instance']->uuid + || ($projection['settings_changed'] ?? null) !== true) { + throw new CloudError('宿主机实例设置证据不完整', 409); + } + if (array_key_exists('hostname', $context['body']) + && ($projection['hostname'] ?? null) + !== $context['body']['hostname']) { + throw new CloudError('宿主机主机名证据与请求不匹配', 409); + } } return [ 'operation_id' => (string) $job->operation_id, + 'action' => (string) $inspection['action'], + 'resource_id' => (string) $inspection['resource_id'], + 'request_fingerprint' => + (string) $inspection['request_fingerprint'], 'status' => 'succeeded', 'effect_may_have_applied' => false, 'safe_to_resubmit' => false, 'error_code' => '', - // The full Agent projection above was strictly validated. Persist - // only the stable settings fields consumed by PHP so a crash retry - // is independent of volatile power/runtime observations. - 'result' => $result, + // CloudAdminOperationRecoveryService already applied the strict + // per-kind projection schema. The existing worker finalizer now + // validates it against PHP's encrypted request and ledgers. + 'result' => $projection, ]; } @@ -629,13 +1201,13 @@ final class CloudAutomaticOperationRecoveryService string $resolution ): string { $projection = $inspection['effect_projection'] ?? []; - $criticalProjection = is_array($projection) - ? array_intersect_key($projection, array_flip([ - 'uuid', 'settings_changed', 'hostname', - ])) : []; + $criticalProjection = is_array($projection) ? $projection : []; + $instance = $context['instance'] ?? null; $evidence = self::canonicalize([ 'operation_id' => (string) $job->operation_id, - 'instance_uuid' => (string) $context['instance']->uuid, + 'kind' => (string) $job->kind, + 'instance_uuid' => $instance === null + ? null : (string) $instance->uuid, 'journal_status' => $inspection['journal_status'] ?? null, 'fence_resolution_required' => $inspection['fence_resolution_required'] ?? null, @@ -678,7 +1250,7 @@ final class CloudAutomaticOperationRecoveryService return null; } if (preg_match( - '/^prepared:(automatic_(applied|not_applied)_(succeeded|failed)_(fence|nofence):[a-f0-9]{64}):[a-f0-9]{64}$/D', + '/^prepared:(automatic_(applied|not_applied)_(succeeded|failed)_(fence|nofence):[a-f0-9]{64}):([a-f0-9]{64})$/D', $marker, $matches ) !== 1) { @@ -698,7 +1270,16 @@ final class CloudAutomaticOperationRecoveryService if (!$validShape) { return null; } - if ($resolution === 'not_applied') { + $operation = CloudWorkerService::preparedRecoveryOperation($job); + if ($operation === null && (string) $job->kind !== 'instance_settings') { + throw new CloudRecoveryPayloadUnavailable( + '任务缺少可恢复的预提交结果', + 409 + ); + } + // Compatibility for settings intents prepared before the generic + // encrypted operation envelope was introduced. + if ($operation === null && $resolution === 'not_applied') { $operation = [ 'operation_id' => (string) $job->operation_id, 'status' => 'failed', @@ -707,7 +1288,7 @@ final class CloudAutomaticOperationRecoveryService 'error_code' => 'settings_not_committed', 'result' => [], ]; - } else { + } elseif ($operation === null) { $result = [ 'uuid' => (string) $context['instance']->uuid, 'settings_changed' => true, @@ -736,6 +1317,30 @@ final class CloudAutomaticOperationRecoveryService 'result' => $result, ]; } + $operationHash = hash( + 'sha256', + json_encode( + self::canonicalize($operation), + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + | JSON_UNESCAPED_UNICODE + ) + ); + $validOperation = $resolution === 'applied' + ? (($operation['status'] ?? null) === 'succeeded' + && ($operation['effect_may_have_applied'] ?? null) === false + && ($operation['safe_to_resubmit'] ?? null) === false) + : (($operation['status'] ?? null) === 'failed' + && ($operation['effect_may_have_applied'] ?? null) === false + && is_bool($operation['safe_to_resubmit'] ?? null) + && is_string($operation['error_code'] ?? null) + && preg_match('/^[a-z][a-z0-9_]{0,63}$/D', + $operation['error_code']) === 1); + if (!$validOperation || !hash_equals($matches[5], $operationHash)) { + throw new CloudRecoveryPayloadUnavailable( + '任务预提交结果与恢复标记不匹配', + 409 + ); + } return [ 'resolution' => $resolution, 'journal_status' => $journalStatus, @@ -754,7 +1359,8 @@ final class CloudAutomaticOperationRecoveryService $evidence = $separator === false ? $source : substr($source, $separator + 1); return sprintf( - 'automatic instance_settings recovery job=%d operation=%s evidence=%s resolution=%s', + 'automatic %s recovery job=%d operation=%s evidence=%s resolution=%s', + (string) $job->kind, (int) $job->id, (string) $job->operation_id, $evidence, @@ -800,10 +1406,78 @@ final class CloudAutomaticOperationRecoveryService return $value; } - private function releaseForRetry(CloudJob $claimed, int $delay): void + private static function recoveryContext(CloudJob $job): array + { + return (string) $job->kind === 'instance_settings' + ? CloudWorkerService::settingsRecoveryContext($job) + : CloudWorkerService::recoveryContext($job); + } + + /** @return array{delay:int,error_code:string} */ + private static function pending(string $errorCode): array + { + return [ + 'delay' => self::RETRY_SECONDS, + 'error_code' => $errorCode, + ]; + } + + private static function recoveryErrorCode(\Throwable $error): string + { + if ($error instanceof CloudRecoveryDispatchLedgerConflict) { + return CloudDispatchLedger::CONFLICT_CODE; + } + if ($error instanceof CloudRecoveryAggregateStateConflict) { + return 'recovery_aggregate_state_conflict'; + } + if ($error instanceof CloudRecoveryPayloadUnavailable) { + return 'recovery_payload_unavailable'; + } + if ($error instanceof CloudRecoveryOperationIdentityConflict) { + return 'recovery_operation_identity_conflict'; + } + if ($error instanceof CloudRecoveryEvidenceConflict) { + return 'recovery_evidence_conflict'; + } + if ($error instanceof CloudRecoveryReceiptInvalid) { + return 'recovery_receipt_invalid'; + } + if ($error instanceof CloudRecoveryInstanceStateConflict) { + return 'recovery_instance_state_conflict'; + } + if ($error instanceof CloudAgentError) { + if (in_array($error->agentCode, [ + 'agent_invalid_inspection', + 'agent_invalid_fence_resolution', + 'fence_resolution_read_failed', + ], true) && $error->agentHttpStatus === 200) { + return 'recovery_evidence_invalid'; + } + if ($error->agentHttpStatus === 404) { + return 'recovery_operation_missing'; + } + if (in_array($error->agentHttpStatus, [401, 403], true)) { + return 'recovery_authentication_failed'; + } + if ($error->agentHttpStatus === 409) { + return 'recovery_operation_conflict'; + } + return 'recovery_waiting_connection'; + } + if ($error instanceof CloudError) { + return 'recovery_ledger_conflict'; + } + return 'recovery_internal_error'; + } + + private function releaseForRetry( + CloudJob $claimed, + int $delay, + string $errorCode + ): void { (new CloudJob())->getConnection()->transaction( - static function () use ($claimed, $delay): void { + static function () use ($claimed, $delay, $errorCode): void { $job = CloudJob::where('id', (int) $claimed->id) ->where('effect_resolution', 'unknown') ->where( @@ -816,22 +1490,106 @@ final class CloudAutomaticOperationRecoveryService return; } $now = time(); - $attempt = self::attemptState( - (string) $job->effect_resolution_reason - ); - $limited = $attempt !== null - && ($attempt['attempts'] >= self::MAX_ATTEMPTS - || $now - $attempt['first_at'] - >= self::MAX_AGE_SECONDS); $job->lease_token = null; $job->lease_until = 0; - $job->available_at = $limited - ? 0 - : $now + max(self::RETRY_SECONDS, $delay); - if ($limited) { - $job->finalization_incident = 1; - $job->finalization_error_code = self::LIMIT_ERROR; + $job->available_at = $now + max( + self::RETRY_SECONDS, + $delay + ); + if (!hash_equals( + (string) ($job->finalization_error_code ?? ''), + $errorCode + )) { + $job->read_at = null; } + $job->finalization_incident = 1; + $job->finalization_error_code = $errorCode; + $job->updated_at = $now; + $job->save(); + }, + 3 + ); + } + + private function resumeDispatchLedgerRepair(CloudJob $claimed): void + { + try { + $result = CloudOperationCompletionService:: + resumeRepairedDispatchLedger($claimed); + if ($result === 'missing') { + $this->releaseLocalClaim( + $claimed, + 'recovery_dispatch_repair_completion_receipt_missing' + ); + } elseif ($result === 'invalid') { + $this->releaseLocalClaim( + $claimed, + 'recovery_dispatch_repair_receipt_invalid' + ); + } + } catch (\Throwable $error) { + $this->releaseLocalClaim( + $claimed, + self::dispatchRepairErrorCode($error) + ); + } + } + + private static function dispatchRepairErrorCode( + \Throwable $error + ): string { + return match (self::recoveryErrorCode($error)) { + CloudDispatchLedger::CONFLICT_CODE => + CloudDispatchLedger::CONFLICT_CODE, + 'recovery_aggregate_state_conflict' => + 'recovery_dispatch_repair_aggregate_state_conflict', + 'recovery_payload_unavailable' => + 'recovery_dispatch_repair_payload_unavailable', + 'recovery_operation_identity_conflict' => + 'recovery_dispatch_repair_operation_identity_conflict', + 'recovery_evidence_conflict' => + 'recovery_dispatch_repair_evidence_conflict', + 'recovery_receipt_invalid' => + 'recovery_dispatch_repair_receipt_invalid', + 'recovery_instance_state_conflict' => + 'recovery_dispatch_repair_instance_state_conflict', + 'recovery_ledger_conflict' => + 'recovery_dispatch_repair_ledger_conflict', + default => 'recovery_dispatch_repair_internal_error', + }; + } + + /** Release a PHP-only recovery claim without requiring unknown effect. */ + private function releaseLocalClaim( + CloudJob $claimed, + string $errorCode + ): void { + (new CloudJob())->getConnection()->transaction( + static function () use ($claimed, $errorCode): void { + $job = CloudJob::where('id', (int) $claimed->id) + ->where( + 'lease_token', + (string) $claimed->lease_token + )->lockForUpdate()->first(); + if ($job === null) { + return; + } + $now = time(); + $job->lease_token = null; + // claim(true) intentionally prioritizes a matching received + // event over ordinary available_at backoff. Keep the lease + // clock as the retry gate as well, otherwise an invalid bound + // receipt would be reclaimed on every worker tick. + $job->lease_until = $now + self::RETRY_SECONDS; + $job->available_at = $now + self::RETRY_SECONDS; + if (!hash_equals( + (string) ($job->finalization_error_code ?? ''), + $errorCode + )) { + $job->read_at = null; + } + $job->finalization_incident = 1; + $job->finalization_error_code = $errorCode; $job->updated_at = $now; $job->save(); }, @@ -843,7 +1601,7 @@ final class CloudAutomaticOperationRecoveryService private static function attemptState(string $marker): ?array { if (preg_match( - '/^automatic_recovery:v1:([1-9][0-9]{0,10}):([1-9]|1[0-2]):(pending|prepared:(?:automatic_(?:applied|not_applied)_(?:succeeded|failed)_(?:fence|nofence):[a-f0-9]{64}|late_completion_receipt:[A-Za-z0-9_.-]{1,160}):[a-f0-9]{64})$/D', + '/^automatic_recovery:v1:([1-9][0-9]{0,10}):([1-9][0-9]{0,9}):(pending|prepared:(?:automatic_(?:applied|not_applied)_(?:succeeded|failed)_(?:fence|nofence):[a-f0-9]{64}|late_completion_receipt:[A-Za-z0-9_.-]{1,160}):[a-f0-9]{64})$/D', $marker, $matches ) !== 1) { @@ -859,7 +1617,7 @@ final class CloudAutomaticOperationRecoveryService private static function nextAttemptMarker( string $marker, int $now - ): string|false|null { + ): string|false { if ($marker === '') { return sprintf( 'automatic_recovery:v1:%d:1:pending', @@ -880,14 +1638,10 @@ final class CloudAutomaticOperationRecoveryService } return false; } - if ($state['attempts'] >= self::MAX_ATTEMPTS - || $now - $state['first_at'] >= self::MAX_AGE_SECONDS) { - return null; - } return sprintf( 'automatic_recovery:v1:%d:%d:%s', $state['first_at'], - $state['attempts'] + 1, + min(9999999999, $state['attempts'] + 1), $state['payload'] ); } diff --git a/web/app/Services/Cloud/CloudCreateFailureFinalizer.php b/web/app/Services/Cloud/CloudCreateFailureFinalizer.php index 6ad77732..54b9859b 100644 --- a/web/app/Services/Cloud/CloudCreateFailureFinalizer.php +++ b/web/app/Services/Cloud/CloudCreateFailureFinalizer.php @@ -3,6 +3,7 @@ namespace App\Services\Cloud; use App\Models\CloudInstance; +use App\Models\CloudAgentCompletionEvent; use App\Models\CloudInvoice; use App\Models\CloudJob; use App\Models\CloudOrder; @@ -74,6 +75,7 @@ final class CloudCreateFailureFinalizer if ($source === null) { throw new CloudError('任务不存在', 404); } + CloudDispatchLedger::assertDispatched($source); self::assertResolutionSupported($source, 'not_applied', $inspection); (new CloudJob())->getConnection()->transaction(function () use ( @@ -98,6 +100,7 @@ final class CloudCreateFailureFinalizer || !hash_equals((string) $job->operation_id, $operationId)) { throw new CloudError('开通任务与资金账本关联不一致', 409); } + CloudDispatchLedger::assertDispatched($job); self::assertResolutionSupported( $job, 'not_applied', @@ -110,6 +113,48 @@ final class CloudCreateFailureFinalizer throw new CloudError('任务不处于可确认的影响未知状态', 409); } + $payload = CloudSecrets::decrypt( + (string) $job->sealed_payload, + 'job-payload' + ); + $identity = CloudOperationRecoveryIdentity::expectedFromPayload( + $job, + $payload, + false + ); + $successEvent = CloudAgentCompletionEvent::where( + 'host_id', + (int) $job->host_id + )->where( + 'operation_id', + (string) $job->operation_id + )->where('disposition', 'received') + ->where('outcome', 'succeeded') + ->lockForUpdate() + ->first(); + if ($successEvent !== null + && CloudOperationCompletionService::isExactStoredEvent( + $successEvent + ) + && CloudOperationRecoveryIdentity::same( + $identity, + CloudOperationCompletionService::identity($successEvent) + )) { + // Receipt publication locks job then event. This financial + // finalizer holds its established wallet/order/job sequence, + // then locks the event before any refund. An exact durable + // create success always wins over a contradictory manual + // absence claim; the receipt-only recovery worker will finish + // materialisation without replaying the mutation. + throw new CloudError( + '已收到匹配的实例创建成功回执,不能按未应用退款', + 409 + ); + } + $safePayload = CloudInput::safeResult($payload); + $safePayload[CloudOperationRecoveryIdentity::payloadKey()] = + CloudOperationRecoveryIdentity::persisted($identity); + self::refundAndReleaseLocked( $job, $user, @@ -125,6 +170,10 @@ final class CloudCreateFailureFinalizer $job->effect_resolved_at = $now; $job->effect_resolved_by = $actorId; $job->effect_resolution_reason = $reason; + $job->sealed_payload = CloudSecrets::encrypt( + $safePayload, + 'job-payload' + ); $job->updated_at = $now; $job->save(); }, 3); @@ -177,6 +226,14 @@ final class CloudCreateFailureFinalizer } $now = time(); + if (CloudDispatchLedger::isInvalid($job)) { + // Revalidate under the same job lock as the financial + // finalizer. A concurrent ledger corruption must never + // take the no-effect refund/release branch. + $effectMayHaveApplied = true; + $safeToResubmit = false; + $errorCode = CloudDispatchLedger::CONFLICT_CODE; + } // Without definitive no-effect evidence, preserve every paid // resource and turn the placement into a durable safety fence. if ($effectMayHaveApplied) { @@ -302,6 +359,26 @@ final class CloudCreateFailureFinalizer string $errorCode, int $now ): void { + $dispatchConflict = CloudDispatchLedger::isInvalid($job); + if ($dispatchConflict) { + $effectMayHaveApplied = true; + $safeToResubmit = false; + $errorCode = CloudDispatchLedger::CONFLICT_CODE; + } else { + $payload = CloudSecrets::decrypt( + (string) $job->sealed_payload, + 'job-payload' + ); + $identity = CloudOperationRecoveryIdentity::expectedFromPayload( + $job, + $payload, + false + ); + $durablePayload = $effectMayHaveApplied + ? $payload : CloudInput::safeResult($payload); + $durablePayload[CloudOperationRecoveryIdentity::payloadKey()] = + CloudOperationRecoveryIdentity::persisted($identity); + } $job->phase = 'terminal'; $job->outcome = 'failed'; $job->status = 'failed'; @@ -312,10 +389,21 @@ final class CloudCreateFailureFinalizer $job->effect_resolution = $effectMayHaveApplied ? 'unknown' : 'not_applied'; $job->error_code = substr($errorCode, 0, 128); - $job->sealed_payload = CloudSecrets::encrypt([], 'job-payload'); + if (!$dispatchConflict) { + $job->sealed_payload = CloudSecrets::encrypt( + $durablePayload, + 'job-payload' + ); + } $job->lease_token = null; $job->lease_until = 0; - $job->available_at = 0; + $job->available_at = $dispatchConflict ? $now + 300 : 0; + if ($dispatchConflict) { + $job->finalization_incident = 1; + $job->finalization_error_code = + CloudDispatchLedger::CONFLICT_CODE; + $job->read_at = null; + } $job->updated_at = $now; $job->save(); } diff --git a/web/app/Services/Cloud/CloudDispatchLedger.php b/web/app/Services/Cloud/CloudDispatchLedger.php new file mode 100644 index 00000000..274f11ff --- /dev/null +++ b/web/app/Services/Cloud/CloudDispatchLedger.php @@ -0,0 +1,105 @@ +dispatch_attempts ?? null; + if (is_int($value)) { + return $value; + } + if (is_string($value) + && preg_match('/^-?[0-9]+$/D', $value) === 1) { + return (int) $value; + } + // A missing, NULL or non-integral value is corruption rather than + // evidence that the mutation never crossed the dispatch boundary. + return PHP_INT_MIN; + } + + public static function isNeverDispatched(object $job): bool + { + return self::attempts($job) === 0; + } + + public static function isDispatched(object $job): bool + { + return self::attempts($job) === 1; + } + + public static function isInvalid(object $job): bool + { + return !in_array(self::attempts($job), [0, 1], true); + } + + /** Invalid non-zero state is conservatively treated as possibly sent. */ + public static function mayHaveDispatched(object $job): bool + { + return !self::isNeverDispatched($job); + } + + public static function assertValid(object $job): void + { + if (self::isInvalid($job)) { + throw new CloudRecoveryDispatchLedgerConflict( + '任务单次派发计数账本异常', + 409 + ); + } + } + + public static function assertDispatched(object $job): void + { + self::assertValid($job); + if (!self::isDispatched($job)) { + throw new CloudError('任务没有跨越 Agent 派发边界', 409); + } + } + + /** @return list */ + public static function repairIncidentCodes(): array + { + return self::REPAIR_INCIDENT_CODES; + } + + /** + * A repaired counter remains sticky until the background coordinator has + * revalidated the immutable terminal row. This closes the brief window in + * which changing 2 to 0/1 could otherwise release the resource early. + */ + public static function hasRepairIncident(object $job): bool + { + return (string) ($job->execution_mode ?? '') === 'agent' + && (string) ($job->phase ?? '') === 'terminal' + && (bool) ($job->finalization_incident ?? false) + && in_array( + (string) ($job->finalization_error_code ?? ''), + self::REPAIR_INCIDENT_CODES, + true + ); + } +} diff --git a/web/app/Services/Cloud/CloudInvoiceService.php b/web/app/Services/Cloud/CloudInvoiceService.php index 2b820577..e422a4c9 100644 --- a/web/app/Services/Cloud/CloudInvoiceService.php +++ b/web/app/Services/Cloud/CloudInvoiceService.php @@ -478,7 +478,8 @@ final class CloudInvoiceService if ($orderIds !== []) { foreach (CloudJob::whereIn('order_id', array_values($orderIds)) ->whereIn('user_id', array_values($ownerIds)) - ->get(['id', 'order_id', 'user_id', 'phase', 'outcome']) as $job) { + ->get(['id', 'order_id', 'user_id', 'instance_id', 'kind', + 'phase', 'outcome', 'effect_resolution']) as $job) { $jobs[self::listKey((int) $job->user_id, (int) $job->order_id)] = $job; } } @@ -534,6 +535,15 @@ final class CloudInvoiceService if ((string) $job->phase !== 'terminal') { return 'active'; } + if ((string) ($job->kind ?? '') === 'create' + && (string) $job->outcome === 'failed' + && (string) ($job->effect_resolution ?? '') === 'applied' + && (int) ($job->instance_id ?? 0) > 0) { + // Preserve the immutable failed task receipt while presenting the + // specialised exact-receipt create finalizer as fulfilled to + // invoices and notification consumers. + return 'succeeded'; + } $outcome = (string) $job->outcome; return in_array($outcome, ['succeeded', 'failed'], true) ? $outcome : 'failed'; @@ -605,9 +615,10 @@ final class CloudInvoiceService if ($order !== null) { $job = CloudJob::where('order_id', $order->id) ->where('user_id', $invoice->user_id) - ->first(['id', 'order_id', 'user_id', 'kind', 'phase', + ->first(['id', 'order_id', 'user_id', 'instance_id', + 'kind', 'phase', 'outcome', 'attempts', 'updated_at', 'error_code', - 'result_json']); + 'result_json', 'effect_resolution']); } } elseif ($purpose === 'renewal' && $invoice->instance_id !== null) { $instance = CloudInstance::where('id', $invoice->instance_id) @@ -709,8 +720,9 @@ final class CloudInvoiceService $job = $order === null ? null : CloudJob::where('order_id', $order->id) ->where('user_id', $invoice->user_id) - ->first(['id', 'order_id', 'user_id', 'kind', 'phase', - 'outcome', 'attempts', 'updated_at', 'error_code']); + ->first(['id', 'order_id', 'user_id', 'instance_id', 'kind', + 'phase', 'outcome', 'attempts', 'updated_at', + 'error_code', 'effect_resolution']); // Successful workers persist both links. Keep the invoice-side link // as a defensive fallback if transaction recovery repaired one side // so the unified bill can still open the created instance. diff --git a/web/app/Services/Cloud/CloudJobService.php b/web/app/Services/Cloud/CloudJobService.php index a8596f79..1e9e694d 100644 --- a/web/app/Services/Cloud/CloudJobService.php +++ b/web/app/Services/Cloud/CloudJobService.php @@ -9,6 +9,8 @@ use App\Models\CloudPublicIp; use App\Models\CloudPublicIpPool; use App\Models\CloudResourcePool; use App\Models\CloudResourceReservation; +use App\Models\CloudTemplate; +use App\Models\CloudUserIso; final class CloudJobService { @@ -41,6 +43,92 @@ final class CloudJobService 'user_iso_import', 'user_iso_delete', ]; + private const AGGREGATE_CHILD_KIND_MAP = [ + 'template_import' => 'template_import_replica', + 'template_metadata_sync' => 'template_metadata_replica', + 'template_delete' => 'template_delete_replica', + 'user_iso_import' => 'user_iso_import_replica', + 'user_iso_delete' => 'user_iso_delete_replica', + ]; + private const RECOVERY_RETRY_SECONDS = 300; + private const RECOVERY_MESSAGES = [ + 'recovery_pending' => + '系统正在核对原任务结果;不会重复执行原操作,仍会继续自动核对。', + 'recovery_limit_reached' => + '旧任务已重新进入持续自动核对;不会重复执行原操作,系统仍会继续自动核对。', + 'recovery_receipt_limit_reached' => + '旧任务回执已重新进入持续自动核对;不会重复执行原操作,系统仍会继续自动核对。', + 'recovery_state_invalid' => + '任务状态与恢复记录暂不一致;不会重复执行原操作,修复记录后系统仍会继续自动核对。', + 'recovery_evidence_conflict' => + 'Agent 回执与宿主机证据暂不一致;资源保持安全锁定,系统仍会继续自动核对。', + 'recovery_evidence_partial' => + '宿主机目前只能确认部分操作结果;资源保持安全锁定,系统仍会继续自动核对。', + 'recovery_evidence_inconclusive' => + '宿主机证据暂不足以确认操作结果;资源保持安全锁定,系统仍会继续自动核对。', + 'recovery_evidence_invalid' => + 'Agent 返回的核对或栅栏证据格式不匹配;不会采信异常证据,系统仍会继续自动核对。', + 'recovery_receipt_invalid' => + 'Agent 回执未通过完整性核验;不会采信异常回执,系统仍会继续自动核对。', + 'recovery_completion_outbox_invalid' => + '宿主机的完成回执队列状态损坏;不会采信当前结果,修复后系统仍会继续自动核对。', + 'recovery_completion_receipt_missing' => + '宿主机的完成回执内容缺失;不会采信当前结果,修复后系统仍会继续自动核对。', + 'recovery_completion_receipt_invalid' => + '宿主机的完成回执内容无效;不会采信当前结果,修复后系统仍会继续自动核对。', + 'recovery_completion_operation_missing' => + '宿主机的完成回执缺少对应原操作记录;不会采信当前结果,修复后系统仍会继续自动核对。', + 'recovery_completion_operation_invalid' => + '宿主机的完成回执对应原操作记录无效;不会采信当前结果,修复后系统仍会继续自动核对。', + 'recovery_completion_identity_mismatch' => + '宿主机的完成回执身份与原操作记录不匹配;不会采信当前结果,修复后系统仍会继续自动核对。', + 'recovery_agent_unavailable' => + '宿主机 Agent 或网络暂不可用;通信恢复后系统仍会继续自动核对。', + 'recovery_authentication_failed' => + '面板与宿主机 Agent 的认证暂未通过;修复认证后系统仍会继续自动核对。', + 'recovery_waiting_connection' => + '宿主机 Agent 或网络暂不可用;通信恢复后系统仍会继续自动核对。', + 'recovery_operation_missing' => + '宿主机暂未找到原任务记录;不会重复执行原操作,系统仍会继续自动核对。', + 'recovery_operation_conflict' => + '任务编号与宿主机记录暂不一致;不会重复执行原操作,系统仍会继续自动核对。', + 'recovery_operation_identity_conflict' => + 'Agent 证据中的操作、资源或请求指纹与原任务不匹配;不会重复执行或解锁,系统仍会继续自动核对。', + 'recovery_payload_invalid' => + '任务恢复数据暂时无法安全读取;修复记录后系统仍会继续自动核对。', + 'recovery_payload_unavailable' => + '任务恢复数据暂时无法安全读取;修复记录后系统仍会继续自动核对。', + 'recovery_instance_state_conflict' => + '实例状态与任务证据暂不一致;资源保持安全锁定,系统仍会继续自动核对。', + 'recovery_aggregate_state_conflict' => + '汇总任务与子任务账本关系异常;资源保持安全锁定,修复账本后系统仍会继续自动核对。', + 'recovery_dispatch_ledger_conflict' => + '任务单次派发计数账本异常;资源保持安全锁定,修复账本后系统仍会继续自动核对。', + 'recovery_dispatch_repair_completion_receipt_missing' => + '派发计数已修复,但原任务绑定的完成回执缺失;终态保持不变,资源保持锁定并持续恢复。', + 'recovery_dispatch_repair_receipt_invalid' => + '派发计数已修复,但原任务回执未通过完整性校验;不会采信异常回执或解锁。', + 'recovery_dispatch_repair_aggregate_state_conflict' => + '派发计数已修复,但汇总任务与子任务账本关系仍不一致;资源保持锁定并持续恢复。', + 'recovery_dispatch_repair_payload_unavailable' => + '派发计数已修复,但原任务恢复数据暂时无法安全读取;不会重复执行或解锁。', + 'recovery_dispatch_repair_operation_identity_conflict' => + '派发计数已修复,但回执中的操作、资源或请求指纹与原任务不匹配;不会重复执行或解锁。', + 'recovery_dispatch_repair_evidence_conflict' => + '派发计数已修复,但原任务回执与宿主机证据仍不一致;资源保持锁定并持续恢复。', + 'recovery_dispatch_repair_instance_state_conflict' => + '派发计数已修复,但实例状态与原任务证据仍不一致;资源保持锁定并持续恢复。', + 'recovery_dispatch_repair_ledger_conflict' => + '派发计数已修复,但面板业务账本仍未安全收敛;终态保持不变,资源保持锁定。', + 'recovery_dispatch_repair_internal_error' => + '派发计数修复后的安全校验遇到内部异常;不会重复执行或解锁,系统会持续恢复。', + 'recovery_child_convergence' => + '子任务仍在持续自动核对;汇总任务会在子任务收敛后更新,原操作不会重复执行。', + 'recovery_ledger_conflict' => + '任务结果已确定,但面板账本暂未安全收敛;资源保持安全锁定,系统仍会继续自动核对并恢复。', + 'recovery_internal_error' => + '自动核对暂时遇到内部异常;不会重复执行原操作,系统仍会继续自动核对。', + ]; /** Absolute dispatch windows are selected once and are never extended. */ public static function dispatchDeadlineSeconds(string $kind): int @@ -124,6 +212,276 @@ final class CloudJobService { return in_array($kind, self::AGGREGATE_KINDS, true); } + + /** @return list */ + public static function aggregateKinds(): array + { + return self::AGGREGATE_KINDS; + } + + /** True only for a damaged terminal recovery or aggregate-local tuple. */ + public static function hasTerminalRecoveryStateConflict(object $job): bool + { + if ((string) ($job->phase ?? '') !== 'terminal') { + return false; + } + $mode = (string) ($job->execution_mode ?? ''); + $kind = (string) ($job->kind ?? ''); + if (CloudOperationRecoveryPolicy::supports($kind)) { + if ($mode !== 'agent' + || self::hasAgentRecoveryEnvelopeConflict($job)) { + return true; + } + if (self::hasResolvedTerminalStateConflict($job)) { + return true; + } + } + if (self::isAggregateKind($kind)) { + if (self::hasAggregateLocalStateConflict($job)) { + return true; + } + if ((string) ($job->effect_resolution ?? '') !== 'unknown') { + return false; + } + } elseif ((string) ($job->effect_resolution ?? '') !== 'unknown') { + return false; + } + $supported = ($mode === 'agent' + && !CloudDispatchLedger::isInvalid($job) + && CloudOperationRecoveryPolicy::supports($kind)) + || ($mode === 'aggregate' + && ($job->parent_job_id ?? null) === null + && self::isAggregateKind($kind)); + if (!$supported) { + return false; + } + // Generation zero proves the mutation never crossed the Agent + // boundary. A terminal/unknown row may remain there only while a + // durable PHP-only finalizer incident is retrying; without that + // incident the otherwise-canonical dispatched safety tuple is itself + // contradictory and must stay in the local invalid-state queue. + if ($mode === 'agent' + && (int) ($job->dispatch_attempts ?? -1) === 0 + && !(bool) ($job->finalization_incident ?? false)) { + return true; + } + return (string) ($job->outcome ?? '') !== 'failed' + || (string) ($job->status ?? '') !== 'failed' + || !(bool) ($job->effect_may_have_applied ?? false) + || (bool) ($job->safe_to_resubmit ?? false); + } + + /** Aggregate parents are PHP-local ledgers and must never resemble Agent work. */ + public static function hasAggregateLocalStateConflict(object $job): bool + { + if ((string) ($job->execution_mode ?? '') !== 'aggregate' + || !self::isAggregateKind((string) ($job->kind ?? '')) + || ($job->parent_job_id ?? null) !== null + || ($job->host_id ?? null) !== null + || ($job->instance_id ?? null) !== null + || ($job->order_id ?? null) !== null + || ($job->invoice_id ?? null) !== null + || ($job->snapshot_id ?? null) !== null + || (int) ($job->user_id ?? 0) < 1 + || (string) ($job->attempts ?? '') !== '0' + || CloudDispatchLedger::attempts($job) !== 0 + || (int) ($job->dispatch_deadline_at ?? 0) < 1 + || (int) ($job->receipt_deadline_at ?? 0) < 1 + || ($job->dispatch_started_at ?? null) !== null + || ($job->agent_accepted_at ?? null) !== null + || ($job->dispatched_at ?? null) !== null + || ($job->completion_event_id ?? null) !== null + || preg_match( + '/^[a-f0-9]{32}$/D', + (string) ($job->operation_id ?? '') + ) !== 1 + || preg_match( + '/^[a-f0-9]{64}$/D', + (string) ($job->request_fingerprint ?? '') + ) !== 1 + || preg_match( + '/^[A-Za-z0-9_.-]{16,128}$/D', + (string) ($job->request_idempotency_key ?? '') + ) !== 1) { + return true; + } + $phase = (string) ($job->phase ?? ''); + if ($phase === 'awaiting_receipt') { + return ($job->outcome ?? null) !== null + || (string) ($job->status ?? '') !== 'running' + || ($job->terminal_at ?? null) !== null + || ($job->effect_may_have_applied ?? null) !== null + || ($job->safe_to_resubmit ?? null) !== null + || (string) ($job->effect_resolution ?? '') + !== 'not_applicable' + || (bool) ($job->finalization_incident ?? false); + } + if ($phase !== 'terminal' + || (int) ($job->terminal_at ?? 0) < 1 + || !in_array( + (string) ($job->outcome ?? ''), + ['succeeded', 'failed'], + true + ) + || (string) ($job->status ?? '') + !== (string) ($job->outcome ?? '')) { + return true; + } + $outcome = (string) $job->outcome; + $resolution = (string) ($job->effect_resolution ?? ''); + $effectMayHaveApplied = $job->effect_may_have_applied ?? null; + $safeToResubmit = $job->safe_to_resubmit ?? null; + if ($outcome === 'succeeded') { + return !in_array( + $effectMayHaveApplied, + [0, '0', false], + true + ) || !in_array($safeToResubmit, [0, '0', false], true) + || $resolution !== 'applied' + || ($job->error_code ?? null) !== null; + } + if (!in_array($resolution, [ + 'unknown', 'applied', 'not_applied', + ], true)) { + return true; + } + if (in_array($effectMayHaveApplied, [1, '1', true], true)) { + return !in_array($safeToResubmit, [0, '0', false], true); + } + return !in_array($effectMayHaveApplied, [0, '0', false], true) + || !in_array( + $safeToResubmit, + [0, '0', false, 1, '1', true], + true + ) + || $resolution !== 'not_applied'; + } + + /** A published terminal effect must retain one canonical immutable tuple. */ + public static function hasResolvedTerminalStateConflict(object $job): bool + { + if ((string) ($job->phase ?? '') !== 'terminal' + || !in_array( + (string) ($job->effect_resolution ?? ''), + ['applied', 'not_applied'], + true + )) { + return false; + } + if ((int) ($job->terminal_at ?? 0) < 1) { + return true; + } + $outcome = (string) ($job->outcome ?? ''); + $status = (string) ($job->status ?? ''); + $resolution = (string) $job->effect_resolution; + $effect = $job->effect_may_have_applied ?? null; + $safe = $job->safe_to_resubmit ?? null; + if ($outcome === 'succeeded') { + $tupleConflict = $status !== 'succeeded' + || $resolution !== 'applied' + || !in_array($effect, [0, '0', false], true) + || !in_array($safe, [0, '0', false], true) + || ($job->error_code ?? null) !== null; + if ($tupleConflict) { + return true; + } + } elseif ($outcome !== 'failed' || $status !== 'failed') { + return true; + } elseif (in_array($effect, [1, '1', true], true)) { + if (!in_array($safe, [0, '0', false], true)) { + return true; + } + } elseif (!in_array($effect, [0, '0', false], true) + || !in_array($safe, [0, '0', false, 1, '1', true], true) + || $resolution !== 'not_applied') { + return true; + } + + $kind = (string) ($job->kind ?? ''); + if (!CloudOperationRecoveryPolicy::supports($kind)) { + return false; + } + return self::hasAgentRecoveryEnvelopeConflict($job); + } + + /** True when one supported Agent generation's immutable envelope is bad. */ + public static function hasAgentRecoveryEnvelopeConflict(object $job): bool + { + $kind = (string) ($job->kind ?? ''); + $outcome = (string) ($job->outcome ?? ''); + if (!CloudOperationRecoveryPolicy::supports($kind)) { + return false; + } + if ((string) ($job->execution_mode ?? '') !== 'agent' + || self::hasAgentRecoveryIdentityConflict($job) + || (int) ($job->host_id ?? 0) < 1 + || (int) ($job->dispatch_deadline_at ?? 0) < 1) { + return true; + } + $dispatchAttempts = CloudDispatchLedger::attempts($job); + if ($dispatchAttempts === 1) { + return (string) ($job->attempts ?? '') !== '1' + || (int) ($job->dispatch_started_at ?? 0) < 1 + || (($job->agent_accepted_at ?? null) !== null + && (int) $job->agent_accepted_at < 1) + || (int) ($job->dispatched_at ?? 0) < 1 + || (int) ($job->receipt_deadline_at ?? 0) < 1; + } + if ($dispatchAttempts !== 0 + || (string) ($job->attempts ?? '') !== '0' + || ($job->dispatch_started_at ?? null) !== null + || ($job->agent_accepted_at ?? null) !== null + || ($job->dispatched_at ?? null) !== null + || ($job->receipt_deadline_at ?? null) !== null + || ($job->completion_event_id ?? null) !== null) { + return true; + } + if ($outcome !== 'succeeded') { + return false; + } + return !self::isValidUndispatchedFirewallNoop($job); + } + + /** True when one supported Agent generation lost immutable request identity. */ + public static function hasAgentRecoveryIdentityConflict(object $job): bool + { + if (!CloudOperationRecoveryPolicy::supports( + (string) ($job->kind ?? '') + )) { + return false; + } + return preg_match( + '/^[a-f0-9]{32}$/D', + (string) ($job->operation_id ?? '') + ) !== 1 || preg_match( + '/^[a-f0-9]{64}$/D', + (string) ($job->request_fingerprint ?? '') + ) !== 1 || preg_match( + '/^[A-Za-z0-9_.-]{16,128}$/D', + (string) ($job->request_idempotency_key ?? '') + ) !== 1; + } + + /** Generation zero success exists only for an unchanged firewall policy. */ + private static function isValidUndispatchedFirewallNoop(object $job): bool + { + if ((string) ($job->kind ?? '') !== 'firewall_apply' + || (int) ($job->instance_id ?? 0) < 1 + || !is_string($job->result_json ?? null)) { + return false; + } + $result = json_decode((string) $job->result_json, true); + return is_array($result) + && !array_is_list($result) + && ($result['unchanged'] ?? null) === true + && is_string($result['policy_digest'] ?? null) + && preg_match( + '/^[a-f0-9]{64}$/D', + $result['policy_digest'] + ) === 1 + && is_int($result['revision'] ?? null) + && $result['revision'] > 0; + } /** * Operations that still own an instance resource. Active work blocks new * mutations; a terminal unknown-effect failure remains fenced until a @@ -147,7 +505,83 @@ final class CloudJobService }); }); }); - }); + })->orWhere(static function ($mode): void { + $mode->whereIn( + 'kind', + CloudOperationRecoveryPolicy::kinds() + )->where('phase', 'terminal') + ->where(static function ($invalid): void { + $invalid->whereNull('execution_mode') + ->orWhere( + 'execution_mode', + '<>', + 'agent' + ); + }); + })->orWhere(static function ($invalid): void { + // Historical rows written by a fail-open release must + // become blocking again immediately after upgrade, + // even before a recovery worker has touched them. + $invalid->where('execution_mode', 'agent') + ->where(static function ($counter): void { + $counter->whereNull('dispatch_attempts') + ->orWhereNotIn( + 'dispatch_attempts', + [0, 1] + ); + }); + })->orWhere(static function ($incident): void { + $incident->where('execution_mode', 'agent') + ->where('phase', 'terminal') + ->where('finalization_incident', 1) + ->where(static function ($recoverable): void { + $recoverable->whereIn( + 'finalization_error_code', + CloudDispatchLedger::repairIncidentCodes() + )->orWhere(static function ($local): void { + $local->where('outcome', 'failed') + ->where('status', 'failed') + ->where('dispatch_attempts', 0) + ->whereIn( + 'kind', + CloudOperationRecoveryPolicy::kinds() + ); + })->orWhere(static function ($resolved): void { + $resolved->whereIn( + 'dispatch_attempts', + [0, 1] + ) + ->whereIn( + 'effect_resolution', + ['applied', 'not_applied'] + )->whereIn( + 'kind', + CloudOperationRecoveryPolicy::kinds() + ); + }); + }); + })->orWhere(static function ($state): void { + $state->where('execution_mode', 'agent') + ->whereIn( + 'kind', + CloudOperationRecoveryPolicy::kinds() + )->where('phase', 'terminal') + ->whereIn('dispatch_attempts', [0, 1]) + ->where('effect_resolution', 'unknown') + ->where(static function ($invalid): void { + self::applyInvalidTerminalTuple($invalid); + }); + })->orWhere(static function ($resolvedState): void { + $resolvedState->whereIn( + 'kind', + CloudOperationRecoveryPolicy::kinds() + )->where('phase', 'terminal') + ->where(static function ($invalid): void { + self::applyInvalidResolvedTerminalTuple( + $invalid + ); + }); + }); }); } @@ -453,6 +887,1369 @@ final class CloudJobService $job->save(); } + /** + * Release a terminal aggregate fence after every Agent child has reached + * an evidence-backed resolution. The parent's failed audit outcome remains + * immutable; only its effect resolution is published. + */ + public static function reconcileAggregateParentEffectLocked( + CloudJob $child, + ?int $resolvedBy + ): void { + if (!in_array( + (string) $child->kind, + array_values(self::AGGREGATE_CHILD_KIND_MAP), + true + )) { + return; + } + $parentId = (int) ($child->parent_job_id ?? 0); + if ($parentId < 1) { + throw new CloudRecoveryAggregateStateConflict( + '汇总子任务缺少父任务账本', + 409 + ); + } + $parent = CloudJob::where('id', $parentId) + ->lockForUpdate()->first(); + if ($parent === null + || (string) $parent->execution_mode !== 'aggregate') { + throw new CloudRecoveryAggregateStateConflict( + '汇总子任务父任务账本不存在或模式不匹配', + 409 + ); + } + // Reject a malformed parent/child topology before catalog discovery. + // This is a read-only preflight while the parent is held; valid paths + // still acquire every write lock in parent -> catalog -> child order + // and revalidate the relationship after the child locks are taken. + $childSnapshot = CloudJob::where('parent_job_id', $parentId) + ->orderBy('id')->get(); + if (self::aggregateRelationshipConflict( + $parent, + $childSnapshot, + (int) $child->id + )) { + self::deferAggregateRecoveryLocked( + $parent, + 'recovery_aggregate_state_conflict', + time() + ); + return; + } + CloudTemplateCatalogService::lockAggregateCatalogLocked($parent); + CloudUserIsoService::lockAggregateCatalogLocked($parent); + $children = CloudJob::where('parent_job_id', $parentId) + ->orderBy('id')->lockForUpdate()->get(); + if (self::aggregateRelationshipConflict( + $parent, + $children, + (int) $child->id + )) { + self::deferAggregateRecoveryLocked( + $parent, + 'recovery_aggregate_state_conflict', + time() + ); + return; + } + $publishedParent = self::aggregateParentHasPublishedEffect($parent); + if ($children->contains(static fn (CloudJob $row): bool => + self::aggregateChildRecoveryPending($row))) { + if ($publishedParent) { + self::deferAggregateRecoveryLocked( + $parent, + 'recovery_child_convergence', + time() + ); + } + return; + } + $resolution = self::aggregateEffectResolution($children); + $metadataMixed = $resolution === 'mixed' + && (string) $parent->kind === 'template_metadata_sync'; + if ($resolution === null) { + self::deferAggregateRecoveryLocked( + $parent, + 'recovery_aggregate_state_conflict', + time() + ); + return; + } + if ($publishedParent) { + self::recheckPublishedAggregateProjectionLocked( + $parent, + $resolution, + $metadataMixed + ); + return; + } + if ($resolution === 'mixed' && !$metadataMixed) { + // Validate every child-to-replica identity before projecting the + // concrete partial failure. A forged all-success replica set must + // never make a mixed import/delete look successful. + CloudTemplateCatalogService::settleRecoveredParentLocked( + $parent, + 'mixed' + ); + CloudUserIsoService::settleRecoveredParentLocked( + $parent, + 'mixed' + ); + if ((string) $parent->phase !== 'terminal') { + $parent->refresh(); + } + self::deferAggregateRecoveryLocked( + $parent, + 'recovery_aggregate_state_conflict', + time() + ); + return; + } + $projectionSettled = false; + if ((string) $parent->phase !== 'terminal') { + // Recovered leaf projections are prepared before the matching + // Agent fence is released. Only this post-commit hook may now + // publish the user-visible aggregate result. + CloudTemplateCatalogService::settleRecoveredParentLocked( + $parent, + $resolution + ); + CloudUserIsoService::settleRecoveredParentLocked( + $parent, + $resolution + ); + $parent->refresh(); + if ((string) $parent->outcome !== 'failed' + || (string) $parent->effect_resolution !== 'unknown') { + return; + } + $projectionSettled = true; + } + if ((string) $parent->outcome !== 'failed' + || (string) $parent->effect_resolution !== 'unknown') { + return; + } + // A deadline may have failed the immutable public task and marked the + // catalog record failed before late Agent evidence converged every + // replica. Recompute only that resource projection now. The service + // finalizers call completeAggregateLocked(), whose terminal guard keeps + // the original parent phase/outcome/status/timestamps/error/result + // immutable. + if (!$projectionSettled) { + CloudTemplateCatalogService::settleRecoveredParentLocked( + $parent, + $resolution + ); + CloudUserIsoService::settleRecoveredParentLocked( + $parent, + $resolution + ); + } + $publishedResolution = $metadataMixed ? 'applied' : $resolution; + $parent->effect_resolution = $publishedResolution; + $parent->effect_resolved_at = time(); + $parent->effect_resolved_by = $resolvedBy; + $parent->effect_resolution_reason = sprintf( + 'child_effects_resolved:%d:%s', + (int) $child->id, + $publishedResolution + ); + $parent->finalization_incident = 0; + $parent->finalization_error_code = null; + $parent->lease_token = null; + $parent->lease_until = 0; + $parent->available_at = 0; + $parent->read_at = null; + $parent->updated_at = time(); + $parent->save(); + } + + /** + * Converge one aggregate fence left behind before the realtime child hook + * existed. This is a PHP-ledger-only sweep: it never dispatches or inspects + * an Agent operation. Parent then children is the only explicit lock order, + * and children are locked by id to avoid sibling-order inversions. It is + * also the durable fallback if a realtime sibling hook loses a deadlock + * retry or PHP exits after committing the final child. + */ + private static function wherePublishedAggregateNeedsRecheck( + $published + ): void { + $published->whereIn( + 'effect_resolution', + ['applied', 'not_applied'] + )->where(static function ($needs): void { + $needs->whereNull('dispatch_attempts') + ->orWhere('dispatch_attempts', '<>', 0) + ->orWhere(static function ($incident): void { + $incident->where('finalization_incident', 1); + })->orWhereExists(static function ($templates): void { + $templates->selectRaw('1') + ->from('cloud_templates as current_templates') + ->whereColumn( + 'current_templates.active_job_id', + 'cloud_jobs.id' + ); + })->orWhereExists(static function ($isos): void { + $isos->selectRaw('1') + ->from('cloud_user_isos as current_isos') + ->whereColumn( + 'current_isos.active_job_id', + 'cloud_jobs.id' + ); + }); + }); + } + + public static function reconcileOneLegacyAggregateEffect(): bool + { + $connection = (new CloudJob())->getConnection(); + $claimedParentId = 0; + try { + return $connection->transaction( + static function () use (&$claimedParentId): bool { + $now = time(); + $parent = CloudJob::where('phase', 'terminal') + ->where(static function ($candidate): void { + $candidate->where( + static function ($aggregate): void { + $aggregate->whereIn( + 'kind', + array_keys( + self::AGGREGATE_CHILD_KIND_MAP + ) + )->where( + static function ($recoverable): void { + $recoverable->where( + static function ($unknown): void { + $unknown->where( + 'outcome', + 'failed' + )->where( + 'status', + 'failed' + )->where( + 'effect_may_have_applied', + 1 + )->where( + 'safe_to_resubmit', + 0 + )->where( + 'effect_resolution', + 'unknown' + ); + } + )->orWhere( + static function ($ledger): void { + $ledger->whereNull( + 'dispatch_attempts' + )->orWhere( + 'dispatch_attempts', + '<>', + 0 + ); + } + )->orWhere( + static function ($published): void { + self::wherePublishedAggregateNeedsRecheck( + $published + ); + } + )->orWhere( + static function ($damaged): void { + self::whereAggregateLocalStateConflict( + $damaged + ); + } + ); + } + ); + } + )->orWhereRaw( + self::aggregateLocalStateConflictSql( + 'cloud_jobs' + ) + )->orWhere( + static function ($bound): void { + self::whereCurrentAggregateCatalogBinding( + $bound + ); + } + )->orWhere(static function ($incident): void { + $incident->whereNull('parent_job_id') + ->where('finalization_incident', 1) + ->where( + 'finalization_error_code', + 'recovery_aggregate_state_conflict' + ); + }); + }) + ->where('available_at', '<=', $now) + ->where('lease_until', '<=', $now) + ->orderByRaw( + "CASE WHEN effect_resolution = 'unknown' " + . 'THEN 0 ELSE 1 END' + ) + ->orderBy('available_at') + ->orderBy('id') + ->lockForUpdate() + ->first(); + if ($parent === null) { + return false; + } + $claimedParentId = (int) $parent->id; + + // Classify a corrupt aggregate locally before catalog + // discovery. The parent lock serializes legitimate child + // writers; valid paths still re-read every child under + // lock after the catalog row is locked. + $childSnapshot = CloudJob::where( + 'parent_job_id', + (int) $parent->id + )->orderBy('id')->get(); + if (self::aggregateRelationshipConflict( + $parent, + $childSnapshot + )) { + self::deferAggregateRecoveryLocked( + $parent, + 'recovery_aggregate_state_conflict', + $now + ); + return true; + } + + CloudTemplateCatalogService::lockAggregateCatalogLocked( + $parent + ); + CloudUserIsoService::lockAggregateCatalogLocked($parent); + + $children = CloudJob::where( + 'parent_job_id', + (int) $parent->id + )->orderBy('id')->lockForUpdate()->get(); + if (self::aggregateRelationshipConflict( + $parent, + $children + )) { + self::deferAggregateRecoveryLocked( + $parent, + 'recovery_aggregate_state_conflict', + $now + ); + return true; + } + + $waiting = $children->contains( + static fn (CloudJob $child): bool => + self::aggregateChildRecoveryPending($child) + ); + if ($waiting) { + self::deferAggregateRecoveryLocked( + $parent, + 'recovery_child_convergence', + $now + ); + return true; + } + + $resolution = self::aggregateEffectResolution($children); + $metadataMixed = $resolution === 'mixed' + && (string) $parent->kind + === 'template_metadata_sync'; + if ($resolution === null) { + self::deferAggregateRecoveryLocked( + $parent, + 'recovery_aggregate_state_conflict', + $now + ); + return true; + } + if (self::aggregateParentHasPublishedEffect($parent)) { + self::recheckPublishedAggregateProjectionLocked( + $parent, + $resolution, + $metadataMixed + ); + return true; + } + if ($resolution === 'mixed' && !$metadataMixed) { + CloudTemplateCatalogService::settleRecoveredParentLocked( + $parent, + 'mixed' + ); + CloudUserIsoService::settleRecoveredParentLocked( + $parent, + 'mixed' + ); + self::deferAggregateRecoveryLocked( + $parent, + 'recovery_aggregate_state_conflict', + $now + ); + return true; + } + + // See reconcileAggregateParentEffectLocked(): only repair + // the catalog projection; never rewrite the failed audit. + CloudTemplateCatalogService::settleRecoveredParentLocked( + $parent, + $resolution + ); + CloudUserIsoService::settleRecoveredParentLocked( + $parent, + $resolution + ); + $publishedResolution = $metadataMixed + ? 'applied' : $resolution; + $lastChild = $children->last(); + $parent->effect_resolution = $publishedResolution; + $parent->effect_resolved_at = $now; + $parent->effect_resolved_by = null; + $parent->effect_resolution_reason = sprintf( + 'legacy_child_effects_resolved:%d:%s', + (int) $lastChild->id, + $publishedResolution + ); + $parent->finalization_incident = 0; + $parent->finalization_error_code = null; + $parent->lease_token = null; + $parent->lease_until = 0; + $parent->available_at = 0; + $parent->read_at = null; + $parent->updated_at = $now; + $parent->save(); + return true; + }, + 3 + ); + } catch (\Throwable $error) { + if ($claimedParentId < 1) { + throw $error; + } + // The first transaction rolled back both the resource projection + // and parent effect resolution. Persist only a delayed incident in + // a fresh transaction so one damaged legacy parent cannot abort + // every recovery tick or starve later jobs. + $connection->transaction( + static function () use ($claimedParentId, $error): void { + $parent = CloudJob::where('id', $claimedParentId) + ->lockForUpdate()->first(); + if ($parent === null + || (string) $parent->execution_mode !== 'aggregate' + || (string) $parent->phase !== 'terminal') { + return; + } + $unknownFence = (string) $parent->outcome === 'failed' + && (string) $parent->status === 'failed' + && (string) $parent->effect_resolution === 'unknown'; + $publishedParent = self::aggregateParentHasPublishedEffect( + $parent + ); + if (!$unknownFence && !$publishedParent) { + return; + } + self::deferAggregateRecoveryLocked( + $parent, + self::aggregateProjectionErrorCode($error), + time() + ); + }, + 3 + ); + error_log(sprintf( + 'cloud aggregate projection recovery pending job_id=%d error=%s', + $claimedParentId, + get_class($error) + )); + return true; + } + } + + /** Reject aggregate topology damage before any external fence mutation. */ + public static function assertAggregateChildRelationshipLocked( + CloudJob $parent, + CloudJob $child, + $children + ): void { + if (self::aggregateRelationshipConflict( + $parent, + $children, + (int) $child->id + )) { + throw new CloudRecoveryAggregateStateConflict( + '汇总任务与子任务账本关系异常', + 409 + ); + } + } + + private static function aggregateRelationshipConflict( + CloudJob $parent, + $children, + ?int $currentChildId = null + ): bool { + $parentId = (int) $parent->id; + $expectedKind = self::AGGREGATE_CHILD_KIND_MAP[ + (string) $parent->kind + ] ?? null; + return self::hasAggregateLocalStateConflict($parent) + || $expectedKind === null + || $children->isEmpty() + || ($currentChildId !== null && !$children->contains( + static fn (CloudJob $child): bool => + (int) $child->id === $currentChildId + )) + || $children->contains( + static fn (CloudJob $child): bool => + (int) ($child->parent_job_id ?? 0) !== $parentId + || (int) $child->user_id !== (int) $parent->user_id + || (string) $child->execution_mode !== 'agent' + || (string) $child->kind !== $expectedKind + || self::aggregateChildHasPhaseResolutionConflict($child) + || self::hasResolvedTerminalStateConflict($child) + ); + } + + /** + * SQL counterpart of hasAggregateLocalStateConflict() for terminal rows. + * This keeps an unbound, already-published parent reachable by the local + * ledger sweep without polling every healthy historical aggregate. + */ + private static function whereAggregateLocalStateConflict($damaged): void + { + $operationInvalid = self::invalidIdentifierCharactersSql( + 'operation_id', '0-9a-f' + ); + $fingerprintInvalid = self::invalidIdentifierCharactersSql( + 'request_fingerprint', '0-9a-f' + ); + $idempotencyInvalid = self::invalidIdentifierCharactersSql( + 'request_idempotency_key', 'A-Za-z0-9_.-' + ); + $damaged->where(static function ($invalid) use ( + $operationInvalid, + $fingerprintInvalid, + $idempotencyInvalid + ): void { + $invalid->whereNotNull('parent_job_id') + ->orWhereNotNull('host_id') + ->orWhereNotNull('instance_id') + ->orWhereNotNull('order_id') + ->orWhereNotNull('invoice_id') + ->orWhereNotNull('snapshot_id') + ->orWhereNull('user_id') + ->orWhere('user_id', '<', 1) + ->orWhereNull('attempts') + ->orWhere('attempts', '<>', 0) + ->orWhereNull('dispatch_attempts') + ->orWhere('dispatch_attempts', '<>', 0) + ->orWhereNull('dispatch_deadline_at') + ->orWhere('dispatch_deadline_at', '<', 1) + ->orWhereNull('receipt_deadline_at') + ->orWhere('receipt_deadline_at', '<', 1) + ->orWhereNotNull('dispatch_started_at') + ->orWhereNotNull('agent_accepted_at') + ->orWhereNotNull('dispatched_at') + ->orWhereNotNull('completion_event_id') + ->orWhereNull('operation_id') + ->orWhereRaw('LENGTH(operation_id) <> 32') + ->orWhereRaw('LOWER(operation_id) <> operation_id') + ->orWhereRaw($operationInvalid) + ->orWhereNull('request_fingerprint') + ->orWhereRaw('LENGTH(request_fingerprint) <> 64') + ->orWhereRaw( + 'LOWER(request_fingerprint) <> request_fingerprint' + )->orWhereRaw($fingerprintInvalid) + ->orWhereNull('request_idempotency_key') + ->orWhereRaw( + 'LENGTH(request_idempotency_key) NOT BETWEEN 16 AND 128' + )->orWhereRaw($idempotencyInvalid) + ->orWhereNull('terminal_at') + ->orWhere('terminal_at', '<', 1) + ->orWhereNull('outcome') + ->orWhereNotIn('outcome', ['succeeded', 'failed']) + ->orWhereNull('status') + ->orWhereColumn('status', '<>', 'outcome') + ->orWhere(static function ($succeeded): void { + $succeeded->where('outcome', 'succeeded') + ->where(static function ($mismatch): void { + $mismatch->whereNull('effect_resolution') + ->orWhere( + 'effect_resolution', + '<>', + 'applied' + )->orWhereNull('effect_may_have_applied') + ->orWhere('effect_may_have_applied', '<>', 0) + ->orWhereNull('safe_to_resubmit') + ->orWhere('safe_to_resubmit', '<>', 0) + ->orWhereNotNull('error_code'); + }); + })->orWhere(static function ($failed): void { + $failed->where('outcome', 'failed') + ->where(static function ($mismatch): void { + $mismatch->whereNull('effect_resolution') + ->orWhereNotIn( + 'effect_resolution', + ['unknown', 'applied', 'not_applied'] + )->orWhereNull('effect_may_have_applied') + ->orWhereNotIn( + 'effect_may_have_applied', + [0, 1] + )->orWhereNull('safe_to_resubmit') + ->orWhereNotIn('safe_to_resubmit', [0, 1]) + ->orWhere(static function ($effectful): void { + $effectful->where( + 'effect_may_have_applied', + 1 + )->where('safe_to_resubmit', '<>', 0); + })->orWhere(static function ($notEffectful): void { + $notEffectful->where( + 'effect_may_have_applied', + 0 + )->where( + 'effect_resolution', + '<>', + 'not_applied' + ); + }); + }); + }); + }); + } + + /** Add resolved Agent rows whose immutable dispatch envelope is damaged. */ + private static function applyInvalidResolvedAgentEnvelope( + $invalid, + string $prefix + ): void { + $operation = $prefix . 'operation_id'; + $fingerprint = $prefix . 'request_fingerprint'; + $idempotency = $prefix . 'request_idempotency_key'; + $invalid->whereNull($prefix . 'execution_mode') + ->orWhere($prefix . 'execution_mode', '<>', 'agent') + ->orWhereNull($prefix . 'dispatch_attempts') + ->orWhereNotIn($prefix . 'dispatch_attempts', [0, 1]) + ->orWhereNull($prefix . 'host_id') + ->orWhere($prefix . 'host_id', '<', 1) + ->orWhereNull($prefix . 'dispatch_deadline_at') + ->orWhere($prefix . 'dispatch_deadline_at', '<', 1) + ->orWhereNull($operation) + ->orWhereRaw('LENGTH(' . $operation . ') <> 32') + ->orWhereRaw('LOWER(' . $operation . ') <> ' . $operation) + ->orWhereRaw(self::invalidIdentifierCharactersSql( + $operation, + '0-9a-f' + ))->orWhereNull($fingerprint) + ->orWhereRaw('LENGTH(' . $fingerprint . ') <> 64') + ->orWhereRaw('LOWER(' . $fingerprint . ') <> ' . $fingerprint) + ->orWhereRaw(self::invalidIdentifierCharactersSql( + $fingerprint, + '0-9a-f' + ))->orWhereNull($idempotency) + ->orWhereRaw( + 'LENGTH(' . $idempotency . ') NOT BETWEEN 16 AND 128' + )->orWhereRaw(self::invalidIdentifierCharactersSql( + $idempotency, + 'A-Za-z0-9_.-' + ))->orWhere(static function ($dispatched) use ($prefix): void { + $dispatched->where($prefix . 'dispatch_attempts', 1) + ->where(static function ($broken) use ($prefix): void { + $broken->whereNull($prefix . 'attempts') + ->orWhere($prefix . 'attempts', '<>', 1) + ->orWhereNull($prefix . 'dispatch_started_at') + ->orWhere($prefix . 'dispatch_started_at', '<', 1) + ->orWhere(static function ($accepted) use ( + $prefix + ): void { + $accepted->whereNotNull( + $prefix . 'agent_accepted_at' + )->where( + $prefix . 'agent_accepted_at', + '<', + 1 + ); + }) + ->orWhereNull($prefix . 'dispatched_at') + ->orWhere($prefix . 'dispatched_at', '<', 1) + ->orWhereNull($prefix . 'receipt_deadline_at') + ->orWhere($prefix . 'receipt_deadline_at', '<', 1); + }); + })->orWhere(static function ($undispatched) use ($prefix): void { + $undispatched->where($prefix . 'dispatch_attempts', 0) + ->where(static function ($broken) use ($prefix): void { + $broken->whereNull($prefix . 'attempts') + ->orWhere($prefix . 'attempts', '<>', 0) + ->orWhereNotNull($prefix . 'dispatch_started_at') + ->orWhereNotNull($prefix . 'agent_accepted_at') + ->orWhereNotNull($prefix . 'dispatched_at') + ->orWhereNotNull($prefix . 'receipt_deadline_at') + ->orWhereNotNull($prefix . 'completion_event_id') + ->orWhere(static function ($success) use ( + $prefix + ): void { + $success->where( + $prefix . 'outcome', + 'succeeded' + )->where(static function ($notNoop) use ( + $prefix + ): void { + $notNoop->where( + $prefix . 'kind', + '<>', + 'firewall_apply' + )->orWhereNull($prefix . 'instance_id') + ->orWhere( + $prefix . 'instance_id', + '<', + 1 + )->orWhereRaw( + self::invalidFirewallNoopResultSql( + $prefix . 'result_json' + ) + ); + }); + }); + }); + }); + } + + /** Driver-specific JSON validation for the sole generation-zero success. */ + private static function invalidFirewallNoopResultSql(string $column): string + { + $driver = (new CloudJob())->getConnection()->getDriverName(); + if ($driver === 'sqlite') { + $digest = "json_extract(" . $column . ", '$.policy_digest')"; + return '(CASE WHEN COALESCE(json_valid(' . $column . '), 0) = 1 ' + . 'THEN CASE WHEN ' + . "json_type(" . $column . ", '$.unchanged') = 'true' AND " + . "json_type(" . $column . ", '$.policy_digest') = 'text' AND " + . 'LENGTH(' . $digest . ') = 64 AND NOT (' + . self::invalidIdentifierCharactersSql($digest, '0-9a-f') + . ') AND ' + . "json_type(" . $column . ", '$.revision') = 'integer' AND " + . "json_extract(" . $column . ", '$.revision') > 0 " + . 'THEN 0 ELSE 1 END ELSE 1 END) = 1'; + } + $digest = "JSON_UNQUOTE(JSON_EXTRACT(" . $column + . ", '$.policy_digest'))"; + $revision = "JSON_UNQUOTE(JSON_EXTRACT(" . $column + . ", '$.revision'))"; + return '(CASE WHEN COALESCE(JSON_VALID(' . $column . '), 0) = 1 ' + . 'THEN CASE WHEN JSON_UNQUOTE(JSON_EXTRACT(' . $column + . ", '$.unchanged')) = 'true' AND LENGTH(" . $digest + . ') = 64 AND NOT (' + . self::invalidIdentifierCharactersSql($digest, '0-9a-f') + . ') AND ' . $revision . " REGEXP '^[1-9][0-9]*$' " + . 'THEN 0 ELSE 1 END ELSE 1 END) = 1'; + } + + /** Build a portable invalid-character predicate for MySQL and SQLite. */ + private static function invalidIdentifierCharactersSql( + string $column, + string $allowedClass + ): string { + $driver = (new CloudJob())->getConnection()->getDriverName(); + if ($driver === 'sqlite') { + return $column . " GLOB '*[^" . $allowedClass . "]*'"; + } + return $column . " REGEXP '[^" . $allowedClass . "]'"; + } + + /** + * Raw-SQL counterpart of hasTerminalRecoveryStateConflict(). Inventory + * filters and counters cannot hydrate every row before filtering, so keep + * their fail-closed envelope test in the same service as the DTO check. + */ + public static function terminalRecoveryStateConflictSql( + string $alias + ): string { + $supported = self::quotedSqlValues( + CloudOperationRecoveryPolicy::kinds() + ); + $operation = $alias . '.operation_id'; + $fingerprint = $alias . '.request_fingerprint'; + $idempotency = $alias . '.request_idempotency_key'; + $invalidEnvelope = '(' . $alias . '.execution_mode IS NULL OR ' + . $alias . ".execution_mode <> 'agent' OR " + . $alias . '.dispatch_attempts IS NULL OR ' + . $alias . '.dispatch_attempts NOT IN (0, 1) OR ' + . $alias . '.host_id IS NULL OR ' . $alias . '.host_id < 1 OR ' + . $alias . '.dispatch_deadline_at IS NULL OR ' + . $alias . '.dispatch_deadline_at < 1 OR ' + . $operation . ' IS NULL OR LENGTH(' . $operation . ') <> 32 OR ' + . 'LOWER(' . $operation . ') <> ' . $operation . ' OR ' + . self::invalidIdentifierCharactersSql($operation, '0-9a-f') + . ' OR ' . $fingerprint . ' IS NULL OR LENGTH(' + . $fingerprint . ') <> 64 OR LOWER(' . $fingerprint . ') <> ' + . $fingerprint . ' OR ' + . self::invalidIdentifierCharactersSql($fingerprint, '0-9a-f') + . ' OR ' . $idempotency . ' IS NULL OR LENGTH(' + . $idempotency . ') NOT BETWEEN 16 AND 128 OR ' + . self::invalidIdentifierCharactersSql( + $idempotency, + 'A-Za-z0-9_.-' + ) . ' OR (' . $alias . '.dispatch_attempts = 1 AND (' + . $alias . '.attempts IS NULL OR ' . $alias . '.attempts <> 1 OR ' + . $alias . '.dispatch_started_at IS NULL OR ' + . $alias . '.dispatch_started_at < 1 OR (' + . $alias . '.agent_accepted_at IS NOT NULL AND ' + . $alias . '.agent_accepted_at < 1) OR ' + . $alias . '.dispatched_at IS NULL OR ' + . $alias . '.dispatched_at < 1 OR ' + . $alias . '.receipt_deadline_at IS NULL OR ' + . $alias . '.receipt_deadline_at < 1)) OR (' + . $alias . '.dispatch_attempts = 0 AND (' + . $alias . '.attempts IS NULL OR ' . $alias . '.attempts <> 0 OR ' + . $alias . '.dispatch_started_at IS NOT NULL OR ' + . $alias . '.agent_accepted_at IS NOT NULL OR ' + . $alias . '.dispatched_at IS NOT NULL OR ' + . $alias . '.receipt_deadline_at IS NOT NULL OR ' + . $alias . '.completion_event_id IS NOT NULL OR (' + . $alias . ".outcome = 'succeeded' AND (" + . $alias . ".kind <> 'firewall_apply' OR " + . $alias . '.instance_id IS NULL OR ' + . $alias . '.instance_id < 1 OR ' + . self::invalidFirewallNoopResultSql( + $alias . '.result_json' + ) . ')))))'; + $invalidResolved = '(' . $alias + . ".effect_resolution IN ('applied', 'not_applied') AND (" + . $alias . '.terminal_at IS NULL OR ' + . $alias . '.terminal_at < 1 OR ' + . $alias . '.outcome IS NULL OR ' + . $alias . ".outcome NOT IN ('succeeded', 'failed') OR (" + . $alias . ".outcome = 'succeeded' AND (" + . $alias . ".status IS NULL OR " + . $alias . ".status <> 'succeeded' OR " + . $alias . ".effect_resolution <> 'applied' OR " + . $alias . '.effect_may_have_applied IS NULL OR ' + . $alias . '.effect_may_have_applied <> 0 OR ' + . $alias . '.safe_to_resubmit IS NULL OR ' + . $alias . '.safe_to_resubmit <> 0 OR ' + . $alias . '.error_code IS NOT NULL)) OR (' + . $alias . ".outcome = 'failed' AND (" + . $alias . ".status IS NULL OR " + . $alias . ".status <> 'failed' OR " + . $alias . '.effect_may_have_applied IS NULL OR ' + . $alias . '.effect_may_have_applied NOT IN (0, 1) OR (' + . $alias . '.effect_may_have_applied = 1 AND (' + . $alias . '.safe_to_resubmit IS NULL OR ' + . $alias . '.safe_to_resubmit <> 0)) OR (' + . $alias . '.effect_may_have_applied = 0 AND (' + . $alias . ".effect_resolution <> 'not_applied' OR " + . $alias . '.safe_to_resubmit IS NULL OR ' + . $alias . '.safe_to_resubmit NOT IN (0, 1))))) OR ' + . $invalidEnvelope . '))'; + $invalidUnknown = '(' . $alias . ".effect_resolution = 'unknown' AND ((" + . $alias . '.dispatch_attempts = 0 AND COALESCE(' + . $alias . '.finalization_incident, 0) = 0) OR NOT (' + . "COALESCE(" . $alias . ".outcome, '') = 'failed' AND " + . "COALESCE(" . $alias . ".status, '') = 'failed' AND " + . 'COALESCE(' . $alias . '.effect_may_have_applied, 0) = 1 AND ' + . 'COALESCE(' . $alias . '.safe_to_resubmit, 1) = 0)))'; + return '(' . $alias . ".phase = 'terminal' AND " + . $alias . '.kind IN (' . $supported . ') AND (' + . $alias . '.execution_mode IS NULL OR ' + . $alias . ".execution_mode <> 'agent' OR " + . $alias . '.dispatch_attempts IS NULL OR ' + . $alias . '.dispatch_attempts NOT IN (0, 1) OR ' + . $invalidEnvelope . ' OR ' . $invalidUnknown . ' OR ' + . $invalidResolved . '))'; + } + + /** SQL counterpart of hasAggregateLocalStateConflict() for terminal rows. */ + public static function aggregateLocalStateConflictSql( + string $alias + ): string { + $kinds = self::quotedSqlValues(self::AGGREGATE_KINDS); + $operation = $alias . '.operation_id'; + $fingerprint = $alias . '.request_fingerprint'; + $idempotency = $alias . '.request_idempotency_key'; + return '(' . $alias . ".phase = 'terminal' AND (" + . $alias . ".execution_mode = 'aggregate' OR " + . $alias . '.kind IN (' . $kinds . ')) AND (' + . $alias . '.execution_mode IS NULL OR ' + . $alias . ".execution_mode <> 'aggregate' OR " + . $alias . '.kind IS NULL OR ' + . $alias . '.kind NOT IN (' . $kinds . ') OR ' + . $alias . '.parent_job_id IS NOT NULL OR ' + . $alias . '.host_id IS NOT NULL OR ' + . $alias . '.instance_id IS NOT NULL OR ' + . $alias . '.order_id IS NOT NULL OR ' + . $alias . '.invoice_id IS NOT NULL OR ' + . $alias . '.snapshot_id IS NOT NULL OR ' + . $alias . '.user_id IS NULL OR ' . $alias . '.user_id < 1 OR ' + . $alias . '.attempts IS NULL OR ' . $alias . '.attempts <> 0 OR ' + . $alias . '.dispatch_attempts IS NULL OR ' + . $alias . '.dispatch_attempts <> 0 OR ' + . $alias . '.dispatch_deadline_at IS NULL OR ' + . $alias . '.dispatch_deadline_at < 1 OR ' + . $alias . '.receipt_deadline_at IS NULL OR ' + . $alias . '.receipt_deadline_at < 1 OR ' + . $alias . '.dispatch_started_at IS NOT NULL OR ' + . $alias . '.agent_accepted_at IS NOT NULL OR ' + . $alias . '.dispatched_at IS NOT NULL OR ' + . $alias . '.completion_event_id IS NOT NULL OR ' + . $operation . ' IS NULL OR LENGTH(' . $operation . ') <> 32 OR ' + . 'LOWER(' . $operation . ') <> ' . $operation . ' OR ' + . self::invalidIdentifierCharactersSql($operation, '0-9a-f') + . ' OR ' . $fingerprint . ' IS NULL OR LENGTH(' + . $fingerprint . ') <> 64 OR LOWER(' . $fingerprint . ') <> ' + . $fingerprint . ' OR ' + . self::invalidIdentifierCharactersSql($fingerprint, '0-9a-f') + . ' OR ' . $idempotency . ' IS NULL OR LENGTH(' + . $idempotency . ') NOT BETWEEN 16 AND 128 OR ' + . self::invalidIdentifierCharactersSql( + $idempotency, + 'A-Za-z0-9_.-' + ) . ' OR ' . $alias . '.terminal_at IS NULL OR ' + . $alias . '.terminal_at < 1 OR ' + . $alias . '.outcome IS NULL OR ' + . $alias . ".outcome NOT IN ('succeeded', 'failed') OR " + . $alias . '.status IS NULL OR ' + . $alias . '.status <> ' . $alias . '.outcome OR (' + . $alias . ".outcome = 'succeeded' AND (" + . $alias . ".effect_resolution IS NULL OR " + . $alias . ".effect_resolution <> 'applied' OR " + . $alias . '.effect_may_have_applied IS NULL OR ' + . $alias . '.effect_may_have_applied <> 0 OR ' + . $alias . '.safe_to_resubmit IS NULL OR ' + . $alias . '.safe_to_resubmit <> 0 OR ' + . $alias . '.error_code IS NOT NULL)) OR (' + . $alias . ".outcome = 'failed' AND (" + . $alias . '.effect_resolution IS NULL OR ' + . $alias . ".effect_resolution NOT IN ('unknown', 'applied', 'not_applied') OR " + . $alias . '.effect_may_have_applied IS NULL OR ' + . $alias . '.effect_may_have_applied NOT IN (0, 1) OR ' + . $alias . '.safe_to_resubmit IS NULL OR ' + . $alias . '.safe_to_resubmit NOT IN (0, 1) OR (' + . $alias . '.effect_may_have_applied = 1 AND ' + . $alias . '.safe_to_resubmit <> 0) OR (' + . $alias . '.effect_may_have_applied = 0 AND ' + . $alias . ".effect_resolution <> 'not_applied')))))"; + } + + /** @param list $values */ + private static function quotedSqlValues(array $values): string + { + return implode(', ', array_map( + static fn (string $value): string => "'" + . str_replace("'", "''", $value) . "'", + $values + )); + } + + /** Add the catalog-driven candidate predicate without assuming job shape. */ + private static function whereCurrentAggregateCatalogBinding($bound): void + { + $bound->whereExists(static function ($templates): void { + $templates->selectRaw('1') + ->from('cloud_templates as current_templates') + ->whereColumn( + 'current_templates.active_job_id', + 'cloud_jobs.id' + ); + })->orWhereExists(static function ($isos): void { + $isos->selectRaw('1') + ->from('cloud_user_isos as current_isos') + ->whereColumn( + 'current_isos.active_job_id', + 'cloud_jobs.id' + ); + })->orWhere(static function ($repairable): void { + self::whereRepairableMissingAggregateCatalogPointer( + $repairable + ); + }); + } + + /** + * Keep a terminal parent discoverable when only active_job_id was cleared. + * This predicate is intentionally broad enough to surface ambiguity; the + * service-level locked repair performs the complete one-to-one proof. + */ + private static function whereRepairableMissingAggregateCatalogPointer( + $candidate + ): void { + $candidate->whereExists(static function ($templates): void { + $templates->selectRaw('1') + ->from('cloud_template_replicas as pointer_template_replicas') + ->join( + 'cloud_templates as pointer_templates', + 'pointer_templates.id', + '=', + 'pointer_template_replicas.template_id' + )->join( + 'cloud_jobs as pointer_template_children', + 'pointer_template_children.id', + '=', + 'pointer_template_replicas.job_id' + )->whereColumn( + 'pointer_template_children.parent_job_id', + 'cloud_jobs.id' + )->where(static function ($missing): void { + $missing->whereNull('pointer_templates.active_job_id') + ->orWhere( + 'pointer_templates.active_job_id', + '<=', + 0 + )->orWhereColumn( + 'pointer_templates.active_job_id', + '<>', + 'cloud_jobs.id' + ); + })->where(static function ($identity): void { + $identity->where(static function ($import): void { + $import->where('cloud_jobs.kind', 'template_import') + ->where( + 'pointer_template_children.kind', + 'template_import_replica' + )->whereIn( + 'pointer_templates.state', + ['importing', 'error', 'active'] + ); + })->orWhere(static function ($metadata): void { + $metadata->where( + 'cloud_jobs.kind', + 'template_metadata_sync' + )->where( + 'pointer_template_children.kind', + 'template_metadata_replica' + )->where( + 'pointer_templates.state', + 'active' + )->where(static function ($evidence): void { + $evidence->whereIn( + 'pointer_template_replicas.state', + ['syncing', 'stale'] + )->orWhere(static function ($unknown): void { + $unknown->where( + 'cloud_jobs.outcome', + 'failed' + )->where( + 'cloud_jobs.status', + 'failed' + )->where( + 'cloud_jobs.effect_resolution', + 'unknown' + ); + })->orWhere( + 'cloud_jobs.finalization_incident', + 1 + )->orWhere(static function ($damaged): void { + $damaged->where( + 'pointer_templates.active_job_id', + '>', + 0 + )->whereColumn( + 'pointer_templates.active_job_id', + '<>', + 'cloud_jobs.id' + ); + }); + }); + })->orWhere(static function ($delete): void { + $delete->where('cloud_jobs.kind', 'template_delete') + ->where( + 'pointer_template_children.kind', + 'template_delete_replica' + )->whereIn( + 'pointer_templates.state', + ['deleting', 'delete_failed', 'active'] + ); + }); + }); + })->orWhereExists(static function ($isos): void { + $isos->selectRaw('1') + ->from('cloud_user_iso_replicas as pointer_iso_replicas') + ->join( + 'cloud_user_isos as pointer_isos', + 'pointer_isos.id', + '=', + 'pointer_iso_replicas.user_iso_id' + )->join( + 'cloud_jobs as pointer_iso_children', + 'pointer_iso_children.id', + '=', + 'pointer_iso_replicas.job_id' + )->whereColumn( + 'pointer_iso_children.parent_job_id', + 'cloud_jobs.id' + )->where(static function ($missing): void { + $missing->whereNull('pointer_isos.active_job_id') + ->orWhere('pointer_isos.active_job_id', '<=', 0) + ->orWhereColumn( + 'pointer_isos.active_job_id', + '<>', + 'cloud_jobs.id' + ); + })->where(static function ($identity): void { + $identity->where(static function ($import): void { + $import->where('cloud_jobs.kind', 'user_iso_import') + ->where( + 'pointer_iso_children.kind', + 'user_iso_import_replica' + )->whereIn( + 'pointer_isos.state', + ['importing', 'import_failed', 'active'] + ); + })->orWhere(static function ($delete): void { + $delete->where('cloud_jobs.kind', 'user_iso_delete') + ->where( + 'pointer_iso_children.kind', + 'user_iso_delete_replica' + )->whereIn( + 'pointer_isos.state', + ['deleting', 'delete_failed', 'active'] + ); + }); + }); + }); + } + + /** A final effect cannot be published while its leaf is still nonterminal. */ + private static function aggregateChildHasPhaseResolutionConflict( + CloudJob $child + ): bool { + return (string) $child->phase !== 'terminal' + && in_array( + (string) $child->effect_resolution, + ['applied', 'not_applied'], + true + ); + } + + /** Return the uniform effect, mixed, or null for an invalid child state. */ + private static function aggregateEffectResolution($children): ?string + { + $resolutions = $children->map( + static fn (CloudJob $child): string => + (string) $child->effect_resolution + )->unique()->values(); + if ($resolutions->contains( + static fn ($resolution): bool => !in_array( + (string) $resolution, + ['applied', 'not_applied'], + true + ) + )) { + return null; + } + return $resolutions->count() === 1 + ? (string) $resolutions->first() : 'mixed'; + } + + private static function aggregateParentHasPublishedEffect( + CloudJob $parent + ): bool { + return (string) $parent->phase === 'terminal' + && in_array( + (string) $parent->effect_resolution, + ['applied', 'not_applied'], + true + ); + } + + /** Revalidate a published aggregate without rewriting its terminal audit. */ + private static function recheckPublishedAggregateProjectionLocked( + CloudJob $parent, + string $resolution, + bool $metadataMixed + ): void { + try { + $bindingState = self::currentAggregateBindingStateLocked($parent); + } catch (\Throwable $error) { + self::deferAggregateRecoveryLocked( + $parent, + self::aggregateProjectionErrorCode($error), + time() + ); + return; + } + if ($bindingState === 'conflict') { + self::deferAggregateRecoveryLocked( + $parent, + 'recovery_aggregate_state_conflict', + time() + ); + return; + } + if ($bindingState === 'absent') { + if ((bool) $parent->finalization_incident) { + $errorCode = strtolower(trim((string) ( + $parent->finalization_error_code ?? '' + ))); + self::deferAggregateRecoveryLocked( + $parent, + preg_match( + '/^recovery_[a-z0-9_]{1,55}$/D', + $errorCode + ) === 1 ? $errorCode : 'recovery_ledger_conflict', + time() + ); + return; + } + $parent->lease_token = null; + $parent->lease_until = 0; + $parent->available_at = time() + self::RECOVERY_RETRY_SECONDS; + $parent->updated_at = time(); + $parent->save(); + return; + } + if ($resolution === 'mixed' && !$metadataMixed) { + self::deferAggregateRecoveryLocked( + $parent, + 'recovery_aggregate_state_conflict', + time() + ); + return; + } + $publishedResolution = $metadataMixed ? 'applied' : $resolution; + if (!hash_equals( + (string) $parent->effect_resolution, + $publishedResolution + )) { + self::deferAggregateRecoveryLocked( + $parent, + 'recovery_aggregate_state_conflict', + time() + ); + return; + } + try { + if (str_starts_with((string) $parent->kind, 'template_')) { + CloudTemplateCatalogService:: + assertSettledParentProjectionLocked( + $parent, + $resolution + ); + } else { + CloudUserIsoService::assertSettledParentProjectionLocked( + $parent, + $resolution + ); + } + } catch (\Throwable $error) { + self::deferAggregateRecoveryLocked( + $parent, + self::aggregateProjectionErrorCode($error), + time() + ); + return; + } + $now = time(); + $clearedIncident = (bool) $parent->finalization_incident; + if ($clearedIncident) { + $parent->finalization_incident = 0; + $parent->finalization_error_code = null; + $parent->read_at = null; + } + $parent->lease_token = null; + $parent->lease_until = 0; + $parent->available_at = $now + self::RECOVERY_RETRY_SECONDS; + $parent->updated_at = $now; + $parent->save(); + } + + /** + * Lock both catalog authorities in one order and classify their binding. + * + * @return 'valid'|'absent'|'conflict' + */ + private static function currentAggregateBindingStateLocked( + CloudJob $parent + ): string { + $templates = CloudTemplate::query() + ->where('active_job_id', (int) $parent->id) + ->orderBy('id')->lockForUpdate()->get(['id']); + $isos = CloudUserIso::query() + ->where('active_job_id', (int) $parent->id) + ->orderBy('id')->lockForUpdate()->get(['id']); + if ($templates->isEmpty() && $isos->isEmpty()) { + $kind = (string) $parent->kind; + if (in_array($kind, [ + 'template_import', 'template_metadata_sync', + 'template_delete', + ], true)) { + CloudTemplateCatalogService::repairMissingParentBindingLocked( + $parent + ); + } elseif (in_array($kind, [ + 'user_iso_import', 'user_iso_delete', + ], true)) { + CloudUserIsoService::repairMissingParentBindingLocked($parent); + } else { + return 'absent'; + } + $templates = CloudTemplate::query() + ->where('active_job_id', (int) $parent->id) + ->orderBy('id')->lockForUpdate()->get(['id']); + $isos = CloudUserIso::query() + ->where('active_job_id', (int) $parent->id) + ->orderBy('id')->lockForUpdate()->get(['id']); + } + if (str_starts_with((string) $parent->kind, 'template_')) { + return $templates->count() === 1 && $isos->isEmpty() + ? 'valid' : 'conflict'; + } + if (str_starts_with((string) $parent->kind, 'user_iso_')) { + return $isos->count() === 1 && $templates->isEmpty() + ? 'valid' : 'conflict'; + } + return 'conflict'; + } + + /** @return list */ + public static function aggregateProjectionIncidentCodes(): array + { + return [ + CloudDispatchLedger::CONFLICT_CODE, + 'recovery_child_convergence', + 'recovery_aggregate_state_conflict', + 'recovery_payload_unavailable', + 'recovery_operation_identity_conflict', + 'recovery_instance_state_conflict', + 'recovery_ledger_conflict', + 'recovery_internal_error', + ]; + } + + private static function deferAggregateRecoveryLocked( + CloudJob $parent, + string $errorCode, + int $now + ): void { + $parent->read_at = null; + $parent->finalization_incident = 1; + $parent->finalization_error_code = $errorCode; + $parent->lease_token = null; + $parent->lease_until = 0; + $parent->available_at = $now + self::RECOVERY_RETRY_SECONDS; + $parent->updated_at = $now; + $parent->save(); + } + + private static function aggregateProjectionErrorCode( + \Throwable $error + ): string { + return match (true) { + $error instanceof CloudRecoveryDispatchLedgerConflict => + CloudDispatchLedger::CONFLICT_CODE, + $error instanceof CloudRecoveryAggregateStateConflict => + 'recovery_aggregate_state_conflict', + $error instanceof CloudRecoveryPayloadUnavailable => + 'recovery_payload_unavailable', + $error instanceof CloudRecoveryOperationIdentityConflict => + 'recovery_operation_identity_conflict', + $error instanceof CloudRecoveryInstanceStateConflict => + 'recovery_instance_state_conflict', + $error instanceof CloudError => 'recovery_ledger_conflict', + default => 'recovery_internal_error', + }; + } + public static function enqueue(CloudInstance $instance, array $actor, string $kind, string $method, string $suffix, array $body = [], ?array $credential = null): CloudJob { @@ -842,11 +2639,19 @@ final class CloudJobService if ($lockedPrior === null) { throw new CloudError('任务不存在', 404); } + if ((bool) ($lockedPrior->finalization_incident ?? false) + || self::hasTerminalRecoveryStateConflict($lockedPrior)) { + throw new CloudError( + '原删除任务的恢复账本异常尚未收敛,不能创建新的强制删除任务', + 409 + ); + } if (!in_array((string) $lockedPrior->kind, ['delete', 'expiry_delete', 'service_suspend'], true) || (string) $lockedPrior->phase !== 'terminal' || (string) $lockedPrior->outcome !== 'failed' || (string) $lockedPrior->error_code !== 'force_required' + || !CloudDispatchLedger::isDispatched($lockedPrior) || $lockedPrior->dispatched_at === null || preg_match('/^[a-f0-9]{32}$/D', (string) $lockedPrior->operation_id) !== 1 @@ -953,6 +2758,10 @@ final class CloudJobService 'action_label' => $labels['action_label'], ]; if (!$completed) { + $recovery = self::recoveryPresentation($job, $administrator); + if ($recovery !== null) { + $base['recovery'] = $recovery; + } return $base; } $result = $job->result_json === null ? null : json_decode($job->result_json, true); @@ -993,9 +2802,859 @@ final class CloudJobService // presenting an already-released resource fence as active. $terminal['effect_resolution'] = $effectResolution; } + $recovery = self::recoveryPresentation($job, $administrator); + if ($recovery !== null) { + $terminal['recovery'] = $recovery; + } return array_merge($base, $terminal); } + /** + * Return a bounded recovery status for panels. Arbitrary server/Agent + * exception text never crosses this DTO; unknown recovery codes collapse + * to one reviewed message. + */ + public static function recoveryPresentation( + CloudJob $job, + bool $administrator = false + ): ?array { + $mode = self::recoveryMode($job); + if ($mode === null) { + return null; + } + if ($mode === 'aggregate') { + $details = self::aggregateRecoveryDetails($job); + $code = $details['code']; + $message = $details['message']; + } else { + $candidate = self::agentRecoveryPresentationCandidate($job); + if ($mode === 'local_finalizer' + && in_array( + $candidate, + CloudDispatchLedger::repairIncidentCodes(), + true + )) { + $candidate = 'recovery_ledger_conflict'; + } + $code = array_key_exists($candidate, self::RECOVERY_MESSAGES) + ? $candidate : ($mode === 'local_finalizer' + ? 'recovery_ledger_conflict' : 'recovery_pending'); + $message = self::RECOVERY_MESSAGES[$code]; + } + $nextCheckAt = max(0, (int) ($job->available_at ?? 0)); + $lastCheckedAt = max(0, (int) ($job->updated_at ?? 0)); + if ($mode === 'aggregate') { + $nextCheckAt = max($nextCheckAt, $details['next_check_at']); + $lastCheckedAt = max( + $lastCheckedAt, + $details['last_checked_at'] + ); + } + $result = [ + 'pending' => true, + 'message' => $message, + 'last_checked_at' => $lastCheckedAt > 0 + ? $lastCheckedAt : null, + 'next_check_at' => $nextCheckAt > time() + ? $nextCheckAt : null, + ]; + if ($administrator) { + $result['code'] = $code; + if ($mode === 'aggregate') { + $result['affected_child_count'] = + $details['affected_child_count']; + $result['additional_error_count'] = + $details['additional_error_count']; + } + } + return $result; + } + + /** Select the most actionable reviewed cause without exposing raw text. */ + private static function agentRecoveryPresentationCandidate( + CloudJob $job + ): string { + if (CloudDispatchLedger::isInvalid($job)) { + return CloudDispatchLedger::CONFLICT_CODE; + } + $stored = strtolower(trim( + (string) ($job->finalization_error_code ?? '') + )); + if (CloudDispatchLedger::hasRepairIncident($job) + && array_key_exists($stored, self::RECOVERY_MESSAGES)) { + return $stored; + } + if (self::hasAgentRecoveryIdentityConflict($job)) { + return 'recovery_operation_identity_conflict'; + } + if (in_array($stored, [ + 'recovery_operation_identity_conflict', + 'recovery_receipt_invalid', + 'recovery_completion_outbox_invalid', + 'recovery_completion_receipt_missing', + 'recovery_completion_receipt_invalid', + 'recovery_completion_operation_missing', + 'recovery_completion_operation_invalid', + 'recovery_completion_identity_mismatch', + 'recovery_payload_invalid', + 'recovery_payload_unavailable', + ], true)) { + return $stored; + } + if (self::hasTerminalRecoveryStateConflict($job)) { + return 'recovery_instance_state_conflict'; + } + return $stored; + } + + private static function recoveryMode(CloudJob $job): ?string + { + $kind = (string) $job->kind; + $aggregateIdentity = (string) $job->execution_mode === 'aggregate' + || in_array($kind, self::AGGREGATE_KINDS, true); + if ($aggregateIdentity) { + $ownFence = (string) $job->phase === 'terminal' + && (string) $job->outcome === 'failed' + && (string) $job->status === 'failed' + && (bool) $job->effect_may_have_applied + && !(bool) $job->safe_to_resubmit + && (string) $job->effect_resolution === 'unknown'; + $stickyIncident = (string) $job->phase === 'terminal' + && (bool) $job->finalization_incident; + if ($ownFence || $stickyIncident + || self::hasTerminalRecoveryStateConflict($job) + || self::hasUnresolvedRecoverableChildren($job)) { + return 'aggregate'; + } + return null; + } + if ((string) $job->execution_mode === 'agent' + && CloudDispatchLedger::isInvalid($job)) { + return 'agent'; + } + if (CloudDispatchLedger::hasRepairIncident($job)) { + return 'agent'; + } + if (self::isLocalFinalizerRecovery($job)) { + return 'local_finalizer'; + } + if (self::isResolvedStickyAgentIncident($job)) { + return 'agent'; + } + if (self::hasTerminalRecoveryStateConflict($job)) { + return 'agent'; + } + if ((string) $job->phase !== 'terminal' + || (string) $job->outcome !== 'failed' + || (string) $job->status !== 'failed' + || !(bool) $job->effect_may_have_applied + || (bool) $job->safe_to_resubmit + || (string) $job->effect_resolution !== 'unknown') { + return null; + } + if ((string) $job->execution_mode === 'agent' + && (int) $job->dispatch_attempts === 1 + && CloudOperationRecoveryPolicy::supports($kind)) { + return 'agent'; + } + return null; + } + + private static function hasUnresolvedRecoverableChildren( + CloudJob $parent + ): bool { + if ((int) $parent->id < 1) { + return false; + } + return CloudJob::where('parent_job_id', (int) $parent->id) + ->whereIn('kind', CloudOperationRecoveryPolicy::kinds()) + ->where(static function ($pending): void { + $pending->where(static function ($mode): void { + $mode->whereNull('execution_mode') + ->orWhere('execution_mode', '<>', 'agent'); + })->orWhere(static function ($invalid): void { + $invalid->whereNull('dispatch_attempts') + ->orWhereNotIn('dispatch_attempts', [0, 1]); + })->orWhere(static function ($repair): void { + $repair->where('phase', 'terminal') + ->where('finalization_incident', 1) + ->whereIn( + 'finalization_error_code', + CloudDispatchLedger::repairIncidentCodes() + ); + })->orWhere(static function ($local): void { + $local->where('phase', 'terminal') + ->where('outcome', 'failed') + ->where('status', 'failed') + ->where('dispatch_attempts', 0) + ->where('finalization_incident', 1); + })->orWhere(static function ($sticky): void { + $sticky->where('phase', 'terminal') + ->where('finalization_incident', 1); + }) + ->orWhere(static function ($normal): void { + $normal->where('phase', 'terminal') + ->where('outcome', 'failed') + ->where('status', 'failed') + ->where('dispatch_attempts', 1) + ->where('effect_may_have_applied', 1) + ->where('safe_to_resubmit', 0) + ->where('effect_resolution', 'unknown'); + })->orWhere(static function ($state): void { + $state->where('phase', 'terminal') + ->whereIn('dispatch_attempts', [0, 1]) + ->where('effect_resolution', 'unknown') + ->where(static function ($invalid): void { + self::applyInvalidTerminalTuple($invalid); + }); + })->orWhere(static function ($phase): void { + $phase->where('phase', '<>', 'terminal') + ->whereIn( + 'effect_resolution', + ['applied', 'not_applied'] + ); + })->orWhere(static function ($resolved): void { + $resolved->where('phase', 'terminal') + ->whereIn('dispatch_attempts', [0, 1]) + ->where(static function ($invalid): void { + self::applyInvalidResolvedTerminalTuple( + $invalid + ); + }); + }); + }) + ->exists(); + } + + private static function unresolvedRecoverableChildExists($children): void + { + $children->selectRaw('1') + ->from('cloud_jobs as recovery_children') + ->whereColumn( + 'recovery_children.parent_job_id', + 'cloud_jobs.id' + ) + ->whereIn( + 'recovery_children.kind', + CloudOperationRecoveryPolicy::kinds() + )->where(static function ($pending): void { + $pending->where(static function ($mode): void { + $mode->whereNull('recovery_children.execution_mode') + ->orWhere( + 'recovery_children.execution_mode', + '<>', + 'agent' + ); + })->orWhere(static function ($invalid): void { + $invalid->whereNull( + 'recovery_children.dispatch_attempts' + )->orWhereNotIn( + 'recovery_children.dispatch_attempts', + [0, 1] + ); + })->orWhere(static function ($repair): void { + $repair->where( + 'recovery_children.phase', + 'terminal' + )->where( + 'recovery_children.finalization_incident', + 1 + )->whereIn( + 'recovery_children.finalization_error_code', + CloudDispatchLedger::repairIncidentCodes() + ); + })->orWhere(static function ($local): void { + $local->where( + 'recovery_children.phase', + 'terminal' + )->where( + 'recovery_children.outcome', + 'failed' + )->where( + 'recovery_children.status', + 'failed' + )->where( + 'recovery_children.dispatch_attempts', + 0 + )->where( + 'recovery_children.finalization_incident', + 1 + ); + })->orWhere(static function ($sticky): void { + $sticky->where( + 'recovery_children.phase', + 'terminal' + )->where( + 'recovery_children.finalization_incident', + 1 + ); + })->orWhere(static function ($normal): void { + $normal->where( + 'recovery_children.phase', + 'terminal' + )->where( + 'recovery_children.outcome', + 'failed' + )->where( + 'recovery_children.status', + 'failed' + )->where( + 'recovery_children.dispatch_attempts', + 1 + )->where( + 'recovery_children.effect_may_have_applied', + 1 + )->where( + 'recovery_children.safe_to_resubmit', + 0 + )->where( + 'recovery_children.effect_resolution', + 'unknown' + ); + })->orWhere(static function ($state): void { + $state->where( + 'recovery_children.phase', + 'terminal' + )->whereIn( + 'recovery_children.dispatch_attempts', + [0, 1] + )->where( + 'recovery_children.effect_resolution', + 'unknown' + )->where(static function ($invalid): void { + self::applyInvalidTerminalTuple( + $invalid, + 'recovery_children.' + ); + }); + })->orWhere(static function ($phase): void { + $phase->where( + 'recovery_children.phase', + '<>', + 'terminal' + )->whereIn( + 'recovery_children.effect_resolution', + ['applied', 'not_applied'] + ); + })->orWhere(static function ($resolved): void { + $resolved->where( + 'recovery_children.phase', + 'terminal' + )->whereIn( + 'recovery_children.dispatch_attempts', + [0, 1] + )->where(static function ($invalid): void { + self::applyInvalidResolvedTerminalTuple( + $invalid, + 'recovery_children.' + ); + }); + }); + }); + } + + /** + * Select one deterministic, reviewed child incident for the public batch. + * Raw Agent/exception text and child result payloads never enter this DTO. + * + * @return array{code:string,message:string,affected_child_count:int,additional_error_count:int,last_checked_at:int,next_check_at:int} + */ + private static function aggregateRecoveryDetails(CloudJob $parent): array + { + if (!$parent->exists) { + // display() is also used with detached, read-only task snapshots + // (for example notification/rendering contracts). Only persisted + // aggregate jobs have child rows that can be safely summarized. + return [ + 'code' => 'recovery_child_convergence', + 'message' => self::RECOVERY_MESSAGES[ + 'recovery_child_convergence' + ], + 'affected_child_count' => 0, + 'additional_error_count' => 0, + 'last_checked_at' => max(0, (int) $parent->updated_at), + 'next_check_at' => max(0, (int) $parent->available_at), + ]; + } + $children = CloudJob::where('parent_job_id', (int) $parent->id) + ->orderBy('id') + ->get([ + 'id', 'operation_id', 'request_idempotency_key', + 'request_fingerprint', 'parent_job_id', 'instance_id', + 'user_id', 'host_id', 'kind', 'execution_mode', + 'phase', 'outcome', 'status', 'attempts', + 'dispatch_attempts', 'dispatch_deadline_at', + 'dispatch_started_at', 'agent_accepted_at', 'dispatched_at', + 'receipt_deadline_at', 'terminal_at', 'completion_event_id', + 'error_code', 'result_json', + 'effect_may_have_applied', 'safe_to_resubmit', + 'effect_resolution', 'finalization_incident', + 'finalization_error_code', + 'available_at', 'updated_at', + ]); + $expectedKind = self::AGGREGATE_CHILD_KIND_MAP[ + (string) $parent->kind + ] ?? null; + $parentStateConflict = self::hasAggregateLocalStateConflict($parent) + || (string) ($parent->finalization_error_code ?? '') + === 'recovery_aggregate_state_conflict'; + $parentCandidate = $parentStateConflict + ? 'recovery_aggregate_state_conflict' + : strtolower(trim( + (string) ($parent->finalization_error_code ?? '') + )); + $parentCode = array_key_exists( + $parentCandidate, + self::RECOVERY_MESSAGES + ) ? $parentCandidate : null; + if ($parentCode === null && (bool) $parent->finalization_incident) { + $parentCode = 'recovery_ledger_conflict'; + } + $relationshipConflict = $parentCandidate + === 'recovery_aggregate_state_conflict' + || $expectedKind === null + || $children->isEmpty() + || $children->contains( + static fn (CloudJob $child): bool => + (int) $child->user_id !== (int) $parent->user_id + || (string) $child->execution_mode !== 'agent' + || (string) $child->kind !== $expectedKind + || self::aggregateChildHasPhaseResolutionConflict($child) + ); + $unresolved = $children->filter( + static fn (CloudJob $child): bool => + (string) $child->execution_mode === 'agent' + && CloudOperationRecoveryPolicy::supports( + (string) $child->kind + ) + && (CloudDispatchLedger::isInvalid($child) + || (bool) $child->finalization_incident + || CloudDispatchLedger::hasRepairIncident($child) + || self::isLocalFinalizerRecovery($child) + || self::hasTerminalRecoveryStateConflict($child) + || self::aggregateChildHasPhaseResolutionConflict($child) + || self::hasResolvedTerminalStateConflict($child) + || ((string) $child->phase === 'terminal' + && (string) $child->outcome === 'failed' + && (string) $child->status === 'failed' + && CloudDispatchLedger::isDispatched($child) + && (bool) $child->effect_may_have_applied + && !(bool) $child->safe_to_resubmit + && (string) $child->effect_resolution === 'unknown')) + ); + $lastCheckedAt = (int) ($unresolved->max('updated_at') ?? 0); + $nextCheckAt = (int) ($unresolved->max('available_at') ?? 0); + $priority = [ + 'recovery_dispatch_ledger_conflict', + 'recovery_dispatch_repair_completion_receipt_missing', + 'recovery_dispatch_repair_receipt_invalid', + 'recovery_dispatch_repair_aggregate_state_conflict', + 'recovery_dispatch_repair_payload_unavailable', + 'recovery_dispatch_repair_operation_identity_conflict', + 'recovery_dispatch_repair_evidence_conflict', + 'recovery_dispatch_repair_instance_state_conflict', + 'recovery_dispatch_repair_ledger_conflict', + 'recovery_dispatch_repair_internal_error', + 'recovery_operation_identity_conflict', + 'recovery_receipt_invalid', + 'recovery_completion_identity_mismatch', + 'recovery_completion_receipt_invalid', + 'recovery_completion_receipt_missing', + 'recovery_completion_operation_invalid', + 'recovery_completion_operation_missing', + 'recovery_completion_outbox_invalid', + 'recovery_payload_unavailable', + 'recovery_payload_invalid', + 'recovery_instance_state_conflict', + 'recovery_evidence_conflict', + 'recovery_evidence_invalid', + 'recovery_state_invalid', + 'recovery_authentication_failed', + 'recovery_agent_unavailable', + 'recovery_waiting_connection', + 'recovery_operation_conflict', + 'recovery_operation_missing', + 'recovery_evidence_partial', + 'recovery_evidence_inconclusive', + 'recovery_ledger_conflict', + 'recovery_internal_error', + 'recovery_pending', + ]; + $codes = $parentCode === null + || $parentCode === 'recovery_child_convergence' + ? [] : [$parentCode]; + if ($relationshipConflict) { + $codes[] = 'recovery_aggregate_state_conflict'; + } + foreach ($unresolved as $child) { + $candidate = self::aggregateChildHasPhaseResolutionConflict($child) + ? 'recovery_aggregate_state_conflict' + : self::agentRecoveryPresentationCandidate($child); + if (self::isLocalFinalizerRecovery($child) + && in_array( + $candidate, + CloudDispatchLedger::repairIncidentCodes(), + true + )) { + $candidate = 'recovery_ledger_conflict'; + } + $codes[] = array_key_exists($candidate, self::RECOVERY_MESSAGES) + ? $candidate : 'recovery_pending'; + } + $codes = array_values(array_unique($codes)); + usort($codes, static function (string $left, string $right) use ( + $priority + ): int { + $leftPriority = array_search($left, $priority, true); + $rightPriority = array_search($right, $priority, true); + $leftPriority = $leftPriority === false + ? PHP_INT_MAX : $leftPriority; + $rightPriority = $rightPriority === false + ? PHP_INT_MAX : $rightPriority; + return $leftPriority <=> $rightPriority + ?: strcmp($left, $right); + }); + $concreteParentCode = $parentCode !== null + && $parentCode !== 'recovery_child_convergence' + ? $parentCode : null; + $code = $concreteParentCode + ?? ($codes[0] ?? ($parentCode ?? 'recovery_child_convergence')); + $parentLevelCode = $concreteParentCode !== null + || ($relationshipConflict + && $code === 'recovery_aggregate_state_conflict'); + $message = $parentLevelCode || $code === 'recovery_child_convergence' + ? self::RECOVERY_MESSAGES[$code] + : '某个宿主机子任务:' . self::RECOVERY_MESSAGES[$code]; + $additional = max(0, count($codes) - 1); + if ($additional > 0) { + $message .= ';另有 ' . $additional + . ' 类子任务异常仍在持续自动核对。'; + } + return [ + 'code' => $code, + 'message' => $message, + 'affected_child_count' => $relationshipConflict + ? max(1, $unresolved->count()) : $unresolved->count(), + 'additional_error_count' => $additional, + 'last_checked_at' => $lastCheckedAt, + 'next_check_at' => $nextCheckAt, + ]; + } + + private static function applyRecoveringFilter($query): void + { + $query->where(static function ($modes): void { + $modes->where(static function ($leaf): void { + $leaf->whereIn('kind', + CloudOperationRecoveryPolicy::kinds()) + ->where(static function ($pending): void { + $pending->where(static function ($mode): void { + $mode->whereNull('execution_mode') + ->orWhere('execution_mode', '<>', 'agent'); + })->orWhere(static function ($invalid): void { + $invalid->whereNull('dispatch_attempts') + ->orWhereNotIn( + 'dispatch_attempts', + [0, 1] + ); + })->orWhere(static function ($repair): void { + $repair->where('phase', 'terminal') + ->where('finalization_incident', 1) + ->whereIn( + 'finalization_error_code', + CloudDispatchLedger::repairIncidentCodes() + ); + })->orWhere(static function ($local): void { + $local->where('phase', 'terminal') + ->where('outcome', 'failed') + ->where('status', 'failed') + ->where('dispatch_attempts', 0) + ->where('finalization_incident', 1); + })->orWhere(static function ($resolved): void { + $resolved->where('phase', 'terminal') + ->whereIn('dispatch_attempts', [0, 1]) + ->whereIn( + 'effect_resolution', + ['applied', 'not_applied'] + )->where('finalization_incident', 1); + })->orWhere(static function ($normal): void { + $normal->where('phase', 'terminal') + ->where('outcome', 'failed') + ->where('status', 'failed') + ->where('effect_may_have_applied', 1) + ->where('safe_to_resubmit', 0) + ->where('effect_resolution', 'unknown') + ->where('dispatch_attempts', 1); + })->orWhere(static function ($state): void { + $state->where('phase', 'terminal') + ->whereIn('dispatch_attempts', [0, 1]) + ->where('effect_resolution', 'unknown') + ->where(static function ($invalid): void { + self::applyInvalidTerminalTuple($invalid); + }); + })->orWhere(static function ($resolvedState): void { + $resolvedState->where('phase', 'terminal') + ->whereIn('dispatch_attempts', [0, 1]) + ->where(static function ($invalid): void { + self::applyInvalidResolvedTerminalTuple( + $invalid + ); + }); + }); + }); + })->orWhere(static function ($aggregate): void { + $aggregate->where('execution_mode', 'aggregate') + ->whereIn('kind', self::AGGREGATE_KINDS) + ->where(static function ($pending): void { + $pending->where(static function ($ledger): void { + $ledger->whereNull('dispatch_attempts') + ->orWhere('dispatch_attempts', '<>', 0); + })->orWhere(static function ($own): void { + $own->where('phase', 'terminal') + ->where('outcome', 'failed') + ->where('status', 'failed') + ->where('effect_may_have_applied', 1) + ->where('safe_to_resubmit', 0) + ->where('effect_resolution', 'unknown'); + })->orWhere(static function ($state): void { + $state->where('phase', 'terminal') + ->where('effect_resolution', 'unknown') + ->where(static function ($invalid): void { + self::applyInvalidTerminalTuple($invalid); + }); + })->orWhere(static function ($published): void { + $published->where('phase', 'terminal') + ->where('finalization_incident', 1); + })->orWhereExists( + static function ($children): void { + self::unresolvedRecoverableChildExists( + $children + ); + } + ); + }); + })->orWhereRaw( + self::aggregateLocalStateConflictSql('cloud_jobs') + )->orWhere(static function ($damagedCatalogParent): void { + $damagedCatalogParent->where('phase', 'terminal') + ->where('finalization_incident', 1) + ->where(static function ($identity): void { + $identity->where('execution_mode', 'aggregate') + ->orWhereIn('kind', self::AGGREGATE_KINDS) + ->orWhere( + 'finalization_error_code', + 'recovery_aggregate_state_conflict' + ); + }); + }); + }); + } + + private static function isLocalFinalizerRecovery(object $job): bool + { + return (string) ($job->execution_mode ?? '') === 'agent' + && (string) ($job->phase ?? '') === 'terminal' + && (string) ($job->outcome ?? '') === 'failed' + && (string) ($job->status ?? '') === 'failed' + && CloudDispatchLedger::isNeverDispatched($job) + && (bool) ($job->finalization_incident ?? false) + && !CloudDispatchLedger::hasRepairIncident($job) + && CloudOperationRecoveryPolicy::supports( + (string) ($job->kind ?? '') + ); + } + + /** A resolved Agent row with a sticky PHP incident remains locally queued. */ + private static function isResolvedStickyAgentIncident(object $job): bool + { + return (string) ($job->execution_mode ?? '') === 'agent' + && (string) ($job->phase ?? '') === 'terminal' + && !CloudDispatchLedger::isInvalid($job) + && in_array( + (string) ($job->effect_resolution ?? ''), + ['applied', 'not_applied'], + true + ) + && (bool) ($job->finalization_incident ?? false) + && !CloudDispatchLedger::hasRepairIncident($job) + && CloudOperationRecoveryPolicy::supports( + (string) ($job->kind ?? '') + ); + } + + /** Add the negation of the canonical failed/effectful/non-retryable tuple. */ + private static function applyInvalidTerminalTuple( + $invalid, + string $prefix = '' + ): void { + $invalid->where(static function ($tuple) use ($prefix): void { + $tuple->whereNull($prefix . 'outcome') + ->orWhere($prefix . 'outcome', '<>', 'failed') + ->orWhereNull($prefix . 'status') + ->orWhere($prefix . 'status', '<>', 'failed') + ->orWhereNull($prefix . 'effect_may_have_applied') + ->orWhere($prefix . 'effect_may_have_applied', '<>', 1) + ->orWhereNull($prefix . 'safe_to_resubmit') + ->orWhere($prefix . 'safe_to_resubmit', '<>', 0); + })->orWhere(static function ($neverDispatched) use ($prefix): void { + $neverDispatched->where($prefix . 'dispatch_attempts', 0) + ->where($prefix . 'finalization_incident', 0); + }); + } + + /** Add terminal applied/not-applied rows that contradict their outcome. */ + public static function applyInvalidResolvedTerminalTuple( + $invalid, + string $prefix = '' + ): void { + $invalid->whereIn( + $prefix . 'effect_resolution', + ['applied', 'not_applied'] + )->where(static function ($shape) use ($prefix): void { + $shape->whereNull($prefix . 'terminal_at') + ->orWhere($prefix . 'terminal_at', '<=', 0) + ->orWhereNull($prefix . 'outcome') + ->orWhereNotIn( + $prefix . 'outcome', + ['succeeded', 'failed'] + )->orWhere(static function ($succeeded) use ($prefix): void { + $succeeded->where($prefix . 'outcome', 'succeeded') + ->where(static function ($mismatch) use ($prefix): void { + $mismatch->whereNull($prefix . 'status') + ->orWhere( + $prefix . 'status', + '<>', + 'succeeded' + )->orWhere( + $prefix . 'effect_resolution', + '<>', + 'applied' + )->orWhereNull( + $prefix . 'effect_may_have_applied' + )->orWhere( + $prefix . 'effect_may_have_applied', + '<>', + 0 + )->orWhereNull( + $prefix . 'safe_to_resubmit' + )->orWhere( + $prefix . 'safe_to_resubmit', + '<>', + 0 + )->orWhereNotNull($prefix . 'error_code'); + }); + })->orWhere(static function ($failed) use ($prefix): void { + $failed->where($prefix . 'outcome', 'failed') + ->where(static function ($mismatch) use ($prefix): void { + $mismatch->whereNull($prefix . 'status') + ->orWhere($prefix . 'status', '<>', 'failed') + ->orWhereNull( + $prefix . 'effect_may_have_applied' + )->orWhereNotIn( + $prefix . 'effect_may_have_applied', + [0, 1] + )->orWhere(static function ($effectful) use ( + $prefix + ): void { + $effectful->where( + $prefix . 'effect_may_have_applied', + 1 + )->where(static function ($safe) use ( + $prefix + ): void { + $safe->whereNull( + $prefix . 'safe_to_resubmit' + )->orWhere( + $prefix . 'safe_to_resubmit', + '<>', + 0 + ); + }); + })->orWhere(static function ($noEffect) use ( + $prefix + ): void { + $noEffect->where( + $prefix . 'effect_may_have_applied', + 0 + )->where(static function ($conclusion) use ( + $prefix + ): void { + $conclusion->where( + $prefix . 'effect_resolution', + '<>', + 'not_applied' + )->orWhereNull( + $prefix . 'safe_to_resubmit' + )->orWhereNotIn( + $prefix . 'safe_to_resubmit', + [0, 1] + ); + }); + }); + }); + })->orWhere(static function ($envelope) use ($prefix): void { + self::applyInvalidResolvedAgentEnvelope( + $envelope, + $prefix + ); + }); + }); + } + + /** + * Keep an aggregate/catalog boundary fenced until every Agent child has a + * trustworthy terminal effect. During ordinary receipt finalization the + * current child is intentionally still nonterminal, so only that expected + * phase/effect transition is ignored; a corrupt dispatch ledger or sticky + * recovery incident on the current child still blocks publication. + */ + public static function aggregateParentRecoveryPending( + CloudJob $parent, + ?int $completingChildId = null, + bool $lockForUpdate = false + ): bool { + $query = CloudJob::where('parent_job_id', (int) $parent->id) + ->orderBy('id'); + if ($lockForUpdate) { + $query->lockForUpdate(); + } + $children = $query->get(); + if (self::aggregateRelationshipConflict( + $parent, + $children, + $completingChildId + )) { + return true; + } + return $children->contains( + static fn (CloudJob $child): bool => + self::aggregateChildRecoveryPending( + $child, + $completingChildId !== null + && (int) $child->id === $completingChildId + ) + ); + } + + /** A child cannot publish its parent while any safety incident is sticky. */ + private static function aggregateChildRecoveryPending( + CloudJob $child, + bool $isCompletingChild = false + ): bool { + return (!$isCompletingChild + && ((string) $child->phase !== 'terminal' + || !in_array( + (string) $child->effect_resolution, + ['applied', 'not_applied'], + true + ))) + || CloudDispatchLedger::isInvalid($child) + || (bool) $child->finalization_incident + || CloudDispatchLedger::hasRepairIncident($child) + || self::isLocalFinalizerRecovery($child) + || self::hasResolvedTerminalStateConflict($child); + } + public static function tasks(array $actor, string $state, ?int $cursor = null, int $limit = 20): array { @@ -1013,9 +3672,21 @@ final class CloudJobService }; // Per-host child jobs are implementation details of one public batch. // Only their parent appears in the task center. - $base = CloudJob::query()->whereNull('parent_job_id'); + $base = CloudJob::query()->where( + static function ($public): void { + $public->whereNull('parent_job_id') + ->orWhere(static function ($currentCatalog): void { + self::whereCurrentAggregateCatalogBinding( + $currentCatalog + ); + }); + } + ); $owner($base); $activeCount = (clone $base)->where('phase', '<>', 'terminal')->count(); + $recovering = clone $base; + self::applyRecoveringFilter($recovering); + $recoveringCount = $recovering->count(); $unreadCount = (clone $base)->where('phase', 'terminal') ->whereNull('read_at')->count(); $query = clone $base; @@ -1039,6 +3710,7 @@ final class CloudJobService 'has_more' => $hasMore, ], 'active_count' => (int) $activeCount, + 'recovering_count' => (int) $recoveringCount, 'unread_count' => (int) $unreadCount, ]; } @@ -1056,7 +3728,14 @@ final class CloudJobService { $query = CloudJob::where('phase', 'terminal')->whereNull('read_at') ->where('user_id', (int) ($actor['user_id'] ?? 0)) - ->whereNull('parent_job_id'); + ->where(static function ($public): void { + $public->whereNull('parent_job_id') + ->orWhere(static function ($currentCatalog): void { + self::whereCurrentAggregateCatalogBinding( + $currentCatalog + ); + }); + }); return (int) $query->count(); } @@ -1219,9 +3898,12 @@ final class CloudJobService $page = max(1, min($pages, $page)); $jobs = $query->offset(($page - 1) * $perPage)->limit($perPage) ->get(['id', 'operation_id', 'kind', 'order_id', 'status', + 'parent_job_id', 'execution_mode', 'dispatch_attempts', 'phase', 'outcome', 'attempts', 'error_code', 'result_json', 'effect_may_have_applied', 'safe_to_resubmit', - 'effect_resolution', 'terminal_at', 'read_at', + 'effect_resolution', 'finalization_incident', + 'finalization_error_code', 'available_at', + 'terminal_at', 'read_at', 'sealed_payload', 'created_at', 'updated_at']); $items = []; foreach ($jobs as $job) { diff --git a/web/app/Services/Cloud/CloudLifecycleService.php b/web/app/Services/Cloud/CloudLifecycleService.php index e833125a..0f62afd9 100644 --- a/web/app/Services/Cloud/CloudLifecycleService.php +++ b/web/app/Services/Cloud/CloudLifecycleService.php @@ -8,6 +8,8 @@ use App\Models\CloudServicePeriod; final class CloudLifecycleService { + private const SAFE_NEW_GENERATION_DELAY = 300; + private array $observedErrors = []; public function __construct(private ?CloudRuntimeHeartbeat $heartbeat = null) @@ -101,12 +103,49 @@ final class CloudLifecycleService return (new CloudInstance())->getConnection()->transaction(function () use ($instanceId) { $now = time(); $instance = CloudInstance::where('id', $instanceId)->lockForUpdate()->first(); - if ($instance === null || in_array((string) $instance->status, - ['deleted', 'delete_failed'], true) + if ($instance === null || (string) $instance->status === 'deleted' || $instance->service_status === 'exempt') { return false; } - if ((string) $instance->service_status === 'purge_failed') { + if ((string) $instance->status === 'delete_failed' + || (string) $instance->service_status === 'purge_failed') { + if ((string) $instance->status !== 'delete_failed' + || (string) $instance->service_status !== 'purge_failed' + || $this->retryableNotAppliedJobLocked( + $instance, + 'expiry_delete', + $now + ) === null) { + return false; + } + $instance->status = 'deleting'; + $instance->service_status = 'purge_deleting'; + $instance->updated_at = $now; + $instance->save(); + CloudJobService::enqueueExpiryDelete($instance); + return true; + } + if ((string) $instance->status === 'deleting' + && (string) $instance->service_status === 'purge_stop_failed') { + if ($this->retryableNotAppliedJobLocked( + $instance, + 'service_suspend', + $now + ) === null) { + return false; + } + $instance->service_status = 'purge_stopping'; + $instance->updated_at = $now; + $instance->save(); + return $this->enqueue( + $instance, + 'service_suspend', + 'service/suspend', + 'purge', + ['reason' => 'purge'] + ); + } + if ((string) $instance->service_status === 'purge_stop_failed') { return false; } // A delete with a lost response is already a terminal failed task, @@ -174,14 +213,10 @@ final class CloudLifecycleService $instance->traffic_quota_bytes = max(0, (int) $period->traffic_quota_bytes); $instance->traffic_download_bytes = (int) $period->download_used_bytes; $instance->traffic_upload_bytes = (int) $period->upload_used_bytes; - if (!in_array((string) $instance->service_status, ['active', 'exempt'], true)) { - $instance->service_status = 'active'; - $instance->suspended_at = null; - } - if ((string) $instance->network_status !== 'active') { - $instance->network_status = 'restore_pending'; - $instance->network_suspended_at = null; - } + $this->convergePaidPeriodProjectionLocked( + $instance, + $now + ); } } @@ -200,11 +235,10 @@ final class CloudLifecycleService $instance->network_status = 'blocking'; } } elseif ($usageKnown) { - if (!in_array((string) $instance->network_status, - ['active', 'restore_failed'], true)) { - $instance->network_status = 'restore_pending'; - $instance->network_suspended_at = null; - } + $this->convergePaidPeriodProjectionLocked( + $instance, + $now + ); } } elseif ($instance->expires_at !== null && (int) $instance->expires_at <= $now) { $invoice = CloudInvoice::where('instance_id', $instance->id) @@ -247,6 +281,40 @@ final class CloudLifecycleService } } } + $network = (string) $instance->network_status; + if ($network === 'block_failed') { + $reason = null; + $nextState = null; + if ($period !== null + && (string) $period->status === 'exhausted') { + $reason = 'traffic'; + $nextState = 'blocking'; + } elseif ($period === null + && (string) $instance->service_status === 'expired_grace' + && $instance->expires_at !== null + && (int) $instance->expires_at <= $now) { + $reason = 'expired'; + $nextState = 'blocking_expired'; + } + if ($reason !== null + && $this->retryableNotAppliedJobLocked( + $instance, + 'network_suspend', + $now + ) !== null) { + $instance->network_status = $nextState; + } + } elseif ($network === 'restore_failed' + && $period !== null + && (string) $period->status === 'active' + && $this->retryableNotAppliedJobLocked( + $instance, + 'network_resume', + $now + ) !== null) { + $instance->network_status = 'restore_pending'; + $instance->network_suspended_at = null; + } $instance->updated_at = $now; $instance->save(); @@ -292,6 +360,202 @@ final class CloudLifecycleService )->exists(); } + /** + * Bring a paid period's local projection forward without overwriting an + * in-flight or uncertain policy mutation. Definitively applied network + * suspension can start a resume; definitively not-applied failures may be + * cleared or moved to a new generation by the strict ledger helper. + */ + private function convergePaidPeriodProjectionLocked( + CloudInstance $instance, + int $now + ): void { + $service = (string) $instance->service_status; + if ($service === 'suspend_failed') { + if ($this->retryableNotAppliedJobLocked( + $instance, + 'service_suspend', + $now + ) !== null) { + $instance->service_status = 'active'; + $instance->suspended_at = null; + } + } elseif (!in_array($service, [ + 'active', + 'exempt', + 'suspending_expired', + 'purge_stopping', + 'purge_stop_failed', + 'purge_force_required', + 'purge_deleting', + 'purge_failed', + ], true)) { + $instance->service_status = 'active'; + $instance->suspended_at = null; + } + + $network = (string) $instance->network_status; + if ($network === 'block_failed') { + if ($this->retryableNotAppliedJobLocked( + $instance, + 'network_suspend', + $now + ) !== null) { + // A proven no-effect suspension means the links never left + // their paid-period target state; no compensating mutation is + // required. + $instance->network_status = 'active'; + $instance->network_suspended_at = null; + } + } elseif ($network === 'restore_failed') { + if ($this->retryableNotAppliedJobLocked( + $instance, + 'network_resume', + $now + ) !== null) { + $instance->network_status = 'restore_pending'; + $instance->network_suspended_at = null; + } + } elseif (!in_array($network, [ + 'active', + 'blocking', + 'blocking_expired', + 'restore_pending', + 'restoring', + ], true)) { + $instance->network_status = 'restore_pending'; + $instance->network_suspended_at = null; + } + } + + /** + * A policy retry is a new audited generation, never a replay. It is + * allowed only after the newest generation proved that no effect happened + * and all immutable Agent and resource bindings still match. + */ + private function retryableNotAppliedJobLocked( + CloudInstance $instance, + string $kind, + int $now + ): ?CloudJob { + $job = CloudJob::where('instance_id', (int) $instance->id) + ->where('kind', $kind) + ->orderByDesc('id') + ->lockForUpdate() + ->first(); + if ($job === null) { + return null; + } + if ((bool) $job->finalization_incident) { + return null; + } + if ((string) $job->execution_mode !== 'agent' + || $job->parent_job_id !== null + || (int) $job->user_id !== (int) $instance->user_id + || (int) $job->host_id !== (int) $instance->host_id) { + $this->markLifecycleRecoveryIncident( + $job, + 'recovery_instance_state_conflict', + $now + ); + return null; + } + if ((string) $job->phase !== 'terminal') { + return null; + } + if (CloudDispatchLedger::isInvalid($job) + || CloudJobService::hasTerminalRecoveryStateConflict($job)) { + $this->markLifecycleRecoveryIncident( + $job, + CloudDispatchLedger::isInvalid($job) + ? 'recovery_dispatch_ledger_conflict' + : 'recovery_instance_state_conflict', + $now + ); + return null; + } + if ((string) $job->outcome !== 'failed' + || (string) $job->status !== 'failed' + || (string) $job->effect_resolution !== 'not_applied' + || (bool) $job->effect_may_have_applied + || (string) ($job->error_code ?? '') === 'force_required') { + if ((string) $job->effect_resolution === 'applied' + || (string) ($job->error_code ?? '') === 'force_required') { + // The resource is still in a failed policy projection even + // though the immutable job says the mutation happened (or + // requires a different authorized action). Keep that + // contradiction visible to the PHP-only recovery queue. + $this->markLifecycleRecoveryIncident( + $job, + 'recovery_instance_state_conflict', + $now + ); + } + return null; + } + if (max( + (int) ($job->terminal_at ?? 0), + (int) ($job->updated_at ?? 0) + ) > $now - self::SAFE_NEW_GENERATION_DELAY) { + return null; + } + try { + $identity = CloudOperationRecoveryIdentity::expected($job); + } catch (\Throwable $error) { + $code = match (true) { + $error instanceof CloudRecoveryPayloadUnavailable => + 'recovery_payload_unavailable', + $error instanceof CloudRecoveryOperationIdentityConflict => + 'recovery_operation_identity_conflict', + $error instanceof CloudRecoveryInstanceStateConflict => + 'recovery_instance_state_conflict', + default => 'recovery_internal_error', + }; + $this->markLifecycleRecoveryIncident($job, $code, $now); + return null; + } + $expectedAction = [ + 'expiry_delete' => 'delete-vm', + 'service_suspend' => 'service-suspend', + 'network_suspend' => 'network-suspend', + 'network_resume' => 'network-resume', + ][$kind] ?? null; + if ($expectedAction === null + || ($identity['action'] ?? null) !== $expectedAction + || ($identity['resource_id'] ?? null) + !== strtolower((string) $instance->uuid) + || !is_string($identity['request_fingerprint'] ?? null) + || preg_match( + '/^[a-f0-9]{64}$/D', + $identity['request_fingerprint'] + ) !== 1) { + $this->markLifecycleRecoveryIncident( + $job, + 'recovery_operation_identity_conflict', + $now + ); + return null; + } + return $job; + } + + private function markLifecycleRecoveryIncident( + CloudJob $job, + string $code, + int $now + ): void { + if ((bool) $job->finalization_incident) { + return; + } + $job->finalization_incident = 1; + $job->finalization_error_code = $code; + $job->lease_token = null; + $job->lease_until = 0; + $job->available_at = $now + self::SAFE_NEW_GENERATION_DELAY; + $job->updated_at = $now; + $job->save(); + } + private function updateUsage(CloudInstance $instance, CloudServicePeriod $period, int $now): bool { if ($period->download_base_bytes === null || $period->upload_base_bytes === null) { diff --git a/web/app/Services/Cloud/CloudOperationCompletionService.php b/web/app/Services/Cloud/CloudOperationCompletionService.php index f8f2e313..181d25a7 100644 --- a/web/app/Services/Cloud/CloudOperationCompletionService.php +++ b/web/app/Services/Cloud/CloudOperationCompletionService.php @@ -8,20 +8,30 @@ use App\Models\CloudJob; /** Applies immutable Agent receipts without ever re-dispatching a mutation. */ final class CloudOperationCompletionService { + private const RESULT_ENVELOPE = 'virt_cloud_completion_event'; + private const RESULT_ENVELOPE_VERSION = 1; + private const IDENTITY_RETRY_SECONDS = 300; + public static function accept(array $input): array { - $receipt = self::validate($input); + try { + $receipt = self::validate($input); + } catch (CloudError $error) { + self::recordInputIncident($input, 'recovery_receipt_invalid'); + throw $error; + } $hash = hash('sha256', json_encode($receipt, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); - $event = (new CloudAgentCompletionEvent())->getConnection() - ->transaction(function () use ($receipt, $hash) { + try { + $event = (new CloudAgentCompletionEvent())->getConnection() + ->transaction(function () use ($receipt, $hash) { // Serialize durable receipt publication with the deadline // finalizer. If expiry owns the job row first, this receipt is // necessarily late; if receipt ingestion owns it first, expiry // cannot pass the event before the event commit becomes // visible. This makes received_at a real durable boundary. - CloudJob::where('host_id', $receipt['host_id']) + $receiptJob = CloudJob::where('host_id', $receipt['host_id']) ->where('execution_mode', 'agent') ->where('operation_id', $receipt['operation_id']) ->lockForUpdate()->first(); @@ -41,6 +51,17 @@ final class CloudOperationCompletionService '同一完成回执标识不能承载不同结果', 409 ); } + if ($receiptJob !== null + && CloudDispatchLedger::isNeverDispatched( + $receiptJob + )) { + self::applyDispatchLedgerConflictLocked( + $receiptJob, + time(), + 'recovery_dispatch_repair_instance_state_conflict', + true + ); + } return $existing; } @@ -54,15 +75,51 @@ final class CloudOperationCompletionService $receipt['effect_may_have_applied'] ? 1 : 0; $event->safe_to_resubmit = $receipt['safe_to_resubmit'] ? 1 : 0; $event->error_code = $receipt['error_code']; - $event->result_json = $receipt['result'] === null ? null - : json_encode($receipt['result'], JSON_THROW_ON_ERROR - | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + // No schema change is needed: result_json stores an internal, + // versioned envelope while operation() keeps exposing only the + // original business result to existing finalizers. + $event->result_json = json_encode([ + 'schema' => self::RESULT_ENVELOPE, + 'version' => self::RESULT_ENVELOPE_VERSION, + 'identity' => [ + 'action' => $receipt['action'], + 'resource_id' => $receipt['resource_id'], + 'request_fingerprint' => + $receipt['request_fingerprint'], + ], + 'result' => $receipt['result'], + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + | JSON_UNESCAPED_UNICODE); $event->disposition = 'received'; $event->received_at = time(); $event->applied_at = null; $event->save(); + // Receipt evidence and a contradictory generation-zero fence + // commit atomically. The ordinary worker must never observe a + // durable completion while the mutation remains dispatchable. + if ($receiptJob !== null + && CloudDispatchLedger::isNeverDispatched($receiptJob)) { + self::applyDispatchLedgerConflictLocked( + $receiptJob, + time(), + 'recovery_dispatch_repair_instance_state_conflict', + true + ); + } return $event; - }, 3); + }, 3); + } catch (CloudError $error) { + if (in_array($error->httpStatus, [400, 409], true)) { + self::recordReceiptIncident( + (int) $receipt['host_id'], + (string) $receipt['operation_id'], + $error->httpStatus === 400 + ? 'recovery_receipt_invalid' + : 'recovery_operation_identity_conflict' + ); + } + throw $error; + } $job = CloudJob::where('host_id', $receipt['host_id']) ->where('execution_mode', 'agent') @@ -73,6 +130,109 @@ final class CloudOperationCompletionService return ['accepted' => true, 'disposition' => (string) $event->disposition]; } + if (CloudDispatchLedger::isInvalid($job)) { + // The receipt may be genuine, but a corrupt PHP dispatch ledger + // cannot prove which generation it belongs to. Keep it received + // so the Agent outbox is not ACKed; repairing the counter to one + // lets the same immutable receipt resume normal convergence. + self::deferDispatchLedgerConflict($job); + $event = self::reload($event); + return ['accepted' => true, + 'disposition' => (string) $event->disposition]; + } + if (CloudDispatchLedger::isNeverDispatched($job)) { + // An authenticated completion for generation zero is positive + // evidence that the PHP ledger is wrong. Never reject/ACK it and + // never let the ordinary worker dispatch the mutation again. + self::deferNeverDispatchedEvidenceConflict($job); + $event = self::reload($event); + return ['accepted' => true, + 'disposition' => (string) $event->disposition]; + } + if (CloudDispatchLedger::hasRepairIncident($job)) { + // The repair coordinator owns both receipt validation and ACK. In + // particular, a retransmission between operator repair and the + // next recovery tick must not turn the only evidence into late or + // rejected data. + return ['accepted' => true, + 'disposition' => (string) $event->disposition]; + } + if (CloudOperationRecoveryIdentity::supports((string) $job->kind)) { + if (!self::isExactStoredEvent($event)) { + self::mark($event, 'rejected'); + $event = self::reload($event); + return ['accepted' => true, + 'disposition' => (string) $event->disposition]; + } + try { + $expectedIdentity = CloudOperationRecoveryIdentity::expected( + $job, + (string) $event->outcome === 'succeeded' + ); + } catch (CloudRecoveryPayloadUnavailable $error) { + if ((string) $job->phase === 'terminal' + && in_array((string) $job->effect_resolution, + ['applied', 'not_applied'], true)) { + // An already-resolved pre-upgrade task cannot be changed by + // this late receipt. Rejecting it is a terminal ACK only; + // no result or ledger field is consumed. + self::mark($event, 'rejected'); + } else { + self::deferIdentityConflict( + $job, + 'recovery_payload_unavailable' + ); + } + $event = self::reload($event); + return ['accepted' => true, + 'disposition' => (string) $event->disposition]; + } catch (CloudRecoveryOperationIdentityConflict $error) { + if ((string) $job->phase === 'terminal' + && in_array((string) $job->effect_resolution, + ['applied', 'not_applied'], true)) { + self::mark($event, 'rejected'); + } else { + // This exception arose while rebuilding PHP's expected + // identity, before comparing the Agent triple. Keep the + // event retryable because repairing the durable request or + // stored binding may make this exact receipt usable. + self::deferIdentityConflict( + $job, + 'recovery_operation_identity_conflict' + ); + } + $event = self::reload($event); + return ['accepted' => true, + 'disposition' => (string) $event->disposition]; + } catch (CloudRecoveryInstanceStateConflict $error) { + if ((string) $job->phase === 'terminal' + && in_array((string) $job->effect_resolution, + ['applied', 'not_applied'], true)) { + self::mark($event, 'rejected'); + } else { + self::deferIdentityConflict( + $job, + 'recovery_instance_state_conflict' + ); + } + $event = self::reload($event); + return ['accepted' => true, + 'disposition' => (string) $event->disposition]; + } + if (!CloudOperationRecoveryIdentity::same( + $expectedIdentity, + self::identity($event) + )) { + // PHP successfully rebuilt the immutable request, so this is a + // definitive wrong-operation receipt rather than temporarily + // unavailable metadata. Isolate it so fresh inspection (or a + // prepared crash resume) is not starved by receipt priority. + self::isolateIdentityMismatch($job, $event); + $event = self::reload($event); + return ['accepted' => true, + 'disposition' => (string) $event->disposition]; + } + } if ((string) $job->phase === 'terminal') { // finish() stores completion_event_id before mark(applied). Repair // that ACK only when the terminal effect fields prove that this @@ -114,23 +274,55 @@ final class CloudOperationCompletionService public static function operation(CloudAgentCompletionEvent $event): array { + $envelope = self::resultEnvelope($event); return [ 'operation_id' => (string) $event->operation_id, 'status' => (string) $event->outcome, 'effect_may_have_applied' => (bool) $event->effect_may_have_applied, 'safe_to_resubmit' => (bool) $event->safe_to_resubmit, 'error_code' => (string) $event->error_code, - 'result' => $event->result_json === null ? null - : json_decode((string) $event->result_json, true, - 64, JSON_THROW_ON_ERROR), + 'action' => $envelope['identity']['action'], + 'resource_id' => $envelope['identity']['resource_id'], + 'request_fingerprint' => + $envelope['identity']['request_fingerprint'], + 'result' => $envelope['result'], ]; } + /** + * @return array{action:string,resource_id:string,request_fingerprint:string} + */ + public static function identity(CloudAgentCompletionEvent $event): array + { + return self::resultEnvelope($event)['identity']; + } + + public static function assertEventIdentityForJob( + CloudJob $job, + CloudAgentCompletionEvent $event + ): void { + if (!self::isExactStoredEvent($event)) { + throw new CloudRecoveryOperationIdentityConflict( + 'Agent 完成回执缺少可信操作身份', + 409 + ); + } + $expected = CloudOperationRecoveryIdentity::expected( + $job, + (string) $event->outcome === 'succeeded' + ); + CloudOperationRecoveryIdentity::assertMatches( + $expected, + self::identity($event) + ); + } + public static function settledTaskWithEvent( CloudJob $job, CloudAgentCompletionEvent $event ): bool { $exactEvent = (string) $job->execution_mode === 'agent' + && CloudDispatchLedger::isDispatched($job) && (string) $job->phase === 'terminal' && !(bool) $job->finalization_incident && $job->host_id !== null @@ -148,19 +340,39 @@ final class CloudOperationCompletionService if (!$exactEvent) { return false; } - // Only instance settings has an audited finalizer which can resume a - // failed local ledger projection from this immutable receipt. Other - // kinds consume the exact on-time event even when their business rule - // deliberately converts Agent success into a fenced failure (for - // example reinstall cleanup_pending). - if ((string) $job->kind !== 'instance_settings') { - return true; + if (CloudOperationRecoveryIdentity::supports((string) $job->kind)) { + try { + self::assertEventIdentityForJob($job, $event); + } catch (\Throwable $error) { + return false; + } } $outcome = (string) $event->outcome; $resolution = $outcome === 'succeeded' ? 'applied' : ((bool) $event->effect_may_have_applied ? 'unknown' : 'not_applied'); + // A stored event ID proves identity, not PHP ledger convergence. This + // applies to create/storage as well as the automatic recovery policy: + // their dedicated financial/configuration finalizer must commit before + // the Agent outbox can receive an ACK. + if ((string) $job->effect_resolution === 'unknown') { + return false; + } + if (!CloudOperationRecoveryPolicy::supports((string) $job->kind)) { + if ((string) $job->kind === 'create' + && $outcome === 'succeeded' + && (string) $job->outcome === 'failed' + && (string) $job->status === 'failed') { + // A late exact create result materializes the paid order while + // preserving the immutable original timeout/failure receipt. + return $job->instance_id !== null + && (string) $job->effect_resolution === 'applied'; + } + return (string) $job->outcome === $outcome + && (string) $job->status === $outcome + && (string) $job->effect_resolution === $resolution; + } return (string) $job->outcome === $outcome && (string) $job->status === $outcome && (string) $job->effect_resolution === $resolution; @@ -173,6 +385,27 @@ final class CloudOperationCompletionService */ public static function isExactStoredEvent( CloudAgentCompletionEvent $event + ): bool { + return (string) $event->disposition === 'received' + && $event->applied_at === null + && self::hasExactStoredEventPayload($event); + } + + public static function isExactAppliedEvent( + CloudAgentCompletionEvent $event + ): bool { + $appliedAt = filter_var( + $event->applied_at, + FILTER_VALIDATE_INT, + ['options' => ['min_range' => 1]] + ); + return (string) $event->disposition === 'applied' + && $appliedAt !== false + && self::hasExactStoredEventPayload($event); + } + + private static function hasExactStoredEventPayload( + CloudAgentCompletionEvent $event ): bool { $eventId = $event->event_id; $hostId = filter_var( @@ -191,9 +424,7 @@ final class CloudOperationCompletionService FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]] ); - if ((string) $event->disposition !== 'received' - || $event->applied_at !== null - || !is_string($eventId) + if (!is_string($eventId) || preg_match('/^[A-Za-z0-9_-]{16,80}$/D', $eventId) !== 1 || $hostId === false || !is_string($operationId) @@ -215,17 +446,12 @@ final class CloudOperationCompletionService return false; } try { - $result = $event->result_json === null - ? null - : json_decode( - (string) $event->result_json, - true, - 64, - JSON_THROW_ON_ERROR - ); - } catch (\JsonException) { + $envelope = self::resultEnvelope($event); + } catch (\Throwable $error) { return false; } + $identity = $envelope['identity']; + $result = $envelope['result']; if ($result !== null && !is_array($result)) { return false; } @@ -233,6 +459,9 @@ final class CloudOperationCompletionService 'event_id' => $eventId, 'host_id' => $hostId, 'operation_id' => $operationId, + 'action' => $identity['action'], + 'resource_id' => $identity['resource_id'], + 'request_fingerprint' => $identity['request_fingerprint'], 'status' => $status, 'effect_may_have_applied' => $effect, 'safe_to_resubmit' => $safe, @@ -257,6 +486,98 @@ final class CloudOperationCompletionService ]); } + /** + * Atomically quarantine a receipt whose well-formed identity definitively + * differs from PHP's reconstructed request, while keeping the job eligible + * for its normal read-only recovery path. + */ + public static function isolateIdentityMismatch( + CloudJob $source, + CloudAgentCompletionEvent $sourceEvent + ): void { + (new CloudJob())->getConnection()->transaction( + static function () use ($source, $sourceEvent): void { + $job = CloudJob::where('id', (int) $source->id) + ->lockForUpdate()->first(); + $event = CloudAgentCompletionEvent::where( + 'event_id', + (string) $sourceEvent->event_id + )->lockForUpdate()->first(); + if ($event === null + || (string) $event->disposition !== 'received') { + return; + } + if ($job !== null && CloudDispatchLedger::isInvalid($job)) { + self::applyDispatchLedgerConflictLocked($job, time()); + return; + } + $sameOperation = $job !== null + && (int) $job->host_id === (int) $event->host_id + && is_string($job->operation_id) + && hash_equals( + (string) $job->operation_id, + (string) $event->operation_id + ); + $event->disposition = 'rejected'; + $event->applied_at = null; + $event->save(); + if (!$sameOperation) { + return; + } + $now = time(); + $active = in_array((string) $job->phase, + ['dispatching', 'awaiting_receipt'], true) + && (int) $job->dispatch_attempts === 1; + if ($active && !CloudOperationRecoveryPolicy::supports( + (string) $job->kind + )) { + // create and host-storage have dedicated financial/config + // finalizers. A malformed receipt may be surfaced, but it + // must not bypass those finalizers by terminalizing the job. + $job->finalization_incident = 1; + $job->finalization_error_code = + 'recovery_operation_identity_conflict'; + $job->read_at = null; + $job->updated_at = $now; + $job->save(); + return; + } + if (in_array((string) $job->phase, + ['dispatching', 'awaiting_receipt'], true) + && (int) $job->dispatch_attempts === 1) { + $job->phase = 'terminal'; + $job->outcome = 'failed'; + $job->status = 'failed'; + $job->terminal_at = $now; + $job->effect_may_have_applied = 1; + $job->safe_to_resubmit = 0; + $job->effect_resolution = 'unknown'; + $job->error_code = + 'recovery_operation_identity_conflict'; + } + if ((string) $job->phase !== 'terminal' + || (string) $job->effect_resolution !== 'unknown') { + return; + } + if (!hash_equals( + (string) ($job->finalization_error_code ?? ''), + 'recovery_operation_identity_conflict' + )) { + $job->read_at = null; + } + $job->finalization_incident = 1; + $job->finalization_error_code = + 'recovery_operation_identity_conflict'; + $job->lease_token = null; + $job->lease_until = 0; + $job->available_at = $now + self::IDENTITY_RETRY_SECONDS; + $job->updated_at = $now; + $job->save(); + }, + 3 + ); + } + private static function reload( CloudAgentCompletionEvent $event ): CloudAgentCompletionEvent { @@ -265,6 +586,532 @@ final class CloudOperationCompletionService )->first() ?? $event; } + /** + * @return array{schema:string,version:int,identity:array{action:string,resource_id:string,request_fingerprint:string},result:?array} + */ + private static function resultEnvelope( + CloudAgentCompletionEvent $event + ): array { + if (!is_string($event->result_json) + || $event->result_json === '') { + throw new CloudRecoveryOperationIdentityConflict( + 'Agent 完成回执没有持久化身份', 409 + ); + } + try { + $value = json_decode( + (string) $event->result_json, + true, + 64, + JSON_THROW_ON_ERROR + ); + } catch (\JsonException $error) { + throw new CloudRecoveryOperationIdentityConflict( + 'Agent 完成回执身份封装无效', 409 + ); + } + $identity = is_array($value) ? ($value['identity'] ?? null) : null; + if (!is_array($value) || array_is_list($value) + || array_diff(array_keys($value), [ + 'schema', 'version', 'identity', 'result', + ]) !== [] + || ($value['schema'] ?? null) !== self::RESULT_ENVELOPE + || ($value['version'] ?? null) !== self::RESULT_ENVELOPE_VERSION + || !is_array($identity) || array_is_list($identity) + || array_diff(array_keys($identity), [ + 'action', 'resource_id', 'request_fingerprint', + ]) !== [] + || !array_key_exists('result', $value) + || ($value['result'] !== null && !is_array($value['result']))) { + throw new CloudRecoveryOperationIdentityConflict( + 'Agent 完成回执身份封装无效', 409 + ); + } + self::assertIdentityShape($identity); + return $value; + } + + private static function assertIdentityShape(array $identity): void + { + if (!is_string($identity['action'] ?? null) + || strlen($identity['action']) > 128 + || preg_match( + '/^[a-z][a-z0-9]*(?:[-:][a-z0-9]+)*$/D', + $identity['action'] + ) !== 1 + || !is_string($identity['resource_id'] ?? null) + || strlen($identity['resource_id']) > 255 + || preg_match('/^[A-Za-z0-9][A-Za-z0-9_.:-]*$/D', + $identity['resource_id']) !== 1 + || !is_string($identity['request_fingerprint'] ?? null) + || preg_match('/^[a-f0-9]{64}$/D', + $identity['request_fingerprint']) !== 1) { + throw new CloudRecoveryOperationIdentityConflict( + 'Agent 完成回执操作身份无效', 409 + ); + } + } + + private static function assertCompletionResultSafe( + ?array $result, + int $depth = 0 + ): void { + if ($result === null) { + return; + } + if ($depth > 16) { + throw new CloudError('Agent 完成回执结构过深', 400); + } + foreach ($result as $key => $value) { + if (is_string($key) && preg_match( + '/password|secret|(?:public|private).?key|ssh.?key|passphrase|credential|(?:(?:access|refresh|auth|api|bearer|session|source).?token)|^token$/i', + $key + ) === 1) { + throw new CloudError( + 'Agent 完成回执包含禁止持久化的敏感字段', + 400 + ); + } + if (is_array($value)) { + self::assertCompletionResultSafe( + $value, + $depth + 1 + ); + } + } + } + + private static function deferIdentityConflict( + CloudJob $source, + string $errorCode + ): void { + (new CloudJob())->getConnection()->transaction( + static function () use ($source, $errorCode): void { + $job = CloudJob::where('id', (int) $source->id) + ->lockForUpdate()->first(); + if ($job !== null && CloudDispatchLedger::isInvalid($job)) { + self::applyDispatchLedgerConflictLocked($job, time()); + return; + } + if ($job === null + || ((string) $job->effect_resolution !== 'unknown' + && (string) $job->phase === 'terminal')) { + return; + } + $now = time(); + $active = in_array((string) $job->phase, + ['dispatching', 'awaiting_receipt'], true) + && (int) $job->dispatch_attempts === 1; + if ($active && !CloudOperationRecoveryPolicy::supports( + (string) $job->kind + )) { + // Do not replace create's atomic refund/placement finalizer + // or host storage's projection finalizer with a receipt-only + // job update. Their existing deadline remains authoritative. + if (!hash_equals( + (string) ($job->finalization_error_code ?? ''), + $errorCode + )) { + $job->read_at = null; + } + $job->finalization_incident = 1; + $job->finalization_error_code = $errorCode; + $job->updated_at = $now; + $job->save(); + return; + } + if ($active) { + $job->phase = 'terminal'; + $job->outcome = 'failed'; + $job->status = 'failed'; + $job->terminal_at = $now; + $job->effect_may_have_applied = 1; + $job->safe_to_resubmit = 0; + $job->effect_resolution = 'unknown'; + $job->error_code = $errorCode; + } + if ((string) $job->phase !== 'terminal' + || (string) $job->effect_resolution !== 'unknown') { + return; + } + if (!hash_equals( + (string) ($job->finalization_error_code ?? ''), + $errorCode + )) { + $job->read_at = null; + } + $job->finalization_incident = 1; + $job->finalization_error_code = $errorCode; + $job->lease_token = null; + $job->lease_until = 0; + $job->available_at = $now + self::IDENTITY_RETRY_SECONDS; + $job->updated_at = $now; + $job->save(); + }, + 3 + ); + } + + /** + * Surface a corrupt single-dispatch counter without consuming Agent proof. + * + * This method deliberately does not touch completion-event disposition. + */ + public static function deferDispatchLedgerConflict( + CloudJob $source + ): void { + (new CloudJob())->getConnection()->transaction( + static function () use ($source): void { + $job = CloudJob::where('id', (int) $source->id) + ->lockForUpdate()->first(); + if ($job === null + || (!CloudDispatchLedger::isInvalid($source) + && !CloudDispatchLedger::isInvalid($job))) { + return; + } + // The caller already observed a corrupt generation. If an + // operator repairs the counter before this row lock is taken, + // retain a sticky incident and let the repair coordinator + // validate the immutable terminal state before unlocking. + self::applyDispatchLedgerConflictLocked($job, time()); + }, + 3 + ); + } + + /** + * Preserve an Agent receipt which contradicts a generation-zero ledger. + * The sticky incident also terminalizes an active row so the normal worker + * cannot replay the mutation while an operator repairs the counter. + */ + public static function deferNeverDispatchedEvidenceConflict( + CloudJob $source + ): void { + (new CloudJob())->getConnection()->transaction( + static function () use ($source): void { + $job = CloudJob::where('id', (int) $source->id) + ->lockForUpdate()->first(); + if ($job === null + || (string) $job->execution_mode !== 'agent' + || (!CloudDispatchLedger::isNeverDispatched($source) + && !CloudDispatchLedger::isNeverDispatched($job) + && !CloudDispatchLedger::hasRepairIncident($job))) { + return; + } + self::applyDispatchLedgerConflictLocked( + $job, + time(), + 'recovery_dispatch_repair_instance_state_conflict', + true + ); + }, + 3 + ); + } + + private static function applyDispatchLedgerConflictLocked( + CloudJob $job, + int $now, + string $incidentCode = CloudDispatchLedger::CONFLICT_CODE, + bool $gateReceivedEvidence = false + ): void { + if (in_array((string) $job->phase, + ['accepted', 'dispatching', 'awaiting_receipt'], true)) { + $job->phase = 'terminal'; + $job->outcome = 'failed'; + $job->status = 'failed'; + $job->terminal_at = $now; + $job->effect_may_have_applied = 1; + $job->safe_to_resubmit = 0; + $job->effect_resolution = 'unknown'; + $job->error_code = CloudDispatchLedger::CONFLICT_CODE; + } + if (!hash_equals( + (string) ($job->finalization_error_code ?? ''), + $incidentCode + )) { + $job->read_at = null; + } + $job->finalization_incident = 1; + $job->finalization_error_code = $incidentCode; + $job->lease_token = null; + $job->lease_until = $gateReceivedEvidence + ? $now + self::IDENTITY_RETRY_SECONDS : 0; + $job->available_at = $now + self::IDENTITY_RETRY_SECONDS; + $job->updated_at = $now; + $job->save(); + } + + /** + * Resume only the local ledger consequences of an operator-repaired + * dispatch counter. Terminal task fields and Agent mutations are immutable. + * + * @return string resolved, pending, missing, or invalid + */ + public static function resumeRepairedDispatchLedger( + CloudJob $source + ): string { + return (new CloudJob())->getConnection()->transaction( + static function () use ($source): string { + $job = CloudJob::where('id', (int) $source->id) + ->lockForUpdate()->first(); + if ($job === null) { + throw new CloudError('任务不存在', 404); + } + if (CloudDispatchLedger::isInvalid($job)) { + self::applyDispatchLedgerConflictLocked($job, time()); + return 'pending'; + } + if (!CloudDispatchLedger::hasRepairIncident($job)) { + return 'resolved'; + } + if ((string) $job->phase !== 'terminal' + || !in_array((string) $job->outcome, + ['failed', 'succeeded'], true) + || (string) $job->status !== (string) $job->outcome) { + throw new CloudRecoveryInstanceStateConflict( + '派发账本修复后的任务终态不一致', + 409 + ); + } + $now = time(); + if ((string) $job->outcome === 'failed') { + if (CloudDispatchLedger::isDispatched($job)) { + if (!self::canEnterAutomaticAgentRecovery($job)) { + throw new CloudRecoveryInstanceStateConflict( + '派发账本修复后仍缺少宿主机恢复身份或派发时间', + 409 + ); + } + $job->effect_may_have_applied = 1; + $job->safe_to_resubmit = 0; + $job->effect_resolution = 'unknown'; + } else { + self::assertNeverDispatchedRecoveryState($job); + if (!CloudOperationRecoveryPolicy::supports( + (string) $job->kind + )) { + throw new CloudRecoveryInstanceStateConflict( + '未派发任务缺少已注册的 PHP 业务终结器', + 409 + ); + } + $job->effect_may_have_applied = 0; + $job->safe_to_resubmit = 0; + $job->effect_resolution = 'not_applied'; + } + $job->finalization_incident = 1; + $job->finalization_error_code = 'recovery_pending'; + $job->lease_token = null; + $job->lease_until = 0; + $job->available_at = 0; + $job->updated_at = $now; + $job->save(); + return 'pending'; + } + if (!CloudDispatchLedger::isDispatched($job) + || (string) $job->effect_resolution !== 'applied') { + throw new CloudRecoveryInstanceStateConflict( + '成功任务与修复后的派发账本状态矛盾', + 409 + ); + } + if (!self::canEnterAutomaticAgentRecovery($job)) { + throw new CloudRecoveryInstanceStateConflict( + '成功任务的派发账本仍缺少宿主机恢复身份、派发时间或受支持操作类型', + 409 + ); + } + $eventId = $job->completion_event_id; + $event = $eventId === null || (string) $eventId === '' + ? CloudAgentCompletionEvent::where( + 'host_id', + (int) $job->host_id + )->where( + 'operation_id', + (string) $job->operation_id + )->lockForUpdate()->first() + : CloudAgentCompletionEvent::where( + 'event_id', + (string) $eventId + )->lockForUpdate()->first(); + if ($event === null + && ($eventId === null || (string) $eventId === '')) { + CloudOperationRecoveryIdentity::expected($job, true); + self::clearDispatchLedgerIncidentLocked($job, $now); + return 'resolved'; + } + if ($event === null) { + return 'missing'; + } + $exact = self::isExactStoredEvent($event) + || self::isExactAppliedEvent($event); + if (!$exact + || $job->host_id === null + || (int) $job->host_id !== (int) $event->host_id + || !is_string($job->operation_id) + || !hash_equals( + (string) $job->operation_id, + (string) $event->operation_id + ) + || (string) $event->outcome !== 'succeeded' + || (bool) $event->effect_may_have_applied + || (bool) $event->safe_to_resubmit) { + return 'invalid'; + } + $expected = CloudOperationRecoveryIdentity::expected( + $job, + true + ); + CloudOperationRecoveryIdentity::assertMatches( + $expected, + self::identity($event) + ); + self::clearDispatchLedgerIncidentLocked($job, $now); + if ((string) $event->disposition === 'received') { + $event->disposition = 'applied'; + $event->applied_at = $now; + $event->save(); + } + return 'resolved'; + }, + 3 + ); + } + + private static function canEnterAutomaticAgentRecovery( + CloudJob $job + ): bool { + $hostId = filter_var( + $job->host_id, + FILTER_VALIDATE_INT, + ['options' => ['min_range' => 1]] + ); + $dispatchedAt = filter_var( + $job->dispatched_at, + FILTER_VALIDATE_INT, + ['options' => ['min_range' => 1]] + ); + if ($hostId === false || $dispatchedAt === false + || !is_string($job->operation_id) + || preg_match( + '/^[a-f0-9]{32}$/D', + (string) $job->operation_id + ) !== 1) { + return false; + } + if (CloudOperationRecoveryPolicy::supports((string) $job->kind)) { + return true; + } + if ((string) $job->kind !== 'create') { + return false; + } + return CloudAgentCompletionEvent::where( + 'host_id', + (int) $hostId + )->where( + 'operation_id', + (string) $job->operation_id + )->where('outcome', 'succeeded') + ->where('disposition', 'received') + ->exists(); + } + + /** + * Generation zero may run only a PHP finalizer. Any durable Agent boundary + * or completion evidence means that zero is not trustworthy and must stay + * in the sticky dispatch-repair queue. + */ + public static function assertNeverDispatchedRecoveryState( + CloudJob $job + ): void { + if (!CloudDispatchLedger::isNeverDispatched($job)) { + throw new CloudRecoveryDispatchLedgerConflict( + '任务不再是未派发代次', + 409 + ); + } + if ($job->dispatched_at !== null + || $job->agent_accepted_at !== null + || $job->receipt_deadline_at !== null + || (is_string($job->completion_event_id) + && $job->completion_event_id !== '')) { + throw new CloudRecoveryInstanceStateConflict( + '未派发任务存在 Agent 派发或完成回执标记', + 409 + ); + } + $hostId = filter_var( + $job->host_id, + FILTER_VALIDATE_INT, + ['options' => ['min_range' => 1]] + ); + $operationId = $job->operation_id; + if ($hostId !== false && is_string($operationId) + && preg_match('/^[a-f0-9]{32}$/D', $operationId) === 1 + && CloudAgentCompletionEvent::where('host_id', (int) $hostId) + ->where('operation_id', $operationId)->exists()) { + throw new CloudRecoveryInstanceStateConflict( + '未派发任务存在同一操作的 Agent 完成证据', + 409 + ); + } + } + + private static function clearDispatchLedgerIncidentLocked( + CloudJob $job, + int $now + ): void { + $job->finalization_incident = 0; + $job->finalization_error_code = null; + $job->read_at = null; + $job->lease_token = null; + $job->lease_until = 0; + $job->available_at = 0; + $job->updated_at = $now; + $job->save(); + } + + private static function recordInputIncident( + array $input, + string $errorCode + ): void { + $hostId = filter_var( + $input['agent_id'] ?? null, + FILTER_VALIDATE_INT, + ['options' => ['min_range' => 1]] + ); + $operationId = $input['operation_id'] ?? null; + if ($hostId === false || !is_string($operationId) + || preg_match('/^[a-f0-9]{32}$/D', $operationId) !== 1) { + return; + } + self::recordReceiptIncident( + (int) $hostId, + $operationId, + $errorCode + ); + } + + private static function recordReceiptIncident( + int $hostId, + string $operationId, + string $errorCode + ): void { + try { + $job = CloudJob::where('host_id', $hostId) + ->where('execution_mode', 'agent') + ->where('operation_id', $operationId) + ->first(); + if ($job !== null) { + self::deferIdentityConflict($job, $errorCode); + } + } catch (\Throwable $ignored) { + // Receipt validation must retain its original bounded 400/409 + // contract even if the best-effort operator incident write fails. + } + } + private static function storedBoolean(mixed $value): ?bool { if ($value === true || $value === 1 || $value === '1') { @@ -278,7 +1125,8 @@ final class CloudOperationCompletionService private static function validate(array $input): array { - $allowed = ['type', 'id', 'agent_id', 'operation_id', 'status', + $allowed = ['type', 'id', 'agent_id', 'operation_id', 'action', + 'resource_id', 'request_fingerprint', 'status', 'effect_may_have_applied', 'safe_to_resubmit', 'error_code', 'result']; if (array_is_list($input) @@ -293,6 +1141,17 @@ final class CloudOperationCompletionService || (int) $input['agent_id'] < 1 || !is_string($input['operation_id'] ?? null) || preg_match('/^[a-f0-9]{32}$/D', $input['operation_id']) !== 1 + || !is_string($input['action'] ?? null) + || strlen($input['action']) > 128 + || preg_match('/^[a-z][a-z0-9]*(?:[-:][a-z0-9]+)*$/D', + $input['action']) !== 1 + || !is_string($input['resource_id'] ?? null) + || strlen($input['resource_id']) > 255 + || preg_match('/^[A-Za-z0-9][A-Za-z0-9_.:-]*$/D', + $input['resource_id']) !== 1 + || !is_string($input['request_fingerprint'] ?? null) + || preg_match('/^[a-f0-9]{64}$/D', + $input['request_fingerprint']) !== 1 || !in_array($input['status'] ?? null, ['succeeded', 'failed'], true) || !is_bool($input['effect_may_have_applied'] ?? null) @@ -313,10 +1172,14 @@ final class CloudOperationCompletionService && ($input['safe_to_resubmit'] ?? false) === true)))) { throw new CloudError('Agent 完成回执无效', 400); } + self::assertCompletionResultSafe($input['result']); return [ 'event_id' => $input['id'], 'host_id' => (int) $input['agent_id'], 'operation_id' => $input['operation_id'], + 'action' => $input['action'], + 'resource_id' => $input['resource_id'], + 'request_fingerprint' => $input['request_fingerprint'], 'status' => $input['status'], 'effect_may_have_applied' => $input['effect_may_have_applied'], 'safe_to_resubmit' => $input['safe_to_resubmit'], diff --git a/web/app/Services/Cloud/CloudOperationRecoveryIdentity.php b/web/app/Services/Cloud/CloudOperationRecoveryIdentity.php new file mode 100644 index 00000000..955573b4 --- /dev/null +++ b/web/app/Services/Cloud/CloudOperationRecoveryIdentity.php @@ -0,0 +1,1156 @@ +sealed_payload, + 'job-payload' + ); + } catch (\Throwable $error) { + throw new CloudRecoveryPayloadUnavailable( + '任务恢复请求无法解密', + 409 + ); + } + if (!is_array($payload) || array_is_list($payload)) { + throw new CloudRecoveryPayloadUnavailable( + '任务恢复请求结构无效', + 409 + ); + } + + $stored = self::stored($payload); + if ($stored !== null && self::isPreparedEscrow($job, $payload, $stored)) { + // prepareRecoveredEffect() may legitimately mutate or remove the + // catalog/instance row used for the original strict validation. + // Its encrypted prepare envelope therefore carries the immutable + // identity which was validated before that ledger mutation. + return $stored; + } + if ($stored !== null + && (string) $job->phase === 'terminal' + && in_array((string) $job->effect_resolution, + ['applied', 'not_applied'], true)) { + // A resolved task intentionally keeps only this non-secret + // binding. Any surviving safeResult body is redacted audit data, + // not the original wire payload and must not be re-fingerprinted. + return $stored; + } + $hasRequest = is_string($payload['method'] ?? null) + && is_string($payload['request_target'] ?? null) + && is_array($payload['body'] ?? null); + if (!$hasRequest) { + throw new CloudRecoveryPayloadUnavailable( + '任务缺少可重建的 Agent 请求', + 409 + ); + } + + $identity = self::expectedFromPayload( + $job, + $payload, + $forAppliedEffect + ); + if ($stored !== null && !self::same($identity, $stored)) { + throw new CloudRecoveryOperationIdentityConflict( + '任务持久化操作身份与原请求不匹配', + 409 + ); + } + return $identity; + } + + /** + * @return array{action:string,resource_id:string,request_fingerprint:string} + */ + public static function expectedFromPayload( + CloudJob $job, + array $payload, + bool $forAppliedEffect = false + ): array { + if (!self::supports((string) $job->kind) + || (string) $job->execution_mode !== 'agent' + || preg_match('/^[a-f0-9]{32}$/D', + (string) $job->operation_id) !== 1 + || (int) $job->host_id < 1 + || array_is_list($payload)) { + throw new CloudRecoveryPayloadUnavailable( + '任务不具备可恢复的 Agent 身份', + 409 + ); + } + $method = strtoupper((string) ($payload['method'] ?? '')); + $target = $payload['request_target'] ?? null; + $body = $payload['body'] ?? null; + if (!in_array($method, ['POST', 'PUT', 'PATCH', 'DELETE'], true) + || !is_string($target) || !str_starts_with($target, '/v1/') + || !is_array($body) + || ($body !== [] && array_is_list($body))) { + throw new CloudRecoveryPayloadUnavailable( + '任务中的 Agent 线上请求无效', + 409 + ); + } + self::assertBodyOperation($job, $body); + + $kind = (string) $job->kind; + if ($kind === 'create') { + [$action, $resourceId] = self::createIdentity( + $job, + $payload, + $method, + $target, + $body, + $forAppliedEffect + ); + } elseif ($kind === 'host_storage_configure') { + [$action, $resourceId] = self::storageIdentity( + $job, + $payload, + $method, + $target, + $body + ); + } elseif (in_array($kind, [ + 'action', 'reinstall', 'rescue', 'delete', 'delete_force', + 'expiry_delete', 'network_change', 'instance_settings', + 'snapshot_create', 'snapshot_restore', 'snapshot_delete', + 'firewall_apply', 'service_suspend', 'network_suspend', + 'network_resume', + ], true)) { + [$action, $resourceId] = self::instanceIdentity( + $job, + $payload, + $method, + $target, + $body, + $forAppliedEffect + ); + } else { + [$action, $resourceId] = self::catalogIdentity( + $job, + $payload, + $method, + $target, + $body + ); + } + $wire = self::wireBody($kind, $body); + $encoded = json_encode( + $wire === [] ? (object) [] : $wire, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + | JSON_UNESCAPED_UNICODE + ); + return [ + 'action' => $action, + 'resource_id' => $resourceId, + 'request_fingerprint' => hash( + 'sha256', + $method . "\n" . $target . "\n" . $encoded + ), + ]; + } + + /** Exact body translation used by both dispatch and identity recovery. */ + public static function wireBody(string $kind, array $body): array + { + if ($kind === 'action' && ($body['action'] ?? null) === 'poweroff') { + $body['action'] = 'destroy'; + } + return $body; + } + + /** @param array{action:string,resource_id:string,request_fingerprint:string} $identity */ + public static function persisted(array $identity): array + { + self::assertIdentityShape($identity); + return [ + 'version' => self::VERSION, + 'action' => $identity['action'], + 'resource_id' => $identity['resource_id'], + 'request_fingerprint' => $identity['request_fingerprint'], + ]; + } + + public static function payloadKey(): string + { + return self::KEY; + } + + public static function same(array $expected, array $actual): bool + { + foreach (['action', 'resource_id', 'request_fingerprint'] as $key) { + if (!is_string($expected[$key] ?? null) + || !is_string($actual[$key] ?? null) + || !hash_equals($expected[$key], $actual[$key])) { + return false; + } + } + return true; + } + + public static function assertMatches(array $expected, array $actual): void + { + if (!self::same($expected, $actual)) { + throw new CloudRecoveryOperationIdentityConflict( + 'Agent 操作身份与当前任务不匹配', + 409 + ); + } + } + + private static function instanceIdentity( + CloudJob $job, + array $payload, + string $method, + string $target, + array $body, + bool $forAppliedEffect + ): array { + $instanceId = filter_var($job->instance_id, FILTER_VALIDATE_INT, + ['options' => ['min_range' => 1]]); + $instance = $instanceId === false ? null + : CloudInstance::find((int) $instanceId); + if ($instance === null + || (int) $instance->host_id !== (int) $job->host_id + || preg_match(self::UUID_PATTERN, + strtolower((string) $instance->uuid)) !== 1 + || (int) ($payload['owner_id'] ?? 0) + !== (int) $instance->user_id + || ((int) $job->user_id !== (int) $instance->user_id + && ($payload['can_manage'] ?? false) !== true)) { + throw new CloudRecoveryInstanceStateConflict( + '任务与实例所属人、宿主机或 UUID 账本不匹配', + 409 + ); + } + $kind = (string) $job->kind; + if ((string) $instance->status === 'deleted' + && !in_array($kind, + ['delete', 'delete_force', 'expiry_delete'], true)) { + throw new CloudRecoveryInstanceStateConflict( + '实例状态与原操作请求矛盾', + 409 + ); + } + $uuid = strtolower((string) $instance->uuid); + $base = '/v1/vms/' . rawurlencode($uuid); + $action = match ($kind) { + 'action' => self::powerAction($method, $target, $base, $body), + 'reinstall' => self::reinstallAction( + $job, $payload, $method, $target, $base, $body, + $forAppliedEffect + ), + 'rescue' => self::rescueAction($method, $target, $base, $body), + 'delete', 'expiry_delete' => self::deleteAction( + $method, $target, $base, $body + ), + 'delete_force' => self::forceDeleteAction( + $job, $payload, $method, $target, $base, $body + ), + 'network_change' => self::networkChangeAction( + $method, $target, $base, $body + ), + 'instance_settings' => self::settingsAction( + $method, $target, $base, $body + ), + 'snapshot_create', 'snapshot_restore', 'snapshot_delete' => + self::snapshotAction( + $job, $payload, $instance, $method, $target, $base, $body + ), + 'firewall_apply' => self::firewallAction( + $job, $payload, $instance, $method, $target, $base, $body + ), + 'service_suspend' => self::policyAction( + $method, $target, $base . '/service/suspend', $body, + ['operation_id', 'reason'], + ($body['reason'] ?? null) === 'purge', + 'service-suspend' + ), + 'network_suspend' => self::policyAction( + $method, $target, $base . '/network/suspend', $body, + ['operation_id', 'reason'], + is_string($body['reason'] ?? null) + && in_array($body['reason'], ['traffic', 'expired'], true), + 'network-suspend' + ), + 'network_resume' => self::policyAction( + $method, $target, $base . '/network/resume', $body, + ['operation_id'], + true, + 'network-resume' + ), + default => throw new CloudRecoveryPayloadUnavailable( + '实例任务类型没有恢复身份映射', 409 + ), + }; + return [$action, $uuid]; + } + + private static function createIdentity( + CloudJob $job, + array $payload, + string $method, + string $target, + array $body, + bool $forAppliedEffect + ): array { + self::expectRequest($method, $target, 'POST', '/v1/vms'); + self::assertAllowedBody($body, [ + 'operation_id', 'uuid', 'source', 'name', 'description', 'vcpu', + 'memory_mib', 'disk_gib', 'bandwidth_mbps', 'network', + 'template_id', 'template_revision', 'template_generation_token', + 'startup_script', 'hostname', 'guest_ssh_public_key', + 'root_password', 'public_pool_key', 'public_pool_cidr', + 'public_ip_cidr', 'gateway', 'dns_servers', + 'platform_network_policy_snapshot', + ]); + $resourceId = self::operationUuid((string) $job->operation_id); + $requestedUuid = $body['uuid'] ?? null; + $integers = ['vcpu', 'memory_mib', 'disk_gib', 'bandwidth_mbps', + 'template_revision']; + $validIntegers = true; + foreach ($integers as $field) { + if (filter_var( + $body[$field] ?? null, + FILTER_VALIDATE_INT, + ['options' => ['min_range' => 1]] + ) === false) { + $validIntegers = false; + break; + } + } + if (($body['source'] ?? null) !== 'cloud' + || !is_string($body['name'] ?? null) + || preg_match('/^[A-Za-z0-9_.-]{1,80}$/D', $body['name']) !== 1 + || !$validIntegers + || !is_string($body['template_id'] ?? null) + || preg_match(self::TEMPLATE_ID_PATTERN, + $body['template_id']) !== 1 + || !is_string($body['template_generation_token'] ?? null) + || preg_match(self::CATALOG_ID_PATTERN, + $body['template_generation_token']) !== 1 + || !is_string($body['network'] ?? null) + || trim($body['network']) === '' + || !is_string($body['public_pool_key'] ?? null) + || preg_match(self::CATALOG_ID_PATTERN, + $body['public_pool_key']) !== 1 + || !is_string($body['public_pool_cidr'] ?? null) + || !is_string($body['public_ip_cidr'] ?? null) + || !is_string($body['gateway'] ?? null) + || !is_array($body['dns_servers'] ?? null) + || !array_is_list($body['dns_servers']) + || $body['dns_servers'] === [] + || !is_array($body['platform_network_policy_snapshot'] ?? null) + || array_is_list($body['platform_network_policy_snapshot']) + || ($requestedUuid !== null + && (!is_string($requestedUuid) + || !hash_equals($resourceId, + strtolower($requestedUuid)))) + || (int) $job->user_id < 1 + || $job->order_id === null + || (int) $job->order_id < 1 + || array_key_exists('owner_id', $payload)) { + self::invalidPayload('创建实例请求与任务账本不匹配'); + } + $metadata = $payload['template_metadata'] ?? null; + if (!is_array($metadata) || array_is_list($metadata) + || ($metadata['template_id'] ?? null) + !== $body['template_id'] + || ($metadata['os_source'] ?? null) !== 'cloud_template' + || !is_string($metadata['os_name'] ?? null) + || trim($metadata['os_name']) === '' + || ($metadata['login_name'] ?? null) !== 'root') { + self::invalidPayload('创建实例任务缺少可信模板快照'); + } + if ($forAppliedEffect) { + self::assertCreateAppliedEscrow($payload, $body); + } + return ['create-vm', $resourceId]; + } + + private static function assertCreateAppliedEscrow( + array $payload, + array $body + ): void { + $credential = $payload['credential'] ?? null; + $publicKey = $body['guest_ssh_public_key'] ?? null; + $hasKey = is_string($publicKey) && $publicKey !== ''; + if (!is_array($credential) || array_is_list($credential) + || array_diff(array_keys($credential), [ + 'password', 'login_name', 'auth_mode', + ]) !== [] + || ($credential['login_name'] ?? null) !== 'root' + || !is_string($credential['password'] ?? null) + || !is_string($body['root_password'] ?? null) + || !hash_equals( + (string) $body['root_password'], + (string) $credential['password'] + ) + || ($credential['auth_mode'] ?? null) + !== ($hasKey ? 'password_and_key' : 'password')) { + throw new CloudRecoveryPayloadUnavailable( + '创建成功恢复缺少完整且匹配的实例凭据', + 409 + ); + } + } + + private static function storageIdentity( + CloudJob $job, + array $payload, + string $method, + string $target, + array $body + ): array { + self::expectRequest( + $method, + $target, + 'POST', + '/v1/storage/configuration' + ); + $fields = [ + 'managed_directory', 'template_directory', 'seed_directory', + 'user_iso_directory', 'rescue_directory', + ]; + self::assertAllowedBody($body, array_merge( + ['operation_id'], + $fields + )); + $revision = filter_var( + $payload['storage_revision'] ?? null, + FILTER_VALIDATE_INT, + ['options' => ['min_range' => 1]] + ); + $row = CloudHostStorageConfiguration::find((int) $job->host_id); + if (($payload['can_manage'] ?? null) !== true + || $revision === false + || $row === null + || (int) $row->revision !== (int) $revision + || (int) ($row->job_id ?? 0) !== (int) $job->id + || !hash_equals((string) $job->operation_id, + (string) ($row->operation_id ?? ''))) { + throw new CloudRecoveryInstanceStateConflict( + '宿主机存储任务与配置账本不匹配', + 409 + ); + } + $paths = []; + foreach ($fields as $field) { + $value = $body[$field] ?? null; + if (!is_string($value) + || preg_match( + '#^/(?:[A-Za-z0-9._-]+)(?:/[A-Za-z0-9._-]+)*$#D', + $value + ) !== 1 + || !hash_equals((string) $row->{$field}, $value)) { + self::invalidPayload( + '宿主机存储请求与配置账本不匹配' + ); + } + $paths[] = $value; + } + foreach ($paths as $leftIndex => $left) { + foreach (array_slice($paths, $leftIndex + 1) as $right) { + if ($left === $right + || str_starts_with($left, $right . '/') + || str_starts_with($right, $left . '/')) { + self::invalidPayload('宿主机存储目录存在重叠'); + } + } + } + return ['configure-storage', 'host-storage']; + } + + /** Exact Go agent/api.operationUUID derivation for body-omitted UUIDs. */ + private static function operationUuid(string $operationId): string + { + $digest = hash( + 'sha256', + 'virt-cloud-operation:' . $operationId, + true + ); + $digest[6] = chr((ord($digest[6]) & 0x0f) | 0x50); + $digest[8] = chr((ord($digest[8]) & 0x3f) | 0x80); + $hex = bin2hex(substr($digest, 0, 16)); + return substr($hex, 0, 8) . '-' + . substr($hex, 8, 4) . '-' + . substr($hex, 12, 4) . '-' + . substr($hex, 16, 4) . '-' + . substr($hex, 20, 12); + } + + private static function powerAction( + string $method, + string $target, + string $base, + array $body + ): string { + self::expectRequest($method, $target, 'POST', $base . '/actions'); + self::assertAllowedBody($body, ['operation_id', 'action']); + $action = $body['action'] ?? null; + if (!is_string($action) + || !in_array($action, + ['start', 'shutdown', 'reboot', 'reset', 'poweroff'], true)) { + self::invalidPayload('电源操作请求无效'); + } + return 'power-' . ($action === 'poweroff' ? 'destroy' : $action); + } + + private static function reinstallAction( + CloudJob $job, + array $payload, + string $method, + string $target, + string $base, + array $body, + bool $forAppliedEffect + ): string { + self::expectRequest($method, $target, 'POST', $base . '/reinstall'); + self::assertAllowedBody($body, [ + 'operation_id', 'template_id', 'template_revision', + 'template_generation_token', 'preserve_data', 'root_password', + 'ssh_public_key', + ]); + $templateId = $body['template_id'] ?? null; + if (!is_string($templateId) + || preg_match(self::TEMPLATE_ID_PATTERN, $templateId) !== 1 + || filter_var($body['template_revision'] ?? null, + FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) === false + || !is_string($body['template_generation_token'] ?? null) + || preg_match('/^[a-f0-9]{32}$/D', + $body['template_generation_token']) !== 1) { + self::invalidPayload('重装请求中的模板快照无效'); + } + if ($forAppliedEffect) { + self::assertReinstallAppliedEscrow($job, $payload, $body); + } + return 'reinstall-vm'; + } + + private static function assertReinstallAppliedEscrow( + CloudJob $job, + array $payload, + array $body + ): void { + $credential = $payload['credential'] ?? null; + $metadata = $payload['template_metadata'] ?? null; + $hasKey = is_string($body['ssh_public_key'] ?? null) + && $body['ssh_public_key'] !== ''; + if (!is_array($credential) || array_is_list($credential) + || array_diff(array_keys($credential), [ + 'password', 'login_name', 'auth_mode', + ]) !== [] + || ($credential['login_name'] ?? null) !== 'root' + || !is_string($credential['password'] ?? null) + || ($credential['password'] ?? null) + !== ($body['root_password'] ?? null) + || ($credential['auth_mode'] ?? null) + !== ($hasKey ? 'password_and_key' : 'password') + || !is_array($metadata) || array_is_list($metadata) + || array_diff(array_keys($metadata), [ + 'template_id', 'os_source', 'os_name', 'login_name', + ]) !== [] + || ($metadata['template_id'] ?? null) + !== ($body['template_id'] ?? null) + || ($metadata['os_source'] ?? null) !== 'cloud_template' + || !is_string($metadata['os_name'] ?? null) + || trim($metadata['os_name']) === '' + || ($metadata['login_name'] ?? null) !== 'root') { + throw new CloudRecoveryPayloadUnavailable( + '重装成功恢复缺少完整凭据或可信模板快照', + 409 + ); + } + } + + private static function rescueAction( + string $method, + string $target, + string $base, + array $body + ): string { + if ($method !== 'POST') { + self::invalidPayload('救援操作请求方法无效'); + } + if ($target === $base . '/rescue/enter') { + self::assertAllowedBody($body, ['operation_id', 'template_id']); + if (!is_string($body['template_id'] ?? null) + || preg_match(self::TEMPLATE_ID_PATTERN, + $body['template_id']) !== 1) { + self::invalidPayload('救援镜像标识无效'); + } + return 'enter-rescue'; + } + if ($target === $base . '/rescue/force-start') { + self::assertAllowedBody($body, ['operation_id', 'ack_data_loss']); + if (($body['ack_data_loss'] ?? null) !== true) { + self::invalidPayload('救援强制启动确认无效'); + } + return 'force-start-rescue'; + } + if ($target === $base . '/rescue/exit') { + self::assertAllowedBody($body, + ['operation_id', 'network_suspended']); + if (!is_bool($body['network_suspended'] ?? null)) { + self::invalidPayload('救援退出网络状态无效'); + } + return 'exit-rescue:' + . ($body['network_suspended'] ? 'suspended' : 'connected'); + } + self::invalidPayload('救援操作路径无效'); + } + + private static function deleteAction( + string $method, + string $target, + string $base, + array $body + ): string { + self::expectRequest($method, $target, 'DELETE', $base); + self::assertAllowedBody($body, + ['operation_id', 'remove_managed_disks']); + if (($body['remove_managed_disks'] ?? null) !== true) { + self::invalidPayload('删除请求缺少托管磁盘清理确认'); + } + return 'delete-vm'; + } + + private static function forceDeleteAction( + CloudJob $job, + array $payload, + string $method, + string $target, + string $base, + array $body + ): string { + self::expectRequest($method, $target, 'POST', $base . '/force-delete'); + self::assertAllowedBody($body, [ + 'operation_id', 'prior_operation_id', 'ack_data_loss', + 'remove_managed_disks', + ]); + if (($body['operation_id'] ?? null) !== (string) $job->operation_id + || !is_string($body['prior_operation_id'] ?? null) + || preg_match('/^[a-f0-9]{32}$/D', + $body['prior_operation_id']) !== 1 + || ($payload['prior_operation_id'] ?? null) + !== $body['prior_operation_id'] + || ($body['ack_data_loss'] ?? null) !== true + || ($body['remove_managed_disks'] ?? null) !== true) { + self::invalidPayload('强制删除请求关联无效'); + } + return 'force-delete-vm'; + } + + private static function networkChangeAction( + string $method, + string $target, + string $base, + array $body + ): string { + self::expectRequest($method, $target, 'POST', $base . '/network'); + self::assertAllowedBody($body, [ + 'operation_id', 'network', 'public_pool_key', 'public_pool_cidr', + 'public_ip_cidr', 'gateway', 'dns_servers', 'confirm_restart', + ]); + if (($body['confirm_restart'] ?? null) !== true + || !is_string($body['network'] ?? null) + || !is_string($body['public_pool_key'] ?? null) + || preg_match('/^[a-f0-9]{32}$/D', + $body['public_pool_key']) !== 1 + || !is_string($body['public_pool_cidr'] ?? null) + || !is_string($body['public_ip_cidr'] ?? null) + || !is_string($body['gateway'] ?? null) + || !is_array($body['dns_servers'] ?? null) + || !array_is_list($body['dns_servers'])) { + self::invalidPayload('公网 IP 变更请求无效'); + } + return 'change-network'; + } + + private static function settingsAction( + string $method, + string $target, + string $base, + array $body + ): string { + if (!in_array($method, ['POST', 'PATCH'], true) + || $target !== $base . '/settings') { + self::invalidPayload('实例设置请求路径无效'); + } + self::assertAllowedBody($body, [ + 'operation_id', 'hostname', 'root_password', 'ssh_public_key', + 'confirm_restart', + ]); + $changed = array_intersect( + array_keys($body), + ['hostname', 'root_password', 'ssh_public_key'] + ); + if (($body['confirm_restart'] ?? null) !== true || $changed === []) { + self::invalidPayload('实例设置恢复字段无效'); + } + return 'update-settings'; + } + + private static function snapshotAction( + CloudJob $job, + array $payload, + CloudInstance $instance, + string $method, + string $target, + string $base, + array $body + ): string { + $snapshotId = filter_var($job->snapshot_id, FILTER_VALIDATE_INT, + ['options' => ['min_range' => 1]]); + $snapshot = $snapshotId === false ? null + : CloudInstanceSnapshot::find((int) $snapshotId); + $key = $payload['snapshot_key'] ?? null; + if ($snapshot === null + || (int) $snapshot->instance_id !== (int) $instance->id + || (int) $snapshot->host_id !== (int) $job->host_id + || (int) $snapshot->user_id !== (int) $instance->user_id + || !is_string($key) + || preg_match(self::CATALOG_ID_PATTERN, $key) !== 1 + || !hash_equals((string) $snapshot->snapshot_key, $key) + || !hash_equals((string) $snapshot->last_operation_id, + (string) $job->operation_id)) { + throw new CloudRecoveryInstanceStateConflict( + '快照任务与实例目录账本不匹配', + 409 + ); + } + if ((string) $job->kind === 'snapshot_create') { + self::expectRequest($method, $target, 'POST', $base . '/snapshots'); + self::assertAllowedBody($body, [ + 'operation_id', 'snapshot_id', 'snapshot_key', 'name', + 'description', 'quiesce', 'consistency_mode', + ]); + $consistency = $body['consistency_mode'] ?? null; + if (($body['snapshot_key'] ?? null) !== $key + || !in_array($consistency, ['filesystem', 'crash'], true)) { + self::invalidPayload('创建快照请求无效'); + } + return 'create-snapshot:' . $key . ':' . $consistency; + } + self::assertAllowedBody($body, ['operation_id']); + if ((string) $job->kind === 'snapshot_restore') { + self::expectRequest($method, $target, 'POST', + $base . '/snapshots/' . rawurlencode($key) . '/restore'); + return 'restore-snapshot:' . $key; + } + self::expectRequest($method, $target, 'DELETE', + $base . '/snapshots/' . rawurlencode($key)); + return 'delete-snapshot:' . $key; + } + + private static function firewallAction( + CloudJob $job, + array $payload, + CloudInstance $instance, + string $method, + string $target, + string $base, + array $body + ): string { + self::expectRequest($method, $target, 'PUT', $base . '/firewall'); + self::assertAllowedBody($body, [ + 'operation_id', 'revision', 'default_in', 'default_out', + 'policy_digest', 'rules', + ]); + $versionId = filter_var($payload['firewall_version_id'] ?? null, + FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); + $version = $versionId === false ? null + : CloudInstanceFirewallVersion::find((int) $versionId); + if ($version === null + || (int) $version->instance_id !== (int) $instance->id + || (int) $version->job_id !== (int) $job->id + || !hash_equals((string) $version->operation_id, + (string) $job->operation_id) + || (int) $version->revision !== (int) ($body['revision'] ?? 0) + || (int) ($payload['firewall_revision'] ?? 0) + !== (int) $version->revision + || !is_string($body['policy_digest'] ?? null) + || preg_match('/^[a-f0-9]{64}$/D', + $body['policy_digest']) !== 1 + || ($payload['agent_firewall_policy_digest'] ?? null) + !== $body['policy_digest'] + || !is_array($body['rules'] ?? null) + || !array_is_list($body['rules'])) { + throw new CloudRecoveryInstanceStateConflict( + '防火墙任务与版本账本不匹配', + 409 + ); + } + return 'apply-firewall'; + } + + private static function policyAction( + string $method, + string $target, + string $expectedTarget, + array $body, + array $allowed, + bool $valid, + string $action + ): string { + self::expectRequest($method, $target, 'POST', $expectedTarget); + self::assertAllowedBody($body, $allowed); + if (!$valid) { + self::invalidPayload('系统策略请求无效'); + } + return $action; + } + + private static function catalogIdentity( + CloudJob $job, + array $payload, + string $method, + string $target, + array $body + ): array { + return match ((string) $job->kind) { + 'template_import_replica', 'template_metadata_replica', + 'template_delete_replica' => self::templateIdentity( + $job, $payload, $method, $target, $body + ), + 'rescue_template_import', 'rescue_template_delete' => + self::rescueTemplateIdentity( + $job, $payload, $method, $target, $body + ), + 'user_iso_import_replica', 'user_iso_delete_replica' => + self::userIsoIdentity( + $job, $payload, $method, $target, $body + ), + default => throw new CloudRecoveryPayloadUnavailable( + '目录任务类型没有恢复身份映射', 409 + ), + }; + } + + private static function templateIdentity( + CloudJob $job, + array $payload, + string $method, + string $target, + array $body + ): array { + $id = $payload['template_id'] ?? null; + $template = is_string($id) ? CloudTemplate::find($id) : null; + $replica = is_string($id) ? CloudTemplateReplica::where( + 'host_id', (int) $job->host_id + )->where('template_id', $id)->first() : null; + $parent = $job->parent_job_id === null ? null + : CloudJob::find((int) $job->parent_job_id); + $expectedParent = [ + 'template_import_replica' => 'template_import', + 'template_metadata_replica' => 'template_metadata_sync', + 'template_delete_replica' => 'template_delete', + ][(string) $job->kind]; + if (!is_string($id) + || preg_match(self::TEMPLATE_ID_PATTERN, $id) !== 1 + || $template === null || $replica === null || $parent === null + || (string) $parent->kind !== $expectedParent + || (int) $template->active_job_id !== (int) $parent->id + || (int) $replica->job_id !== (int) $job->id + || !hash_equals((string) $replica->operation_id, + (string) $job->operation_id)) { + throw new CloudRecoveryInstanceStateConflict( + '云镜像子任务与副本账本不匹配', 409 + ); + } + $resource = 'template:' . $id; + if ((string) $job->kind === 'template_import_replica') { + self::expectRequest($method, $target, 'POST', '/v1/templates'); + self::assertAllowedBody($body, [ + 'operation_id', 'id', 'name', 'source_url', 'source_token', + 'os_family', 'version', 'architecture', 'sha256', 'revision', + 'generation_token', + ]); + if (($body['id'] ?? null) !== $id + || (int) ($body['revision'] ?? 0) !== (int) $replica->revision + || ($body['generation_token'] ?? null) + !== (string) $replica->generation_token) { + self::invalidPayload('云镜像导入请求与副本不匹配'); + } + return ['import-template', $resource]; + } + if ((string) $job->kind === 'template_metadata_replica') { + self::expectRequest($method, $target, 'PATCH', + '/v1/templates/' . rawurlencode($id)); + self::assertAllowedBody($body, [ + 'operation_id', 'name', 'revision', 'generation_token', + ]); + if ((int) ($body['revision'] ?? 0) !== (int) $template->revision + || ($body['generation_token'] ?? null) + !== (string) $template->generation_token) { + self::invalidPayload('云镜像元数据请求与目录不匹配'); + } + return ['update-template', $resource]; + } + self::expectRequest($method, $target, 'DELETE', + '/v1/templates/' . rawurlencode($id)); + self::assertAllowedBody($body, ['operation_id']); + return ['delete-template', $resource]; + } + + private static function rescueTemplateIdentity( + CloudJob $job, + array $payload, + string $method, + string $target, + array $body + ): array { + $id = $payload['rescue_template_id'] ?? null; + if (!is_string($id) + || preg_match(self::CATALOG_ID_PATTERN, $id) !== 1) { + self::invalidPayload('救援镜像任务标识无效'); + } + if ((string) $job->kind === 'rescue_template_import') { + $row = CloudRescueTemplateImport::where( + 'operation_id', (string) $job->operation_id + )->where('host_id', (int) $job->host_id)->first(); + self::expectRequest($method, $target, 'POST', + '/v1/rescue-templates'); + self::assertAllowedBody($body, [ + 'operation_id', 'id', 'name', 'source_url', 'source_token', + 'sha256', + ]); + if ($row === null || (int) $row->job_id !== (int) $job->id + || ($body['id'] ?? null) !== $id + || (string) $row->template_id !== $id + || ($body['name'] ?? null) !== (string) $row->name) { + throw new CloudRecoveryInstanceStateConflict( + '救援镜像导入任务与目录账本不匹配', + 409 + ); + } + return ['import-rescue-template', 'rescue-template:' . $id]; + } + $row = CloudRescueTemplateDeletion::where( + 'host_id', (int) $job->host_id + )->where('operation_id', (string) $job->operation_id)->first(); + self::expectRequest($method, $target, 'DELETE', + '/v1/rescue-templates/' . rawurlencode($id)); + self::assertAllowedBody($body, ['operation_id']); + if ($row === null || (int) $row->job_id !== (int) $job->id + || (string) $row->template_id !== $id) { + throw new CloudRecoveryInstanceStateConflict( + '救援镜像删除任务与目录账本不匹配', + 409 + ); + } + return ['delete-rescue-template', 'rescue-template:' . $id]; + } + + private static function userIsoIdentity( + CloudJob $job, + array $payload, + string $method, + string $target, + array $body + ): array { + $id = $payload['user_iso_id'] ?? null; + $owner = filter_var($payload['owner_id'] ?? null, + FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); + $iso = is_string($id) ? CloudUserIso::find($id) : null; + $replica = is_string($id) ? CloudUserIsoReplica::where( + 'host_id', (int) $job->host_id + )->where('user_iso_id', $id)->first() : null; + $parent = $job->parent_job_id === null ? null + : CloudJob::find((int) $job->parent_job_id); + $expectedParent = [ + 'user_iso_import_replica' => 'user_iso_import', + 'user_iso_delete_replica' => 'user_iso_delete', + ][(string) $job->kind]; + if (!is_string($id) + || preg_match(self::CATALOG_ID_PATTERN, $id) !== 1 + || $owner === false || $iso === null || $replica === null + || $parent === null + || $parent->parent_job_id !== null + || (string) $parent->execution_mode !== 'aggregate' + || (string) $parent->kind !== $expectedParent + || (int) $parent->user_id !== (int) $owner + || (int) $job->user_id !== (int) $owner + || (int) $iso->active_job_id !== (int) $parent->id + || (int) $iso->user_id !== (int) $owner + || (int) $replica->user_id !== (int) $owner + || (int) $replica->job_id !== (int) $job->id + || !hash_equals((string) $replica->operation_id, + (string) $job->operation_id)) { + throw new CloudRecoveryInstanceStateConflict( + 'ISO 子任务与所属人或副本账本不匹配', 409 + ); + } + $resource = 'user-iso:' . (int) $owner . ':' . $id; + if ((string) $job->kind === 'user_iso_import_replica') { + self::expectRequest($method, $target, 'POST', '/v1/user-isos'); + self::assertAllowedBody($body, [ + 'operation_id', 'id', 'owner_id', 'name', 'source_url', + 'source_token', 'sha256', + ]); + if (($body['id'] ?? null) !== $id + || (int) ($body['owner_id'] ?? 0) !== (int) $owner + || ($body['name'] ?? null) !== (string) $iso->name) { + self::invalidPayload('ISO 导入请求与目录不匹配'); + } + return ['import-user-iso', $resource]; + } + self::expectRequest($method, $target, 'DELETE', + '/v1/user-isos/' . rawurlencode($id) + . '?owner_id=' . (int) $owner); + self::assertAllowedBody($body, ['operation_id']); + return ['delete-user-iso', $resource]; + } + + private static function assertBodyOperation(CloudJob $job, array $body): void + { + if (array_key_exists('operation_id', $body) + && (!is_string($body['operation_id']) + || !hash_equals((string) $job->operation_id, + $body['operation_id']))) { + self::invalidPayload('Agent 请求中的操作标识不匹配'); + } + } + + private static function expectRequest( + string $method, + string $target, + string $expectedMethod, + string $expectedTarget + ): void { + if ($method !== $expectedMethod || $target !== $expectedTarget) { + self::invalidPayload('Agent 请求方法或路径与任务不匹配'); + } + } + + private static function assertAllowedBody(array $body, array $allowed): void + { + if (($body !== [] && array_is_list($body)) + || array_diff(array_keys($body), $allowed) !== []) { + self::invalidPayload('Agent 请求字段超出固定协议'); + } + } + + private static function invalidPayload(string $message): never + { + throw new CloudRecoveryPayloadUnavailable($message, 409); + } + + private static function stored(array $payload): ?array + { + if (!array_key_exists(self::KEY, $payload)) { + return null; + } + $stored = $payload[self::KEY]; + if (!is_array($stored) || array_is_list($stored) + || array_diff(array_keys($stored), [ + 'version', 'action', 'resource_id', 'request_fingerprint', + ]) !== [] + || ($stored['version'] ?? null) !== self::VERSION) { + throw new CloudRecoveryPayloadUnavailable( + '任务持久化操作身份无效', 409 + ); + } + $identity = [ + 'action' => $stored['action'] ?? null, + 'resource_id' => $stored['resource_id'] ?? null, + 'request_fingerprint' => $stored['request_fingerprint'] ?? null, + ]; + self::assertIdentityShape($identity); + return $identity; + } + + private static function isPreparedEscrow( + CloudJob $job, + array $payload, + array $identity + ): bool { + $recovery = $payload['_operation_recovery'] ?? null; + $operation = is_array($recovery) + ? ($recovery['operation'] ?? null) : null; + $operationIdentity = is_array($operation) ? [ + 'action' => $operation['action'] ?? null, + 'resource_id' => $operation['resource_id'] ?? null, + 'request_fingerprint' => $operation['request_fingerprint'] + ?? $operation['fingerprint'] ?? null, + ] : []; + return is_array($recovery) && !array_is_list($recovery) + && ($recovery['version'] ?? null) === 1 + && ($recovery['kind'] ?? null) === (string) $job->kind + && is_string($recovery['prepared_marker'] ?? null) + && str_starts_with( + $recovery['prepared_marker'], + 'prepared:' + ) + && is_array($operation) && !array_is_list($operation) + && ($operation['operation_id'] ?? null) + === (string) $job->operation_id + && self::same($identity, $operationIdentity); + } + + private static function assertIdentityShape(array $identity): void + { + if (!is_string($identity['action'] ?? null) + || strlen($identity['action']) > 128 + || preg_match( + '/^[a-z][a-z0-9]*(?:[-:][a-z0-9]+)*$/D', + $identity['action'] + ) !== 1 + || !is_string($identity['resource_id'] ?? null) + || strlen($identity['resource_id']) > 255 + || preg_match('/^[A-Za-z0-9][A-Za-z0-9_.:-]*$/D', + $identity['resource_id']) !== 1 + || !is_string($identity['request_fingerprint'] ?? null) + || preg_match('/^[a-f0-9]{64}$/D', + $identity['request_fingerprint']) !== 1) { + throw new CloudRecoveryPayloadUnavailable( + '任务操作身份结构无效', 409 + ); + } + } +} diff --git a/web/app/Services/Cloud/CloudOperationRecoveryPolicy.php b/web/app/Services/Cloud/CloudOperationRecoveryPolicy.php new file mode 100644 index 00000000..bf25a115 --- /dev/null +++ b/web/app/Services/Cloud/CloudOperationRecoveryPolicy.php @@ -0,0 +1,49 @@ + */ + public static function kinds(): array + { + return self::AGENT_LEAF_KINDS; + } + + public static function supports(string $kind): bool + { + return in_array($kind, self::AGENT_LEAF_KINDS, true); + } +} diff --git a/web/app/Services/Cloud/CloudOperationRecoveryService.php b/web/app/Services/Cloud/CloudOperationRecoveryService.php index 3a2b298f..ba705b76 100644 --- a/web/app/Services/Cloud/CloudOperationRecoveryService.php +++ b/web/app/Services/Cloud/CloudOperationRecoveryService.php @@ -15,26 +15,7 @@ use App\Models\CloudJob; */ final class CloudOperationRecoveryService { - private const LATE_RECEIPT_MAX_AGE_SECONDS = 21600; - - /** - * Each entry is an audited late-success finalizer policy. New Agent - * mutations must opt in only after their ledger finalizer is proven safe - * when the original job has already reached terminal failure. - */ - private const APPLIED_RECOVERY_KINDS = [ - 'instance_settings' => true, - ]; - - /** - * A proved-not-applied settings operation has no resource ledger delta, - * but it still uses the same prepare -> Agent fence -> commit protocol. - * Keeping this registry separate prevents a generic failed operation from - * silently becoming authority to release an unrelated resource fence. - */ - private const NOT_APPLIED_RECOVERY_KINDS = [ - 'instance_settings' => true, - ]; + private const INCIDENT_RETRY_SECONDS = 300; /** * Apply the kind-specific PHP ledger finalizer while the job remains @@ -83,19 +64,49 @@ final class CloudOperationRecoveryService ?CloudAgentCompletionEvent $completionEvent = null ): CloudJob { self::assertResolvedBy($resolvedBy); + $aggregateParentId = (int) (CloudJob::where('id', $jobId) + ->value('parent_job_id') ?? 0); return (new CloudJob())->getConnection()->transaction( function () use ( $jobId, $operation, $evidenceSource, $resolvedBy, - $completionEvent + $completionEvent, + $aggregateParentId ): CloudJob { + if ($aggregateParentId > 0) { + $aggregateParent = CloudJob::where( + 'id', + $aggregateParentId + ) + ->lockForUpdate()->first(); + if ($aggregateParent === null) { + throw new CloudRecoveryAggregateStateConflict( + '任务的汇总父任务不存在', + 409 + ); + } + CloudTemplateCatalogService::lockAggregateCatalogLocked( + $aggregateParent + ); + CloudUserIsoService::lockAggregateCatalogLocked( + $aggregateParent + ); + } $job = CloudJob::where('id', $jobId) ->lockForUpdate()->first(); if ($job === null) { throw new CloudError('任务不存在', 404); } + if ((int) ($job->parent_job_id ?? 0) + !== $aggregateParentId) { + throw new CloudRecoveryAggregateStateConflict( + '任务的汇总父级关系在提交期间发生变化', + 409 + ); + } + self::assertLockedAgentRecoveryEnvelope($job); self::assertEvidenceSource($evidenceSource); self::assertAppliedOperationIdentity($job, $operation); $lockedEvent = self::lockLateReceiptEvent( @@ -133,25 +144,23 @@ final class CloudOperationRecoveryService )) { throw new CloudError('任务效果尚未完成账本预提交', 409); } - $payload = CloudSecrets::decrypt( - (string) $job->sealed_payload, - 'job-payload' - ); $job->effect_resolution = 'applied'; $job->effect_resolved_at = time(); $job->effect_resolved_by = $resolvedBy; $job->effect_resolution_reason = $finalReason; - $job->sealed_payload = CloudSecrets::encrypt( - CloudInput::safeResult($payload), - 'job-payload' - ); + $job->sealed_payload = self::finalizedRecoveryPayload($job); $job->lease_token = null; $job->lease_until = 0; $job->available_at = 0; $job->finalization_incident = 0; $job->finalization_error_code = null; + $job->read_at = null; $job->updated_at = time(); $job->save(); + CloudJobService::reconcileAggregateParentEffectLocked( + $job, + $resolvedBy + ); self::markLateReceiptApplied($job, $lockedEvent); return $job; }, @@ -160,61 +169,37 @@ final class CloudOperationRecoveryService } /** - * Persist a no-effect intent while the original unknown-effect blocker is - * still active. No instance ledger field changes in this phase. + * Roll back the kind-specific PHP pending ledger and persist a no-effect + * intent while the original unknown-effect blocker remains active. */ public static function prepareNotApplied( int $jobId, array $operation, string $evidenceSource ): CloudJob { - return (new CloudJob())->getConnection()->transaction( - function () use ($jobId, $operation, $evidenceSource): CloudJob { - $job = CloudJob::where('id', $jobId) - ->lockForUpdate()->first(); - if ($job === null) { - throw new CloudError('任务不存在', 404); - } - self::assertRecoveryIncidentAllowsPrepare($job); - self::assertRecoverableNotAppliedEvidence( - $job, - $operation, - $evidenceSource - ); - $marker = self::transitionPreparedMarker( - (string) $job->effect_resolution_reason, - self::preparedMarker( - $operation, - $evidenceSource - ), - $evidenceSource, - 'not_applied' - ); - // Prove the complete encrypted settings intent is intact - // before publishing anything which may authorize fence - // release. Conflict classification above is independent of - // local escrow health and must remain deterministic. - CloudWorkerService::settingsRecoveryContext($job); - if (hash_equals( - $marker, - (string) $job->effect_resolution_reason - )) { - self::clearLateReceiptRecoveryIncident( - $job, - $evidenceSource - ); - return $job; - } - $job->effect_resolution_reason = $marker; - self::clearLateReceiptRecoveryIncident( - $job, - $evidenceSource - ); - $job->updated_at = time(); - $job->save(); - return $job; - }, - 3 + $job = CloudJob::find($jobId); + if ($job === null) { + throw new CloudError('任务不存在', 404); + } + self::assertRecoverableNotAppliedEvidence( + $job, + $operation, + $evidenceSource + ); + $marker = self::transitionPreparedMarker( + (string) $job->effect_resolution_reason, + self::preparedMarker($operation, $evidenceSource), + $evidenceSource, + 'not_applied' + ); + // A proved no-effect operation must still drive the original failed + // finalizer. Network reservations, snapshots, firewall revisions and + // catalog replicas all have PHP-owned pending/uncertain ledger state + // which only that finalizer can roll back safely. + return (new CloudWorkerService())->prepareRecoveredEffect( + $jobId, + $operation, + $marker ); } @@ -230,19 +215,49 @@ final class CloudOperationRecoveryService ?CloudAgentCompletionEvent $completionEvent = null ): CloudJob { self::assertResolvedBy($resolvedBy); + $aggregateParentId = (int) (CloudJob::where('id', $jobId) + ->value('parent_job_id') ?? 0); return (new CloudJob())->getConnection()->transaction( function () use ( $jobId, $operation, $evidenceSource, $resolvedBy, - $completionEvent + $completionEvent, + $aggregateParentId ): CloudJob { + if ($aggregateParentId > 0) { + $aggregateParent = CloudJob::where( + 'id', + $aggregateParentId + ) + ->lockForUpdate()->first(); + if ($aggregateParent === null) { + throw new CloudRecoveryAggregateStateConflict( + '任务的汇总父任务不存在', + 409 + ); + } + CloudTemplateCatalogService::lockAggregateCatalogLocked( + $aggregateParent + ); + CloudUserIsoService::lockAggregateCatalogLocked( + $aggregateParent + ); + } $job = CloudJob::where('id', $jobId) ->lockForUpdate()->first(); if ($job === null) { throw new CloudError('任务不存在', 404); } + if ((int) ($job->parent_job_id ?? 0) + !== $aggregateParentId) { + throw new CloudRecoveryAggregateStateConflict( + '任务的汇总父级关系在提交期间发生变化', + 409 + ); + } + self::assertLockedAgentRecoveryEnvelope($job); self::assertEvidenceSource($evidenceSource); self::assertNotAppliedOperationIdentity($job, $operation); $lockedEvent = self::lockLateReceiptEvent( @@ -280,25 +295,23 @@ final class CloudOperationRecoveryService )) { throw new CloudError('任务效果尚未完成账本预提交', 409); } - $payload = CloudSecrets::decrypt( - (string) $job->sealed_payload, - 'job-payload' - ); $job->effect_resolution = 'not_applied'; $job->effect_resolved_at = time(); $job->effect_resolved_by = $resolvedBy; $job->effect_resolution_reason = $finalReason; - $job->sealed_payload = CloudSecrets::encrypt( - CloudInput::safeResult($payload), - 'job-payload' - ); + $job->sealed_payload = self::finalizedRecoveryPayload($job); $job->lease_token = null; $job->lease_until = 0; $job->available_at = 0; $job->finalization_incident = 0; $job->finalization_error_code = null; + $job->read_at = null; $job->updated_at = time(); $job->save(); + CloudJobService::reconcileAggregateParentEffectLocked( + $job, + $resolvedBy + ); self::markLateReceiptApplied($job, $lockedEvent); return $job; }, @@ -323,16 +336,56 @@ final class CloudOperationRecoveryService (string) $event->event_id ); } + if (CloudDispatchLedger::isInvalid($source)) { + CloudOperationCompletionService::deferDispatchLedgerConflict( + $source + ); + return 'received'; + } + if (CloudDispatchLedger::isNeverDispatched($source)) { + CloudOperationCompletionService:: + deferNeverDispatchedEvidenceConflict($source); + return 'received'; + } + if (CloudDispatchLedger::hasRepairIncident($source)) { + return 'received'; + } $current = $source; try { $current = CloudJob::find((int) $source->id) ?? $source; + CloudOperationCompletionService::assertEventIdentityForJob( + $current, + $event + ); if (self::wasReconciledBy($current, $event)) { return self::acknowledgeReconciledLateReceipt( (int) $current->id, (string) $event->event_id ); } + if ((string) $current->kind === 'create') { + if ((string) $event->outcome !== 'succeeded' + || (bool) $event->effect_may_have_applied + || (bool) $event->safe_to_resubmit + || !CloudOperationCompletionService::isExactStoredEvent( + $event + )) { + CloudOperationCompletionService::mark($event, 'late'); + return 'late'; + } + (new CloudWorkerService())->settleRecoveredCreateCompletion( + (int) $current->id, + $event + ); + $reloadedCreateEvent = CloudAgentCompletionEvent::where( + 'event_id', + (string) $event->event_id + )->first(); + return $reloadedCreateEvent === null + ? 'received' + : (string) $reloadedCreateEvent->disposition; + } $lateResolution = self::lateReceiptResolution($current, $event); if ($lateResolution === null) { CloudOperationCompletionService::mark($event, 'late'); @@ -404,28 +457,17 @@ final class CloudOperationRecoveryService return 'received'; } } catch (CloudRecoveryReceiptInvalid $error) { - try { - $repaired = self::acknowledgeReconciledLateReceipt( - (int) $current->id, - (string) $event->event_id - ); - if ($repaired !== 'received') { - return $repaired; - } - return self::parkLateReceiptValidationFailure( - (int) $current->id, - (string) $event->event_id + return self::isolateLateReceiptValidationFailure( + $current, + $event + ); + } catch (CloudError $error) { + if ($error->httpStatus === 502) { + return self::isolateLateReceiptValidationFailure( + $current, + $event ); - } catch (\Throwable $parkingError) { - error_log(sprintf( - 'cloud late completion invalid receipt parking pending job_id=%d kind=%s error=%s', - (int) $current->id, - (string) $current->kind, - get_class($parkingError) - )); - return 'received'; } - } catch (CloudError $error) { return self::retryOrParkLateReceiptFailure( $current, $event, @@ -451,67 +493,18 @@ final class CloudOperationRecoveryService CloudAgentCompletionEvent $event, string $resolution ): array { - if ($resolution === 'applied') { - $operation = CloudOperationCompletionService::operation($event); - $result = $operation['result'] ?? null; - $context = CloudWorkerService::settingsRecoveryContext($job); - if (!is_array($result) || array_is_list($result)) { - throw new CloudRecoveryReceiptInvalid( - 'Agent 成功结果缺少已确认的实例设置', - 502 - ); - } - $instanceUuid = (string) $context['instance']->uuid; - if (array_key_exists('uuid', $result) - && (!is_string($result['uuid']) - || !hash_equals($instanceUuid, $result['uuid']))) { - throw new CloudRecoveryReceiptInvalid( - 'Agent 成功结果的实例标识不匹配', - 502 - ); - } - if (($result['settings_changed'] ?? null) !== true) { - throw new CloudRecoveryReceiptInvalid( - 'Agent 成功结果缺少已确认的实例设置', - 502 - ); - } - if (array_key_exists('hostname', $context['body']) - && (!is_string($result['hostname'] ?? null) - || !hash_equals( - (string) $context['body']['hostname'], - (string) $result['hostname'] - ))) { - throw new CloudRecoveryReceiptInvalid( - 'Agent 成功结果缺少已确认的主机名', - 502 - ); - } - // Bind the receipt marker to the exact ledger fields consumed by - // the original request. Agent metadata may legitimately include - // the current hostname for password/key-only changes; that - // unrelated observation must not conflict with an earlier - // automatic prepared marker. - $critical = ['uuid' => $instanceUuid]; - $critical['settings_changed'] = true; - if (array_key_exists('hostname', $context['body'])) { - $critical['hostname'] = $result['hostname']; - } - $operation['result'] = $critical; - return $operation; + if (!in_array($resolution, ['applied', 'not_applied'], true) + || !CloudOperationRecoveryPolicy::supports((string) $job->kind)) { + throw new CloudRecoveryReceiptInvalid( + 'Agent 完成回执不支持该任务的效果收敛', + 409 + ); } - // An exact immutable Agent failure explicitly declaring no possible - // effect is stronger than a later host snapshot. Its transport-level - // error/result need not use the live inspection vocabulary, so - // normalize it into the sole settings no-effect finalizer contract. - return [ - 'operation_id' => (string) $event->operation_id, - 'status' => 'failed', - 'effect_may_have_applied' => false, - 'safe_to_resubmit' => false, - 'error_code' => 'settings_not_committed', - 'result' => [], - ]; + // Keep the exact authenticated Agent operation. Every supported kind's + // existing worker finalizer validates the result fields it consumes; + // replacing those fields with a settings-shaped synthetic result would + // discard snapshot, network, firewall and catalog ledger evidence. + return CloudOperationCompletionService::operation($event); } private static function acknowledgeReconciledLateReceipt( @@ -533,6 +526,12 @@ final class CloudOperationRecoveryService if ($disposition !== 'received') { return $disposition; } + if ($job !== null + && self::sameOperation($job, $event) + && CloudDispatchLedger::isInvalid($job)) { + self::holdDispatchLedgerConflictLocked($job); + return 'received'; + } if ($job === null || !self::sameOperation($job, $event) || !CloudOperationCompletionService::isExactStoredEvent( @@ -548,6 +547,13 @@ final class CloudOperationRecoveryService // caller loaded its snapshot. Once this job is no longer // eligible for the immutable receipt, terminate the event // instead of leaving an unclaimable "received" row. + if (self::retryableCreateCompletion($job, $event)) { + // Create is intentionally outside the generic + // inspection policy. Its exact success receipt is the + // only safe recovery evidence, so a temporary local + // ledger fault must not consume that evidence. + return 'received'; + } if (self::lateReceiptResolution($job, $event) === null) { $event->disposition = 'late'; $event->applied_at = null; @@ -591,9 +597,9 @@ final class CloudOperationRecoveryService } /** - * Stop retrying a valid receipt which contradicts already prepared - * durable evidence. The job lock is always acquired before the event lock, - * matching receipt ingestion and recovery claiming. + * Isolate a receipt which contradicts already prepared durable evidence. + * The job itself remains scheduled for fresh inspection; only this exact + * conflicting event leaves the recovery queue. */ private static function parkLateReceiptEvidenceConflict( int $jobId, @@ -619,16 +625,31 @@ final class CloudOperationRecoveryService ); } - private static function parkLateReceiptRetryLimit( - int $jobId, - string $eventId + private static function isolateLateReceiptValidationFailure( + CloudJob $job, + CloudAgentCompletionEvent $event ): string { - return self::parkLateReceiptIncident( - $jobId, - $eventId, - 'recovery_receipt_limit_reached', - false - ); + try { + $repaired = self::acknowledgeReconciledLateReceipt( + (int) $job->id, + (string) $event->event_id + ); + if ($repaired !== 'received') { + return $repaired; + } + return self::parkLateReceiptValidationFailure( + (int) $job->id, + (string) $event->event_id + ); + } catch (\Throwable $parkingError) { + error_log(sprintf( + 'cloud late completion invalid receipt parking pending job_id=%d kind=%s error=%s', + (int) $job->id, + (string) $job->kind, + get_class($parkingError) + )); + return 'received'; + } } private static function retryOrParkLateReceiptFailure( @@ -644,15 +665,6 @@ final class CloudOperationRecoveryService if ($repaired !== 'received') { return $repaired; } - $receivedAt = (int) $event->received_at; - if ($receivedAt > 0 - && $receivedAt <= time() - - self::LATE_RECEIPT_MAX_AGE_SECONDS) { - return self::parkLateReceiptRetryLimit( - (int) $job->id, - (string) $event->event_id - ); - } } catch (\Throwable $parkingError) { error_log(sprintf( 'cloud late completion retry parking pending job_id=%d kind=%s error=%s', @@ -662,9 +674,9 @@ final class CloudOperationRecoveryService )); return 'received'; } - // Keep the immutable receipt in "received" so a retransmission or a - // later worker can retry PHP-only ledger convergence. The Agent - // mutation is never dispatched again. + // Keep the immutable receipt in "received" without an age limit so a + // retransmission or later worker can retry PHP-only ledger convergence. + // The original Agent mutation is never dispatched again. error_log(sprintf( 'cloud late completion recovery pending job_id=%d kind=%s error=%s', (int) $job->id, @@ -700,6 +712,12 @@ final class CloudOperationRecoveryService if ($disposition !== 'received') { return $disposition; } + if ($job !== null + && self::sameOperation($job, $event) + && CloudDispatchLedger::isInvalid($job)) { + self::holdDispatchLedgerConflictLocked($job); + return 'received'; + } if ($job === null || !self::sameOperation($job, $event) || !CloudOperationCompletionService::isExactStoredEvent( @@ -750,12 +768,19 @@ final class CloudOperationRecoveryService // The typed conflict was reproduced under both locks. } } + if (!hash_equals( + (string) ($job->finalization_error_code ?? ''), + $errorCode + )) { + $job->read_at = null; + } $job->finalization_incident = 1; $job->finalization_error_code = $errorCode; $job->lease_token = null; $job->lease_until = 0; - $job->available_at = 0; - $job->updated_at = time(); + $now = time(); + $job->available_at = $now + self::INCIDENT_RETRY_SECONDS; + $job->updated_at = $now; $job->save(); $event->disposition = 'late'; $event->applied_at = null; @@ -855,24 +880,34 @@ final class CloudOperationRecoveryService } } - public static function assertRecoveryIncidentAllowsPrepare( + /** Fail closed on immutable generation damage at the locked publish seam. */ + private static function assertLockedAgentRecoveryEnvelope( CloudJob $job ): void { - $incident = (string) ($job->finalization_error_code ?? ''); - if ($incident === 'recovery_evidence_conflict') { - throw new CloudRecoveryEvidenceConflict( - '冲突的恢复证据尚未人工处置', + CloudDispatchLedger::assertValid($job); + if (CloudJobService::hasAgentRecoveryIdentityConflict($job)) { + throw new CloudRecoveryOperationIdentityConflict( + '任务不可变 Agent 请求身份异常', 409 ); } - if ($incident === 'recovery_receipt_invalid') { - throw new CloudError('无效的恢复回执尚未人工处置', 409); - } - if ($incident === 'recovery_receipt_limit_reached') { - throw new CloudError('回执恢复重试已达上限,尚未人工处置', 409); + if (CloudJobService::hasAgentRecoveryEnvelopeConflict($job)) { + throw new CloudRecoveryInstanceStateConflict( + '任务不可变 Agent 派发信封状态异常', + 409 + ); } } + public static function assertRecoveryIncidentAllowsPrepare( + CloudJob $job + ): void { + // Recovery incidents are operator-visible diagnostics, not terminal + // queue states. Exact marker/evidence comparisons below still prevent + // conflicting conclusions from publishing, while a later fresh Agent + // inspection remains free to converge repaired host or panel state. + } + private static function sameOperation( CloudJob $job, CloudAgentCompletionEvent $event @@ -893,7 +928,9 @@ final class CloudOperationRecoveryService CloudAgentCompletionEvent $event ): ?string { if (!self::recoverableUnknownEffect($job) - || !isset(self::APPLIED_RECOVERY_KINDS[(string) $job->kind])) { + || !CloudOperationRecoveryPolicy::supports( + (string) $job->kind + )) { return null; } if ((string) $event->outcome === 'succeeded' @@ -901,8 +938,7 @@ final class CloudOperationRecoveryService && !(bool) $event->safe_to_resubmit) { return 'applied'; } - if (isset(self::NOT_APPLIED_RECOVERY_KINDS[(string) $job->kind]) - && (string) $event->outcome === 'failed' + if ((string) $event->outcome === 'failed' && !(bool) $event->effect_may_have_applied) { // safe_to_resubmit belongs to the completed Agent generation. It // never authorizes replay here; both true and false settle only @@ -912,6 +948,24 @@ final class CloudOperationRecoveryService return null; } + private static function retryableCreateCompletion( + CloudJob $job, + CloudAgentCompletionEvent $event + ): bool { + return (string) $job->kind === 'create' + && (string) $job->execution_mode === 'agent' + && (string) $job->phase === 'terminal' + && (string) $job->outcome === 'failed' + && (string) $job->status === 'failed' + && (int) $job->dispatch_attempts === 1 + && (bool) $job->effect_may_have_applied + && !(bool) $job->safe_to_resubmit + && (string) $job->effect_resolution === 'unknown' + && (string) $event->outcome === 'succeeded' + && !(bool) $event->effect_may_have_applied + && !(bool) $event->safe_to_resubmit; + } + private static function assertRecoverableAppliedEvidence( CloudJob $job, array $operation, @@ -919,7 +973,7 @@ final class CloudOperationRecoveryService ): void { self::assertEvidenceSource($evidenceSource); self::assertAppliedOperationIdentity($job, $operation); - if (!isset(self::APPLIED_RECOVERY_KINDS[(string) $job->kind]) + if (!CloudOperationRecoveryPolicy::supports((string) $job->kind) || !self::recoverableUnknownEffect($job)) { throw new CloudError('任务效果恢复证据不满足安全策略', 409); } @@ -932,7 +986,7 @@ final class CloudOperationRecoveryService ): void { self::assertEvidenceSource($evidenceSource); self::assertNotAppliedOperationIdentity($job, $operation); - if (!isset(self::NOT_APPLIED_RECOVERY_KINDS[(string) $job->kind]) + if (!CloudOperationRecoveryPolicy::supports((string) $job->kind) || !self::recoverableUnknownEffect($job)) { throw new CloudError('任务效果恢复证据不满足安全策略', 409); } @@ -963,6 +1017,7 @@ final class CloudOperationRecoveryService || ($operation['safe_to_resubmit'] ?? null) !== false) { throw new CloudError('任务效果恢复证据与原操作不匹配', 409); } + self::assertOperationBinding($job, $operation, true); } private static function assertNotAppliedOperationIdentity( @@ -971,17 +1026,36 @@ final class CloudOperationRecoveryService ): void { $operationId = $operation['operation_id'] ?? null; $errorCode = $operation['error_code'] ?? null; - $result = $operation['result'] ?? []; + $result = $operation['result'] ?? null; if (!is_string($operationId) || !is_string($job->operation_id) || !hash_equals((string) $job->operation_id, $operationId) || ($operation['status'] ?? null) !== 'failed' || ($operation['effect_may_have_applied'] ?? null) !== false - || ($operation['safe_to_resubmit'] ?? null) !== false - || $errorCode !== 'settings_not_committed' - || !is_array($result) || $result !== []) { + || !is_bool($operation['safe_to_resubmit'] ?? null) + || !is_string($errorCode) + || preg_match('/^[a-z][a-z0-9_]{0,63}$/D', $errorCode) !== 1 + || ($result !== null && !is_array($result))) { throw new CloudError('任务效果恢复证据与原操作不匹配', 409); } + self::assertOperationBinding($job, $operation, false); + } + + private static function assertOperationBinding( + CloudJob $job, + array $operation, + bool $forAppliedEffect + ): void { + $expected = CloudOperationRecoveryIdentity::expected( + $job, + $forAppliedEffect + ); + CloudOperationRecoveryIdentity::assertMatches($expected, [ + 'action' => $operation['action'] ?? null, + 'resource_id' => $operation['resource_id'] ?? null, + 'request_fingerprint' => $operation['request_fingerprint'] + ?? $operation['fingerprint'] ?? null, + ]); } private static function assertEvidenceSource(string $source): void @@ -1023,7 +1097,7 @@ final class CloudOperationRecoveryService /** * Preserve the durable automatic-attempt envelope while replacing its * pending payload with the exact prepared evidence. An immutable late - * completion may replace only a still-pending/exhausted envelope; it may + * completion may replace only a still-pending legacy envelope; it may * never overwrite a different prepared conclusion. */ private static function transitionPreparedMarker( @@ -1108,7 +1182,7 @@ final class CloudOperationRecoveryService private static function automaticRecoveryState(string $marker): ?array { if (preg_match( - '/^automatic_recovery:v1:([1-9][0-9]{0,10}):([1-9]|1[0-2]):(pending|prepared:(?:automatic_(?:applied|not_applied)_(?:succeeded|failed)_(?:fence|nofence):[a-f0-9]{64}|late_completion_receipt:[A-Za-z0-9_.-]{1,160}):[a-f0-9]{64})$/D', + '/^automatic_recovery:v1:([1-9][0-9]*):([1-9][0-9]*):(pending|prepared:(?:automatic_(?:applied|not_applied)_(?:succeeded|failed)_(?:fence|nofence):[a-f0-9]{64}|late_completion_receipt:[A-Za-z0-9_.-]{1,160}):[a-f0-9]{64})$/D', $marker, $matches ) !== 1) { @@ -1121,44 +1195,35 @@ final class CloudOperationRecoveryService ]; } - private static function clearLateReceiptRecoveryIncident( - CloudJob $job, - string $source - ): void { - if (!str_starts_with($source, 'late_completion_receipt:') - || !in_array( - (string) ($job->finalization_error_code ?? ''), - ['recovery_limit_reached', 'recovery_state_invalid'], - true - )) { - return; - } - $job->finalization_incident = 0; - $job->finalization_error_code = null; - // Persist here when an identical prepared marker is being replayed; - // the caller otherwise saves these fields with the new marker. - if ($job->isDirty()) { - $job->updated_at = time(); - $job->save(); - } + private static function finalizedRecoveryPayload(CloudJob $job): string + { + $payload = CloudSecrets::decrypt( + (string) $job->sealed_payload, + 'job-payload' + ); + $identity = CloudOperationRecoveryIdentity::expected( + $job, + (string) $job->effect_resolution === 'applied' + ); + // The prepared operation is retained only across the PHP prepare -> + // Agent fence -> PHP commit crash window. It must never survive in the + // ordinary terminal audit payload. + unset($payload['_operation_recovery']); + $payload[CloudOperationRecoveryIdentity::payloadKey()] = + CloudOperationRecoveryIdentity::persisted($identity); + return CloudSecrets::encrypt( + CloudInput::safeResult($payload), + 'job-payload' + ); } - /** - * Settings inspection may also contain volatile runtime observations - * (for example the current power state). They are useful to operators but - * cannot make a crash-retry produce a different prepared intent. Bind the - * marker only to fields which the settings ledger finalizer consumes. - */ private static function recoveryCriticalOperation(array $operation): array { - $critical = $operation; - $result = $operation['result'] ?? null; - if (is_array($result) && !array_is_list($result)) { - $critical['result'] = array_intersect_key($result, array_flip([ - 'uuid', 'settings_changed', 'hostname', - ])); - } - return $critical; + // The normalized operation is bounded by the completion/inspection + // schemas. Hash every allow-listed result field because different kinds + // consume different immutable evidence (snapshot keys, policy digests, + // catalog generation identifiers, deletion proofs, and so on). + return $operation; } private static function canonicalize($value) @@ -1179,7 +1244,8 @@ final class CloudOperationRecoveryService CloudJob $job, CloudAgentCompletionEvent $event ): bool { - return (string) $job->phase === 'terminal' + return CloudDispatchLedger::isDispatched($job) + && (string) $job->phase === 'terminal' && (string) $job->outcome === 'failed' && in_array((string) $job->effect_resolution, ['applied', 'not_applied'], true) @@ -1188,4 +1254,30 @@ final class CloudOperationRecoveryService (string) $job->effect_resolution_reason ); } + + private static function holdDispatchLedgerConflictLocked( + CloudJob $job + ): void { + $now = time(); + if ((string) $job->phase === 'terminal' + && (string) $job->outcome === 'failed') { + $job->effect_may_have_applied = 1; + $job->safe_to_resubmit = 0; + $job->effect_resolution = 'unknown'; + } + if (!hash_equals( + (string) ($job->finalization_error_code ?? ''), + CloudDispatchLedger::CONFLICT_CODE + )) { + $job->read_at = null; + } + $job->finalization_incident = 1; + $job->finalization_error_code = + CloudDispatchLedger::CONFLICT_CODE; + $job->lease_token = null; + $job->lease_until = 0; + $job->available_at = $now + self::INCIDENT_RETRY_SECONDS; + $job->updated_at = $now; + $job->save(); + } } diff --git a/web/app/Services/Cloud/CloudRecoveryAggregateStateConflict.php b/web/app/Services/Cloud/CloudRecoveryAggregateStateConflict.php new file mode 100644 index 00000000..84bad79c --- /dev/null +++ b/web/app/Services/Cloud/CloudRecoveryAggregateStateConflict.php @@ -0,0 +1,8 @@ +traffic_quota_bytes = $addedTraffic; $locked->traffic_download_bytes = 0; $locked->traffic_upload_bytes = 0; - if (!in_array((string) $locked->service_status, ['active', 'exempt'], true)) { + if (!in_array((string) $locked->service_status, [ + 'active', + 'exempt', + 'suspending_expired', + 'suspend_failed', + 'purge_stopping', + 'purge_stop_failed', + 'purge_force_required', + 'purge_deleting', + 'purge_failed', + ], true)) { $locked->service_status = 'active'; $locked->suspended_at = null; } - if ((string) $locked->network_status !== 'active') { + if (!in_array((string) $locked->network_status, [ + 'active', + 'blocking', + 'blocking_expired', + 'block_failed', + 'restore_pending', + 'restoring', + 'restore_failed', + ], true)) { $locked->network_status = 'restore_pending'; $locked->network_suspended_at = null; } diff --git a/web/app/Services/Cloud/CloudRescueTemplateDeletionService.php b/web/app/Services/Cloud/CloudRescueTemplateDeletionService.php index ae63f17f..83a66933 100644 --- a/web/app/Services/Cloud/CloudRescueTemplateDeletionService.php +++ b/web/app/Services/Cloud/CloudRescueTemplateDeletionService.php @@ -37,11 +37,44 @@ final class CloudRescueTemplateDeletionService if ($catalog === null) { throw new CloudError('救援镜像不存在', 404); } - if (CloudRescueTemplateDeletion::query() + $priorJobId = (int) ($catalog->job_id ?? 0); + $priorJob = $priorJobId < 1 ? null + : CloudJob::where('id', $priorJobId) + ->lockForUpdate()->first(); + self::assertActiveImportLocked($catalog, $priorJob); + $existing = CloudRescueTemplateDeletion::query() ->where('host_id', $hostId) ->where('template_id', $templateId) - ->lockForUpdate()->exists()) { - throw new CloudError('该救援镜像已有删除任务,禁止重复下发', 409); + ->lockForUpdate()->first(); + if ($existing !== null) { + $existingJobId = (int) ($existing->job_id ?? 0); + $existingJob = $existingJobId < 1 ? null + : CloudJob::where('id', $existingJobId) + ->lockForUpdate()->first(); + self::assertReusableFailedDeletionLocked( + $existing, + $existingJob + ); + $updated = CloudRescueTemplateDeletion::query() + ->where('host_id', $hostId) + ->where('template_id', $templateId) + ->where('operation_id', (string) $existing->operation_id) + ->where('job_id', (int) $existing->job_id) + ->update([ + 'operation_id' => $operationId, + 'job_id' => (int) $job->id, + 'state' => 'deleting', + 'error_code' => '', + 'created_at' => time(), + 'updated_at' => time(), + ]); + if ($updated !== 1) { + throw new CloudRecoveryInstanceStateConflict( + '救援镜像删除账本在重新绑定时发生变化', + 409 + ); + } + return $job; } $record = new CloudRescueTemplateDeletion(); $record->host_id = $hostId; @@ -61,7 +94,8 @@ final class CloudRescueTemplateDeletionService CloudJob $job, string $status, $result, - array $operation + array $operation, + bool $recovery = false ): void { if ((string) $job->kind !== 'rescue_template_delete') { return; @@ -73,9 +107,12 @@ final class CloudRescueTemplateDeletionService if ($record === null) { throw new CloudError('救援镜像删除账本不存在', 409); } - if (in_array((string) $record->state, - ['succeeded', 'failed'], true)) { - return; + if ((string) $record->state !== 'deleting' + && !($recovery && (string) $record->state === 'failed')) { + throw new CloudError( + '救援镜像状态与删除任务恢复证据不一致', + 409 + ); } if ($status === 'succeeded') { if (!CloudAgentCatalogDeletion::confirms( @@ -117,6 +154,126 @@ final class CloudRescueTemplateDeletionService ? $code : $fallback; } + /** The active catalog row must still be the exact settled import. */ + private static function assertActiveImportLocked( + CloudRescueTemplateImport $catalog, + ?CloudJob $job + ): void { + if ($job === null + || (string) $catalog->state !== 'active' + || (int) ($catalog->job_id ?? 0) !== (int) $job->id + || (int) $catalog->host_id !== (int) $job->host_id + || !hash_equals( + (string) $catalog->operation_id, + (string) $job->operation_id + ) + || (string) $job->kind !== 'rescue_template_import' + || (string) $job->execution_mode !== 'agent' + || $job->parent_job_id !== null + || (int) $job->host_id < 1 + || preg_match( + '/^[a-f0-9]{32}$/D', + (string) $job->operation_id + ) !== 1 + || preg_match( + '/^[a-f0-9]{64}$/D', + (string) $job->request_fingerprint + ) !== 1 + || preg_match( + '/^[A-Za-z0-9_.-]{16,128}$/D', + (string) $job->request_idempotency_key + ) !== 1 + || CloudDispatchLedger::isInvalid($job) + || (string) $job->phase !== 'terminal' + || (string) $job->effect_resolution !== 'applied' + || CloudJobService::hasResolvedTerminalStateConflict($job) + || (bool) $job->finalization_incident + || $job->finalization_error_code !== null) { + throw new CloudRecoveryInstanceStateConflict( + '救援镜像导入账本尚未安全收敛,禁止下发删除', + 409 + ); + } + $identity = CloudOperationRecoveryIdentity::expected($job, true); + if (!hash_equals( + 'import-rescue-template', + (string) ($identity['action'] ?? '') + ) || !hash_equals( + 'rescue-template:' . (string) $catalog->template_id, + (string) ($identity['resource_id'] ?? '') + )) { + throw new CloudRecoveryOperationIdentityConflict( + '救援镜像导入任务与目录身份不一致', + 409 + ); + } + } + + /** + * Reusing the composite-key slot creates a new operation generation. The + * previous CloudJob remains immutable and may be replaced only after its + * exact deletion identity is proven not applied. + */ + private static function assertReusableFailedDeletionLocked( + CloudRescueTemplateDeletion $record, + ?CloudJob $job + ): void { + if ($job === null + || (string) $record->state !== 'failed' + || (int) ($record->job_id ?? 0) !== (int) $job->id + || (int) $record->host_id !== (int) $job->host_id + || !hash_equals( + (string) $record->operation_id, + (string) $job->operation_id + ) + || (string) $job->kind !== 'rescue_template_delete' + || (string) $job->execution_mode !== 'agent' + || $job->parent_job_id !== null + || (int) $job->host_id < 1 + || preg_match( + '/^[a-f0-9]{32}$/D', + (string) $job->operation_id + ) !== 1 + || preg_match( + '/^[a-f0-9]{64}$/D', + (string) $job->request_fingerprint + ) !== 1 + || preg_match( + '/^[A-Za-z0-9_.-]{16,128}$/D', + (string) $job->request_idempotency_key + ) !== 1 + || CloudDispatchLedger::isInvalid($job) + || (string) $job->phase !== 'terminal' + || (string) $job->outcome !== 'failed' + || (string) $job->status !== 'failed' + || (string) $job->effect_resolution !== 'not_applied' + || CloudJobService::hasResolvedTerminalStateConflict($job) + || (bool) $job->finalization_incident + || $job->finalization_error_code !== null + || preg_match( + '/^[a-z][a-z0-9_]{0,63}$/D', + (string) $record->error_code + ) !== 1) { + throw new CloudRecoveryInstanceStateConflict( + '原救援镜像删除任务未确认为未生效,禁止下发新删除', + 409 + ); + } + $identity = CloudOperationRecoveryIdentity::expected($job, false); + if (!hash_equals( + 'delete-rescue-template', + (string) ($identity['action'] ?? '') + ) || !hash_equals( + 'rescue-template:' . (string) $record->template_id, + (string) ($identity['resource_id'] ?? '') + )) { + throw new CloudRecoveryOperationIdentityConflict( + '原救援镜像删除任务与账本身份不一致', + 409 + ); + } + } + private static function validateTemplateId(string $id): void { if (preg_match('/^[a-f0-9]{32}$/D', $id) !== 1) { diff --git a/web/app/Services/Cloud/CloudRescueTemplateImportService.php b/web/app/Services/Cloud/CloudRescueTemplateImportService.php index b004af10..ec33b5e9 100644 --- a/web/app/Services/Cloud/CloudRescueTemplateImportService.php +++ b/web/app/Services/Cloud/CloudRescueTemplateImportService.php @@ -66,13 +66,7 @@ final class CloudRescueTemplateImportService $priorJob = (int) ($prior->job_id ?? 0) < 1 ? null : CloudJob::where('id', (int) $prior->job_id) ->lockForUpdate()->first(); - if ($priorJob === null - || (string) $priorJob->phase !== 'terminal' - || (string) $priorJob->effect_resolution === 'unknown') { - throw new CloudError( - '同名救援镜像上一任务尚未安全收敛', 409 - ); - } + self::assertReusableFailedImportLocked($prior, $priorJob); } $record = new CloudRescueTemplateImport(); $record->operation_id = $operationId; @@ -115,7 +109,8 @@ final class CloudRescueTemplateImportService CloudJob $job, string $status, $result, - array $operation + array $operation, + bool $recovery = false ): void { if ((string) $job->kind !== 'rescue_template_import') { return; @@ -127,8 +122,12 @@ final class CloudRescueTemplateImportService if ($record === null) { throw new CloudError('救援镜像导入账本不存在', 409); } - if (in_array((string) $record->state, ['active', 'failed'], true)) { - return; + if ((string) $record->state !== 'importing' + && !($recovery && (string) $record->state === 'failed')) { + throw new CloudError( + '救援镜像状态与导入任务恢复证据不一致', + 409 + ); } if ($status === 'succeeded') { $bytes = is_array($result) ? filter_var( @@ -169,6 +168,71 @@ final class CloudRescueTemplateImportService ? $code : $fallback; } + /** + * A same-name retry is a new mutation, never a replay. It is admitted + * only after the previous durable row is bound to an exact terminal job + * whose effect is proven not to have happened. + */ + private static function assertReusableFailedImportLocked( + CloudRescueTemplateImport $prior, + ?CloudJob $job + ): void { + if ($job === null + || (string) $prior->state !== 'failed' + || (int) ($prior->job_id ?? 0) !== (int) $job->id + || (int) $prior->host_id !== (int) $job->host_id + || !hash_equals( + (string) $prior->operation_id, + (string) $job->operation_id + ) + || (string) $job->kind !== 'rescue_template_import' + || (string) $job->execution_mode !== 'agent' + || $job->parent_job_id !== null + || (int) $job->host_id < 1 + || preg_match( + '/^[a-f0-9]{32}$/D', + (string) $job->operation_id + ) !== 1 + || preg_match( + '/^[a-f0-9]{64}$/D', + (string) $job->request_fingerprint + ) !== 1 + || preg_match( + '/^[A-Za-z0-9_.-]{16,128}$/D', + (string) $job->request_idempotency_key + ) !== 1 + || CloudDispatchLedger::isInvalid($job) + || (string) $job->phase !== 'terminal' + || (string) $job->outcome !== 'failed' + || (string) $job->status !== 'failed' + || (string) $job->effect_resolution !== 'not_applied' + || CloudJobService::hasResolvedTerminalStateConflict($job) + || (bool) $job->finalization_incident + || $job->finalization_error_code !== null + || preg_match( + '/^[a-z][a-z0-9_]{0,63}$/D', + (string) $prior->error_code + ) !== 1) { + throw new CloudRecoveryInstanceStateConflict( + '同名救援镜像上一任务未确认为未生效,禁止下发新导入', + 409 + ); + } + $identity = CloudOperationRecoveryIdentity::expected($job, false); + if (!hash_equals( + 'import-rescue-template', + (string) ($identity['action'] ?? '') + ) || !hash_equals( + 'rescue-template:' . (string) $prior->template_id, + (string) ($identity['resource_id'] ?? '') + )) { + throw new CloudRecoveryOperationIdentityConflict( + '同名救援镜像上一任务与目录身份不一致', + 409 + ); + } + } + private static function validateInput(int $hostId, string $importType, string $name, string $sourceUrl, string $sourceToken, string $sha256): void diff --git a/web/app/Services/Cloud/CloudTemplateCatalogService.php b/web/app/Services/Cloud/CloudTemplateCatalogService.php index e828abef..04e20ecb 100644 --- a/web/app/Services/Cloud/CloudTemplateCatalogService.php +++ b/web/app/Services/Cloud/CloudTemplateCatalogService.php @@ -6,6 +6,7 @@ use App\Models\CloudJob; use App\Models\CloudOrder; use App\Models\CloudTemplate; use App\Models\CloudTemplateReplica; +use App\Models\CloudUserIsoReplica; /** PHP authority for the global template catalog and its durable replicas. */ final class CloudTemplateCatalogService @@ -25,7 +26,10 @@ final class CloudTemplateCatalogService { return ['templates' => CloudTemplate::query()->where('state', 'active') ->orderBy('os_family')->orderBy('os_version')->orderBy('name') - ->get()->map(static fn (CloudTemplate $row): array => [ + ->get()->filter(static fn (CloudTemplate $row): bool => + self::activeJobSafelySettled($row) + && self::hasCurrentActiveReplica($row) + )->values()->map(static fn (CloudTemplate $row): array => [ 'id' => (string) $row->id, 'name' => (string) $row->name, 'os_family' => (string) $row->os_family, @@ -191,15 +195,13 @@ final class CloudTemplateCatalogService $parent = $connection->transaction(static function () use ( $id, $name, $expectedRevision, $generationToken, $actor ): CloudJob { - $template = CloudTemplate::query()->where('id', $id) - ->lockForUpdate()->first(); + $template = self::lockTemplateForMutation($id); if ($template === null || (string) $template->state === 'retired') { throw new CloudError('云镜像模板不存在', 404); } if ((string) $template->state !== 'active') { throw new CloudError('云镜像当前状态不允许修改元数据', 409); } - self::assertMutationBoundaryLocked($template); if ((int) $template->revision !== $expectedRevision || !hash_equals((string) $template->generation_token, (string) $generationToken)) { @@ -267,21 +269,23 @@ final class CloudTemplateCatalogService $parent = $connection->transaction(static function () use ( $id, $expectedRevision, $generationToken, $actor ): CloudJob { - $template = CloudTemplate::query()->where('id', $id) - ->lockForUpdate()->first(); + // Payment already owns its order before it snapshots a template. + // Take the same order -> aggregate parent -> template sequence so + // template deletion cannot deadlock with invoice settlement. + self::assertNoOrderReferencesLocked($id); + $template = self::lockTemplateForMutation($id); if ($template === null || (string) $template->state === 'retired') { throw new CloudError('云镜像模板不存在', 404); } if ((string) $template->state !== 'active') { throw new CloudError('云镜像存在未完成或失败任务,禁止删除', 409); } - self::assertMutationBoundaryLocked($template); if ((int) $template->revision !== $expectedRevision || !hash_equals((string) $template->generation_token, (string) $generationToken)) { throw new CloudError('云镜像版本已变化,请刷新后重试', 409); } - self::assertNoReferencesLocked($id); + self::assertNoJobReferencesLocked($id); $replicas = CloudTemplateReplica::query() ->where('template_id', $id)->orderBy('host_id') ->lockForUpdate()->get(); @@ -331,7 +335,8 @@ final class CloudTemplateCatalogService } public static function finishJobLocked(CloudJob $job, string $status, - $result, array $payload, array $operation): void + $result, array $payload, array $operation, + bool $recovery = false): void { if (!in_array((string) $job->kind, [ 'template_import_replica', 'template_metadata_replica', @@ -350,30 +355,434 @@ final class CloudTemplateCatalogService if ($template === null || $replica === null) { throw new CloudError('云镜像任务账本不存在', 409); } + // Only project this replica here. CloudWorkerService persists the + // child's terminal effect first, then reconciles the aggregate parent + // through settleRecoveredParentLocked(), where the complete child / + // replica topology and content can be verified atomically. if ((string) $job->kind === 'template_import_replica') { self::finishImportReplica($template, $replica, $status, $result, - $operation); - self::settleImportParent($template, (int) $job->parent_job_id, - $operation); + $operation, $recovery); } elseif ((string) $job->kind === 'template_metadata_replica') { self::finishMetadataReplica($template, $replica, $status, $result, - $operation); - self::settleMetadataParent($template, (int) $job->parent_job_id, - $operation); + $operation, $recovery); } else { self::finishDeleteReplica($template, $replica, $status, - $operation); - self::settleDeleteParent($template, (int) $job->parent_job_id, - $operation); + $operation, $recovery); } } + /** + * Lock the catalog projection immediately after its aggregate parent. + * Every caller must do this before locking any child or replica row. + */ + public static function lockAggregateCatalogLocked(CloudJob $parent): void + { + if (!in_array((string) $parent->kind, [ + 'template_import', 'template_metadata_sync', 'template_delete', + ], true)) { + return; + } + self::templateBoundToParentLocked($parent); + } + + /** + * Publish an aggregate catalog result only after every recovered child + * has committed its final effect resolution. prepareRecoveredEffect() + * may update the replica first, but must never make the public parent look + * complete before the Agent fence is released. + */ + public static function settleRecoveredParentLocked( + CloudJob $parent, + string $resolution + ): void { + if (!in_array((string) $parent->kind, [ + 'template_import', 'template_metadata_sync', 'template_delete', + ], true) || (string) $parent->execution_mode !== 'aggregate' + || ((string) $parent->phase === 'terminal' + && ((string) $parent->outcome !== 'failed' + || (string) $parent->effect_resolution !== 'unknown'))) { + return; + } + $template = self::templateBoundToParentLocked($parent); + if (!in_array( + $resolution, + ['applied', 'not_applied', 'mixed'], + true + )) { + throw new CloudRecoveryAggregateStateConflict( + '云镜像汇总任务的子任务效果状态无效', + 409 + ); + } + self::assertRecoveredReplicaProjectionLocked( + $template, + $parent, + $resolution + ); + if ($resolution === 'not_applied') { + self::restoreNotAppliedProjectionLocked($template, $parent); + return; + } + $operation = ['effect_may_have_applied' => true]; + if ((string) $parent->kind === 'template_import') { + self::settleImportParent( + $template, + (int) $parent->id, + $operation + ); + } elseif ((string) $parent->kind === 'template_metadata_sync') { + self::settleMetadataParent( + $template, + (int) $parent->id, + $operation + ); + } else { + self::settleDeleteParent( + $template, + (int) $parent->id, + $operation + ); + } + } + + /** + * Verify an already-published aggregate without mutating its immutable + * task audit or catalog projection. This intentionally differs from the + * pre-settlement assertion below: successful deletes and no-effect imports + * have already removed their replica rows, while no-effect deletes have + * restored the surviving replicas to active/stale. + */ + public static function assertSettledParentProjectionLocked( + CloudJob $parent, + string $resolution + ): void { + $kind = (string) $parent->kind; + if (!in_array($kind, [ + 'template_import', 'template_metadata_sync', 'template_delete', + ], true) || (string) $parent->execution_mode !== 'aggregate' + || !in_array($resolution, [ + 'applied', 'not_applied', 'mixed', + ], true)) { + throw new CloudRecoveryAggregateStateConflict( + '云镜像汇总任务的已结算效果状态无效', + 409 + ); + } + + $template = self::templateBoundToParentLocked($parent); + $children = CloudJob::where('parent_job_id', (int) $parent->id) + ->orderBy('id')->lockForUpdate()->get(); + if ($children->isEmpty()) { + throw new CloudRecoveryAggregateStateConflict( + '云镜像汇总任务缺少子任务账本', + 409 + ); + } + $settledChildIds = $children->map( + static fn (CloudJob $child): int => (int) $child->id + )->all(); + if (CloudUserIsoReplica::query()->whereIn( + 'job_id', + $settledChildIds + )->exists()) { + throw new CloudRecoveryOperationIdentityConflict( + '云镜像汇总子任务被 ISO 副本账本重复引用', + 409 + ); + } + $expectedChildKind = match ($kind) { + 'template_import' => 'template_import_replica', + 'template_metadata_sync' => 'template_metadata_replica', + 'template_delete' => 'template_delete_replica', + }; + $childResolutions = []; + foreach ($children as $child) { + $childResolution = (string) $child->effect_resolution; + if ((int) ($child->parent_job_id ?? 0) !== (int) $parent->id + || (int) $child->user_id !== (int) $parent->user_id + || (string) $child->execution_mode !== 'agent' + || (string) $child->kind !== $expectedChildKind + || !in_array( + $childResolution, + ['applied', 'not_applied'], + true + )) { + throw new CloudRecoveryAggregateStateConflict( + '云镜像汇总任务与子任务账本关系异常', + 409 + ); + } + $childResolutions[$childResolution] = true; + } + $actualResolution = count($childResolutions) === 1 + ? (string) array_key_first($childResolutions) : 'mixed'; + if ($actualResolution !== $resolution + || ($resolution === 'mixed' + && $kind !== 'template_metadata_sync')) { + throw new CloudRecoveryAggregateStateConflict( + '云镜像汇总任务与已结算效果不一致', + 409 + ); + } + + $replicas = self::lockedReplicas((string) $template->id); + if (($kind === 'template_import' && $resolution === 'not_applied') + || ($kind === 'template_delete' && $resolution === 'applied')) { + if ((string) $template->state !== 'retired' + || !$replicas->isEmpty()) { + throw new CloudRecoveryInstanceStateConflict( + '云镜像汇总任务的已结算清理投影不一致', + 409 + ); + } + return; + } + + if ((string) $template->state !== 'active') { + throw new CloudRecoveryInstanceStateConflict( + '云镜像汇总任务的已结算主记录状态不一致', + 409 + ); + } + if ($replicas->count() !== $children->count()) { + throw new CloudRecoveryAggregateStateConflict( + '云镜像汇总任务的已结算子任务与副本数量不一致', + 409 + ); + } + foreach ($children as $child) { + $matches = $replicas->filter( + static fn (CloudTemplateReplica $replica): bool => + (int) ($replica->job_id ?? 0) === (int) $child->id + ); + $replica = $matches->count() === 1 ? $matches->first() : null; + if ($replica === null + || (int) $replica->host_id !== (int) $child->host_id + || !hash_equals( + (string) $child->operation_id, + (string) $replica->operation_id + )) { + throw new CloudRecoveryOperationIdentityConflict( + '云镜像汇总任务的已结算子任务与副本身份不一致', + 409 + ); + } + + $childResolution = (string) $child->effect_resolution; + $replicaRevision = (int) $replica->revision; + $templateRevision = (int) $template->revision; + $expectedState = match ($kind) { + 'template_import' => 'active', + 'template_metadata_sync' => $childResolution === 'applied' + ? 'active' : 'stale', + 'template_delete' => $replicaRevision === $templateRevision + ? 'active' : 'stale', + }; + $revisionInvalid = match ($kind) { + 'template_import' => $replicaRevision !== $templateRevision, + 'template_metadata_sync' => $childResolution === 'applied' + ? $replicaRevision !== $templateRevision + : $replicaRevision >= $templateRevision, + 'template_delete' => $replicaRevision > $templateRevision, + }; + if (!hash_equals( + (string) $template->generation_token, + (string) $replica->generation_token + ) + || (string) $replica->state !== $expectedState + || $revisionInvalid + || (int) $replica->image_bytes + !== (int) $template->image_bytes + || !hash_equals( + (string) $template->sha256, + (string) $replica->sha256 + )) { + throw new CloudRecoveryInstanceStateConflict( + '云镜像汇总任务的已结算副本状态或内容不一致', + 409 + ); + } + } + } + + /** + * A recovered aggregate is stricter than ordinary incremental completion: + * every child must own exactly one replica with the same host, operation + * and final state. Empty, pending, extra or cross-wired ledgers stay fenced. + */ + private static function assertRecoveredReplicaProjectionLocked( + CloudTemplate $template, + CloudJob $parent, + string $resolution + ): void { + $children = CloudJob::where('parent_job_id', (int) $parent->id) + ->orderBy('id')->lockForUpdate()->get(); + $replicas = self::lockedReplicas((string) $template->id); + if ($children->isEmpty() || $replicas->count() !== $children->count()) { + throw new CloudRecoveryAggregateStateConflict( + '云镜像汇总任务的子任务与副本数量不一致', + 409 + ); + } + if (CloudUserIsoReplica::query()->whereIn( + 'job_id', + $children->map( + static fn (CloudJob $child): int => (int) $child->id + )->all() + )->exists()) { + throw new CloudRecoveryOperationIdentityConflict( + '云镜像汇总子任务被 ISO 副本账本重复引用', + 409 + ); + } + foreach ($children as $child) { + $childResolution = $resolution === 'mixed' + ? (string) $child->effect_resolution : $resolution; + $expectedState = match ((string) $parent->kind) { + 'template_import' => $childResolution === 'applied' + ? 'active' : 'failed', + 'template_metadata_sync' => $childResolution === 'applied' + ? 'active' : 'stale', + 'template_delete' => $childResolution === 'applied' + ? 'delete_succeeded' : 'delete_failed', + default => '', + }; + $matches = $replicas->filter( + static fn (CloudTemplateReplica $replica): bool => + (int) ($replica->job_id ?? 0) === (int) $child->id + ); + $replica = $matches->count() === 1 ? $matches->first() : null; + if ($replica === null + || (int) $replica->host_id !== (int) $child->host_id + || !hash_equals( + (string) $child->operation_id, + (string) $replica->operation_id + )) { + throw new CloudRecoveryOperationIdentityConflict( + '云镜像汇总任务的子任务与副本身份不一致', + 409 + ); + } + if (!hash_equals( + (string) $template->generation_token, + (string) $replica->generation_token + ) + || (string) $replica->state !== $expectedState + || ((string) $parent->kind !== 'template_import' + && ((int) $replica->image_bytes + !== (int) $template->image_bytes + || !hash_equals( + (string) $template->sha256, + (string) $replica->sha256 + ))) + || ((string) $parent->kind === 'template_metadata_sync' + && (($childResolution === 'applied' + && (int) $replica->revision + !== (int) $template->revision) + || ($childResolution === 'not_applied' + && (int) $replica->revision + >= (int) $template->revision))) + || ((string) $parent->kind === 'template_import' + && $childResolution === 'applied' + && ((int) $replica->revision + !== (int) $template->revision + || (int) $replica->image_bytes + !== (int) $template->image_bytes + || !hash_equals( + (string) $template->sha256, + (string) $replica->sha256 + ))) + || ((string) $parent->kind === 'template_import' + && $childResolution === 'not_applied' + && ((int) $replica->image_bytes !== 0 + || ((string) $replica->sha256 !== '' + && !hash_equals( + (string) $template->sha256, + (string) $replica->sha256 + ))))) { + throw new CloudRecoveryInstanceStateConflict( + '云镜像汇总任务的副本状态或内容不一致', + 409 + ); + } + } + } + + /** Restore the resource boundary only when every host proves no effect. */ + private static function restoreNotAppliedProjectionLocked( + CloudTemplate $template, + CloudJob $parent + ): void { + if ((string) $parent->kind === 'template_import') { + CloudTemplateReplica::query()->where( + 'template_id', + (string) $template->id + )->delete(); + $template->state = 'retired'; + $template->updated_at = time(); + $template->save(); + CloudJobService::completeAggregateLocked( + $parent, + 'failed', + false, + true, + 'template_import_not_applied' + ); + return; + } + if ((string) $parent->kind === 'template_delete') { + $replicas = CloudTemplateReplica::query()->where( + 'template_id', + (string) $template->id + )->orderBy('host_id')->lockForUpdate()->get(); + foreach ($replicas as $replica) { + $replica->state = (int) $replica->revision + === (int) $template->revision ? 'active' : 'stale'; + $replica->error_code = ''; + $replica->updated_at = time(); + $replica->save(); + } + $template->state = 'active'; + $template->updated_at = time(); + $template->save(); + CloudJobService::completeAggregateLocked( + $parent, + 'failed', + false, + true, + 'template_delete_not_applied' + ); + return; + } + CloudTemplateReplica::query()->where( + 'template_id', + (string) $template->id + )->update([ + 'state' => 'stale', + 'updated_at' => time(), + ]); + $template->state = 'active'; + $template->updated_at = time(); + $template->save(); + CloudJobService::completeAggregateLocked( + $parent, + 'failed', + false, + true, + 'template_metadata_not_applied' + ); + } + private static function finishImportReplica(CloudTemplate $template, CloudTemplateReplica $replica, string $status, $result, - array $operation): void + array $operation, bool $recovery): void { - if ((string) $replica->state !== 'importing') { - return; + if ((string) $replica->state !== 'importing' + && !($recovery && (string) $replica->state === 'failed')) { + throw new CloudError( + '云镜像副本状态与导入任务恢复证据不一致', + 409 + ); } if ($status === 'succeeded') { $digest = is_array($result) @@ -426,7 +835,8 @@ final class CloudTemplateCatalogService } private static function settleImportParent(CloudTemplate $template, - int $parentId, array $operation): void + int $parentId, array $operation, + ?int $completingChildId = null): void { $replicas = self::lockedReplicas((string) $template->id); if ($replicas->isEmpty() || $replicas->contains(static fn ($row): bool => @@ -434,6 +844,14 @@ final class CloudTemplateCatalogService return; } $parent = self::parent($parentId, 'template_import'); + self::assertTemplateParentBindingLocked($template, $parent); + if (CloudJobService::aggregateParentRecoveryPending( + $parent, + $completingChildId, + true + )) { + return; + } $success = !$replicas->contains(static fn ($row): bool => (string) $row->state !== 'active'); if ($success) { @@ -458,10 +876,14 @@ final class CloudTemplateCatalogService private static function finishMetadataReplica(CloudTemplate $template, CloudTemplateReplica $replica, string $status, $result, - array $operation): void + array $operation, bool $recovery): void { - if ((string) $replica->state !== 'syncing') { - return; + if ((string) $replica->state !== 'syncing' + && !($recovery && (string) $replica->state === 'stale')) { + throw new CloudError( + '云镜像副本状态与元数据任务恢复证据不一致', + 409 + ); } if ($status === 'succeeded') { if (!is_array($result) || array_is_list($result) @@ -493,7 +915,8 @@ final class CloudTemplateCatalogService } private static function settleMetadataParent(CloudTemplate $template, - int $parentId, array $operation): void + int $parentId, array $operation, + ?int $completingChildId = null): void { $replicas = self::lockedReplicas((string) $template->id); if ($replicas->isEmpty() || $replicas->contains(static fn ($row): bool => @@ -501,6 +924,14 @@ final class CloudTemplateCatalogService return; } $parent = self::parent($parentId, 'template_metadata_sync'); + self::assertTemplateParentBindingLocked($template, $parent); + if (CloudJobService::aggregateParentRecoveryPending( + $parent, + $completingChildId, + true + )) { + return; + } $success = !$replicas->contains(static fn ($row): bool => (string) $row->state !== 'active' || (int) $row->revision !== (int) $template->revision); @@ -521,10 +952,15 @@ final class CloudTemplateCatalogService private static function finishDeleteReplica(CloudTemplate $template, CloudTemplateReplica $replica, string $status, - array $operation): void + array $operation, bool $recovery): void { - if ((string) $replica->state !== 'deleting') { - return; + if ((string) $replica->state !== 'deleting' + && !($recovery + && (string) $replica->state === 'delete_failed')) { + throw new CloudError( + '云镜像副本状态与删除任务恢复证据不一致', + 409 + ); } if ($status === 'succeeded') { if (!CloudAgentCatalogDeletion::confirms( @@ -551,7 +987,8 @@ final class CloudTemplateCatalogService } private static function settleDeleteParent(CloudTemplate $template, - int $parentId, array $operation): void + int $parentId, array $operation, + ?int $completingChildId = null): void { $replicas = self::lockedReplicas((string) $template->id); if ($replicas->isEmpty() || $replicas->contains(static fn ($row): bool => @@ -559,6 +996,14 @@ final class CloudTemplateCatalogService return; } $parent = self::parent($parentId, 'template_delete'); + self::assertTemplateParentBindingLocked($template, $parent); + if (CloudJobService::aggregateParentRecoveryPending( + $parent, + $completingChildId, + true + )) { + return; + } $success = !$replicas->contains(static fn ($row): bool => (string) $row->state !== 'delete_succeeded'); if ($success) { @@ -606,7 +1051,7 @@ final class CloudTemplateCatalogService $children = CloudJob::where('parent_job_id', (int) $parent->id) ->lockForUpdate()->get(); $effect = $children->contains(static fn ($child): bool => - (int) $child->dispatch_attempts === 1 + CloudDispatchLedger::mayHaveDispatched($child) || (bool) $child->effect_may_have_applied); $from = match ((string) $parent->kind) { 'template_import' => 'importing', @@ -644,12 +1089,13 @@ final class CloudTemplateCatalogService public static function applyProvisioningSnapshot(array $body, bool $includeStartupScript = true): array { - $template = CloudTemplate::query() - ->where('id', self::templateId($body['template_id'] ?? '')) - ->where('state', 'active')->lockForUpdate()->first(); - if ($template === null) { + $template = self::lockTemplateForMutation( + self::templateId($body['template_id'] ?? '') + ); + if ($template === null || (string) $template->state !== 'active') { throw new CloudError('云镜像模板不存在或暂不可用', 409); } + self::assertCurrentActiveReplica($template, true); unset($body['startup_script'], $body['template_revision'], $body['template_generation_token']); $body['template_id'] = (string) $template->id; @@ -668,14 +1114,15 @@ final class CloudTemplateCatalogService $revision = filter_var($body['template_revision'] ?? null, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); $generation = $body['template_generation_token'] ?? null; - $template = CloudTemplate::query()->where('id', $id) - ->where('state', 'active')->lockForUpdate()->first(); - if ($template === null || $revision === false + $template = self::lockTemplateForMutation($id); + if ($template === null || (string) $template->state !== 'active' + || $revision === false || !is_string($generation) || !hash_equals((string) $template->generation_token, $generation) || (int) $template->revision !== (int) $revision) { throw new CloudError('云镜像模板版本已变化,请重新提交', 409); } + self::assertCurrentActiveReplica($template, true); return ['template_id' => $id, 'os_source' => 'cloud_template', 'os_name' => self::name((string) $template->name), 'login_name' => 'root']; @@ -683,10 +1130,18 @@ final class CloudTemplateCatalogService public static function assertProvisionable(string $id): void { - if (!CloudTemplate::query()->where('id', self::templateId($id)) - ->where('state', 'active')->exists()) { + $template = CloudTemplate::query() + ->where('id', self::templateId($id)) + ->where('state', 'active')->first(); + if ($template === null) { throw new CloudError('云镜像模板不存在或暂不可用', 409); } + if (!self::activeJobSafelySettled($template, false)) { + throw new CloudError( + '云镜像上一任务尚未安全收敛,禁止提交新的修改', 409 + ); + } + self::assertCurrentActiveReplica($template); } public static function saveStartupScript(string $id, $script, @@ -698,9 +1153,9 @@ final class CloudTemplateCatalogService static function () use ( $id, $normalized, $expectedRevision, $generationToken ): array { - $template = CloudTemplate::query() - ->where('id', self::templateId($id)) - ->lockForUpdate()->first(); + $template = self::lockTemplateForMutation( + self::templateId($id) + ); if ($template === null || (string) $template->state === 'retired') { throw new CloudError('云镜像模板不存在', 404); } @@ -710,7 +1165,6 @@ final class CloudTemplateCatalogService (string) $generationToken)) { throw new CloudError('初始化脚本已被修改,请重新打开对话框', 409); } - self::assertMutationBoundaryLocked($template); $template->startup_script = $normalized; $template->revision = (int) $template->revision + 1; $template->updated_at = time(); @@ -741,17 +1195,24 @@ final class CloudTemplateCatalogService return $script; } - private static function assertNoReferencesLocked(string $templateId): void + private static function assertNoOrderReferencesLocked( + string $templateId + ): void { foreach (CloudOrder::query()->whereIn('status', [ 'awaiting_payment', 'queued', 'running', - ])->lockForUpdate()->get(['id', 'spec_json']) as $order) { + ])->orderBy('id')->lockForUpdate()->get(['id', 'spec_json']) as $order) { $spec = json_decode((string) $order->spec_json, true); if (is_array($spec) && !array_is_list($spec) && ($spec['template_id'] ?? null) === $templateId) { throw new CloudError('云镜像仍被未完成订单使用,暂不能删除', 409); } } + } + + private static function assertNoJobReferencesLocked( + string $templateId + ): void { $jobs = CloudJob::query()->whereIn('kind', ['create', 'reinstall']) ->where(static function ($query): void { $query->where('phase', '<>', 'terminal') @@ -771,23 +1232,416 @@ final class CloudTemplateCatalogService } } + /** + * Discover the old parent without a row lock, then acquire the canonical + * parent -> catalog order and reject a pointer that changed in between. + */ + private static function lockTemplateForMutation( + string $id + ): ?CloudTemplate { + $snapshot = CloudTemplate::query()->where('id', $id)->first(); + if ($snapshot === null) { + return null; + } + $jobId = (int) ($snapshot->active_job_id ?? 0); + $parentSnapshot = $jobId > 0 + ? CloudJob::where('id', $jobId)->first() : null; + $parent = self::isTemplateAggregateParent($parentSnapshot) + ? CloudJob::where('id', $jobId) + ->where('execution_mode', 'aggregate') + ->whereNull('parent_job_id') + ->whereIn('kind', [ + 'template_import', + 'template_metadata_sync', + 'template_delete', + ])->lockForUpdate()->first() + : null; + $template = CloudTemplate::query()->where('id', $id) + ->lockForUpdate()->first(); + if ($template === null) { + return null; + } + if ((int) ($template->active_job_id ?? 0) !== $jobId) { + throw new CloudError( + '云镜像任务状态已变化,请刷新后重试', + 409 + ); + } + self::assertMutationBoundaryLocked($template, $parent); + return $template; + } + + /** Never take a child/dangling pointer as the canonical parent lock. */ + private static function isTemplateAggregateParent(?CloudJob $job): bool + { + return $job !== null + && (string) $job->execution_mode === 'aggregate' + && $job->parent_job_id === null + && in_array((string) $job->kind, [ + 'template_import', + 'template_metadata_sync', + 'template_delete', + ], true); + } + /** Do not overlap a new mutation with an active or unresolved effect. */ private static function assertMutationBoundaryLocked( - CloudTemplate $template + CloudTemplate $template, + ?CloudJob $lockedParent = null ): void { + if (!self::activeJobSafelySettled( + $template, + true, + $lockedParent + )) { + throw new CloudError( + '云镜像上一任务尚未安全收敛,禁止提交新的修改', 409 + ); + } + } + + /** A historical fail-open parent must not expose or mutate its template. */ + private static function activeJobSafelySettled( + CloudTemplate $template, + bool $lockForUpdate = false, + ?CloudJob $lockedParent = null + ): bool { $jobId = (int) ($template->active_job_id ?? 0); if ($jobId < 1) { - return; + // The catalog row is already locked by every mutation caller. + // Do not take the parent lock in the reverse worker lock order; + // instead, recognize any uniquely or ambiguously linked in-flight + // ledger and keep the mutation fenced until the parent-first + // recovery sweep repairs or diagnoses the pointer. + return !self::missingPointerRecoveryPending($template); + } + if ($template->exists) { + $bindings = CloudTemplate::query() + ->where('active_job_id', $jobId) + ->orderBy('id'); + if ($lockForUpdate) { + $bindings->lockForUpdate(); + } + $bound = $bindings->get(['id']); + if ($bound->count() !== 1 + || (string) $bound->first()->id + !== (string) $template->id) { + return false; + } + } + if ($lockedParent !== null + && (int) $lockedParent->id !== $jobId) { + return false; + } + // A write boundary must arrive with the parent already locked. Never + // acquire a parent after the catalog row. + if ($lockForUpdate && $lockedParent === null) { + return false; + } + $job = $lockedParent ?? CloudJob::where('id', $jobId)->first(); + return $job !== null && self::aggregateParentSafelySettled( + $job, + $lockForUpdate + ) && self::currentParentProjectionMatches( + $template, + $job, + $lockForUpdate + ); + } + + /** The current resource must own every child and replica of its parent. */ + private static function currentParentProjectionMatches( + CloudTemplate $template, + CloudJob $parent, + bool $lockForUpdate + ): bool { + $expectedChildKind = match ((string) $parent->kind) { + 'template_import' => 'template_import_replica', + 'template_metadata_sync' => 'template_metadata_replica', + 'template_delete' => 'template_delete_replica', + default => null, + }; + if ($expectedChildKind === null + || (string) $template->state !== 'active') { + return false; + } + $childQuery = CloudJob::where( + 'parent_job_id', + (int) $parent->id + )->orderBy('id'); + if ($lockForUpdate) { + $childQuery->lockForUpdate(); + } + $children = $childQuery->get(); + $replicaQuery = CloudTemplateReplica::query() + ->where('template_id', (string) $template->id) + ->orderBy('host_id'); + if ($lockForUpdate) { + $replicaQuery->lockForUpdate(); + } + $replicas = $replicaQuery->get(); + if ($children->isEmpty() + || $children->count() !== $replicas->count()) { + return false; + } + $childResolutions = $children->map( + static fn (CloudJob $child): string => + (string) $child->effect_resolution + )->unique()->values(); + if ($childResolutions->contains( + static fn (string $resolution): bool => !in_array( + $resolution, + ['applied', 'not_applied'], + true + ) + )) { + return false; + } + $actualResolution = $childResolutions->count() === 1 + ? (string) $childResolutions->first() : 'mixed'; + $publishedResolution = (string) $parent->kind + === 'template_metadata_sync' + && $actualResolution === 'mixed' + ? 'applied' : $actualResolution; + if (!hash_equals( + (string) $parent->effect_resolution, + $publishedResolution + ) || ($actualResolution === 'mixed' + && (string) $parent->kind !== 'template_metadata_sync')) { + return false; + } + $jobIds = $children->map( + static fn (CloudJob $child): int => (int) $child->id + )->all(); + if (CloudTemplateReplica::query()->whereIn('job_id', $jobIds) + ->where('template_id', '<>', (string) $template->id)->exists() + || CloudUserIsoReplica::query()->whereIn( + 'job_id', + $jobIds + )->exists()) { + return false; } - $job = CloudJob::where('id', $jobId)->lockForUpdate()->first(); - if ($job === null + foreach ($children as $child) { + $matches = $replicas->filter( + static fn (CloudTemplateReplica $replica): bool => + (int) ($replica->job_id ?? 0) === (int) $child->id + ); + $replica = $matches->count() === 1 ? $matches->first() : null; + $childResolution = (string) $child->effect_resolution; + $replicaRevision = (int) ($replica?->revision ?? 0); + $expectedState = match ((string) $parent->kind) { + 'template_import' => 'active', + 'template_metadata_sync' => $childResolution === 'applied' + ? 'active' : 'stale', + 'template_delete' => $replicaRevision + === (int) $template->revision + ? 'active' : 'stale', + default => '', + }; + $revisionInvalid = match ((string) $parent->kind) { + 'template_import' => $replicaRevision + !== (int) $template->revision, + 'template_metadata_sync' => $childResolution === 'applied' + ? $replicaRevision !== (int) $template->revision + : $replicaRevision >= (int) $template->revision, + 'template_delete' => $replicaRevision + > (int) $template->revision, + default => true, + }; + if ($replica === null + || (int) ($child->parent_job_id ?? 0) !== (int) $parent->id + || (int) $child->user_id !== (int) $parent->user_id + || (string) $child->execution_mode !== 'agent' + || (string) $child->kind !== $expectedChildKind + || (int) $child->host_id !== (int) $replica->host_id + || !hash_equals( + (string) $child->operation_id, + (string) $replica->operation_id + ) + || !hash_equals( + (string) $template->generation_token, + (string) $replica->generation_token + ) + || (string) $replica->state !== $expectedState + || $revisionInvalid + || (int) $replica->image_bytes + !== (int) $template->image_bytes + || !hash_equals( + (string) $template->sha256, + (string) $replica->sha256 + )) { + return false; + } + } + return true; + } + + private static function aggregateParentSafelySettled( + CloudJob $job, + bool $lockForUpdate + ): bool { + return !( + $job->parent_job_id !== null + || (string) $job->execution_mode !== 'aggregate' + || !in_array((string) $job->kind, [ + 'template_import', + 'template_metadata_sync', + 'template_delete', + ], true) + || CloudJobService::hasAggregateLocalStateConflict($job) || (string) $job->phase !== 'terminal' - || ((string) $job->outcome === 'failed' - && (string) $job->effect_resolution === 'unknown')) { - throw new CloudError( - '云镜像上一任务尚未安全收敛,禁止提交新的修改', 409 + || !in_array( + (string) $job->effect_resolution, + ['applied', 'not_applied'], + true + ) + || (bool) $job->finalization_incident + || CloudJobService::aggregateParentRecoveryPending( + $job, + null, + $lockForUpdate + )); + } + + /** + * Treat a NULL/zero pointer as safe only when the current immutable + * replica/child chain proves that its one historical parent is fully + * settled. Any in-flight, incomplete, cross-wired or ambiguous chain + * remains fenced for the parent-first recovery sweep. + */ + private static function missingPointerRecoveryPending( + CloudTemplate $template + ): bool { + $templateId = (string) ($template->id ?? ''); + if ($templateId === '') { + return false; + } + if ((string) $template->state !== 'active') { + return true; + } + $replicas = CloudTemplateReplica::query() + ->where('template_id', $templateId) + ->orderBy('host_id') + ->get([ + 'host_id', 'job_id', 'state', 'operation_id', + 'generation_token', + ]); + if ($replicas->isEmpty()) { + return false; + } + $jobIds = $replicas->map( + static fn (CloudTemplateReplica $replica): int => + (int) ($replica->job_id ?? 0) + )->filter(static fn (int $id): bool => $id > 0) + ->unique()->values()->all(); + // A replica without a child ledger is historical catalog data, not + // proof of an in-flight operation. A partial mapping is damage. + if ($jobIds === []) { + return false; + } + if (count($jobIds) !== $replicas->count()) { + return true; + } + if (CloudUserIsoReplica::query()->whereIn( + 'job_id', + $jobIds + )->exists()) { + return true; + } + $children = CloudJob::whereIn('id', $jobIds)->orderBy('id')->get(); + if ($children->count() !== count($jobIds)) { + return true; + } + $parentIds = []; + foreach ($children as $child) { + $matches = $replicas->filter( + static fn (CloudTemplateReplica $replica): bool => + (int) ($replica->job_id ?? 0) === (int) $child->id + ); + $replica = $matches->count() === 1 ? $matches->first() : null; + $parentId = (int) ($child->parent_job_id ?? 0); + if ($replica === null + || $parentId < 1 + || (string) $child->execution_mode !== 'agent' + || (int) $child->host_id < 1 + || (int) $replica->host_id !== (int) $child->host_id + || preg_match( + '/^[a-f0-9]{32}$/D', + (string) $child->operation_id + ) !== 1 + || !hash_equals( + (string) $child->operation_id, + (string) $replica->operation_id + ) + || !hash_equals( + (string) $template->generation_token, + (string) $replica->generation_token + )) { + return true; + } + $parentIds[$parentId] = true; + } + if (count($parentIds) !== 1) { + return true; + } + $parent = CloudJob::find((int) array_key_first($parentIds)); + $expectedChildKind = match ((string) ($parent?->kind ?? '')) { + 'template_import' => 'template_import_replica', + 'template_metadata_sync' => 'template_metadata_replica', + 'template_delete' => 'template_delete_replica', + default => null, + }; + if ($parent === null + || $expectedChildKind === null + || (string) $parent->execution_mode !== 'aggregate' + || $parent->parent_job_id !== null + || CloudJob::where('parent_job_id', (int) $parent->id)->count() + !== $children->count() + || CloudTemplateReplica::query()->whereIn('job_id', $jobIds) + ->where('template_id', '<>', $templateId)->exists() + || CloudUserIsoReplica::query()->whereIn( + 'job_id', + $jobIds + )->exists() + || CloudTemplate::query() + ->where('active_job_id', (int) $parent->id) + ->where('id', '<>', $templateId)->exists() + || $children->contains(static fn (CloudJob $child): bool => + (string) $child->kind !== $expectedChildKind + || (int) $child->user_id !== (int) $parent->user_id)) { + return true; + } + return !self::aggregateParentSafelySettled($parent, false) + || !self::currentParentProjectionMatches( + $template, + $parent, + false ); + } + + private static function assertCurrentActiveReplica( + CloudTemplate $template, + bool $lockForUpdate = false + ): void { + if (!self::hasCurrentActiveReplica($template, $lockForUpdate)) { + throw new CloudError('云镜像模板暂无可用宿主机副本', 409); + } + } + + private static function hasCurrentActiveReplica( + CloudTemplate $template, + bool $lockForUpdate = false + ): bool { + $query = CloudTemplateReplica::query() + ->where('template_id', (string) $template->id) + ->where('state', 'active') + ->where('generation_token', (string) $template->generation_token) + ->where('revision', (int) $template->revision) + ->orderBy('host_id'); + if ($lockForUpdate) { + $query->lockForUpdate(); } + return $query->first(['host_id']) !== null; } private static function lockedReplicas(string $id) @@ -796,6 +1650,237 @@ final class CloudTemplateCatalogService ->orderBy('host_id')->lockForUpdate()->get(); } + private static function templateBoundToParentLocked( + CloudJob $parent + ): CloudTemplate { + $templates = CloudTemplate::query() + ->where('active_job_id', (int) $parent->id) + ->orderBy('id') + ->lockForUpdate() + ->get(); + if ($templates->count() > 1) { + throw new CloudRecoveryAggregateStateConflict( + '云镜像汇总任务绑定了多个目录主记录', + 409 + ); + } + if ($templates->isEmpty()) { + return self::repairMissingParentBindingLocked($parent); + } + return $templates->first(); + } + + /** + * Repair only a single damaged active_job_id field. The immutable child + * and replica ledgers must identify one in-flight catalog row exactly; + * this never creates a job or replays an Agent mutation. + */ + public static function repairMissingParentBindingLocked( + CloudJob $parent + ): CloudTemplate { + $kind = (string) $parent->kind; + $expectedChildKind = match ($kind) { + 'template_import' => 'template_import_replica', + 'template_metadata_sync' => 'template_metadata_replica', + 'template_delete' => 'template_delete_replica', + default => null, + }; + $expectedStates = match ($kind) { + 'template_import' => ['importing', 'error', 'active'], + 'template_metadata_sync' => ['active'], + 'template_delete' => ['deleting', 'delete_failed', 'active'], + default => [], + }; + if ($expectedChildKind === null + || $expectedStates === [] + || (string) $parent->execution_mode !== 'aggregate' + || $parent->parent_job_id !== null + || CloudJobService::hasAggregateLocalStateConflict($parent)) { + throw new CloudRecoveryInstanceStateConflict( + '云镜像活动任务指针缺失,且父任务状态不能证明唯一目录绑定', + 409 + ); + } + + // Discover without locks first so the established lock order remains + // parent -> catalog row -> children -> replicas. Every value is then + // re-read and verified under locks before the pointer is written. + $childIds = CloudJob::where('parent_job_id', (int) $parent->id) + ->orderBy('id')->pluck('id')->map( + static fn ($id): int => (int) $id + )->all(); + if ($childIds === []) { + throw new CloudRecoveryAggregateStateConflict( + '云镜像活动任务指针缺失,且父任务没有子任务账本', + 409 + ); + } + $candidateIds = CloudTemplateReplica::query() + ->whereIn('job_id', $childIds) + ->orderBy('template_id') + ->pluck('template_id') + ->map(static fn ($id): string => (string) $id) + ->unique()->values(); + if ($candidateIds->isEmpty()) { + throw new CloudRecoveryInstanceStateConflict( + '云镜像活动任务指针缺失,副本账本无法定位目录主记录', + 409 + ); + } + if ($candidateIds->count() !== 1) { + throw new CloudRecoveryOperationIdentityConflict( + '云镜像活动任务指针缺失,副本账本指向多个目录主记录', + 409 + ); + } + + $template = CloudTemplate::query() + ->where('id', (string) $candidateIds->first()) + ->lockForUpdate()->first(); + if ($template === null) { + throw new CloudRecoveryInstanceStateConflict( + '云镜像活动任务指针缺失,副本账本引用的目录主记录不存在', + 409 + ); + } + $currentJobId = (int) ($template->active_job_id ?? 0); + if ($currentJobId > 0 && $currentJobId !== (int) $parent->id) { + throw new CloudRecoveryOperationIdentityConflict( + '云镜像活动任务正数指针指向其他任务,不能自动改写', + 409 + ); + } + if (!in_array( + (string) $template->state, + $expectedStates, + true + )) { + throw new CloudRecoveryInstanceStateConflict( + '云镜像活动任务指针或目录状态与原父任务不一致', + 409 + ); + } + + $otherBindings = CloudTemplate::query() + ->where('active_job_id', (int) $parent->id) + ->where('id', '<>', (string) $template->id) + ->orderBy('id')->lockForUpdate()->get(['id']); + if (!$otherBindings->isEmpty()) { + throw new CloudRecoveryOperationIdentityConflict( + '云镜像父任务已绑定其他目录主记录,不能修复活动任务指针', + 409 + ); + } + + $children = CloudJob::where('parent_job_id', (int) $parent->id) + ->orderBy('id')->lockForUpdate()->get(); + $replicas = self::lockedReplicas((string) $template->id); + if (CloudUserIsoReplica::query()->whereIn( + 'job_id', + $childIds + )->exists()) { + throw new CloudRecoveryOperationIdentityConflict( + '云镜像活动任务子任务被 ISO 副本账本重复引用', + 409 + ); + } + if ($children->count() !== count($childIds) + || $replicas->count() !== $children->count() + || preg_match( + '/^[a-f0-9]{32}$/D', + (string) $template->generation_token + ) !== 1) { + throw new CloudRecoveryAggregateStateConflict( + '云镜像活动任务指针缺失,子任务与副本数量不一致', + 409 + ); + } + if ($kind === 'template_metadata_sync' + && !$replicas->contains( + static fn (CloudTemplateReplica $replica): bool => in_array( + (string) $replica->state, + ['syncing', 'stale'], + true + ) + ) + && !((string) $parent->phase === 'terminal' + && (string) $parent->outcome === 'failed' + && (string) $parent->status === 'failed' + && (string) $parent->effect_resolution === 'unknown') + && !(bool) $parent->finalization_incident) { + throw new CloudRecoveryInstanceStateConflict( + '云镜像元数据任务指针缺失,但当前账本不能证明仍有待恢复操作', + 409 + ); + } + foreach ($children as $child) { + $matches = $replicas->filter( + static fn (CloudTemplateReplica $replica): bool => + (int) ($replica->job_id ?? 0) === (int) $child->id + ); + $replica = $matches->count() === 1 ? $matches->first() : null; + if ($replica === null + || (int) ($child->parent_job_id ?? 0) !== (int) $parent->id + || (int) $child->user_id !== (int) $parent->user_id + || (string) $child->execution_mode !== 'agent' + || (string) $child->kind !== $expectedChildKind + || (int) $child->host_id < 1 + || (int) $replica->host_id !== (int) $child->host_id + || preg_match( + '/^[a-f0-9]{32}$/D', + (string) $child->operation_id + ) !== 1 + || !hash_equals( + (string) $child->operation_id, + (string) $replica->operation_id + ) + || !hash_equals( + (string) $template->generation_token, + (string) $replica->generation_token + )) { + throw new CloudRecoveryOperationIdentityConflict( + '云镜像活动任务指针缺失,子任务与副本身份不一致', + 409 + ); + } + } + + if ($currentJobId !== (int) $parent->id) { + $update = CloudTemplate::query() + ->where('id', (string) $template->id) + ->where(static function ($missing): void { + $missing->whereNull('active_job_id') + ->orWhere('active_job_id', '<=', 0); + }); + $updated = $update->update([ + 'active_job_id' => (int) $parent->id, + 'updated_at' => time(), + ]); + if ($updated !== 1) { + throw new CloudRecoveryOperationIdentityConflict( + '云镜像活动任务指针在修复时发生并发变化', + 409 + ); + } + $template->refresh(); + } + return $template; + } + + private static function assertTemplateParentBindingLocked( + CloudTemplate $template, + CloudJob $parent + ): void { + $bound = self::templateBoundToParentLocked($parent); + if (!hash_equals((string) $bound->id, (string) $template->id) + || (int) $template->active_job_id !== (int) $parent->id) { + throw new CloudRecoveryOperationIdentityConflict( + '云镜像汇总任务与目录主记录身份不一致', + 409 + ); + } + } + private static function parent(int $id, string $kind): CloudJob { $job = CloudJob::where('id', $id)->where('kind', $kind) diff --git a/web/app/Services/Cloud/CloudUserIsoService.php b/web/app/Services/Cloud/CloudUserIsoService.php index 81c61334..70c6cdf8 100644 --- a/web/app/Services/Cloud/CloudUserIsoService.php +++ b/web/app/Services/Cloud/CloudUserIsoService.php @@ -3,6 +3,7 @@ namespace App\Services\Cloud; use App\Models\CloudJob; +use App\Models\CloudTemplateReplica; use App\Models\CloudUserIso; use App\Models\CloudUserIsoReplica; @@ -63,23 +64,7 @@ final class CloudUserIsoService if (!$created) { return $parent; } - $rows = CloudUserIso::query()->where('user_id', $userId) - ->where('state', '<>', 'retired')->lockForUpdate()->get(); - foreach ($rows as $row) { - $jobId = (int) ($row->active_job_id ?? 0); - if ($jobId < 1) { - continue; - } - $prior = CloudJob::where('id', $jobId) - ->lockForUpdate()->first(); - if ($prior === null - || (string) $prior->phase !== 'terminal' - || (string) $prior->effect_resolution === 'unknown') { - throw new CloudError( - '已有用户 ISO 任务尚未安全收敛', 409 - ); - } - } + $rows = self::lockIsoRowsForImport($userId); if ($rows->count() >= self::MAX_ISOS) { throw new CloudError('每个用户最多保存 5 个 ISO', 409); } @@ -146,12 +131,13 @@ final class CloudUserIsoService $parent = $connection->transaction(static function () use ( $id, $actor, $userId ): CloudJob { - $iso = CloudUserIso::query()->where('id', $id) - ->where('user_id', $userId)->lockForUpdate()->first(); + $iso = self::lockIsoForMutation($id, $userId); if ($iso === null || (string) $iso->state === 'retired') { throw new CloudError('ISO 不存在或不属于当前用户', 404); } - if ((string) $iso->state !== 'active') { + $quotaCleanup = (string) $iso->state === 'import_failed' + && self::quotaExceededImportCleanupAllowed($iso, false); + if ((string) $iso->state !== 'active' && !$quotaCleanup) { throw new CloudError( 'ISO 尚有未确认或失败的任务,禁止重复下发删除', 409 ); @@ -207,7 +193,8 @@ final class CloudUserIsoService string $status, $result, array $payload, - array $operation + array $operation, + bool $recovery = false ): void { if (!in_array((string) $job->kind, [ 'user_iso_import_replica', 'user_iso_delete_replica', @@ -225,16 +212,367 @@ final class CloudUserIsoService if ($iso === null || $replica === null) { throw new CloudError('ISO 任务账本不存在', 409); } + // Parent publication is deliberately deferred until CloudWorkerService + // has persisted this child's terminal effect. The shared recovered + // settle path then validates the full child / replica ledger. if ((string) $job->kind === 'user_iso_import_replica') { self::finishImportReplica($iso, $replica, $status, $result, - $operation); - self::settleImportParent($iso, (int) $job->parent_job_id, - $operation); + $operation, $recovery); + return; + } + self::finishDeleteReplica( + $iso, $replica, $status, $operation, $recovery + ); + } + + /** See CloudTemplateCatalogService::lockAggregateCatalogLocked(). */ + public static function lockAggregateCatalogLocked(CloudJob $parent): void + { + if (!in_array((string) $parent->kind, [ + 'user_iso_import', 'user_iso_delete', + ], true)) { + return; + } + self::isoBoundToParentLocked($parent); + } + + /** See CloudTemplateCatalogService::settleRecoveredParentLocked(). */ + public static function settleRecoveredParentLocked( + CloudJob $parent, + string $resolution + ): void { + if (!in_array((string) $parent->kind, [ + 'user_iso_import', 'user_iso_delete', + ], true) || (string) $parent->execution_mode !== 'aggregate' + || ((string) $parent->phase === 'terminal' + && ((string) $parent->outcome !== 'failed' + || (string) $parent->effect_resolution !== 'unknown'))) { return; } - self::finishDeleteReplica($iso, $replica, $status, $operation); - self::settleDeleteParent($iso, (int) $job->parent_job_id, - $operation); + $iso = self::isoBoundToParentLocked($parent); + if (!in_array( + $resolution, + ['applied', 'not_applied', 'mixed'], + true + )) { + throw new CloudRecoveryAggregateStateConflict( + 'ISO 汇总任务的子任务效果状态无效', + 409 + ); + } + self::assertRecoveredReplicaProjectionLocked( + $iso, + $parent, + $resolution + ); + if ($resolution === 'not_applied') { + self::restoreNotAppliedProjectionLocked($iso, $parent); + return; + } + $operation = ['effect_may_have_applied' => true]; + if ((string) $parent->kind === 'user_iso_import') { + self::settleImportParent( + $iso, + (int) $parent->id, + $operation + ); + return; + } + self::settleDeleteParent( + $iso, + (int) $parent->id, + $operation + ); + } + + /** Validate an already-published aggregate without changing its audit. */ + public static function assertSettledParentProjectionLocked( + CloudJob $parent, + string $resolution + ): void { + if (!in_array((string) $parent->kind, [ + 'user_iso_import', 'user_iso_delete', + ], true)) { + return; + } + if (!in_array($resolution, ['applied', 'not_applied'], true)) { + throw new CloudRecoveryAggregateStateConflict( + 'ISO 已发布汇总任务的子任务效果状态无效', + 409 + ); + } + $iso = self::isoBoundToParentLocked($parent); + $children = CloudJob::where('parent_job_id', (int) $parent->id) + ->orderBy('id')->lockForUpdate()->get(); + if ($children->isEmpty()) { + throw new CloudRecoveryAggregateStateConflict( + 'ISO 已发布汇总任务缺少子任务账本', + 409 + ); + } + if (CloudTemplateReplica::query()->whereIn( + 'job_id', + $children->map( + static fn (CloudJob $child): int => (int) $child->id + )->all() + )->exists()) { + throw new CloudRecoveryOperationIdentityConflict( + 'ISO 汇总子任务被云镜像副本账本重复引用', + 409 + ); + } + $replicas = CloudUserIsoReplica::query() + ->where('user_iso_id', (string) $iso->id) + ->orderBy('host_id')->lockForUpdate()->get(); + + if ((string) $parent->kind === 'user_iso_import') { + if (!hash_equals( + (string) $parent->operation_id, + (string) $iso->import_operation_id + )) { + throw new CloudRecoveryOperationIdentityConflict( + 'ISO 导入主记录与已发布汇总任务身份不一致', + 409 + ); + } + if ($resolution === 'not_applied') { + if ((string) $iso->state !== 'retired' + || (string) $iso->name !== '' + || (string) $iso->sealed_source_url !== '' + || (int) $iso->size_bytes !== 0 + || (string) $iso->sha256 !== '' + || !$replicas->isEmpty()) { + throw new CloudRecoveryInstanceStateConflict( + 'ISO 导入无效果结论与清理状态不一致', + 409 + ); + } + return; + } + if ((string) $iso->state !== 'active' + && !((string) $iso->state === 'import_failed' + && (string) $parent->outcome === 'failed')) { + throw new CloudRecoveryInstanceStateConflict( + 'ISO 导入已生效结论与目录状态不一致', + 409 + ); + } + self::assertRecoveredReplicaProjectionLocked( + $iso, + $parent, + 'applied' + ); + return; + } + + if ($resolution === 'applied') { + if ((string) $iso->state !== 'retired' + || (string) $iso->name !== '' + || (string) $iso->sealed_source_url !== '' + || (int) $iso->size_bytes !== 0 + || (string) $iso->sha256 !== '' + || !$replicas->isEmpty()) { + throw new CloudRecoveryInstanceStateConflict( + 'ISO 删除已生效结论与清理状态不一致', + 409 + ); + } + return; + } + + if ((string) $iso->state !== 'active') { + throw new CloudRecoveryInstanceStateConflict( + 'ISO 删除无效果结论未恢复目录状态', + 409 + ); + } + if ($children->isEmpty() || $replicas->count() !== $children->count()) { + throw new CloudRecoveryAggregateStateConflict( + 'ISO 删除无效果结论的子任务与副本数量不一致', + 409 + ); + } + foreach ($children as $child) { + $matches = $replicas->filter( + static fn (CloudUserIsoReplica $replica): bool => + (int) ($replica->job_id ?? 0) === (int) $child->id + ); + $replica = $matches->count() === 1 ? $matches->first() : null; + if ($replica === null + || (string) $child->effect_resolution !== 'not_applied' + || (int) $replica->host_id !== (int) $child->host_id + || (int) $replica->user_id !== (int) $child->user_id + || (int) $replica->user_id !== (int) $iso->user_id + || !hash_equals( + (string) $child->operation_id, + (string) $replica->operation_id + )) { + throw new CloudRecoveryOperationIdentityConflict( + 'ISO 删除无效果结论的子任务与副本身份不一致', + 409 + ); + } + if ((string) $replica->state !== 'active' + || (int) $replica->size_bytes !== (int) $iso->size_bytes + || !hash_equals( + (string) $iso->sha256, + (string) $replica->sha256 + )) { + throw new CloudRecoveryInstanceStateConflict( + 'ISO 删除无效果结论的副本状态或内容不一致', + 409 + ); + } + } + } + + /** See CloudTemplateCatalogService::assertRecoveredReplicaProjectionLocked(). */ + private static function assertRecoveredReplicaProjectionLocked( + CloudUserIso $iso, + CloudJob $parent, + string $resolution, + bool $lockForUpdate = true + ): void { + if ((int) $iso->user_id !== (int) $parent->user_id) { + throw new CloudRecoveryOperationIdentityConflict( + 'ISO 主记录与汇总任务用户身份不一致', + 409 + ); + } + if ((string) $parent->kind === 'user_iso_import' + && !hash_equals( + (string) $parent->operation_id, + (string) $iso->import_operation_id + )) { + throw new CloudRecoveryOperationIdentityConflict( + 'ISO 导入主记录与汇总任务身份不一致', + 409 + ); + } + $childQuery = CloudJob::where( + 'parent_job_id', + (int) $parent->id + )->orderBy('id'); + $replicaQuery = CloudUserIsoReplica::query() + ->where('user_iso_id', (string) $iso->id) + ->orderBy('host_id'); + if ($lockForUpdate) { + $childQuery->lockForUpdate(); + $replicaQuery->lockForUpdate(); + } + $children = $childQuery->get(); + $replicas = $replicaQuery->get(); + if ($children->isEmpty() || $replicas->count() !== $children->count()) { + throw new CloudRecoveryAggregateStateConflict( + 'ISO 汇总任务的子任务与副本数量不一致', + 409 + ); + } + if (CloudTemplateReplica::query()->whereIn( + 'job_id', + $children->map( + static fn (CloudJob $child): int => (int) $child->id + )->all() + )->exists()) { + throw new CloudRecoveryOperationIdentityConflict( + 'ISO 汇总子任务被云镜像副本账本重复引用', + 409 + ); + } + foreach ($children as $child) { + $childResolution = $resolution === 'mixed' + ? (string) $child->effect_resolution : $resolution; + $expectedState = (string) $parent->kind === 'user_iso_import' + ? ($childResolution === 'applied' ? 'active' : 'failed') + : ($childResolution === 'applied' + ? 'delete_succeeded' : 'delete_failed'); + $matches = $replicas->filter( + static fn (CloudUserIsoReplica $replica): bool => + (int) ($replica->job_id ?? 0) === (int) $child->id + ); + $replica = $matches->count() === 1 ? $matches->first() : null; + if ($replica === null + || (int) $replica->host_id !== (int) $child->host_id + || (int) $replica->user_id !== (int) $child->user_id + || (int) $replica->user_id !== (int) $iso->user_id + || !hash_equals( + (string) $child->operation_id, + (string) $replica->operation_id + )) { + throw new CloudRecoveryOperationIdentityConflict( + 'ISO 汇总任务的子任务与副本身份不一致', + 409 + ); + } + if ((string) $replica->state !== $expectedState + || ((string) $parent->kind === 'user_iso_import' + && $childResolution === 'applied' + && ((int) $replica->size_bytes + !== (int) $iso->size_bytes + || !hash_equals( + (string) $iso->sha256, + (string) $replica->sha256 + ))) + || ((string) $parent->kind === 'user_iso_delete' + && $childResolution === 'not_applied' + && ((int) $replica->size_bytes + !== (int) $iso->size_bytes + || !hash_equals( + (string) $iso->sha256, + (string) $replica->sha256 + )))) { + throw new CloudRecoveryInstanceStateConflict( + 'ISO 汇总任务的副本状态或内容不一致', + 409 + ); + } + } + } + + /** Restore the resource boundary only when every host proves no effect. */ + private static function restoreNotAppliedProjectionLocked( + CloudUserIso $iso, + CloudJob $parent + ): void { + if ((string) $parent->kind === 'user_iso_import') { + CloudUserIsoReplica::query()->where( + 'user_iso_id', + (string) $iso->id + )->delete(); + $iso->name = ''; + $iso->sealed_source_url = ''; + $iso->size_bytes = 0; + $iso->sha256 = ''; + $iso->state = 'retired'; + $iso->updated_at = time(); + $iso->save(); + CloudJobService::completeAggregateLocked( + $parent, + 'failed', + false, + true, + 'user_iso_import_not_applied' + ); + return; + } + CloudUserIsoReplica::query()->where( + 'user_iso_id', + (string) $iso->id + )->update([ + 'state' => 'active', + 'error_code' => '', + 'updated_at' => time(), + ]); + $iso->state = 'active'; + $iso->updated_at = time(); + $iso->save(); + CloudJobService::completeAggregateLocked( + $parent, + 'failed', + false, + true, + 'user_iso_delete_not_applied' + ); } /** Close a batch whose absolute parent deadline elapsed. */ @@ -258,7 +596,7 @@ final class CloudUserIsoService $children = CloudJob::where('parent_job_id', (int) $parent->id) ->lockForUpdate()->get(); $effect = $children->contains(static fn ($child): bool => - (int) $child->dispatch_attempts === 1 + CloudDispatchLedger::mayHaveDispatched($child) || (bool) $child->effect_may_have_applied); if ((string) $parent->kind === 'user_iso_import') { CloudUserIsoReplica::query() @@ -289,10 +627,14 @@ final class CloudUserIsoService private static function finishImportReplica(CloudUserIso $iso, CloudUserIsoReplica $replica, string $status, $result, - array $operation): void + array $operation, bool $recovery): void { - if ((string) $replica->state !== 'importing') { - return; + if ((string) $replica->state !== 'importing' + && !($recovery && (string) $replica->state === 'failed')) { + throw new CloudError( + 'ISO 副本状态与导入任务恢复证据不一致', + 409 + ); } if ($status === 'succeeded') { $digest = is_array($result) @@ -346,7 +688,8 @@ final class CloudUserIsoService } private static function settleImportParent(CloudUserIso $iso, - int $parentId, array $operation): void + int $parentId, array $operation, + ?int $completingChildId = null): void { $replicas = CloudUserIsoReplica::query() ->where('user_iso_id', (string) $iso->id)->orderBy('host_id') @@ -360,6 +703,14 @@ final class CloudUserIsoService if ($parent === null || (string) $parent->kind !== 'user_iso_import') { throw new CloudError('ISO 聚合任务不存在', 409); } + self::assertIsoParentBindingLocked($iso, $parent); + if (CloudJobService::aggregateParentRecoveryPending( + $parent, + $completingChildId, + true + )) { + return; + } $allActive = !$replicas->contains(static fn ($row): bool => (string) $row->state !== 'active'); $quotaUsed = (int) CloudUserIso::query() @@ -394,10 +745,15 @@ final class CloudUserIsoService private static function finishDeleteReplica(CloudUserIso $iso, CloudUserIsoReplica $replica, string $status, - array $operation): void + array $operation, bool $recovery): void { - if ((string) $replica->state !== 'deleting') { - return; + if ((string) $replica->state !== 'deleting' + && !($recovery + && (string) $replica->state === 'delete_failed')) { + throw new CloudError( + 'ISO 副本状态与删除任务恢复证据不一致', + 409 + ); } if ($status === 'succeeded') { if (!CloudAgentCatalogDeletion::confirms( @@ -425,7 +781,8 @@ final class CloudUserIsoService } private static function settleDeleteParent(CloudUserIso $iso, - int $parentId, array $operation): void + int $parentId, array $operation, + ?int $completingChildId = null): void { $replicas = CloudUserIsoReplica::query() ->where('user_iso_id', (string) $iso->id)->orderBy('host_id') @@ -438,6 +795,14 @@ final class CloudUserIsoService if ($parent === null || (string) $parent->kind !== 'user_iso_delete') { throw new CloudError('ISO 删除聚合任务不存在', 409); } + self::assertIsoParentBindingLocked($iso, $parent); + if (CloudJobService::aggregateParentRecoveryPending( + $parent, + $completingChildId, + true + )) { + return; + } $allDeleted = !$replicas->contains(static fn ($row): bool => (string) $row->state !== 'delete_succeeded'); if ($allDeleted) { @@ -472,14 +837,23 @@ final class CloudUserIsoService private static function dto(CloudUserIso $iso): array { - return [ + $quotaCleanup = (string) $iso->state === 'import_failed' + && self::quotaExceededImportCleanupAllowed($iso, false); + $result = [ 'id' => (string) $iso->id, 'name' => (string) $iso->name, 'size_bytes' => (int) $iso->size_bytes, 'sha256' => (string) $iso->sha256, 'state' => (string) $iso->state, 'created_at' => (int) $iso->created_at, + 'can_delete' => ((string) $iso->state === 'active' + && self::activeJobSafelySettled($iso, false)) + || $quotaCleanup, ]; + if ($quotaCleanup) { + $result['cleanup_reason'] = 'quota_exceeded_after_import'; + } + return $result; } private static function errorCode(array $operation, string $fallback): string @@ -490,6 +864,674 @@ final class CloudUserIsoService ? $code : $fallback; } + private static function isoBoundToParentLocked( + CloudJob $parent + ): CloudUserIso { + $isos = CloudUserIso::query() + ->where('active_job_id', (int) $parent->id) + ->orderBy('id') + ->lockForUpdate() + ->get(); + if ($isos->count() > 1) { + throw new CloudRecoveryAggregateStateConflict( + 'ISO 汇总任务绑定了多个目录主记录', + 409 + ); + } + if ($isos->isEmpty()) { + return self::repairMissingParentBindingLocked($parent); + } + $iso = $isos->first(); + if ((int) $iso->user_id !== (int) $parent->user_id) { + throw new CloudRecoveryOperationIdentityConflict( + 'ISO 汇总任务与目录主记录所属人不一致', + 409 + ); + } + return $iso; + } + + /** + * Recover a NULL/zero active_job_id only from one complete immutable + * child-to-replica identity chain. No Agent request or replacement task is + * ever created here. + */ + public static function repairMissingParentBindingLocked( + CloudJob $parent + ): CloudUserIso { + $kind = (string) $parent->kind; + $expectedChildKind = match ($kind) { + 'user_iso_import' => 'user_iso_import_replica', + 'user_iso_delete' => 'user_iso_delete_replica', + default => null, + }; + $expectedStates = match ($kind) { + 'user_iso_import' => ['importing', 'import_failed', 'active'], + 'user_iso_delete' => ['deleting', 'delete_failed', 'active'], + default => [], + }; + if ($expectedChildKind === null + || $expectedStates === [] + || (string) $parent->execution_mode !== 'aggregate' + || $parent->parent_job_id !== null + || (int) $parent->user_id < 1 + || CloudJobService::hasAggregateLocalStateConflict($parent)) { + throw new CloudRecoveryInstanceStateConflict( + 'ISO 活动任务指针缺失,且父任务状态不能证明唯一目录绑定', + 409 + ); + } + + $childIds = CloudJob::where('parent_job_id', (int) $parent->id) + ->orderBy('id')->pluck('id')->map( + static fn ($id): int => (int) $id + )->all(); + if ($childIds === []) { + throw new CloudRecoveryAggregateStateConflict( + 'ISO 活动任务指针缺失,且父任务没有子任务账本', + 409 + ); + } + $candidateIds = CloudUserIsoReplica::query() + ->whereIn('job_id', $childIds) + ->orderBy('user_iso_id') + ->pluck('user_iso_id') + ->map(static fn ($id): string => (string) $id) + ->unique()->values(); + if ($candidateIds->isEmpty()) { + throw new CloudRecoveryInstanceStateConflict( + 'ISO 活动任务指针缺失,副本账本无法定位目录主记录', + 409 + ); + } + if ($candidateIds->count() !== 1) { + throw new CloudRecoveryOperationIdentityConflict( + 'ISO 活动任务指针缺失,副本账本指向多个目录主记录', + 409 + ); + } + + $iso = CloudUserIso::query() + ->where('id', (string) $candidateIds->first()) + ->lockForUpdate()->first(); + if ($iso === null) { + throw new CloudRecoveryInstanceStateConflict( + 'ISO 活动任务指针缺失,副本账本引用的目录主记录不存在', + 409 + ); + } + $currentJobId = (int) ($iso->active_job_id ?? 0); + if ($currentJobId > 0 && $currentJobId !== (int) $parent->id) { + throw new CloudRecoveryOperationIdentityConflict( + 'ISO 活动任务正数指针指向其他任务,不能自动改写', + 409 + ); + } + if (!in_array((string) $iso->state, $expectedStates, true)) { + throw new CloudRecoveryInstanceStateConflict( + 'ISO 活动任务指针或目录状态与原父任务不一致', + 409 + ); + } + if ((int) $iso->user_id !== (int) $parent->user_id + || ($kind === 'user_iso_import' + && !hash_equals( + (string) $parent->operation_id, + (string) $iso->import_operation_id + ))) { + throw new CloudRecoveryOperationIdentityConflict( + 'ISO 活动任务指针缺失,目录主记录与父任务身份不一致', + 409 + ); + } + + $otherBindings = CloudUserIso::query() + ->where('active_job_id', (int) $parent->id) + ->where('id', '<>', (string) $iso->id) + ->orderBy('id')->lockForUpdate()->get(['id']); + if (!$otherBindings->isEmpty()) { + throw new CloudRecoveryOperationIdentityConflict( + 'ISO 父任务已绑定其他目录主记录,不能修复活动任务指针', + 409 + ); + } + + $children = CloudJob::where('parent_job_id', (int) $parent->id) + ->orderBy('id')->lockForUpdate()->get(); + $replicas = CloudUserIsoReplica::query() + ->where('user_iso_id', (string) $iso->id) + ->orderBy('host_id')->lockForUpdate()->get(); + if (CloudTemplateReplica::query()->whereIn( + 'job_id', + $childIds + )->exists()) { + throw new CloudRecoveryOperationIdentityConflict( + 'ISO 活动任务子任务被云镜像副本账本重复引用', + 409 + ); + } + if ($children->count() !== count($childIds) + || $replicas->count() !== $children->count()) { + throw new CloudRecoveryAggregateStateConflict( + 'ISO 活动任务指针缺失,子任务与副本数量不一致', + 409 + ); + } + foreach ($children as $child) { + $matches = $replicas->filter( + static fn (CloudUserIsoReplica $replica): bool => + (int) ($replica->job_id ?? 0) === (int) $child->id + ); + $replica = $matches->count() === 1 ? $matches->first() : null; + if ($replica === null + || (int) ($child->parent_job_id ?? 0) !== (int) $parent->id + || (int) $child->user_id !== (int) $parent->user_id + || (string) $child->execution_mode !== 'agent' + || (string) $child->kind !== $expectedChildKind + || (int) $child->host_id < 1 + || (int) $replica->host_id !== (int) $child->host_id + || (int) $replica->user_id !== (int) $child->user_id + || (int) $replica->user_id !== (int) $iso->user_id + || preg_match( + '/^[a-f0-9]{32}$/D', + (string) $child->operation_id + ) !== 1 + || !hash_equals( + (string) $child->operation_id, + (string) $replica->operation_id + )) { + throw new CloudRecoveryOperationIdentityConflict( + 'ISO 活动任务指针缺失,子任务与副本身份不一致', + 409 + ); + } + } + + if ($currentJobId !== (int) $parent->id) { + $update = CloudUserIso::query() + ->where('id', (string) $iso->id) + ->where(static function ($missing): void { + $missing->whereNull('active_job_id') + ->orWhere('active_job_id', '<=', 0); + }); + $updated = $update->update([ + 'active_job_id' => (int) $parent->id, + 'updated_at' => time(), + ]); + if ($updated !== 1) { + throw new CloudRecoveryOperationIdentityConflict( + 'ISO 活动任务指针在修复时发生并发变化', + 409 + ); + } + $iso->refresh(); + } + return $iso; + } + + private static function assertIsoParentBindingLocked( + CloudUserIso $iso, + CloudJob $parent + ): void { + $bound = self::isoBoundToParentLocked($parent); + if (!hash_equals((string) $bound->id, (string) $iso->id) + || (int) $iso->active_job_id !== (int) $parent->id + || (int) $iso->user_id !== (int) $parent->user_id) { + throw new CloudRecoveryOperationIdentityConflict( + 'ISO 汇总任务与目录主记录身份不一致', + 409 + ); + } + } + + /** Lock one ISO in parent -> catalog order before a mutation. */ + private static function lockIsoForMutation( + string $id, + int $userId + ): ?CloudUserIso { + $snapshot = CloudUserIso::query()->where('id', $id) + ->where('user_id', $userId)->first(); + if ($snapshot === null) { + return null; + } + $jobId = (int) ($snapshot->active_job_id ?? 0); + $parentSnapshot = $jobId > 0 + ? CloudJob::where('id', $jobId)->first() : null; + $parent = self::isIsoAggregateParent($parentSnapshot) + ? CloudJob::where('id', $jobId) + ->where('execution_mode', 'aggregate') + ->whereNull('parent_job_id') + ->whereIn('kind', [ + 'user_iso_import', + 'user_iso_delete', + ])->lockForUpdate()->first() + : null; + $iso = CloudUserIso::query()->where('id', $id) + ->where('user_id', $userId)->lockForUpdate()->first(); + if ($iso === null) { + return null; + } + if ((int) ($iso->active_job_id ?? 0) !== $jobId) { + throw new CloudError('ISO 任务状态已变化,请刷新后重试', 409); + } + self::assertMutationBoundaryLocked($iso, $parent); + return $iso; + } + + /** Never take a child/dangling pointer as the canonical parent lock. */ + private static function isIsoAggregateParent(?CloudJob $job): bool + { + return $job !== null + && (string) $job->execution_mode === 'aggregate' + && $job->parent_job_id === null + && in_array((string) $job->kind, [ + 'user_iso_import', + 'user_iso_delete', + ], true); + } + + /** Lock all existing ISO parents before their catalog rows. */ + private static function lockIsoRowsForImport(int $userId) + { + $snapshots = CloudUserIso::query()->where('user_id', $userId) + ->where('state', '<>', 'retired')->orderBy('id') + ->get(['id', 'active_job_id']); + $jobIds = $snapshots->map( + static fn (CloudUserIso $iso): int => + (int) ($iso->active_job_id ?? 0) + )->filter(static fn (int $jobId): bool => $jobId > 0) + ->unique()->sort()->values()->all(); + $parentSnapshots = $jobIds === [] ? collect() + : CloudJob::whereIn('id', $jobIds)->get()->keyBy('id'); + $parentIds = $parentSnapshots->filter( + static fn (CloudJob $job): bool => + self::isIsoAggregateParent($job) + )->keys()->map(static fn ($id): int => (int) $id) + ->sort()->values()->all(); + $parents = $parentIds === [] ? collect() + : CloudJob::whereIn('id', $parentIds) + ->where('execution_mode', 'aggregate') + ->whereNull('parent_job_id') + ->whereIn('kind', [ + 'user_iso_import', + 'user_iso_delete', + ])->orderBy('id')->lockForUpdate()->get()->keyBy('id'); + $rows = CloudUserIso::query()->where('user_id', $userId) + ->where('state', '<>', 'retired')->orderBy('id') + ->lockForUpdate()->get(); + if ($rows->count() !== $snapshots->count()) { + throw new CloudError('ISO 目录状态已变化,请刷新后重试', 409); + } + foreach ($rows as $index => $row) { + $snapshot = $snapshots->get($index); + $jobId = (int) ($snapshot->active_job_id ?? 0); + if ($snapshot === null + || !hash_equals((string) $snapshot->id, (string) $row->id) + || (int) ($row->active_job_id ?? 0) !== $jobId) { + throw new CloudError('ISO 目录状态已变化,请刷新后重试', 409); + } + self::assertMutationBoundaryLocked( + $row, + $jobId > 0 ? $parents->get($jobId) : null, + '已有用户 ISO 任务尚未安全收敛' + ); + } + return $rows; + } + + /** Do not overlap a catalog mutation with an invalid prior job ledger. */ + private static function assertMutationBoundaryLocked( + CloudUserIso $iso, + ?CloudJob $lockedParent = null, + string $message = 'ISO 上一任务尚未安全收敛,禁止提交新的操作' + ): void { + if (!self::activeJobSafelySettled( + $iso, + true, + $lockedParent + )) { + throw new CloudError($message, 409); + } + } + + private static function activeJobSafelySettled( + CloudUserIso $iso, + bool $lockForUpdate, + ?CloudJob $lockedParent = null + ): bool { + $jobId = (int) ($iso->active_job_id ?? 0); + if ($jobId < 1) { + return !self::missingPointerRecoveryPending($iso); + } + if ($iso->exists) { + $bindings = CloudUserIso::query() + ->where('active_job_id', $jobId) + ->orderBy('id'); + if ($lockForUpdate) { + $bindings->lockForUpdate(); + } + $bound = $bindings->get(['id']); + if ($bound->count() !== 1 + || (string) $bound->first()->id !== (string) $iso->id) { + return false; + } + } + if ($lockedParent !== null + && (int) $lockedParent->id !== $jobId) { + return false; + } + if ($lockForUpdate && $lockedParent === null) { + return false; + } + $job = $lockedParent ?? CloudJob::where('id', $jobId)->first(); + return $job !== null && self::aggregateParentSafelySettled( + $iso, + $job, + $lockForUpdate + ) && self::currentParentProjectionMatches( + $iso, + $job, + $lockForUpdate + ); + } + + /** The current ISO must own every child and replica of its parent. */ + private static function currentParentProjectionMatches( + CloudUserIso $iso, + CloudJob $parent, + bool $lockForUpdate + ): bool { + $expectedChildKind = match ((string) $parent->kind) { + 'user_iso_import' => 'user_iso_import_replica', + 'user_iso_delete' => 'user_iso_delete_replica', + default => null, + }; + $projectionStateMatches = match ((string) $parent->kind) { + 'user_iso_import' => in_array( + (string) $iso->state, + ['active', 'import_failed'], + true + ) && hash_equals( + (string) $parent->operation_id, + (string) $iso->import_operation_id + ), + 'user_iso_delete' => (string) $iso->state === 'active', + default => false, + }; + if ($expectedChildKind === null || !$projectionStateMatches) { + return false; + } + $childQuery = CloudJob::where( + 'parent_job_id', + (int) $parent->id + )->orderBy('id'); + if ($lockForUpdate) { + $childQuery->lockForUpdate(); + } + $children = $childQuery->get(); + $replicaQuery = CloudUserIsoReplica::query() + ->where('user_iso_id', (string) $iso->id) + ->orderBy('host_id'); + if ($lockForUpdate) { + $replicaQuery->lockForUpdate(); + } + $replicas = $replicaQuery->get(); + if ($children->isEmpty() + || $children->count() !== $replicas->count()) { + return false; + } + $childResolutions = $children->map( + static fn (CloudJob $child): string => + (string) $child->effect_resolution + )->unique()->values(); + if ($childResolutions->count() !== 1 + || !in_array( + (string) $childResolutions->first(), + ['applied', 'not_applied'], + true + ) + || !hash_equals( + (string) $parent->effect_resolution, + (string) $childResolutions->first() + ) + || ((string) $parent->kind === 'user_iso_import' + && (string) $childResolutions->first() !== 'applied') + || ((string) $parent->kind === 'user_iso_delete' + && (string) $childResolutions->first() !== 'not_applied')) { + return false; + } + $jobIds = $children->map( + static fn (CloudJob $child): int => (int) $child->id + )->all(); + if (CloudUserIsoReplica::query()->whereIn('job_id', $jobIds) + ->where('user_iso_id', '<>', (string) $iso->id)->exists() + || CloudTemplateReplica::query()->whereIn( + 'job_id', + $jobIds + )->exists()) { + return false; + } + foreach ($children as $child) { + $matches = $replicas->filter( + static fn (CloudUserIsoReplica $replica): bool => + (int) ($replica->job_id ?? 0) === (int) $child->id + ); + $replica = $matches->count() === 1 ? $matches->first() : null; + if ($replica === null + || (int) ($child->parent_job_id ?? 0) !== (int) $parent->id + || (int) $child->user_id !== (int) $parent->user_id + || (string) $child->execution_mode !== 'agent' + || (string) $child->kind !== $expectedChildKind + || (int) $child->host_id !== (int) $replica->host_id + || (int) $replica->user_id !== (int) $iso->user_id + || !hash_equals( + (string) $child->operation_id, + (string) $replica->operation_id + ) + || (string) $replica->state !== 'active' + || (int) $replica->size_bytes !== (int) $iso->size_bytes + || !hash_equals( + (string) $iso->sha256, + (string) $replica->sha256 + )) { + return false; + } + } + return true; + } + + private static function aggregateParentSafelySettled( + CloudUserIso $iso, + CloudJob $job, + bool $lockForUpdate + ): bool { + return !( + $job->parent_job_id !== null + || (string) $job->execution_mode !== 'aggregate' + || !in_array((string) $job->kind, [ + 'user_iso_import', + 'user_iso_delete', + ], true) + || (int) $job->user_id !== (int) $iso->user_id + || CloudJobService::hasAggregateLocalStateConflict($job) + || (string) $job->phase !== 'terminal' + || !in_array( + (string) $job->effect_resolution, + ['applied', 'not_applied'], + true + ) + || (bool) $job->finalization_incident + || CloudJobService::aggregateParentRecoveryPending( + $job, + null, + $lockForUpdate + )); + } + + /** Keep lost catalog pointers fenced before a second ISO mutation starts. */ + private static function missingPointerRecoveryPending( + CloudUserIso $iso + ): bool { + $isoId = (string) ($iso->id ?? ''); + if ($isoId === '') { + return false; + } + if ((string) $iso->state !== 'active') { + return true; + } + $replicas = CloudUserIsoReplica::query() + ->where('user_iso_id', $isoId) + ->orderBy('host_id') + ->get([ + 'host_id', 'user_id', 'job_id', 'state', 'operation_id', + ]); + if ($replicas->isEmpty()) { + return false; + } + $jobIds = $replicas->map( + static fn (CloudUserIsoReplica $replica): int => + (int) ($replica->job_id ?? 0) + )->filter(static fn (int $id): bool => $id > 0) + ->unique()->values()->all(); + if ($jobIds === []) { + return false; + } + if (count($jobIds) !== $replicas->count()) { + return true; + } + if (CloudTemplateReplica::query()->whereIn( + 'job_id', + $jobIds + )->exists()) { + return true; + } + $children = CloudJob::whereIn('id', $jobIds)->orderBy('id')->get(); + if ($children->count() !== count($jobIds)) { + return true; + } + $parentIds = []; + foreach ($children as $child) { + $matches = $replicas->filter( + static fn (CloudUserIsoReplica $replica): bool => + (int) ($replica->job_id ?? 0) === (int) $child->id + ); + $replica = $matches->count() === 1 ? $matches->first() : null; + $parentId = (int) ($child->parent_job_id ?? 0); + if ($replica === null + || $parentId < 1 + || (string) $child->execution_mode !== 'agent' + || (int) $child->host_id < 1 + || (int) $replica->host_id !== (int) $child->host_id + || (int) $replica->user_id !== (int) $child->user_id + || (int) $replica->user_id !== (int) $iso->user_id + || preg_match( + '/^[a-f0-9]{32}$/D', + (string) $child->operation_id + ) !== 1 + || !hash_equals( + (string) $child->operation_id, + (string) $replica->operation_id + )) { + return true; + } + $parentIds[$parentId] = true; + } + if (count($parentIds) !== 1) { + return true; + } + $parent = CloudJob::find((int) array_key_first($parentIds)); + $expectedChildKind = match ((string) ($parent?->kind ?? '')) { + 'user_iso_import' => 'user_iso_import_replica', + 'user_iso_delete' => 'user_iso_delete_replica', + default => null, + }; + if ($parent === null + || $expectedChildKind === null + || (string) $parent->execution_mode !== 'aggregate' + || $parent->parent_job_id !== null + || (int) $parent->user_id !== (int) $iso->user_id + || CloudJob::where('parent_job_id', (int) $parent->id)->count() + !== $children->count() + || CloudUserIsoReplica::query()->whereIn('job_id', $jobIds) + ->where('user_iso_id', '<>', $isoId)->exists() + || CloudTemplateReplica::query()->whereIn( + 'job_id', + $jobIds + )->exists() + || CloudUserIso::query() + ->where('active_job_id', (int) $parent->id) + ->where('id', '<>', $isoId)->exists() + || ((string) $parent->kind === 'user_iso_import' + && !hash_equals( + (string) $parent->operation_id, + (string) $iso->import_operation_id + )) + || $children->contains(static fn (CloudJob $child): bool => + (string) $child->kind !== $expectedChildKind + || (int) $child->user_id !== (int) $parent->user_id)) { + return true; + } + return !self::aggregateParentSafelySettled( + $iso, + $parent, + false + ) || !self::currentParentProjectionMatches( + $iso, + $parent, + false + ); + } + + /** + * A quota-rejected import may already exist on every host. It is not made + * active (which would exceed quota), but its owner may start a new, + * independently identified delete aggregate after exact ledger recheck. + */ + private static function quotaExceededImportCleanupAllowed( + CloudUserIso $iso, + bool $lockForUpdate + ): bool { + $jobId = (int) ($iso->active_job_id ?? 0); + if ((string) $iso->state !== 'import_failed' || $jobId < 1) { + return false; + } + if (!self::activeJobSafelySettled($iso, $lockForUpdate)) { + return false; + } + $query = CloudJob::where('id', $jobId); + if ($lockForUpdate) { + $query->lockForUpdate(); + } + $parent = $query->first(); + if ($parent === null + || (string) $parent->kind !== 'user_iso_import' + || (string) $parent->execution_mode !== 'aggregate' + || (int) $parent->user_id !== (int) $iso->user_id + || (string) $parent->phase !== 'terminal' + || (string) $parent->outcome !== 'failed' + || (string) $parent->status !== 'failed' + || (string) $parent->effect_resolution !== 'applied' + || (bool) $parent->finalization_incident + || CloudJobService::aggregateParentRecoveryPending( + $parent, + null, + $lockForUpdate + )) { + return false; + } + try { + self::assertRecoveredReplicaProjectionLocked( + $iso, + $parent, + 'applied', + $lockForUpdate + ); + } catch (CloudError $error) { + return false; + } + return true; + } + private static function name($value): string { if (!is_string($value) || preg_match('//u', $value) !== 1) { diff --git a/web/app/Services/Cloud/CloudWorkerService.php b/web/app/Services/Cloud/CloudWorkerService.php index 0a1d5def..d74ee13a 100644 --- a/web/app/Services/Cloud/CloudWorkerService.php +++ b/web/app/Services/Cloud/CloudWorkerService.php @@ -120,16 +120,87 @@ final class CloudWorkerService public function tick(): bool { $this->observedErrors = []; + $quarantined = self::quarantineInvalidExecutionModeJob(); $expired = self::expireDueJobs(); // Deadline convergence is always first. Recovery inspection runs in // the dedicated --recovery-only worker, so this worker never waits on // an offline recovery target before dispatching ordinary work. - if ($this->tickJob()) { + if ($quarantined || $this->tickJob()) { return true; } return $expired > 0; } + /** + * Fail closed when a durable job's execution-domain discriminator is + * damaged. Reinterpreting a local row as an Agent mutation (or an + * aggregate parent as a leaf) could replay the original operation. Keep + * the immutable dispatch evidence and encrypted payload untouched, publish + * one sticky PHP-only incident, and let the recovery worker recheck it + * with bounded leases forever without contacting the Agent. + */ + private static function quarantineInvalidExecutionModeJob(): bool + { + return (new CloudJob())->getConnection()->transaction( + static function (): bool { + $job = CloudJob::where('phase', '<>', 'terminal') + ->where(static function ($invalid): void { + $invalid->where(static function ($leaf): void { + $leaf->whereIn( + 'kind', + CloudOperationRecoveryPolicy::kinds() + )->where(static function ($mode): void { + $mode->whereNull('execution_mode') + ->orWhere('execution_mode', '<>', 'agent'); + }); + })->orWhere(static function ($aggregate): void { + $aggregate->whereIn( + 'kind', + CloudJobService::aggregateKinds() + )->where(static function ($mode): void { + $mode->whereNull('execution_mode') + ->orWhere( + 'execution_mode', + '<>', + 'aggregate' + ); + }); + }); + }) + ->orderBy('id') + ->lockForUpdate() + ->first(); + if ($job === null) { + return false; + } + $now = time(); + $aggregate = CloudJobService::isAggregateKind( + (string) $job->kind + ); + $job->phase = 'terminal'; + $job->outcome = 'failed'; + $job->status = 'failed'; + $job->terminal_at = $now; + $job->effect_may_have_applied = 1; + $job->safe_to_resubmit = 0; + $job->effect_resolution = 'unknown'; + $job->error_code = $aggregate + ? 'recovery_aggregate_state_conflict' + : 'recovery_instance_state_conflict'; + $job->finalization_incident = 1; + $job->finalization_error_code = $job->error_code; + $job->read_at = null; + $job->lease_token = null; + $job->lease_until = 0; + $job->available_at = $now + 300; + $job->updated_at = $now; + $job->save(); + return true; + }, + 3 + ); + } + /** Claim and advance at most one durable cloud job. */ private function tickJob(): bool { @@ -137,7 +208,13 @@ final class CloudWorkerService $now = time(); $query = self::dispatchableBeforeDeadline( CloudJob::where('phase', 'accepted') - ->whereIn('execution_mode', ['agent', 'local']) + ->where(static function ($mode): void { + $mode->where('execution_mode', 'agent') + ->orWhere(static function ($local): void { + $local->where('execution_mode', 'local') + ->where('kind', 'payment_create'); + }); + }) ->where('dispatch_attempts', 0), $now )->where('available_at', '<=', $now) @@ -178,7 +255,7 @@ final class CloudWorkerService if (!$crossed) { $fresh = CloudJob::find((int) $job->id); $crossed = $fresh !== null - && (int) $fresh->dispatch_attempts === 1; + && CloudDispatchLedger::mayHaveDispatched($fresh); } self::forceTerminalFailure( (int) $job->id, @@ -310,6 +387,21 @@ final class CloudWorkerService if ($updated !== 1) { return true; } + // Keep the claimed model aligned with the successful CAS. The + // synchronous response is finalized through this same object; a + // stale dispatch_attempts=0 value would incorrectly classify a + // real Agent response as a local pre-dispatch failure and omit its + // immutable identity from the terminal payload. + $job->phase = 'dispatching'; + $job->status = 'running'; + $job->attempts = 1; + $job->dispatch_attempts = 1; + $job->dispatch_started_at = $now; + $job->dispatched_at = $now; + $job->receipt_deadline_at = $now + + CloudJobService::receiptDeadlineSeconds( + (string) $job->kind + ); CloudFirewallService::markJobRunning($job); $dispatched = true; $operation = self::operationForJob( @@ -394,7 +486,26 @@ final class CloudWorkerService $storageWindow = CloudJobService::dispatchDeadlineSeconds( 'host_storage_configure' ); - return $query->where('dispatch_deadline_at', '>', $now) + return $query->where(static function ($safe): void { + $safe->where(static function ($payment): void { + $payment->where('execution_mode', 'local') + ->where('kind', 'payment_create'); + })->orWhere(static function ($agent): void { + $agent->where('execution_mode', 'agent') + ->whereNotExists(static function ($events): void { + $events->selectRaw('1') + ->from( + 'cloud_agent_completion_events as dispatch_events' + )->whereColumn( + 'dispatch_events.host_id', + 'cloud_jobs.host_id' + )->whereColumn( + 'dispatch_events.operation_id', + 'cloud_jobs.operation_id' + ); + }); + }); + })->where('dispatch_deadline_at', '>', $now) ->where(static function ($eligible) use ( $now, $storageWindow ): void { @@ -559,6 +670,7 @@ final class CloudWorkerService $now, $storageDispatchWindow ): void { $deadline->where('dispatch_deadline_at', '<=', $now) + ->orWhereNull('dispatch_deadline_at') ->orWhere(static function ($storage) use ( $now, $storageDispatchWindow ): void { @@ -572,11 +684,15 @@ final class CloudWorkerService $now, $storageWindow ): void { $sent->whereIn('phase', ['dispatching', 'awaiting_receipt']) - ->whereNotNull('receipt_deadline_at') ->where(static function ($deadline) use ( $now, $storageWindow ): void { - $deadline->where('receipt_deadline_at', '<=', $now) + $deadline->where(static function ($due) use ( + $now + ): void { + $due->whereNotNull('receipt_deadline_at') + ->where('receipt_deadline_at', '<=', $now); + })->orWhereNull('receipt_deadline_at') ->orWhere(static function ($storage) use ( $now, $storageWindow ): void { @@ -604,7 +720,13 @@ final class CloudWorkerService ->limit(max(1, min(100, $limit)))->get(); $expired = 0; foreach ($rows as $row) { - $effect = (int) $row->dispatch_attempts === 1; + $dispatchConflict = CloudDispatchLedger::isInvalid($row); + $effect = CloudDispatchLedger::mayHaveDispatched($row); + $failureCode = $dispatchConflict + ? CloudDispatchLedger::CONFLICT_CODE + : ($effect + ? 'completion_deadline_exceeded' + : 'dispatch_deadline_exceeded'); $token = bin2hex(random_bytes(16)); $claim = CloudJob::where('id', (int) $row->id) ->where('phase', (string) $row->phase) @@ -628,8 +750,19 @@ final class CloudWorkerService $expired++; $claimed = CloudJob::find((int) $row->id); try { + if ($claimed !== null + && CloudDispatchLedger::isInvalid($claimed)) { + self::forceTerminalFailure( + (int) $row->id, + $token, + true, + false, + CloudDispatchLedger::CONFLICT_CODE + ); + continue; + } if ($claimed !== null && $claimed->host_id !== null - && (int) $claimed->dispatch_attempts === 1) { + && CloudDispatchLedger::isDispatched($claimed)) { $event = CloudOperationCompletionService::pendingForJob( $claimed ); @@ -667,17 +800,13 @@ final class CloudWorkerService ? self::createNotDispatchedFailure() : ['status' => 'failed']; $operation['operation_id'] = (string) $claimed->operation_id; - $operation['error_code'] = $effect - ? 'completion_deadline_exceeded' - : 'dispatch_deadline_exceeded'; + $operation['error_code'] = $failureCode; $operation['effect_may_have_applied'] = $effect; $operation['safe_to_resubmit'] = !$effect; (new self())->finish($claimed, $operation, $payload); } catch (\Throwable $error) { self::forceTerminalFailure((int) $row->id, $token, - $effect, !$effect, $effect - ? 'completion_deadline_exceeded' - : 'dispatch_deadline_exceeded'); + $effect, !$effect, $failureCode); } } return $expired; @@ -738,6 +867,12 @@ final class CloudWorkerService CloudOperationCompletionService::mark($event, 'rejected'); throw new CloudError('完成回执与任务不匹配', 409); } + if (CloudDispatchLedger::isInvalid($source)) { + CloudOperationCompletionService::deferDispatchLedgerConflict( + $source + ); + return CloudJob::find($jobId) ?? $source; + } if ((string) $source->phase === 'terminal') { if (CloudOperationCompletionService::settledTaskWithEvent( $source, @@ -871,8 +1006,31 @@ final class CloudWorkerService $claimed = CloudJob::where('id', $jobId) ->where('lease_token', $token)->where('phase', '<>', 'terminal') ->first(); - $recoveryEnvelope = ''; - if ($claimed !== null) { + $recoverableFinalizer = $claimed !== null + && CloudOperationRecoveryPolicy::supports( + (string) $claimed->kind + ); + $preserveRecoveryEnvelope = $recoverableFinalizer + || ($claimed !== null && (string) $claimed->kind === 'create'); + // Preserve the opaque escrow before attempting decryption. A temporary + // key/configuration failure is itself recoverable; replacing the only + // encrypted request with an empty string would make the PHP-only + // finalizer impossible to resume after the environment is repaired. + $recoveryEnvelope = $preserveRecoveryEnvelope + ? (string) $claimed->sealed_payload : ''; + $incidentCode = $code; + $dispatchConflict = $claimed !== null + && CloudDispatchLedger::isInvalid($claimed); + if ($dispatchConflict) { + // A corrupt counter can never prove non-dispatch. Do not invoke a + // normal success/not-applied finalizer or consume Agent evidence; + // preserve the encrypted escrow so repair can resume this exact + // operation without replaying it. + $effect = true; + $safe = false; + $code = CloudDispatchLedger::CONFLICT_CODE; + $recoveryEnvelope = (string) $claimed->sealed_payload; + } elseif ($claimed !== null) { try { if ((string) $claimed->execution_mode === 'aggregate') { if (!self::forceAggregateFailure($claimed, $token)) { @@ -894,20 +1052,50 @@ final class CloudWorkerService $paymentCode ); } else { - $payload = CloudSecrets::decrypt( - (string) $claimed->sealed_payload, 'job-payload' - ); - // Only instance settings has an audited recovery - // finalizer. Other kinds must not retain credentials or - // mutation bodies merely because their business - // finalizer failed. Invalid envelopes stay empty. - $recoveryEnvelope = (string) $claimed->kind - === 'instance_settings' - ? (string) $claimed->sealed_payload - : CloudSecrets::encrypt( - CloudInput::safeResult($payload), + try { + $payload = CloudSecrets::decrypt( + (string) $claimed->sealed_payload, + 'job-payload' + ); + } catch (\Throwable $error) { + throw new CloudRecoveryPayloadUnavailable( + '任务加密恢复数据暂时无法读取', + 409 + ); + } + // Every explicitly registered recovery kind retains its + // encrypted request until the exact Agent operation is + // reconciled. The recovery worker never re-dispatches + // this payload; it is needed only by PHP's existing + // kind-specific ledger finalizers. + if (CloudOperationRecoveryPolicy::supports( + (string) $claimed->kind + ) || (string) $claimed->kind === 'create') { + // An exact create success receipt can finish the paid + // order only while the encrypted wire request and + // credential escrow remain available. Keep it across + // a local finalizer crash just like policy recovery + // payloads; successful convergence scrubs it. + $recoveryEnvelope = (string) $claimed->sealed_payload; + } else { + $safePayload = CloudInput::safeResult($payload); + if (CloudDispatchLedger::isDispatched($claimed) + && CloudOperationRecoveryIdentity::supports( + (string) $claimed->kind + )) { + $identity = CloudOperationRecoveryIdentity:: + expectedFromPayload($claimed, $payload, false); + $safePayload[ + CloudOperationRecoveryIdentity::payloadKey() + ] = CloudOperationRecoveryIdentity::persisted( + $identity + ); + } + $recoveryEnvelope = CloudSecrets::encrypt( + $safePayload, 'job-payload' ); + } (new self())->finish($claimed, [ 'operation_id' => (string) $claimed->operation_id, 'status' => 'failed', @@ -922,6 +1110,9 @@ final class CloudWorkerService return; } } catch (\Throwable $finalizationError) { + $incidentCode = self::localFinalizationIncidentCode( + $finalizationError + ); error_log(sprintf( 'cloud task ledger finalization failed job_id=%d kind=%s error=%s', $jobId, @@ -986,23 +1177,61 @@ final class CloudWorkerService // failed. Retain a validated encrypted request only when it can support // later ledger recovery, retain every resource fence, and publish an // explicit durable incident for operators. + // Only policy kinds have the PHP-only retry path that can safely + // publish a known not-applied Agent effect while keeping the business + // ledger fenced. Aggregate/create/other special finalizers retain the + // older conservative unknown effect if their atomic fallback fails. + $neverDispatched = $recoverableFinalizer + && CloudDispatchLedger::isNeverDispatched($claimed); CloudJob::where('id', $jobId)->where('lease_token', $token) ->where('phase', '<>', 'terminal')->update([ 'phase' => 'terminal', 'outcome' => 'failed', 'status' => 'failed', 'terminal_at' => time(), - 'effect_may_have_applied' => 1, + 'effect_may_have_applied' => $neverDispatched ? 0 : 1, 'safe_to_resubmit' => 0, - 'effect_resolution' => 'unknown', - 'error_code' => 'local_finalization_failed', + 'effect_resolution' => $neverDispatched + ? 'not_applied' : 'unknown', + 'error_code' => $dispatchConflict + ? CloudDispatchLedger::CONFLICT_CODE + : 'local_finalization_failed', 'finalization_incident' => 1, - 'finalization_error_code' => substr($code, 0, 128), + 'finalization_error_code' => substr( + $dispatchConflict + ? CloudDispatchLedger::CONFLICT_CODE + : $incidentCode, + 0, + 128 + ), 'sealed_payload' => $recoveryEnvelope, 'lease_token' => null, - 'lease_until' => 0, 'available_at' => 0, + 'lease_until' => 0, + 'available_at' => ($dispatchConflict + || $recoverableFinalizer) ? time() + 300 : 0, 'updated_at' => time(), ]); } + private static function localFinalizationIncidentCode( + \Throwable $error + ): string { + return match (true) { + $error instanceof CloudRecoveryDispatchLedgerConflict => + CloudDispatchLedger::CONFLICT_CODE, + $error instanceof CloudRecoveryAggregateStateConflict => + 'recovery_aggregate_state_conflict', + $error instanceof CloudRecoveryPayloadUnavailable => + 'recovery_payload_unavailable', + $error instanceof CloudRecoveryOperationIdentityConflict => + 'recovery_operation_identity_conflict', + $error instanceof CloudRecoveryReceiptInvalid => + 'recovery_receipt_invalid', + $error instanceof CloudRecoveryInstanceStateConflict => + 'recovery_instance_state_conflict', + $error instanceof CloudError => 'recovery_ledger_conflict', + default => 'recovery_internal_error', + }; + } + /** Close aggregate children first, then atomically converge its catalog. */ private static function forceAggregateFailure(CloudJob $parent, string $token): bool @@ -1024,13 +1253,16 @@ final class CloudWorkerService 'lease_until' => time() + self::LEASE_SECONDS, 'updated_at' => time(), ]) === 1) { - $crossed = (int) $child->dispatch_attempts === 1; + $crossed = CloudDispatchLedger::mayHaveDispatched($child); + $failureCode = CloudDispatchLedger::isInvalid($child) + ? CloudDispatchLedger::CONFLICT_CODE + : 'aggregate_finalization_failed'; self::forceTerminalFailure( (int) $child->id, $childToken, $crossed, !$crossed, - 'aggregate_finalization_failed' + $failureCode ); } } @@ -1100,7 +1332,7 @@ final class CloudWorkerService ->where('phase', '<>', 'terminal')->orderBy('id')->get(); foreach ($children as $child) { if ($child->host_id !== null - && (int) $child->dispatch_attempts === 1) { + && CloudDispatchLedger::isDispatched($child)) { $event = CloudOperationCompletionService::pendingForJob( $child ); @@ -1137,9 +1369,12 @@ final class CloudWorkerService if ($claimed !== 1) { continue; } - $crossed = (int) $child->dispatch_attempts === 1; + $crossed = CloudDispatchLedger::mayHaveDispatched($child); + $failureCode = CloudDispatchLedger::isInvalid($child) + ? CloudDispatchLedger::CONFLICT_CODE + : 'aggregate_deadline_exceeded'; self::forceTerminalFailure((int) $child->id, $childToken, - $crossed, !$crossed, 'aggregate_deadline_exceeded'); + $crossed, !$crossed, $failureCode); } if (CloudJob::where('parent_job_id', (int) $parent->id) ->where('phase', '<>', 'terminal')->exists()) { @@ -1208,15 +1443,35 @@ final class CloudWorkerService '/^prepared:[a-z][a-z0-9_]{2,63}:[A-Za-z0-9_.-]{1,160}:[a-f0-9]{64}$/D', $marker ) === 1 || preg_match( - '/^automatic_recovery:v1:[1-9][0-9]{0,10}:([1-9]|1[0-2]):prepared:(?:automatic_(?:applied|not_applied)_(?:succeeded|failed)_(?:fence|nofence):[a-f0-9]{64}|late_completion_receipt:[A-Za-z0-9_.-]{1,160}):[a-f0-9]{64}$/D', + '/^automatic_recovery:v1:[1-9][0-9]{0,10}:[1-9][0-9]{0,9}:prepared:(?:automatic_(?:applied|not_applied)_(?:succeeded|failed)_(?:fence|nofence):[a-f0-9]{64}|late_completion_receipt:[A-Za-z0-9_.-]{1,160}):[a-f0-9]{64}$/D', $marker ) === 1; } + /** + * Return the immutable prepared-evidence binding without the mutable + * automatic retry counter. Older prepared envelopes stored the complete + * automatic marker, while new envelopes store only this stable suffix. + */ + private static function preparedRecoveryBinding(string $marker): ?string + { + if (preg_match( + '/^(?:automatic_recovery:v1:[1-9][0-9]{0,10}:' + . '[1-9][0-9]{0,9}:)?' + . '(prepared:[a-z][a-z0-9_]{2,63}:' + . '[A-Za-z0-9_.-]{1,160}:[a-f0-9]{64})$/D', + $marker, + $matches + ) !== 1) { + return null; + } + return $matches[1]; + } + private static function lateReceiptRecoveryMarker(string $marker): bool { return preg_match( - '/^(?:automatic_recovery:v1:[1-9][0-9]{0,10}:([1-9]|1[0-2]):)?prepared:late_completion_receipt:[A-Za-z0-9_.-]{1,160}:[a-f0-9]{64}$/D', + '/^(?:automatic_recovery:v1:[1-9][0-9]{0,10}:[1-9][0-9]{0,9}:)?prepared:late_completion_receipt:[A-Za-z0-9_.-]{1,160}:[a-f0-9]{64}$/D', $marker ) === 1; } @@ -1230,7 +1485,7 @@ final class CloudWorkerService return true; } if (preg_match( - '/^automatic_recovery:v1:[1-9][0-9]{0,10}:([1-9]|1[0-2]):pending$/D', + '/^automatic_recovery:v1:[1-9][0-9]{0,10}:[1-9][0-9]{0,9}:pending$/D', $current ) === 1) { if (preg_match( @@ -1250,7 +1505,7 @@ final class CloudWorkerService } if (preg_match( '/^automatic_recovery:v1:[1-9][0-9]{0,10}:' - . '([1-9]|1[0-2]):prepared:automatic_' + . '[1-9][0-9]{0,9}:prepared:automatic_' . '(applied|not_applied)_(succeeded|failed)' . '_(fence|nofence):[a-f0-9]{64}:([a-f0-9]{64})$/D', $current, @@ -1265,13 +1520,13 @@ final class CloudWorkerService ) !== 1) { return false; } - return $existing[4] === 'nofence' - && hash_equals($existing[5], $late[1]) - && (($existing[2] === 'applied' - && $existing[3] === 'succeeded' + return $existing[3] === 'nofence' + && hash_equals($existing[4], $late[1]) + && (($existing[1] === 'applied' + && $existing[2] === 'succeeded' && ($operation['status'] ?? null) === 'succeeded') - || ($existing[2] === 'not_applied' - && $existing[3] === 'failed' + || ($existing[1] === 'not_applied' + && $existing[2] === 'failed' && ($operation['status'] ?? null) === 'failed')); } @@ -1288,16 +1543,16 @@ final class CloudWorkerService } /** - * Validate PHP's encrypted settings intent before recovery evidence can - * affect ledgers. Both live inspection and immutable receipt recovery use - * this exact contract so neither path can silently finalize an empty or - * damaged escrow. + * Validate the common immutable job envelope used by every automatic + * recovery strategy. Kind-specific business validation remains in + * finish(), which is the one authoritative ledger finalizer. * - * @return array{instance:CloudInstance,payload:array,body:array,fields:array} + * @return array{payload:array,instance:?CloudInstance} */ - public static function settingsRecoveryContext(CloudJob $job): array + public static function recoveryContext(CloudJob $job): array { - if ((string) $job->kind !== 'instance_settings' + CloudDispatchLedger::assertValid($job); + if (!CloudOperationRecoveryPolicy::supports((string) $job->kind) || (string) $job->execution_mode !== 'agent' || (string) $job->phase !== 'terminal' || (string) $job->outcome !== 'failed' @@ -1306,23 +1561,127 @@ final class CloudWorkerService || !(bool) $job->effect_may_have_applied || (bool) $job->safe_to_resubmit || (string) $job->effect_resolution !== 'unknown') { + throw new CloudRecoveryInstanceStateConflict( + '任务不处于可自动核对状态', + 409 + ); + } + if (!is_string($job->operation_id) + || preg_match('/^[a-f0-9]{32}$/D', $job->operation_id) !== 1) { + throw new CloudRecoveryOperationIdentityConflict( + '任务缺少合法的 Agent 操作标识', + 409 + ); + } + if ((int) $job->host_id < 1 + || $job->dispatched_at === null + || (int) $job->dispatched_at < 1) { + throw new CloudRecoveryInstanceStateConflict( + '任务缺少宿主机或派发时间', + 409 + ); + } + try { + $payload = CloudSecrets::decrypt( + (string) $job->sealed_payload, + 'job-payload' + ); + } catch (\Throwable $error) { + throw new CloudRecoveryPayloadUnavailable( + '任务恢复数据无法解密', + 409 + ); + } + if (!is_array($payload) || array_is_list($payload)) { + throw new CloudRecoveryPayloadUnavailable( + '任务恢复数据结构不完整', + 409 + ); + } + $instance = null; + if ($job->instance_id !== null) { + $instance = CloudInstance::find((int) $job->instance_id); + if ($instance === null + || (int) $instance->host_id !== (int) $job->host_id + || !is_string($instance->uuid) + || preg_match( + '/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/D', + strtolower((string) $instance->uuid) + ) !== 1) { + throw new CloudRecoveryInstanceStateConflict( + '任务与实例账本不匹配', + 409 + ); + } + } + return compact('payload', 'instance'); + } + + /** + * Return the exact normalized operation durably stored with a prepared + * recovery. This is encrypted at rest and bound to both kind and marker. + */ + public static function preparedRecoveryOperation(CloudJob $job): ?array + { + $context = self::recoveryContext($job); + $envelope = $context['payload']['_operation_recovery'] ?? null; + if ($envelope === null) { + return null; + } + $operation = is_array($envelope) + ? ($envelope['operation'] ?? null) : null; + $storedMarker = is_array($envelope) + && is_string($envelope['prepared_marker'] ?? null) + ? self::preparedRecoveryBinding($envelope['prepared_marker']) + : null; + $currentMarker = self::preparedRecoveryBinding( + (string) $job->effect_resolution_reason + ); + if (!is_array($envelope) || array_is_list($envelope) + || array_diff(array_keys($envelope), [ + 'version', 'kind', 'prepared_marker', 'operation', + ]) !== [] + || ($envelope['version'] ?? null) !== 1 + || ($envelope['kind'] ?? null) !== (string) $job->kind + || $storedMarker === null || $currentMarker === null + || !hash_equals($currentMarker, $storedMarker) + || !is_array($operation) || array_is_list($operation) + || ($operation['operation_id'] ?? null) + !== (string) $job->operation_id + || !in_array($operation['status'] ?? null, + ['succeeded', 'failed'], true)) { + throw new CloudRecoveryPayloadUnavailable( + '任务预提交恢复数据不完整', + 409 + ); + } + return $operation; + } + + /** + * Validate PHP's encrypted settings intent before recovery evidence can + * affect ledgers. Both live inspection and immutable receipt recovery use + * this exact contract so neither path can silently finalize an empty or + * damaged escrow. + * + * @return array{instance:CloudInstance,payload:array,body:array,fields:array} + */ + public static function settingsRecoveryContext(CloudJob $job): array + { + if ((string) $job->kind !== 'instance_settings') { throw new CloudError('任务不处于可自动核对状态', 409); } - $instance = CloudInstance::find((int) $job->instance_id); + $context = self::recoveryContext($job); + $instance = $context['instance']; if ($instance === null || (string) $instance->status === 'deleted' - || (int) $instance->host_id !== (int) $job->host_id - || !is_string($instance->uuid) - || preg_match( - '/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/D', - strtolower((string) $instance->uuid) - ) !== 1) { - throw new CloudError('任务与实例账本不匹配', 409); - } - $payload = CloudSecrets::decrypt( - (string) $job->sealed_payload, - 'job-payload' - ); + ) { + throw new CloudRecoveryInstanceStateConflict( + '任务与实例账本不匹配', + 409 + ); + } + $payload = $context['payload']; $body = $payload['body'] ?? null; $allowedBody = [ 'hostname', 'root_password', 'ssh_public_key', @@ -1452,15 +1811,126 @@ final class CloudWorkerService if ($job === null) { throw new CloudError('任务不存在', 404); } - if ((string) $job->kind !== 'instance_settings') { + if (!CloudOperationRecoveryPolicy::supports((string) $job->kind)) { throw new CloudError('任务类型不支持自动效果恢复', 409); } - $context = self::settingsRecoveryContext($job); + $context = (string) $job->kind === 'instance_settings' + ? self::settingsRecoveryContext($job) + : self::recoveryContext($job); $payload = $context['payload']; $normalized = self::normalizeAgentOperation( self::operationForJob($job, $operation) ); - $this->finish($job, $normalized, $payload, $preparedMarker); + try { + $this->finish($job, $normalized, $payload, $preparedMarker); + } catch (CloudRecoveryPayloadUnavailable + | CloudRecoveryEvidenceConflict + | CloudRecoveryReceiptInvalid + | CloudRecoveryOperationIdentityConflict + | CloudRecoveryAggregateStateConflict + | CloudRecoveryInstanceStateConflict $error) { + throw $error; + } catch (CloudError $error) { + if ($job->instance_id !== null) { + throw new CloudRecoveryInstanceStateConflict( + '实例或关联资源账本与原任务证据不一致', + 409 + ); + } + throw $error; + } + return CloudJob::find($jobId) ?? $job; + } + + /** + * Materialize one paid create from its exact immutable success receipt. + * + * This is deliberately not part of the generic recovery policy: it never + * inspects or replays an Agent mutation. The original failed task remains + * terminal for audit, while its create ledgers and receipt ACK commit as + * one local database transaction. + */ + public function settleRecoveredCreateCompletion( + int $jobId, + \App\Models\CloudAgentCompletionEvent $event + ): CloudJob { + $job = CloudJob::find($jobId); + if ($job === null) { + throw new CloudError('任务不存在', 404); + } + if ((string) $job->kind !== 'create') { + throw new CloudError('任务类型不支持开通回执恢复', 409); + } + try { + $payload = CloudSecrets::decrypt( + (string) $job->sealed_payload, + 'job-payload' + ); + } catch (\Throwable $error) { + throw new CloudRecoveryPayloadUnavailable( + '任务加密恢复数据暂时无法读取', + 409 + ); + } + $operation = self::normalizeAgentOperation( + self::operationForJob( + $job, + CloudOperationCompletionService::operation($event) + ) + ); + $this->finish( + $job, + $operation, + $payload, + null, + (string) $event->event_id + ); + return CloudJob::find($jobId) ?? $job; + } + + /** + * Retry only the PHP ledger finalizer for a generation proven never sent. + * The terminal task receipt remains immutable and no Agent request occurs. + */ + public function retryUndispatchedFinalization( + int $jobId, + string $leaseToken + ): CloudJob { + $job = CloudJob::find($jobId); + if ($job === null) { + throw new CloudError('任务不存在', 404); + } + try { + $payload = CloudSecrets::decrypt( + (string) $job->sealed_payload, + 'job-payload' + ); + } catch (\Throwable $error) { + throw new CloudRecoveryPayloadUnavailable( + '任务恢复数据无法解密', + 409 + ); + } + if (!is_array($payload) || array_is_list($payload)) { + throw new CloudRecoveryPayloadUnavailable( + '任务恢复数据结构不完整', + 409 + ); + } + $this->finish( + $job, + [ + 'operation_id' => (string) $job->operation_id, + 'status' => 'failed', + 'error_code' => 'dispatch_not_sent', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => true, + ], + $payload, + null, + null, + $leaseToken + ); return CloudJob::find($jobId) ?? $job; } @@ -1468,9 +1938,14 @@ final class CloudWorkerService CloudJob $claimed, array $operation, array $payload, - ?string $preparedRecoveryMarker = null + ?string $preparedRecoveryMarker = null, + ?string $recoveredCreateEventId = null, + ?string $localFinalizerToken = null ): void { + if ((string) $claimed->execution_mode === 'agent') { + CloudDispatchLedger::assertValid($claimed); + } $operation['operation_id'] = $operation['operation_id'] ?? (string) $claimed->operation_id; $status = self::disposition($operation, $claimed->kind === 'create', @@ -1478,6 +1953,27 @@ final class CloudWorkerService if (!in_array($status, ['succeeded', 'failed'], true)) { throw new CloudError('任务尚未取得终态回执', 409); } + $operationIdentity = null; + // The Agent triple exists only after the immutable mutation crossed + // the dispatch boundary. A locally rejected, never-dispatched task is + // already proven not-applied and must still reach its kind finalizer; + // requiring an Agent identity there would turn damaged local input + // into an unnecessary unknown-effect fence. + if (CloudDispatchLedger::isDispatched($claimed) + && CloudOperationRecoveryIdentity::supports( + (string) $claimed->kind + )) { + $operationIdentity = CloudOperationRecoveryIdentity:: + expectedFromPayload( + $claimed, + $payload, + $status === 'succeeded' + ); + $payload[CloudOperationRecoveryIdentity::payloadKey()] = + CloudOperationRecoveryIdentity::persisted( + $operationIdentity + ); + } if ($status === 'succeeded' && in_array((string) $claimed->kind, ['delete', 'expiry_delete', 'delete_force'], true) @@ -1529,15 +2025,131 @@ final class CloudWorkerService $resourceStatus = $status === 'failed' && $effectMayHaveApplied ? 'uncertain' : $status; $result = $operation['result'] ?? null; - (new CloudJob())->getConnection()->transaction(function () use ($claimed, $payload, $status, $resourceStatus, $effectMayHaveApplied, $safeToResubmit, $forceRequired, $result, $operation, $preparedRecoveryMarker) { + $aggregateParentId = (int) ($claimed->parent_job_id ?? 0); + (new CloudJob())->getConnection()->transaction(function () use ($claimed, $payload, $status, $resourceStatus, $effectMayHaveApplied, $safeToResubmit, $forceRequired, $result, $operation, $preparedRecoveryMarker, $operationIdentity, $recoveredCreateEventId, $localFinalizerToken, $aggregateParentId) { // All financial transactions acquire the wallet first, avoiding wallet/order deadlocks. $user = User::where('id', $claimed->user_id)->lockForUpdate()->first(); $order = $claimed->order_id === null ? null : CloudOrder::where('id', $claimed->order_id)->lockForUpdate()->first(); + // Aggregate recovery and the legacy sweep both use the same + // parent -> children lock order. Never lock a leaf first and then + // wait for its parent: concurrent sibling completions otherwise + // form a deadlock cycle with the parent-led sweep. + if ($aggregateParentId > 0) { + $aggregateParent = CloudJob::where('id', $aggregateParentId) + ->lockForUpdate()->first(); + if ($aggregateParent === null) { + throw new CloudRecoveryAggregateStateConflict( + '任务的汇总父任务不存在', + 409 + ); + } + CloudTemplateCatalogService::lockAggregateCatalogLocked( + $aggregateParent + ); + CloudUserIsoService::lockAggregateCatalogLocked( + $aggregateParent + ); + } $job = CloudJob::where('id', $claimed->id)->lockForUpdate()->first(); if ($job === null) { throw new CloudError('任务不存在', 404); } - if ($preparedRecoveryMarker !== null) { + if ((string) $job->execution_mode === 'agent') { + CloudDispatchLedger::assertValid($job); + if (CloudDispatchLedger::attempts($job) + !== CloudDispatchLedger::attempts($claimed)) { + throw new CloudRecoveryDispatchLedgerConflict( + '任务单次派发代次在收敛期间发生变化', + 409 + ); + } + } + if ((int) ($job->parent_job_id ?? 0) !== $aggregateParentId) { + throw new CloudRecoveryAggregateStateConflict( + '任务的汇总父级关系在收敛期间发生变化', + 409 + ); + } + $localFinalizerRecovery = $localFinalizerToken !== null; + if ($localFinalizerRecovery + && (!CloudOperationRecoveryPolicy::supports( + (string) $job->kind + ) + || (string) $job->execution_mode !== 'agent' + || (string) $job->phase !== 'terminal' + || (string) $job->outcome !== 'failed' + || (string) $job->status !== 'failed' + || !CloudDispatchLedger::isNeverDispatched($job) + || !(bool) $job->finalization_incident + || !in_array((string) $job->effect_resolution, + ['unknown', 'not_applied'], true) + || !is_string($job->lease_token) + || !hash_equals( + (string) $job->lease_token, + $localFinalizerToken + ))) { + throw new CloudError( + '任务不处于可恢复的本地收尾状态', + 409 + ); + } + if ($localFinalizerRecovery) { + if (CloudDispatchLedger::hasRepairIncident($job)) { + throw new CloudRecoveryInstanceStateConflict( + '任务仍处于派发账本修复状态', + 409 + ); + } + CloudOperationCompletionService:: + assertNeverDispatchedRecoveryState($job); + } + $recoveredCreateEvent = null; + if ($recoveredCreateEventId !== null) { + $recoveredCreateEvent = \App\Models\CloudAgentCompletionEvent::where( + 'event_id', + $recoveredCreateEventId + )->lockForUpdate()->first(); + if ($preparedRecoveryMarker !== null + || (string) $job->kind !== 'create' + || (string) $job->execution_mode !== 'agent' + || (string) $job->phase !== 'terminal' + || (string) $job->outcome !== 'failed' + || (string) $job->status !== 'failed' + || (int) $job->dispatch_attempts !== 1 + || !(bool) $job->effect_may_have_applied + || (bool) $job->safe_to_resubmit + || (string) $job->effect_resolution !== 'unknown' + || $job->order_id === null + || $order === null + || $operationIdentity === null + || $recoveredCreateEvent === null + || (string) $recoveredCreateEvent->disposition !== 'received' + || (int) $recoveredCreateEvent->host_id + !== (int) $job->host_id + || !hash_equals( + (string) $job->operation_id, + (string) $recoveredCreateEvent->operation_id + ) + || (string) $recoveredCreateEvent->outcome !== 'succeeded' + || (bool) $recoveredCreateEvent->effect_may_have_applied + || (bool) $recoveredCreateEvent->safe_to_resubmit + || !CloudOperationCompletionService::isExactStoredEvent( + $recoveredCreateEvent + )) { + throw new CloudError( + '开通完成回执不处于可安全收敛状态', + 409 + ); + } + $lockedIdentity = CloudOperationRecoveryIdentity:: + expectedFromPayload($job, $payload, true); + CloudOperationRecoveryIdentity::assertMatches( + $lockedIdentity, + CloudOperationCompletionService::identity( + $recoveredCreateEvent + ) + ); + } elseif ($preparedRecoveryMarker !== null) { CloudOperationRecoveryService:: assertRecoveryIncidentAllowsPrepare($job); if ((string) $job->phase !== 'terminal' @@ -1584,8 +2196,9 @@ final class CloudWorkerService } return; } - } elseif ($job->lease_token !== $claimed->lease_token - || (string) $job->phase === 'terminal') { + } elseif (!$localFinalizerRecovery + && ($job->lease_token !== $claimed->lease_token + || (string) $job->phase === 'terminal')) { return; } $safe = is_array($result) @@ -1608,16 +2221,20 @@ final class CloudWorkerService // replica rows and aggregate parent are settled in this same // transaction as the child job. CloudTemplateCatalogService::finishJobLocked( - $job, $status, $result, $payload, $operation + $job, $status, $result, $payload, $operation, + $preparedRecoveryMarker !== null || $localFinalizerRecovery ); CloudUserIsoService::finishJobLocked( - $job, $status, $result, $payload, $operation + $job, $status, $result, $payload, $operation, + $preparedRecoveryMarker !== null || $localFinalizerRecovery ); CloudRescueTemplateImportService::finishJobLocked( - $job, $status, $result, $operation + $job, $status, $result, $operation, + $preparedRecoveryMarker !== null || $localFinalizerRecovery ); CloudRescueTemplateDeletionService::finishJobLocked( - $job, $status, $result, $operation + $job, $status, $result, $operation, + $preparedRecoveryMarker !== null || $localFinalizerRecovery ); CloudHostStorageConfigurationService::finishJobLocked( $job, $status, $result, $operation @@ -1706,6 +2323,11 @@ final class CloudWorkerService $vm = is_array($result) ? ($result['vm'] ?? $result) : []; $uuid = $vm['uuid'] ?? ''; if ($order === null || !is_string($uuid) + || $operationIdentity === null + || !hash_equals( + (string) $operationIdentity['resource_id'], + strtolower($uuid) + ) || preg_match('/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iD', $uuid) !== 1) { throw new CloudError('Agent 成功结果缺少虚拟机标识', 502); } @@ -1733,6 +2355,73 @@ final class CloudWorkerService 'Agent 成功结果与预留公网 IP 不一致,必须人工核查', 502 ); } + $provisionInvoice = CloudInvoice::where( + 'order_id', + (int) $order->id + )->lockForUpdate()->first(); + $reservation = $order->reservation_id === null ? null + : \App\Models\CloudResourceReservation::where( + 'id', + (int) $order->reservation_id + )->lockForUpdate()->first(); + $publicIp = $reservation === null + || $reservation->public_ip_id === null ? null + : \App\Models\CloudPublicIp::where( + 'id', + (int) $reservation->public_ip_id + )->lockForUpdate()->first(); + if (!in_array((string) $order->status, + ['queued', 'failed', 'uncertain'], true) + || $order->refunded_at !== null + || $order->stock_reserved_at === null + || $order->stock_released_at !== null + || $order->instance_id !== null + || $provisionInvoice === null + || (string) $provisionInvoice->purpose !== 'provision' + || (string) $provisionInvoice->status !== 'paid' + || $provisionInvoice->paid_at === null + || (int) $provisionInvoice->order_id !== (int) $order->id + || (int) $provisionInvoice->user_id !== (int) $order->user_id + || (int) $provisionInvoice->plan_id !== (int) $order->plan_id + || (int) $provisionInvoice->offer_id !== (int) $order->offer_id + || strtoupper((string) $provisionInvoice->currency) + !== strtoupper((string) $order->currency) + || CloudMoney::cents((string) $provisionInvoice->amount) + !== CloudMoney::cents((string) $order->amount) + || $reservation === null + || (int) $reservation->order_id !== (int) $order->id + || (int) $reservation->user_id !== (int) $order->user_id + || (int) $reservation->offer_id !== (int) $order->offer_id + || (int) $reservation->resource_pool_id + !== (int) $order->resource_pool_id + || (int) $reservation->host_id !== (int) $order->host_id + || !hash_equals( + (string) $job->operation_id, + (string) $reservation->operation_id + ) + || !in_array((string) $reservation->state, + ['held', 'uncertain'], true) + || $reservation->instance_id !== null + || $publicIp === null + || (int) $publicIp->host_id !== (int) $reservation->host_id + || (int) ($publicIp->reservation_id ?? 0) + !== (int) $reservation->id + || !hash_equals( + (string) $reservation->operation_id, + (string) ($publicIp->operation_id ?? '') + ) + || !in_array((string) $publicIp->state, + ['reserved', 'uncertain'], true) + || !hash_equals( + (string) $publicIp->address . '/' + . (int) $publicIp->prefix_length, + $confirmedPublicIpCidr + )) { + throw new CloudRecoveryInstanceStateConflict( + '开通成功回执与资金、库存或资源预留账本不一致', + 409 + ); + } $instance = CloudInstance::where('order_id', $order->id)->first(); $newInstance = $instance === null; $instance ??= new CloudInstance(); @@ -1838,17 +2527,12 @@ final class CloudWorkerService $instance->current_period_id = $period->id; $instance->save(); $job->instance_id = $order->instance_id = $instance->id; - $provisionInvoice = CloudInvoice::where('order_id', $order->id) - ->lockForUpdate()->first(); - if ($provisionInvoice !== null - && (string) $provisionInvoice->purpose === 'provision') { - $provisionInvoice->instance_id = $instance->id; - $provisionInvoice->updated_at = time(); - $provisionInvoice->save(); - CloudInvoiceService::queueProvisionSucceeded( - $provisionInvoice, $now - ); - } + $provisionInvoice->instance_id = $instance->id; + $provisionInvoice->updated_at = time(); + $provisionInvoice->save(); + CloudInvoiceService::queueProvisionSucceeded( + $provisionInvoice, $now + ); $safe = $safe ?? []; $safe['id'] = (string) $instance->id; $safe['uuid'] = $uuid; @@ -1857,47 +2541,48 @@ final class CloudWorkerService && $status === 'succeeded') { $instance = CloudInstance::where('id', $job->instance_id) ->lockForUpdate()->first(); - if ($instance !== null) { - if (isset($payload['credential']) - && is_array($payload['credential'])) { - $instance->sealed_credential = CloudSecrets::encrypt( - $payload['credential'], 'instance-credential' - ); - } + if ($instance === null) { + throw new CloudRecoveryInstanceStateConflict( + '重装任务关联实例已缺失', + 409 + ); + } + $instance->sealed_credential = CloudSecrets::encrypt( + $payload['credential'], 'instance-credential' + ); // Once the Agent proves the replacement guest committed, // its credential and template snapshot supersede the old // guest even if deletion of the old volume still requires // operator review. The task still ends as failed. - $decoded = json_decode((string) $instance->spec_json, true); - if (is_array($decoded) && !array_is_list($decoded)) { - $templateMetadata = - self::trustedTemplateMetadata($payload); - $templateId = is_array($payload['body'] ?? null) - ? ($payload['body']['template_id'] ?? null) : null; - if (is_string($templateId) - && preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/D', - $templateId) === 1) { - $decoded['template_id'] = $templateId; - } - $decoded = array_replace( - $decoded, - $templateMetadata - ); - unset($decoded['install_iso']); - $decoded['managed'] = true; - // Force one fresh capacity/IP observation while the - // trusted PHP presentation snapshot remains usable. - unset($decoded['agent_metadata_version']); - $instance->spec_json = json_encode($decoded, - JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES - | JSON_UNESCAPED_UNICODE); - } - self::recordRuntime($instance, - is_array($result) ? $result : [], - (string) $job->kind, $payload); - $instance->updated_at = time(); - $instance->save(); + $decoded = json_decode((string) $instance->spec_json, true); + if (!is_array($decoded) || array_is_list($decoded)) { + throw new CloudRecoveryInstanceStateConflict( + '重装任务关联实例配置账本损坏', + 409 + ); + } + $templateMetadata = self::trustedTemplateMetadata($payload); + $templateId = is_array($payload['body'] ?? null) + ? ($payload['body']['template_id'] ?? null) : null; + if (is_string($templateId) + && preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/D', + $templateId) === 1) { + $decoded['template_id'] = $templateId; } + $decoded = array_replace($decoded, $templateMetadata); + unset($decoded['install_iso']); + $decoded['managed'] = true; + // Force one fresh capacity/IP observation while the trusted + // PHP presentation snapshot remains usable. + unset($decoded['agent_metadata_version']); + $instance->spec_json = json_encode($decoded, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + | JSON_UNESCAPED_UNICODE); + self::recordRuntime($instance, + is_array($result) ? $result : [], + (string) $job->kind, $payload); + $instance->updated_at = time(); + $instance->save(); } elseif ($status === 'failed' && !$effectMayHaveApplied && $job->kind === 'create' && $order !== null) { if ($user === null) { @@ -1912,11 +2597,26 @@ final class CloudWorkerService } elseif ($forceRequired && $job->instance_id !== null) { $instance = CloudInstance::where('id', $job->instance_id) ->lockForUpdate()->first(); - if ($instance !== null - && (string) $instance->status === 'deleting') { + if ($instance === null) { + throw new CloudRecoveryInstanceStateConflict( + '删除任务关联实例已缺失', 409 + ); + } + if ((string) $job->kind === 'delete' + && (string) $instance->status === 'active') { + // A tenant graceful-delete request deliberately leaves the + // live instance unchanged when the Agent requires a new, + // separately authorized force-delete generation. + } elseif ((string) $instance->status === 'deleting') { $instance->service_status = 'purge_force_required'; $instance->updated_at = time(); $instance->save(); + } elseif ((string) $instance->service_status + !== 'purge_force_required') { + throw new CloudRecoveryInstanceStateConflict( + '删除任务的实例状态与强制阶段矛盾', + 409 + ); } } elseif ($status === 'failed' && $job->kind === 'expiry_delete' && $job->instance_id !== null) { @@ -1934,12 +2634,28 @@ final class CloudWorkerService // Latch a visible policy failure. This generation is never // queued again automatically. $instance = CloudInstance::where('id', $job->instance_id)->lockForUpdate()->first(); - if ($instance !== null) { - $expected = [ - 'service_suspend' => ['suspending_expired', 'purge_stopping'], - 'network_suspend' => ['blocking', 'blocking_expired'], - 'network_resume' => ['restore_pending', 'restoring'], - ][$job->kind]; + if ($instance === null) { + throw new CloudRecoveryInstanceStateConflict( + '系统策略任务关联实例已缺失', 409 + ); + } + $expected = [ + 'service_suspend' => ['suspending_expired', 'purge_stopping'], + 'network_suspend' => ['blocking', 'blocking_expired'], + 'network_resume' => ['restore_pending', 'restoring'], + ][$job->kind]; + $already = match ((string) $job->kind) { + 'service_suspend' => in_array( + (string) $instance->service_status, + ['suspend_failed', 'purge_stop_failed'], true + ), + 'network_suspend' => (string) $instance->network_status + === 'block_failed', + 'network_resume' => (string) $instance->network_status + === 'restore_failed', + default => false, + }; + $transitioned = false; if ($job->kind === 'service_suspend' && in_array((string) $instance->service_status, $expected, true)) { if ((string) $instance->status === 'deleting' @@ -1950,19 +2666,31 @@ final class CloudWorkerService } else { $instance->service_status = 'suspend_failed'; } + $transitioned = true; } elseif ($job->kind === 'network_suspend' && in_array((string) $instance->network_status, $expected, true)) { $instance->network_status = 'block_failed'; + $transitioned = true; } elseif ($job->kind === 'network_resume' && in_array((string) $instance->network_status, $expected, true)) { $instance->network_status = 'restore_failed'; + $transitioned = true; } + if (!$transitioned && !$already) { + throw new CloudRecoveryInstanceStateConflict( + '系统策略失败结论与实例当前状态矛盾', + 409 + ); + } $instance->updated_at = time(); $instance->save(); - } } elseif ($status === 'succeeded' && $job->instance_id !== null) { $instance = CloudInstance::where('id', $job->instance_id)->lockForUpdate()->first(); - if ($instance !== null) { + if ($instance === null) { + throw new CloudRecoveryInstanceStateConflict( + '任务成功结论的关联实例已缺失', 409 + ); + } if (in_array((string) $job->kind, ['delete', 'expiry_delete', 'delete_force'], true)) { $instance->status = 'deleted'; @@ -2019,25 +2747,62 @@ final class CloudWorkerService | JSON_UNESCAPED_UNICODE); } elseif ($job->kind === 'service_suspend' && in_array((string) $instance->service_status, - ['purge_stopping', 'purge_force_required'], true)) { + array_merge( + ['purge_stopping', 'purge_force_required'], + $preparedRecoveryMarker === null + ? [] : ['purge_stop_failed', 'suspend_failed'] + ), true)) { if ((string) $instance->status === 'deleting' && in_array((string) $instance->service_status, - ['purge_stopping', 'purge_force_required'], true)) { - // Only the Agent's active terminal receipt can - // advance expiry cleanup; read-only inspection - // never settles or reopens a timed-out task. + [ + 'purge_stopping', 'purge_force_required', + 'purge_stop_failed', + ], true)) { $instance->service_status = 'purge_deleting'; + } elseif ((string) $instance->service_status + === 'suspend_failed') { + $instance->service_status = 'suspended_expired'; + $instance->suspended_at = time(); } + } elseif ($job->kind === 'service_suspend' + && !in_array((string) $instance->service_status, + ['suspended_expired', 'purge_deleting'], true)) { + throw new CloudRecoveryInstanceStateConflict( + '服务暂停成功结论与实例状态矛盾', + 409 + ); } elseif ($job->kind === 'network_suspend' && in_array((string) $instance->network_status, - ['blocking', 'blocking_expired'], true)) { + array_merge( + ['blocking', 'blocking_expired'], + $preparedRecoveryMarker === null + ? [] : ['block_failed'] + ), true)) { $instance->network_status = ($payload['suspend_reason'] ?? '') === 'expired' ? 'blocked_expired' : 'blocked_traffic'; $instance->network_suspended_at = time(); + } elseif ($job->kind === 'network_suspend' + && !in_array((string) $instance->network_status, + ['blocked_expired', 'blocked_traffic'], true)) { + throw new CloudRecoveryInstanceStateConflict( + '网络暂停成功结论与实例状态矛盾', + 409 + ); } elseif ($job->kind === 'network_resume' - && in_array((string) $instance->network_status, ['restoring', 'restore_pending'], true)) { + && in_array((string) $instance->network_status, + array_merge( + ['restoring', 'restore_pending'], + $preparedRecoveryMarker === null + ? [] : ['restore_failed'] + ), true)) { $instance->network_status = 'active'; $instance->network_suspended_at = null; + } elseif ($job->kind === 'network_resume' + && (string) $instance->network_status !== 'active') { + throw new CloudRecoveryInstanceStateConflict( + '网络恢复成功结论与实例状态矛盾', + 409 + ); } // Successful power/reinstall/policy operations often // include the resulting VM state. Persist that bounded @@ -2047,14 +2812,122 @@ final class CloudWorkerService (string) $job->kind, $payload); $instance->updated_at = time(); $instance->save(); - } + } + if ($localFinalizerRecovery) { + // The kind-specific projection above is the only work being + // retried. Preserve the original terminal receipt audit + // (phase/outcome/status/terminal_at/error/result/event) and + // update only the independently recoverable effect ledger. + $now = time(); + $job->effect_may_have_applied = 0; + $job->safe_to_resubmit = 1; + $job->effect_resolution = 'not_applied'; + $job->effect_resolved_at = $now; + $job->effect_resolved_by = null; + $job->effect_resolution_reason = + 'automatic_local_not_dispatched'; + $job->sealed_payload = CloudSecrets::encrypt( + CloudInput::safeResult($payload), + 'job-payload' + ); + $job->finalization_incident = 0; + $job->finalization_error_code = null; + $job->read_at = null; + $job->lease_token = null; + $job->lease_until = 0; + $job->available_at = 0; + $job->updated_at = $now; + $job->save(); + CloudJobService::reconcileAggregateParentEffectLocked( + $job, + null + ); + return; + } + if ($recoveredCreateEvent !== null) { + $now = time(); + $safePayload = CloudInput::safeResult($payload); + $safePayload[CloudOperationRecoveryIdentity::payloadKey()] = + CloudOperationRecoveryIdentity::persisted( + $operationIdentity + ); + $job->completion_event_id = + (string) $recoveredCreateEvent->event_id; + $job->effect_resolution = 'applied'; + $job->effect_resolved_at = $now; + $job->effect_resolved_by = null; + $job->effect_resolution_reason = + 'late_completion_receipt:' + . (string) $recoveredCreateEvent->event_id; + $job->sealed_payload = CloudSecrets::encrypt( + $safePayload, + 'job-payload' + ); + $job->result_json = $safe === null ? null : json_encode( + $safe, + JSON_THROW_ON_ERROR + ); + $job->finalization_incident = 0; + $job->finalization_error_code = null; + $job->read_at = null; + $job->lease_token = null; + $job->lease_until = 0; + $job->available_at = 0; + $job->updated_at = $now; + $job->save(); + $order->status = 'succeeded'; + $order->updated_at = $now; + $order->save(); + $recoveredCreateEvent->disposition = 'applied'; + $recoveredCreateEvent->applied_at = $now; + $recoveredCreateEvent->save(); + return; } if ($preparedRecoveryMarker !== null) { // The resource projection and this marker commit atomically. - // Keep every original terminal task field and the encrypted - // recovery payload unchanged until commitApplied() runs after - // the matching Agent fence has been released. + // Keep the original encrypted request plus the exact validated + // operation until commit runs after the matching Agent fence + // has been released. This makes the prepare/fence crash window + // resumable for every registered kind, not only settings. + $preparedPayload = $payload; + $preparedBinding = self::preparedRecoveryBinding( + $preparedRecoveryMarker + ); + if ($preparedBinding === null) { + throw new CloudRecoveryPayloadUnavailable( + '任务预提交恢复标记无效', + 409 + ); + } + $preparedPayload['_operation_recovery'] = [ + 'version' => 1, + 'kind' => (string) $job->kind, + 'prepared_marker' => $preparedBinding, + 'operation' => $operation, + ]; + $encodedPrepared = json_encode( + $preparedPayload, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + | JSON_UNESCAPED_UNICODE + ); + if (strlen($encodedPrepared) > 196608) { + throw new CloudRecoveryPayloadUnavailable( + '任务预提交恢复数据过大', + 409 + ); + } $job->effect_resolution_reason = $preparedRecoveryMarker; + $job->sealed_payload = CloudSecrets::encrypt( + $preparedPayload, + 'job-payload' + ); + if ($forceRequired) { + // This exact no-effect Agent conclusion authorizes a new, + // separately audited force-delete generation. Keep the + // concrete code on the immutable graceful task instead of + // its earlier transport/deadline summary. + $job->error_code = 'force_required'; + } if (self::lateReceiptRecoveryMarker( $preparedRecoveryMarker ) && in_array( @@ -2087,14 +2960,23 @@ final class CloudWorkerService : ($effectMayHaveApplied ? 'unknown' : 'not_applied'); $retainRecoveryEscrow = $status === 'failed' && $effectMayHaveApplied - && (string) $job->kind === 'instance_settings'; + && (CloudOperationRecoveryPolicy::supports( + (string) $job->kind + ) || (string) $job->kind === 'create'); if (!$retainRecoveryEscrow) { // A resolved terminal task never needs credentials again. - // Only an unknown instance-settings failure has a reviewed - // finalizer and therefore retains its encrypted payload as a - // recovery escrow. Every other kind is immediately redacted. + // Unknown operations in the explicit recovery policy retain + // encrypted escrow only until their effect is resolved. + $safePayload = CloudInput::safeResult($payload); + if ($operationIdentity !== null) { + $safePayload[ + CloudOperationRecoveryIdentity::payloadKey() + ] = CloudOperationRecoveryIdentity::persisted( + $operationIdentity + ); + } $job->sealed_payload = CloudSecrets::encrypt( - CloudInput::safeResult($payload), 'job-payload' + $safePayload, 'job-payload' ); } $job->result_json = $safe === null ? null : json_encode($safe, JSON_THROW_ON_ERROR); @@ -2107,6 +2989,15 @@ final class CloudWorkerService $job->available_at = 0; $job->updated_at = time(); $job->save(); + // Aggregate catalog parents may be failed/unknown even though all + // leaf effects are already known (for example one replica applied + // and another failed before changing the host). Publish the parent + // effect now as well as after a later recovery commit, otherwise a + // fully-known partial aggregate would retain a permanent fence. + CloudJobService::reconcileAggregateParentEffectLocked( + $job, + null + ); if ($order !== null) { if ($job->kind === 'create' && $effectMayHaveApplied) { CloudPlacementService::markUncertain($order); @@ -2238,10 +3129,7 @@ final class CloudWorkerService */ private static function agentRequestBody(string $kind, array $body): array { - if ($kind === 'action' && ($body['action'] ?? null) === 'poweroff') { - $body['action'] = 'destroy'; - } - return $body; + return CloudOperationRecoveryIdentity::wireBody($kind, $body); } /** @@ -2261,6 +3149,23 @@ final class CloudWorkerService 502 ); } + if (CloudOperationRecoveryIdentity::supports((string) $job->kind)) { + $expectedIdentity = CloudOperationRecoveryIdentity::expected( + $job, + strtolower((string) ($operation['status'] ?? '')) + === 'succeeded' + ); + $fingerprint = $operation['fingerprint'] + ?? $operation['request_fingerprint'] ?? null; + CloudOperationRecoveryIdentity::assertMatches( + $expectedIdentity, + [ + 'action' => $operation['action'] ?? null, + 'resource_id' => $operation['resource_id'] ?? null, + 'request_fingerprint' => $fingerprint, + ] + ); + } return $operation; } diff --git a/web/public/cloud/admin-instances.js b/web/public/cloud/admin-instances.js index ea6c1236..afd12f76 100644 --- a/web/public/cloud/admin-instances.js +++ b/web/public/cloud/admin-instances.js @@ -1,4 +1,7 @@ -import { announceTaskAccepted, observeTask, taskUrl } from './task-observer.js?v=2026102005'; +import { + announceTaskAccepted, observeTask, recoveryTaskFailureNotice, taskUrl, + taskSucceededWithoutRecovery, +} from './task-observer.js?v=2026102101'; const root = document.querySelector('[data-admin-instances]'); const byId = id => document.getElementById(id); @@ -321,6 +324,14 @@ function paintPower(node, vm) { function jobStatus(task) { if (task?.completed === false && task.status === 'active') return '执行中'; if (task?.completed === true) { + if (task.recovery?.pending === true) { + const code = String(task.recovery?.code || task.finalization_error_code || ''); + if (code === 'recovery_dispatch_ledger_conflict' || task.dispatch_state === 'invalid') { + return '派发账本异常 · 待修复'; + } + if (task.dispatch_state === 'not_dispatched') return 'PHP 本地账本收尾中'; + return task.status === 'failed' ? '已失败 · 持续恢复中' : '安全恢复中'; + } return ({ succeeded: '已成功', failed: '已失败' })[task.status] || '任务状态协议无效'; } @@ -333,6 +344,16 @@ function mutationBlockMessage(task, action) { if (task.completed === false && task.status === 'active') { return `实例已有任务 #${id}(执行中),完成前不能${action}。`; } + if (task.completed === true && task.recovery?.pending === true) { + const code = String(task.recovery?.code || task.finalization_error_code || ''); + if (code === 'recovery_dispatch_ledger_conflict' || task.dispatch_state === 'invalid') { + return `任务 #${id} 的派发账本异常,资源保持安全锁定;修复账本并完成核验前不能${action}。`; + } + if (task.dispatch_state === 'not_dispatched') { + return `任务 #${id} 已确认未派发到宿主机,但 PHP 本地账本收尾尚未完成;收尾成功前不能${action}。`; + } + return `任务 #${id} 尚在持续恢复,资源保持安全锁定;恢复收敛前不能${action}。`; + } if (task.completed === true && task.status === 'failed') { return `任务 #${id} 已失败,资源安全锁定,需管理员人工处理后才能${action}。`; } @@ -341,6 +362,8 @@ function mutationBlockMessage(task, action) { function taskFailureMessage(task, fallback) { const message = task?.error || fallback; + const recoveryNotice = recoveryTaskFailureNotice(task); + if (recoveryNotice) return recoveryNotice; if (task?.effect_may_have_applied) { return `${message} 任务已失败,操作效果可能已经发生,相关资源已锁定。请勿再次提交,并将任务编号交由管理员核查。`; } @@ -361,8 +384,8 @@ function row(vm) { statuses.append(power, el('span', 'fs-12', `服务:${text(vm.display?.service)}`), el('span', 'fs-12', `网络:${text(vm.display?.network)}`)); if (vm.active_job) { - const locked = vm.active_job.blocks_mutation === true && vm.active_job.completed === true && vm.active_job.status === 'failed'; - statuses.append(el('span', 'text-warning fs-12', `任务 #${vm.active_job.id} · ${jobStatus(vm.active_job)}${locked ? ' · 资源安全锁定,需管理员人工处理' : ''}`)); + const locked = vm.active_job.blocks_mutation === true; + statuses.append(el('span', 'text-warning fs-12', `任务 #${vm.active_job.id} · ${jobStatus(vm.active_job)}${locked ? ' · 资源安全锁定' : ''}`)); } const detail = el('button', 'btn btn-primary btn-sm', '查看详情'); detail.type = 'button'; @@ -675,7 +698,7 @@ function pollSettingsJob(vm, section, result) { if (serial !== state.settingsSerial || state.detailId !== String(vm.id)) return; state.settingsObserver = null; void (async () => { - const succeeded = task.status === 'succeeded'; + const succeeded = taskSucceededWithoutRecovery(task); const message = succeeded ? `实例设置任务 #${jobId} 已成功。` : taskFailureMessage(task, `任务 #${jobId} 执行失败。`); @@ -976,7 +999,7 @@ function pollNetworkJob(vm, section, result) { if (serial !== state.networkSerial || state.detailId !== String(vm.id)) return; state.networkObserver = null; void (async () => { - const succeeded = task.status === 'succeeded'; + const succeeded = taskSucceededWithoutRecovery(task); const message = succeeded ? `网络变更任务 #${jobId} 已成功。` : taskFailureMessage(task, `任务 #${jobId} 执行失败。`); diff --git a/web/public/cloud/admin-operations.js b/web/public/cloud/admin-operations.js index fee04994..3945375d 100644 --- a/web/public/cloud/admin-operations.js +++ b/web/public/cloud/admin-operations.js @@ -1,4 +1,7 @@ -import { announceTaskAccepted, observeTask, taskUrl } from './task-observer.js?v=2026102005'; +import { + announceTaskAccepted, observeTask, recoveryTaskFailureNotice, taskUrl, + taskSucceededWithoutRecovery, +} from './task-observer.js?v=2026102101'; const root = document.querySelector('[data-admin-operations]'); const byId = id => document.getElementById(id); @@ -50,6 +53,20 @@ function taskView(task) { return { terminal: false, status: 'running', label: '执行中', tone: 'text-primary', protocolError: false }; } if (task.completed === true && typeof task.status === 'string' && terminalStates.has(task.status)) { + if (task.recovery?.pending === true) { + const code = String(task.recovery?.code || task.finalization_error_code || ''); + const label = code === 'recovery_dispatch_ledger_conflict' + || task.dispatch_state === 'invalid' ? '派发账本异常 · 待修复' + : task.dispatch_state === 'not_dispatched' ? 'PHP 本地账本收尾中' + : task.status === 'failed' ? '已失败 · 持续恢复中' : '安全恢复中'; + return { + terminal: true, + status: task.status, + label, + tone: 'text-warning', + protocolError: false, + }; + } return { terminal: true, status: task.status, @@ -170,6 +187,17 @@ function shownFilters() { function failureText(job, view) { if (view.protocolError) return '任务数据不符合公开协议;资源按可能已生效处理并保持锁定。'; + if (job.recovery?.pending === true) { + const code = String(job.recovery?.code || job.finalization_error_code || ''); + const message = text(job.recovery.message, '系统仍会继续恢复。'); + if (code === 'recovery_dispatch_ledger_conflict' || job.dispatch_state === 'invalid') { + return `派发账本异常,任务原终态保持不变,资源继续安全锁定;修复账本后系统会重新核验。${message}`; + } + if (job.dispatch_state === 'not_dispatched') { + return `宿主机操作已确认未派发,但 PHP 本地账本收尾尚未完成;资源保持安全锁定,系统会持续重试本地收尾。${message}`; + } + return `任务尚在持续恢复,资源保持安全锁定;系统不会重复执行原操作。${message}`; + } if (view.status !== 'failed') return ''; if (job.kind === 'host_storage_configure') { return '旧存储任务已终止且不会重放;部分固定存储池可能已应用。可到宿主机存储目录页修正后提交新的独立任务。'; @@ -178,7 +206,7 @@ function failureText(job, view) { return '操作效果可能已发生;资源已安全锁定,需管理员人工处理。'; } if (job.effect_may_have_applied === true && ['applied', 'not_applied'].includes(job.effect_resolution)) { - return `任务仍为失败;人工审计已确认操作效果${job.effect_resolution === 'applied' ? '已经发生' : '未发生'},任务级安全栅栏已解除。`; + return `任务仍为失败;系统已确认操作${job.effect_resolution === 'applied' ? '已应用' : '未应用'},任务级安全栅栏已解除。`; } return text(job.error, '任务执行失败。'); } @@ -336,6 +364,8 @@ function detailNotice(message, error = false) { function taskFailureMessage(task, fallback) { const message = task?.error || fallback; + const recoveryNotice = recoveryTaskFailureNotice(task); + if (recoveryNotice) return recoveryNotice; if (task?.effect_may_have_applied === true) { return `${message} 操作效果可能已经发生,请勿再次提交,并联系管理员核查。`; } @@ -382,8 +412,28 @@ function renderDetail(payload) { const failure = failureText(job, view); const storageFailure = job.kind === 'host_storage_configure' && view.status === 'failed'; - if (failure) body.append(el('h3', 'h6 mt-4', '失败详情'), el('p', 'text-danger text-break', failure)); - if (job.finalization_incident === true) { + if (failure) body.append(el('h3', 'h6 mt-4', job.recovery?.pending === true + ? '安全恢复状态' : '失败详情'), el('p', 'text-danger text-break', failure)); + if (job.recovery?.pending === true) { + const code = String(job.recovery.code || job.finalization_error_code || ''); + const recoveryTitle = code === 'recovery_dispatch_ledger_conflict' + || job.dispatch_state === 'invalid' ? '派发账本修复' + : job.dispatch_state === 'not_dispatched' + ? 'PHP 本地账本收尾' : '持续恢复详情'; + const recoveryMode = recoveryTitle === '派发账本修复' + ? '修复派发计数后,使用原任务身份和已保存回执重新核验;不会重放宿主机操作' + : recoveryTitle === 'PHP 本地账本收尾' + ? '只重试面板本地账本收尾;不会联系 Agent 或执行宿主机操作' + : '按原任务身份持续核对;不会重复执行原操作'; + body.append(el('h3', 'h6 mt-4', recoveryTitle), infoList([ + ['恢复方式', recoveryMode], + ['最近异常', job.recovery.message], + ['异常代码', job.recovery.code], + ['最近核对', date(job.recovery.last_checked_at)], + ['下次核对', job.recovery.next_check_at + ? date(job.recovery.next_check_at) : '等待后台调度'], + ])); + } else if (job.finalization_incident === true) { body.append(el('h3', 'h6 mt-4', '业务账本收尾事件'), el('p', 'text-danger text-break', storageFailure ? `旧存储任务已终态失败,收尾事件仅保留审计且不会重放;存储目录页仍可以终态任务账本为准提交新的独立任务。${job.finalization_error_code ? ` 事件代码:${job.finalization_error_code}` : ''}` @@ -392,12 +442,19 @@ function renderDetail(payload) { if (state.inspection) { const inspectedAt = state.inspection.checked_at || state.inspection.inspected_at; const paymentEvidence = job.kind === 'payment_create'; + const completionDeliveryError = typeof state.inspection.completion_delivery_error === 'string' + ? state.inspection.completion_delivery_error.trim() : ''; body.append(el('h3', 'h6 mt-4', paymentEvidence ? '支付账本审计' : '宿主机只读检查'), el('p', 'text-muted fs-13', paymentEvidence ? `已记录外部支付平台核验结论${inspectedAt ? ` · ${date(inspectedAt)}` : ''}。原任务仍保持失败,且没有重新下单。` : storageFailure ? `已完成只读检查${inspectedAt ? ` · ${date(inspectedAt)}` : ''}。检查不会执行 Agent 操作;旧任务仍保持失败,也不会影响存储目录页提交新的独立任务。` : `已完成只读检查${inspectedAt ? ` · ${date(inspectedAt)}` : ''}。检查不会执行 Agent 操作;任务仍以失败详情和资源安全栅栏为准。`)); + if (completionDeliveryError) { + // infoList/el write via textContent; Agent-supplied text never becomes + // markup even if a future protocol regression returns HTML-like data. + body.append(infoList([['回执异常', completionDeliveryError]])); + } } for (const note of payload.notes || []) body.append(el('p', 'text-muted fs-13 mt-3 mb-0', note)); const links = byId('operation-detail-links'); links.replaceChildren(); @@ -480,7 +537,7 @@ async function forceDelete(id) { if (state.detailId === String(id) && !task.terminal) detailNotice(`强制删除任务 #${task.id} 正在后台执行。`); }, onTerminal: task => { - const succeeded = task.status === 'succeeded'; + const succeeded = taskSucceededWithoutRecovery(task); const message = succeeded ? `强制删除任务 #${task.id} 已成功。` : taskFailureMessage(task, `强制删除任务 #${task.id} 失败。`); diff --git a/web/public/cloud/admin.js b/web/public/cloud/admin.js index ef93d8eb..d39c0e5f 100644 --- a/web/public/cloud/admin.js +++ b/web/public/cloud/admin.js @@ -1,4 +1,4 @@ -import { announceTaskAccepted, observeTask, taskUrl } from './task-observer.js?v=2026102005'; +import { announceTaskAccepted, observeTask, recoveryTaskFailureNotice, taskSucceededWithoutRecovery, taskUrl } from './task-observer.js?v=2026102101'; const root = document.querySelector('[data-cloud-admin]'); const byId = id => document.getElementById(id); @@ -232,7 +232,8 @@ function refreshHostStorageAfterTask(hostId, task, message) { .then(payload => { if (!currentHost()) return; renderHostStorage(payload); - hostStorageNotice(message(payload), task?.status === 'failed' + hostStorageNotice(message(payload), task?.terminal === true + && !taskSucceededWithoutRecovery(task) || payload.state === 'failed'); }) .catch(error => { @@ -257,7 +258,9 @@ function observeHostStorageTask(receipt, hostId) { onTerminal: task => { if (!currentHost()) return; void refreshHostStorageAfterTask(hostId, task, payload => { - if (task.status === 'succeeded') return `任务 #${task.id} 已成功,存储配置已刷新。`; + if (taskSucceededWithoutRecovery(task)) return `任务 #${task.id} 已成功,存储配置已刷新。`; + const recoveryNotice = recoveryTaskFailureNotice(task); + if (recoveryNotice) return recoveryNotice; const failure = task.error || '宿主机存储配置失败。'; const partial = task.effect_may_have_applied === true ? ' 部分固定存储池可能已经应用;新任务只会核验并补全,不会迁移或删除数据。' : ''; @@ -731,6 +734,8 @@ async function loadCatalog() { } function taskFailureMessage(task, fallback) { const message = task?.error || fallback; + const recoveryNotice = recoveryTaskFailureNotice(task); + if (recoveryNotice) return recoveryNotice; if (task?.effect_may_have_applied) { return `${message} 操作效果可能已经发生,请勿再次提交,并将任务编号交由管理员核查。`; } @@ -742,7 +747,7 @@ function importProgress(result, title = '导入镜像', onSuccess = loadCatalog, const handle = observeTask(result, { onUpdate: () => notice(`${title}任务正在后台执行。`), onTerminal: task => { - if (task.status === 'succeeded') { + if (taskSucceededWithoutRecovery(task)) { void Promise.resolve(onSuccess()).catch(error => notice(error.message, true)); } else { notice(taskFailureMessage(task, `${title}失败。`), true); diff --git a/web/public/cloud/app.js b/web/public/cloud/app.js index ecbe3452..22d6fe9a 100644 --- a/web/public/cloud/app.js +++ b/web/public/cloud/app.js @@ -1,4 +1,4 @@ -import { initializeTaskCenter } from './task-center.js?v=2026102005'; +import { initializeTaskCenter } from './task-center.js?v=2026102101'; const pageModules = Object.freeze({ instances: '/cloud/instances.js', diff --git a/web/public/cloud/detail.js b/web/public/cloud/detail.js index a0de2cf0..d2a26913 100644 --- a/web/public/cloud/detail.js +++ b/web/public/cloud/detail.js @@ -1,4 +1,8 @@ -import { announceTaskAccepted, normalizeTask, observeTask, resolvedTaskFailureNotice } from './task-observer.js?v=2026102005'; +import { + announceTaskAccepted, normalizeTask, observeTask, + recoveryTaskFailureNotice, resolvedTaskFailureNotice, + taskSucceededWithoutRecovery, +} from './task-observer.js?v=2026102101'; const runtimeUrl = new URL('/cloud/runtime.js', location.origin); const assetVersion = new URL(import.meta.url).searchParams.get('v'); @@ -34,6 +38,8 @@ function taskFailureMessage(task, fallback = '任务执行失败。') { const message = task?.error || fallback; const resolvedNotice = resolvedTaskFailureNotice(task); if (resolvedNotice) return resolvedNotice; + const recoveryNotice = recoveryTaskFailureNotice(task); + if (recoveryNotice) return recoveryNotice; if (task?.effect_may_have_applied) { return `${message} 任务已失败,操作效果可能已经发生,相关资源已锁定。请勿再次提交,并在任务中心复制任务编号交由管理员核查。`; } @@ -233,7 +239,10 @@ function renderOperationLogs(items, pagination = {}) { const result = operationLogElement('span', `vm-operation-log-cell result ${statusClass}`, statusLabel); result.setAttribute('role', 'cell'); const resolvedNotice = resolvedTaskFailureNotice(normalizeTask(entry)); - if (resolvedNotice || entry.error) result.title = resolvedNotice || entry.error; + const recoveryNotice = recoveryTaskFailureNotice(normalizeTask(entry)); + if (resolvedNotice || recoveryNotice || entry.error) { + result.title = resolvedNotice || recoveryNotice || entry.error; + } item.append(operation, submitted, result); list.append(item); } @@ -760,10 +769,10 @@ function pollVmFirewall(vmId, receipt) { firewallPolling = false; void (async () => { await loadVmFirewall(vmId, true, true); - if (task.status === 'failed') { - setFirewallStatus(taskFailureMessage(task, '防火墙任务失败。'), 'error'); - } else { + if (taskSucceededWithoutRecovery(task)) { setFirewallStatus('防火墙策略已生效。', 'success'); + } else { + setFirewallStatus(taskFailureMessage(task, '防火墙任务失败。'), 'error'); } })(); }, @@ -1188,13 +1197,15 @@ function pollSnapshotJob(vmId, receipt, action, accepted = true) { onTerminal: task => { void (async () => { snapshotMutation = null; - if (task.status === 'failed') { + const succeeded = taskSucceededWithoutRecovery(task); + if (!succeeded) { // Fail closed until the authoritative snapshot projection reloads; // loadVmSnapshots replaces this transient receipt-derived guard. - snapshotEffectLocked = task.effect_may_have_applied || task.safe_to_resubmit === false; + snapshotEffectLocked = task.recovery?.pending === true + || task.effect_may_have_applied || task.safe_to_resubmit === false; } await loadVmSnapshots(vmId, true, false); - if (task.status === 'succeeded') { + if (succeeded) { const actualConsistency = String(task?.result?.consistency || '').toLowerCase(); const completedMessage = action === 'create' && ['filesystem', 'crash'].includes(actualConsistency) @@ -1349,7 +1360,7 @@ function pollInstanceSettingJob(vmId, receipt, kind, form) { void (async () => { await refreshMetadataAndStatus(vmId, false, true, true); syncInstanceSettingForm(form); - if (task.status === 'succeeded') { + if (taskSucceededWithoutRecovery(task)) { settingStatus(`${label}已完成,实例正在使用新的设置。`, 'success'); if (kind === 'password') { await loadGeneratedPassword(vmId); diff --git a/web/public/cloud/invoice-detail-runtime.js b/web/public/cloud/invoice-detail-runtime.js index 9e383de5..9bc713b0 100644 --- a/web/public/cloud/invoice-detail-runtime.js +++ b/web/public/cloud/invoice-detail-runtime.js @@ -1,5 +1,8 @@ import { toast } from './toast.js?v=2026100102'; -import { announceTaskAccepted, observeTask, taskUrl } from './task-observer.js?v=2026102005'; +import { + announceTaskAccepted, observeTask, recoveryTaskFailureNotice, + taskSucceededWithoutRecovery, taskUrl, +} from './task-observer.js?v=2026102101'; // Lightweight invoice-detail runtime. This module deliberately contains no VM, // deployment, metrics or console code so the bill is interactive without @@ -57,6 +60,18 @@ function firstText(...values) { return ''; } +function terminalTaskProblem(task, fallback) { + const recoveryNotice = recoveryTaskFailureNotice(task); + if (recoveryNotice) return recoveryNotice; + const message = firstText(task?.error, fallback); + if (task?.effect_may_have_applied === true) { + return `${message} 操作效果可能已经发生,请勿再次提交,并联系管理员核查。`; + } + return task?.safe_to_resubmit === false + ? `${message} 相关资源保持安全锁定,请勿再次提交,并联系管理员核查。` + : message; +} + function firstNumber(...values) { for (const value of values) { if (value === null || value === undefined || value === '') continue; @@ -934,11 +949,11 @@ async function payInvoiceBalance(invoice, container) { onTerminal: task => { void (async () => { await refreshInvoiceDetail(invoice.id); - if (task.status === 'succeeded') { + if (taskSucceededWithoutRecovery(task)) { toast('实例创建完成。', 'success'); } else { - toast(task.error || '实例创建失败,请在任务中心查看详情。', - 'error'); + toast(terminalTaskProblem(task, + '实例创建任务未能安全完成,请在任务中心查看详情。'), 'error'); } })(); }, @@ -1009,19 +1024,21 @@ async function createInvoicePayment(invoice, method, container, paymentResult) { toast('支付订单创建任务已接收。', 'success'); observeTask(result, { onTerminal: task => { - if (task.status === 'succeeded' && task?.result?.payment) { + if (taskSucceededWithoutRecovery(task) && task?.result?.payment) { renderOnlinePayment(paymentResult, task.result.payment); return; } if (task.safe_to_resubmit === true) { clearInvoicePaymentKey(invoice.id, method.id); } - const warning = task.effect_may_have_applied + const recoveryNotice = recoveryTaskFailureNotice(task); + const warning = !recoveryNotice && task.effect_may_have_applied ? ' 支付订单可能已在网关创建,请勿再次提交,并联系管理员处理。' : ''; + const failure = recoveryNotice || task.error || '支付订单创建失败。'; paymentResult.replaceChildren(makeElement('p', - 'invoice-payment-error', `${task.error || '支付订单创建失败。'}${warning}`)); - toast(`${task.error || '支付订单创建失败。'}${warning}`, 'error'); + 'invoice-payment-error', `${failure}${warning}`)); + toast(`${failure}${warning}`, 'error'); }, }); } catch (error) { diff --git a/web/public/cloud/iso-images.js b/web/public/cloud/iso-images.js index 38974d6a..207b20b7 100644 --- a/web/public/cloud/iso-images.js +++ b/web/public/cloud/iso-images.js @@ -1,4 +1,7 @@ -import { announceTaskAccepted, observeTask, taskUrl } from './task-observer.js?v=2026102005'; +import { + announceTaskAccepted, observeTask, recoveryTaskFailureNotice, taskUrl, + taskSucceededWithoutRecovery, +} from './task-observer.js?v=2026102101'; const runtimeUrl = new URL('/cloud/runtime.js', location.origin); const assetVersion = new URL(import.meta.url).searchParams.get('v'); @@ -59,9 +62,15 @@ function renderIsos() { const fingerprint = String(record.sha256 || ''); details.append(element('strong', '', record.name || '未命名 ISO'), element('small', '', `${formatBytes(record.size_bytes)}${fingerprint ? ` · SHA-256 ${fingerprint.slice(0, 12)}…` : ''}`)); + const canDelete = record.can_delete === true; + const quotaCleanup = canDelete + && record.cleanup_reason === 'quota_exceeded_after_import'; + if (quotaCleanup) { + details.append(element('small', '', '该 ISO 已下载到宿主机,但导入后超出个人库配额;可删除以释放空间。')); + } const remove = element('button', 'row-button user-iso-delete', '删除'); remove.type = 'button'; - const canDelete = String(record.state || '') === 'active'; + if (quotaCleanup) remove.textContent = '清理'; remove.disabled = !canDelete; if (!canDelete) { remove.textContent = String(record.state || '') === 'deleting' ? '删除中' : '不可删除'; @@ -73,9 +82,11 @@ function renderIsos() { if (!canDelete) return; const isoName = record.name || record.id; const confirmed = await requestUserConfirmation({ - title: '删除个人 ISO', - message: `确定从个人镜像库删除“${isoName}”?存在未完成账单或仍在安装的实例时,服务端会阻止删除。`, - confirmText: '删除 ISO', + title: quotaCleanup ? '清理已下载 ISO' : '删除个人 ISO', + message: quotaCleanup + ? `“${isoName}”已下载到宿主机,但导入后超出个人库配额。确定删除其宿主机副本并释放空间?` + : `确定从个人镜像库删除“${isoName}”?存在未完成账单或仍在安装的实例时,服务端会阻止删除。`, + confirmText: quotaCleanup ? '清理 ISO' : '删除 ISO', tone: 'danger', }); if (!confirmed) return; @@ -89,7 +100,7 @@ function renderIsos() { void (async () => { const refreshed = await loadIsos({ observeActive: false }); if (!refreshed) remove.disabled = task.safe_to_resubmit !== true; - if (task.status === 'succeeded') { + if (taskSucceededWithoutRecovery(task)) { toast('ISO 已从全局个人库删除。', 'success'); } else { showError('user-iso-list-error', taskFailureMessage(task, 'ISO 删除失败。')); @@ -161,6 +172,8 @@ async function loadIsos({ observeActive = true } = {}) { function taskFailureMessage(task, fallback) { const message = task?.error || fallback; + const recoveryNotice = recoveryTaskFailureNotice(task); + if (recoveryNotice) return recoveryNotice; if (task?.effect_may_have_applied) { return `${message} 任务已失败,操作效果可能已经发生,相关资源已锁定。请勿再次提交,并在任务中心复制任务编号交由管理员核查。`; } @@ -185,7 +198,7 @@ function watchImport(receipt, accepted = true) { pageState.importObserver = null; pageState.activeStatusUrl = ''; await loadIsos({ observeActive: false }); - if (task.status === 'succeeded') { + if (taskSucceededWithoutRecovery(task)) { setImportStatus('ISO 已导入全局个人库。'); toast('ISO 已保存,可用于所有地区。', 'success'); } else { diff --git a/web/public/cloud/runtime.js b/web/public/cloud/runtime.js index 842f2437..d6bbb2bd 100644 --- a/web/public/cloud/runtime.js +++ b/web/public/cloud/runtime.js @@ -1,5 +1,8 @@ import { toast } from './toast.js?v=2026100102'; -import { announceTaskAccepted, observeTask, resolvedTaskFailureNotice, taskUrl } from './task-observer.js?v=2026102005'; +import { + announceTaskAccepted, observeTask, recoveryTaskFailureNotice, + resolvedTaskFailureNotice, taskSucceededWithoutRecovery, taskUrl, +} from './task-observer.js?v=2026102101'; // PHP owns authentication, authorisation, ownership and purchasing. No Agent // address, token, host credential or unrestricted create API exists in this UI. @@ -397,6 +400,8 @@ function taskFailureMessage(task, fallback = '任务执行失败。') { const message = task?.error || fallback; const resolvedNotice = resolvedTaskFailureNotice(task); if (resolvedNotice) return resolvedNotice; + const recoveryNotice = recoveryTaskFailureNotice(task); + if (recoveryNotice) return recoveryNotice; if (task?.effect_may_have_applied) { return `${message} 任务已失败,操作效果可能已经发生,相关资源已锁定。请勿再次提交,并在任务中心复制任务编号交由管理员核查。`; } @@ -437,7 +442,9 @@ async function powerAction(action, dangerous = false) { }); const observer = observeAcceptedTask(result, { title: '电源任务' }, { onTerminal: task => { - if (task.status === 'failed') toast(taskFailureMessage(task), 'error', '电源任务失败'); + if (!taskSucceededWithoutRecovery(task)) { + toast(taskFailureMessage(task), 'error', '电源任务需恢复'); + } void loadVmStatus(vm.api_id, { live: true, force: true }); }, }); @@ -975,7 +982,7 @@ function trackReinstallJob(vm, result) { byId('reinstall-progress').hidden = true; const refreshed = await loadVm(vm.api_id); syncReinstallControls(refreshed || selectedVm()); - if (task.status === 'succeeded') { + if (taskSucceededWithoutRecovery(task)) { await loadReinstallCredential(refreshed || vm); if (state.reinstallPassword) text('reinstall-password-card-note', '重装任务已成功。请将密码保存到安全位置。'); return; @@ -1111,7 +1118,7 @@ async function rescueAction(action) { if (!confirmed) return; } state.mutationBusy = true; showError('rescue-error', ''); - try { const body = { confirmation_name: vm.name }; if (action === 'load') { body.template_id = byId('rescue-template-id').value; body.ack_data_loss = true; } if (action === 'force-start') body.ack_data_loss = true; const result = await api(`${vmPath(vm)}/rescue${action === 'load' ? '' : '/' + action}`, { method: 'POST', body, expectedStatus: 202, requireTaskReceipt: true }); const rescueLabels = { load: '救援', 'force-start': '强制进入救援', exit: '退出救援' }; const title = rescueLabels[action] || '救援'; const observer = observeAcceptedTask(result, { title }, { onTerminal: task => { if (task.status === 'failed') showError('rescue-error', taskFailureMessage(task, `${title}任务失败。`)); void api(`${vmPath(vm)}/rescue`).then(renderRescueStatus).catch(error => showError('rescue-error', error.message)); } }); if (observer) { toast('任务已接收,可在任务中心查看结果。', 'success', title); text('rescue-status', '任务已接收,正在后台执行;你可以离开当前页面。'); } else { showError('rescue-error', '请求已送达,但任务回执协议无效。请勿再次提交,并联系管理员核查。'); } } + try { const body = { confirmation_name: vm.name }; if (action === 'load') { body.template_id = byId('rescue-template-id').value; body.ack_data_loss = true; } if (action === 'force-start') body.ack_data_loss = true; const result = await api(`${vmPath(vm)}/rescue${action === 'load' ? '' : '/' + action}`, { method: 'POST', body, expectedStatus: 202, requireTaskReceipt: true }); const rescueLabels = { load: '救援', 'force-start': '强制进入救援', exit: '退出救援' }; const title = rescueLabels[action] || '救援'; const observer = observeAcceptedTask(result, { title }, { onTerminal: task => { if (!taskSucceededWithoutRecovery(task)) showError('rescue-error', taskFailureMessage(task, `${title}任务失败。`)); void api(`${vmPath(vm)}/rescue`).then(renderRescueStatus).catch(error => showError('rescue-error', error.message)); } }); if (observer) { toast('任务已接收,可在任务中心查看结果。', 'success', title); text('rescue-status', '任务已接收,正在后台执行;你可以离开当前页面。'); } else { showError('rescue-error', '请求已送达,但任务回执协议无效。请勿再次提交,并联系管理员核查。'); } } catch (error) { showError('rescue-error', error.message); } finally { state.mutationBusy = false; } } diff --git a/web/public/cloud/task-center.js b/web/public/cloud/task-center.js index 59c9a34e..4962a992 100644 --- a/web/public/cloud/task-center.js +++ b/web/public/cloud/task-center.js @@ -1,4 +1,6 @@ -import { normalizeTask, resolvedTaskFailureNotice } from './task-observer.js?v=2026102005'; +import { + normalizeTask, recoveryTaskFailureNotice, resolvedTaskFailureNotice, +} from './task-observer.js?v=2026102101'; const REFRESH_MS = 10000; // Covers the longest server-side absolute task deadline (145 minutes) while @@ -8,7 +10,8 @@ const REQUEST_TIMEOUT_MS = 12000; const byId = id => document.getElementById(id); const state = { - items: [], nextCursor: '', hasMore: false, activeCount: 0, unreadCount: 0, + items: [], nextCursor: '', hasMore: false, + activeCount: 0, recoveringCount: 0, unreadCount: 0, loading: false, request: null, serial: 0, timer: null, deadline: 0, opener: null, scroll: null, closing: false, initialized: false, readQueue: new Set(), readAttempted: new Set(), readInFlight: false, @@ -110,11 +113,16 @@ export function taskTitle(task) { function statusText(task) { if (!task.terminal) return '执行中'; + if (task.recovery?.pending === true) { + return task.status === 'failed' + ? '已失败 · 自动核对中' : '账本异常 · 待修复'; + } return { succeeded: '已成功', failed: '已失败' }[task.status] || '已失败'; } function statusClass(task) { - return task.terminal ? task.status : 'running'; + return task.recovery?.pending === true + ? 'failed' : (task.terminal ? task.status : 'running'); } function setMessage(message, tone = '') { @@ -159,6 +167,13 @@ function detailBlock(task) { append('任务编号', task.id); append('当前状态', statusText(task)); append('错误代码', task.error_code); + if (task.recovery?.pending === true) { + append('恢复状态', '持续自动核对'); + append('最近异常', task.recovery.message); + append('最近核对', dateText(task.recovery.last_checked_at)); + append('下次核对', + dateText(task.recovery.next_check_at) || '等待后台调度'); + } if (task.result !== null && task.result !== undefined) { let result = ''; try { result = typeof task.result === 'string' ? task.result : JSON.stringify(task.result, null, 2); } @@ -192,13 +207,19 @@ function renderItems(emptyMessage = '暂无任务记录。') { if (recordedAt) meta.append(element('time', '', recordedAt)); if (task.id) meta.append(element('code', '', task.id)); if (meta.children.length) article.append(meta); + const recoveryNotice = recoveryTaskFailureNotice(task); + if (task.status !== 'failed' && recoveryNotice) { + article.append(element('p', 'panel-task-warning', recoveryNotice)); + } if (task.status === 'failed') { const resolvedNotice = resolvedTaskFailureNotice(task); if (resolvedNotice) { article.append(element('p', 'panel-task-warning', resolvedNotice)); } else { article.append(element('p', 'panel-task-error', task.error || '任务执行失败。')); - if (raw?.kind === 'host_storage_configure') { + if (recoveryNotice) { + article.append(element('p', 'panel-task-warning', recoveryNotice)); + } else if (raw?.kind === 'host_storage_configure') { article.append(element('p', 'panel-task-warning', '旧存储任务已终止且不会重放;可到宿主机存储目录页修正后提交新的独立任务。')); } else if (task.effect_may_have_applied) { article.append(element('p', 'panel-task-warning', '操作效果可能已经发生。为避免重复执行,请勿再次提交;请将任务编号提供给管理员核查。')); @@ -262,8 +283,11 @@ async function loadBadgeCounts() { }); const payload = await response.json(); if (!response.ok || !Array.isArray(payload?.items) || !validPagination(payload?.pagination) - || !validCount(payload?.active_count) || !validCount(payload?.unread_count)) return; + || !validCount(payload?.active_count) + || !validCount(payload?.recovering_count) + || !validCount(payload?.unread_count)) return; state.activeCount = payload.active_count; + state.recoveringCount = payload.recovering_count; state.unreadCount = payload.unread_count; renderBadge(); } catch { @@ -277,8 +301,9 @@ async function loadBadgeCounts() { function scheduleRefresh() { clearTimer(); - if (!canRead() || state.loading || state.activeCount < 1) return; - if (Date.now() >= state.deadline) { + if (!canRead() || state.loading + || state.activeCount + state.recoveringCount < 1) return; + if (state.recoveringCount < 1 && Date.now() >= state.deadline) { setMessage('自动刷新已停止。任务仍会在后台执行,可点击“刷新”查看结果。'); return; } @@ -306,7 +331,9 @@ async function requestPage(taskState, cursor, controller) { throw error; } if (!Array.isArray(payload?.items) || !validPagination(payload?.pagination) - || !validCount(payload?.active_count) || !validCount(payload?.unread_count)) { + || !validCount(payload?.active_count) + || !validCount(payload?.recovering_count) + || !validCount(payload?.unread_count)) { throw new Error('任务中心数据格式无效。'); } return payload; @@ -336,6 +363,9 @@ async function load(cursor = '', source = 'manual') { ...completed, items: [...active.items, ...completed.items], active_count: active.active_count, + recovering_count: Math.max( + active.recovering_count, completed.recovering_count, + ), unread_count: Math.max(active.unread_count, completed.unread_count), })); if (controller.signal.aborted || serial !== state.serial || !canRead()) return; @@ -351,10 +381,15 @@ async function load(cursor = '', source = 'manual') { state.nextCursor = String(payload.pagination.next_cursor || ''); state.hasMore = payload.pagination.has_more === true && Boolean(state.nextCursor); state.activeCount = payload.active_count; + state.recoveringCount = payload.recovering_count; state.unreadCount = payload.unread_count; renderItems(); void markPresentedRead(state.items); - setMessage(state.activeCount > 0 ? `${state.activeCount} 个任务正在后台执行。` : '已读取最新任务。'); + setMessage(state.activeCount > 0 + ? String(state.activeCount) + ' 个任务正在后台执行。' + : (state.recoveringCount > 0 + ? String(state.recoveringCount) + ' 个失败任务仍在持续自动核对。' + : '已读取最新任务。')); } catch (error) { if (serial !== state.serial || (controller.signal.aborted && controller.signal.reason !== 'timeout')) return; if (!state.items.length) renderItems('任务记录暂时不可用,请稍后刷新。'); diff --git a/web/public/cloud/task-observer.js b/web/public/cloud/task-observer.js index 6877bbe8..a71ab4e6 100644 --- a/web/public/cloud/task-observer.js +++ b/web/public/cloud/task-observer.js @@ -30,6 +30,7 @@ function protocolFailureTask(raw) { completed: true, effect_may_have_applied: true, effect_resolution: null, + recovery: null, safe_to_resubmit: false, error: '任务状态协议无效,请联系管理员核查。', error_code: 'task_protocol_invalid', @@ -58,12 +59,36 @@ export function normalizeTask(payload) { const status = validRunning ? 'running' : rawStatus; const effectMayHaveApplied = raw.effect_may_have_applied === true; - const effectResolution = status === 'failed' && effectMayHaveApplied + let effectResolution = status === 'failed' && effectMayHaveApplied && Object.prototype.hasOwnProperty.call(raw, 'effect_resolution') && RESOLVED_EFFECT_STATES.has(raw.effect_resolution) ? raw.effect_resolution : null; const safeValue = raw.safe_to_resubmit; const safeToResubmit = status === 'failed' && !effectMayHaveApplied && safeValue === true; + let recovery = null; + if (terminal && Object.prototype.hasOwnProperty.call(raw, 'recovery')) { + const candidate = asObject(raw.recovery); + const message = typeof candidate.message === 'string' + ? candidate.message.trim() : ''; + const timestamp = value => value === null + ? null + : (Number.isSafeInteger(value) && value > 0 ? value : undefined); + const lastCheckedAt = timestamp(candidate.last_checked_at); + const nextCheckAt = timestamp(candidate.next_check_at); + if (candidate.pending === true && message && message.length <= 400 + && lastCheckedAt !== undefined && nextCheckAt !== undefined) { + recovery = { + pending: true, + message, + last_checked_at: lastCheckedAt, + next_check_at: nextCheckAt, + }; + // A later dispatch-ledger or finalization incident can make an otherwise + // resolved failed task unsafe again. The live recovery fence is the + // authoritative UI state until the backend clears that incident. + effectResolution = null; + } + } return { id, @@ -72,6 +97,7 @@ export function normalizeTask(payload) { completed: terminal, effect_may_have_applied: effectMayHaveApplied, effect_resolution: effectResolution, + recovery, safe_to_resubmit: safeToResubmit, error: firstText(raw.error), error_code: firstText(raw.error_code), @@ -85,16 +111,29 @@ export function normalizeTask(payload) { * now-stale unknown-effect error that said the resource fence was active. */ export function resolvedTaskFailureNotice(task) { - if (task?.status !== 'failed' || task?.effect_may_have_applied !== true) return ''; + if (task?.status !== 'failed' || task?.effect_may_have_applied !== true + || task?.recovery?.pending === true) return ''; if (task.effect_resolution === 'applied') { - return '原任务失败,但系统已确认操作已生效,资源锁已解除。'; + return '原任务失败,但系统已确认操作已应用,资源锁已解除。'; } if (task.effect_resolution === 'not_applied') { - return '原任务失败,但系统已确认操作未生效,资源锁已解除。'; + return '原任务失败,但系统已确认操作未应用,资源锁已解除。'; } return ''; } +/** Explain a pending recovery or fail-closed ledger incident safely. */ +export function recoveryTaskFailureNotice(task) { + if (task?.terminal !== true || task?.recovery?.pending !== true) return ''; + return firstText(task.recovery.message); +} + +/** A terminal success is actionable only after every recovery fence clears. */ +export function taskSucceededWithoutRecovery(task) { + return task?.terminal === true && task?.status === 'succeeded' + && task?.recovery?.pending !== true; +} + export function taskUrl(receipt) { const value = asObject(receipt); const keys = Object.keys(value).sort(); diff --git a/web/resources/views/venix/admin/cloud/instances.tpl b/web/resources/views/venix/admin/cloud/instances.tpl index b7ec0784..5e545c00 100644 --- a/web/resources/views/venix/admin/cloud/instances.tpl +++ b/web/resources/views/venix/admin/cloud/instances.tpl @@ -40,7 +40,7 @@ {$vm.host_name|escape}{$vm.region|default:'地区未记录'|escape} {$vm.public_ip|default:'未记录'|escape}{if $vm.public_ip}{/if} {$vm.display.configuration|escape}{$vm.plan_name|default:'无关联套餐'|escape} -
电源:待获取服务:{$vm.display.service|escape}网络:{$vm.display.network|escape}{if $vm.active_job}任务 #{$vm.active_job.id|escape} · {if isset($vm.active_job.completed) && !$vm.active_job.completed && $vm.active_job.status == 'active'}执行中{elseif isset($vm.active_job.completed) && $vm.active_job.completed && $vm.active_job.status == 'succeeded'}已成功{elseif isset($vm.active_job.completed) && $vm.active_job.completed && $vm.active_job.status == 'failed'}已失败{if $vm.active_job.blocks_mutation|default:false} · 资源安全锁定,需管理员人工处理{/if}{else}任务状态协议错误 · 资源安全锁定{/if}{/if}
+
电源:待获取服务:{$vm.display.service|escape}网络:{$vm.display.network|escape}{if $vm.active_job}任务 #{$vm.active_job.id|escape} · {if isset($vm.active_job.completed) && !$vm.active_job.completed && $vm.active_job.status == 'active'}执行中{elseif isset($vm.active_job.completed) && $vm.active_job.completed && $vm.active_job.status == 'succeeded'}已成功{elseif isset($vm.active_job.completed) && $vm.active_job.completed && $vm.active_job.status == 'failed'}已失败{if $vm.active_job.blocks_mutation|default:false}{if $vm.active_job.recovery.pending|default:false} · 资源安全锁定,仍会继续自动核对{else} · 资源安全锁定,需管理员人工处理{/if}{/if}{else}任务状态协议错误 · 资源安全锁定{/if}{/if}
{$vm.display.traffic|escape}{$vm.display.expiry|escape}{if $vm.service_expires_at && $vm.service_status != 'exempt'}到期 {$vm.service_expires_at|date_format:'%Y-%m-%d'|escape}{/if} diff --git a/web/resources/views/venix/admin/cloud/operations.tpl b/web/resources/views/venix/admin/cloud/operations.tpl index 73f7120b..f92b103a 100644 --- a/web/resources/views/venix/admin/cloud/operations.tpl +++ b/web/resources/views/venix/admin/cloud/operations.tpl @@ -5,7 +5,7 @@ {assign var=operations_statuses value=['all'=>'全部状态','active'=>'执行中','succeeded'=>'已成功','failed'=>'已失败']}
-

系统运行与任务记录

任务只展示执行中、成功或失败。失败且效果可能已发生时,资源保持安全锁定并由管理员人工处理;固定存储池配置失败不保留跨任务栅栏。

+

系统运行与任务记录

任务只展示执行中、成功或失败。失败且效果尚未确认时,资源保持安全锁定;支持恢复的 Agent 任务会持续自动核对,且绝不会重放原操作。

{if $operations_error|default:''}{$operations_error|escape}{else}已读取 {$operations_page.pagination.total|default:0|escape} 条任务{/if}
@@ -18,7 +18,7 @@ {/foreach}
-

查找任务

摘要和列表均按筛选条件统计。任务失败不会在此页自动重新提交。

+

查找任务

摘要和列表均按筛选条件统计。自动核对只读取原任务证据,不会重新提交原操作。

@@ -39,7 +39,7 @@

任务详情

任务

正在读取任务详情…

-
失败任务不会自动重提。资源已锁定时,请按失败详情进行人工处理。
+
失败任务不会自动重提。详情标为持续自动核对时,只需修复所示通信或数据异常;系统会继续收敛。
diff --git a/web/resources/views/venix/admin/cloud/operations_rows.tpl b/web/resources/views/venix/admin/cloud/operations_rows.tpl index c64dfcc7..1edeeac6 100644 --- a/web/resources/views/venix/admin/cloud/operations_rows.tpl +++ b/web/resources/views/venix/admin/cloud/operations_rows.tpl @@ -4,7 +4,7 @@ {$job.instance_name|default:'无关联实例'|escape}{if $job.instance_id}实例 #{$job.instance_id|escape}{/if}{if $job.order_id}订单 #{$job.order_id|escape}{/if} 操作人:{$job.actor_name|default:'未记录'|escape}{if $job.actor_id} #{$job.actor_id|escape}{/if}{if $job.owner_id}所属:{$job.owner_name|default:'未记录'|escape} #{$job.owner_id|escape}{/if} {$job.host_name|default:'未记录'|escape}{$job.region|default:'地区未记录'|escape} - {if isset($job.completed) && !$job.completed && $job.status == 'active'}执行中{elseif isset($job.completed) && $job.completed && in_array($job.status,['succeeded','failed'])}{if $job.status == 'succeeded'}已成功{else}已失败{/if}{if $job.status == 'failed' && $job.kind == 'host_storage_configure'}旧存储任务已终止且不会重放;后续任务须沿用已定义固定池的路径。{elseif $job.status == 'failed' && $job.effect_may_have_applied|default:false && $job.effect_resolution == 'unknown'}操作效果可能已发生;资源已安全锁定,需管理员人工处理。{elseif $job.status == 'failed' && $job.effect_may_have_applied|default:false && in_array($job.effect_resolution,['applied','not_applied'])}任务仍为失败;人工审计已解除任务级安全栅栏。{/if}{else}协议错误资源按可能已生效处理并保持锁定。{/if} + {if $job.recovery.pending|default:false}安全恢复中{$job.recovery.message|default:'资源保持安全锁定,系统仍会继续自动核对。'|escape}{elseif isset($job.completed) && !$job.completed && $job.status == 'active'}执行中{elseif isset($job.completed) && $job.completed && in_array($job.status,['succeeded','failed'])}{if $job.status == 'succeeded'}已成功{else}已失败{/if}{if $job.status == 'failed' && $job.kind == 'host_storage_configure'}旧存储任务已终止且不会重放;后续任务须沿用已定义固定池的路径。{elseif $job.status == 'failed' && $job.effect_may_have_applied|default:false && $job.effect_resolution == 'unknown'}操作效果可能已发生;资源已安全锁定,需管理员人工处理。{elseif $job.status == 'failed' && $job.effect_may_have_applied|default:false && in_array($job.effect_resolution,['applied','not_applied'])}任务仍为失败;系统已确认操作{if $job.effect_resolution == 'applied'}已应用{else}未应用{/if},安全栅栏已解除。{/if}{else}协议错误资源按可能已生效处理并保持锁定。{/if} {$job.operation_id|default:'无操作标识'|escape}{$job.phase|default:'未记录阶段'|escape} {if $job.updated_at}{$job.updated_at|date_format:'%Y-%m-%d %H:%M:%S'|escape}{else}更新时间未记录{/if}{if $job.error}{$job.error|escape}{else}未记录错误{/if}
diff --git a/web/resources/views/venix/admin/index.tpl b/web/resources/views/venix/admin/index.tpl index 1d2c3dff..8012ae1a 100644 --- a/web/resources/views/venix/admin/index.tpl +++ b/web/resources/views/venix/admin/index.tpl @@ -142,7 +142,7 @@ {$overview.jobs.active} - 资源安全锁定失败且效果可能已发生,需管理员人工处理 + 资源安全锁定支持恢复的 Agent 任务会持续自动核对,不会重放原操作 {$overview.jobs.unresolved_effect|default:0} diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index 6052a7d1..eb46e226 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1,2 +1,2 @@ {* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *} -{assign var=venix_asset_version value='2026102005' scope='global'} +{assign var=venix_asset_version value='2026102101' scope='global'} diff --git a/web/resources/views/venix/user/task_center_drawer.tpl b/web/resources/views/venix/user/task_center_drawer.tpl index a745e734..c8d9a646 100644 --- a/web/resources/views/venix/user/task_center_drawer.tpl +++ b/web/resources/views/venix/user/task_center_drawer.tpl @@ -2,7 +2,7 @@

任务中心

-

查看后台任务的执行结果。离开页面不会取消已经接收的任务。

+

查看后台任务的执行结果。离开页面不会取消任务;效果待确认的失败任务会持续自动核对,且不会重复执行原操作。

diff --git a/web/tests/AdminAcceptedTaskBehaviorTest.mjs b/web/tests/AdminAcceptedTaskBehaviorTest.mjs index 064136fb..d7784bf2 100644 --- a/web/tests/AdminAcceptedTaskBehaviorTest.mjs +++ b/web/tests/AdminAcceptedTaskBehaviorTest.mjs @@ -10,7 +10,7 @@ const { taskUrl } = await import('../public/cloud/task-observer.js'); // api(), so their 200 responses remain valid. assert.match(source, /async function acceptedTask\(path, options = \{\}\)/); assert.match(source, /status !== 202 \|\| !taskUrl\(payload\)/); -assert.match(source, /import \{ announceTaskAccepted, observeTask, taskUrl \}/); +assert.match(source, /taskSucceededWithoutRecovery, taskUrl/); assert.equal(taskUrl({ task_id: 42, status_url: '/api/v1/tasks/42' }), '/api/v1/tasks/42'); assert.equal(taskUrl({ task_id: 42, status_url: '/api/v1/tasks/42', status: 'active' }), ''); assert.equal(taskUrl({ task_id: 42, status_url: 'https://other.test/api/v1/tasks/42' }), ''); @@ -24,7 +24,8 @@ assert.match(storage, /acceptedTask\(`\/api\/v1\/admin\/hosts\/\$\{encodeURIComp assert.match(storage, /announceTaskAccepted\(receipt/); assert.match(storage, /observeHostStorageTask\(receipt, hostId\)/); assert.match(storageObserver, /observeTask\(receipt/); -assert.match(storageObserver, /task\.status === 'succeeded'/); +assert.match(storageObserver, /taskSucceededWithoutRecovery\(task\)/); +assert.doesNotMatch(storageObserver, /task\.status === 'succeeded'/); assert.match(storageObserver, /api\(`\/api\/v1\/admin\/hosts\/\$\{encodeURIComponent\(hostId\)\}\/storage-configuration`\)/); assert.match(storageObserver, /renderHostStorage\(payload\)/); assert.match(storageObserver, /task\.effect_may_have_applied === true/); diff --git a/web/tests/AdminInstanceViewTest.php b/web/tests/AdminInstanceViewTest.php index dfd93626..3e922f08 100644 --- a/web/tests/AdminInstanceViewTest.php +++ b/web/tests/AdminInstanceViewTest.php @@ -41,6 +41,8 @@ $items = [ 'active_job' => ['id' => '61', 'kind' => 'reinstall', 'completed' => true, 'status' => 'failed', 'blocks_mutation' => true, 'effect_may_have_applied' => true, 'safe_to_resubmit' => false, + 'recovery' => ['pending' => true, + 'message' => '系统仍会继续自动核对。'], 'attempts' => 1, 'error' => '任务失败', 'phase' => null, 'created_at' => $now - 300, 'updated_at' => $now - 10]]), ]; @@ -142,7 +144,7 @@ $assert(str_contains($dom->textContent, '192.0.2.101') && str_contains($dom->textContent, '20 GiB / 100 GiB') && str_contains($dom->textContent, '香港宿主机 A') && str_contains($dom->textContent, '已失败') - && str_contains($dom->textContent, '资源安全锁定,需管理员人工处理'), + && str_contains($dom->textContent, '资源安全锁定,仍会继续自动核对'), 'Useful instance data or terminal safety-lock state is missing before scripts run.'); $assert(str_contains($clientScript, "task?.completed === false && task.status === 'active'") diff --git a/web/tests/AdminOperationsCancelBehaviorTest.mjs b/web/tests/AdminOperationsCancelBehaviorTest.mjs index bbde6afb..26630335 100644 --- a/web/tests/AdminOperationsCancelBehaviorTest.mjs +++ b/web/tests/AdminOperationsCancelBehaviorTest.mjs @@ -7,11 +7,17 @@ const rows = await readFile(new URL('../resources/views/venix/admin/cloud/operat const shipped = `${source}\n${template}\n${rows}`; // The fresh task architecture deliberately has no browser control that -// replays, inspects, aborts, cleans, or stops an old task workflow. +// replays, aborts, cleans, or stops an old task workflow. Read-only recovery +// status is visible, but it never becomes a browser-triggered mutation retry. for (const forbidden of [ 'stop-auto', 'abort-job', '/cleanup', 'can_stop_auto_reconcile', - 'job_id', 'uncertain', 'needs_attention', '自动核对', '待核对', '正在核对', + 'job_id', 'uncertain', 'needs_attention', '待核对', ]) assert.doesNotMatch(shipped, new RegExp(forbidden)); +assert.match(source, /job\.recovery\?\.pending === true/); +assert.match(source, /系统不会重复执行原操作/); +assert.match(source, /账本异常 · 待修复/); +assert.match(source, /派发账本修复/); +assert.match(source, /PHP 本地账本收尾/); // Admin task rendering accepts one active representation and the exact two // public terminal states. Unknown payloads are rendered as protocol failures. @@ -38,6 +44,8 @@ assert.match(source, /taskUrl\(payload\)/); assert.match(source, /announceTaskAccepted\(payload/); assert.match(source, /observeTask\(payload/); assert.match(source, /taskFailureMessage\(task/); +assert.match(source, /taskSucceededWithoutRecovery\(task\)/); +assert.doesNotMatch(source, /task\.status === 'succeeded'/); assert.match(source, /await loadPage\(listUrl\(\), 'none'\)/); assert.match(source, /await openDetail\(task\.id, null\)/); assert.match(source, /forceDeleteAccepted = true/); @@ -51,6 +59,10 @@ assert.doesNotMatch(source, /setInterval\(/); // retries or changes the original task to success in the browser. assert.match(source, /\/inspect`/); assert.match(source, /method: 'POST', body: '\{\}'/); +assert.match(source, /state\.inspection\.completion_delivery_error/); +assert.match(source, /infoList\(\[\['回执异常', completionDeliveryError\]\]\)/); +assert.match(source, /if \(content !== undefined\) node\.textContent = String\(content\)/); +assert.doesNotMatch(source, /completion_delivery_error[^\n]*innerHTML/); assert.match(source, /\/resolve-effect`/); assert.match(source, /JSON\.stringify\(\{ resolution, reason \}\)/); assert.match(source, /reason\.length < 20 \|\| reason\.length > 500/); diff --git a/web/tests/AdminOperationsViewTest.php b/web/tests/AdminOperationsViewTest.php index faef307e..b8e98546 100644 --- a/web/tests/AdminOperationsViewTest.php +++ b/web/tests/AdminOperationsViewTest.php @@ -16,6 +16,13 @@ $common = [ 'completed' => true, 'status' => 'failed', 'attempts' => 1, 'effect_may_have_applied' => true, 'safe_to_resubmit' => false, 'effect_resolution' => 'unknown', + 'recovery' => [ + 'pending' => true, + 'code' => 'recovery_waiting_connection', + 'message' => '宿主机 Agent 或网络暂不可用;通信恢复后系统仍会继续自动核对。', + 'last_checked_at' => $now - 60, + 'next_check_at' => $now + 240, + ], 'error' => '回执超时,操作效果可能已发生', 'phase' => null, 'host_id' => '7', 'host_name' => '香港宿主机 A', 'region' => 'HongKong', 'actor_id' => '42', 'actor_name' => '演示管理员', 'actor_email' => 'a***@example.test', @@ -35,12 +42,14 @@ $items = [ 'error' => '镜像不可用,创建未完成', 'attention_reason' => 'failed', 'order_id' => '301', 'effect_may_have_applied' => false, 'safe_to_resubmit' => false, 'effect_resolution' => 'not_applicable', + 'recovery' => null, 'links' => ['instance' => null, 'billing' => '/admin/billing?view=orders&q=301'], 'display' => ['kind' => '创建实例', 'status' => '失败', 'attention' => '执行失败', 'lease' => '未持有执行租约']]), array_replace($common, ['id' => '43', 'kind' => 'expiry_delete', 'kind_label' => '到期清理', 'completed' => false, 'status' => 'active', 'effect_may_have_applied' => null, 'safe_to_resubmit' => null, 'effect_resolution' => 'not_applicable', + 'recovery' => null, 'can_inspect' => false, 'inspect_reason' => '任务未关联可核对的宿主机操作', 'attempts' => 0, 'error' => null, 'phase' => null, 'dispatched_at' => null, 'available_at' => $now - 600, 'attention' => false, 'attention_reason' => null, @@ -53,7 +62,17 @@ $items = [ 'kind_label' => '配置宿主机存储', 'instance_id' => null, 'instance_name' => null, 'instance_uuid' => null, 'instance_status' => null, 'owner_id' => null, 'owner_name' => null, - 'owner_email' => null]), + 'owner_email' => null, 'recovery' => null]), + array_replace($common, ['id' => '45', 'status' => 'succeeded', + 'error' => null, 'effect_may_have_applied' => false, + 'effect_resolution' => 'applied', + 'recovery' => [ + 'pending' => true, + 'code' => 'recovery_dispatch_repair_instance_state_conflict', + 'message' => '派发账本已修复,但任务状态仍与恢复证据矛盾;资源保持锁定并持续核对。', + 'last_checked_at' => $now - 60, + 'next_check_at' => $now + 240, + ]]), ]; $page = [ 'items' => $items, @@ -119,9 +138,13 @@ $dom = new DOMDocument(); libxml_use_internal_errors(true); $dom->loadHTML('' . $html); $xpath = new DOMXPath($dom); -$assert($xpath->query('//tbody[@id="operations-body"]/tr')->length === 4, 'SSR must include all task rows.'); +$assert($xpath->query('//tbody[@id="operations-body"]/tr')->length === 5, 'SSR must include all task rows.'); +$assert($xpath->query('//tr[@data-operation-id="45"]//strong[contains(@class,"text-warning") and contains(.,"安全恢复中")]')->length === 1 + && $xpath->query('//tr[@data-operation-id="45"]//strong[contains(@class,"text-success")]')->length === 0, + 'A succeeded terminal receipt with a sticky repair incident was falsely rendered as ordinary success.'); $assert(str_contains($dom->textContent, 'vm-demo') && str_contains($dom->textContent, '系统策略') - && str_contains($dom->textContent, '操作效果可能已发生') + && str_contains($dom->textContent, '安全恢复中') + && str_contains($dom->textContent, '仍会继续自动核对') && str_contains($dom->textContent, '后续任务须沿用已定义固定池的路径') && str_contains($dom->textContent, '执行中'), 'Useful task records and terminal safety state are absent before JavaScript.'); diff --git a/web/tests/AdminOverviewContractTest.php b/web/tests/AdminOverviewContractTest.php index ebf6d3c6..f112ab62 100644 --- a/web/tests/AdminOverviewContractTest.php +++ b/web/tests/AdminOverviewContractTest.php @@ -92,7 +92,7 @@ $assert(str_contains($template, 'card overflow-hidden admin-stat-card') && str_contains($template, '/admin/operations?status=failed') && str_contains($template, '资源锁定') && !str_contains($template, 'needs_attention') - && !str_contains($template, '自动核对') + && str_contains($template, '持续自动核对') && substr_count($template, 'card overflow-hidden admin-stat-card') === 4 && !preg_match('/text-bg-(?:success|info|warning|danger)/', $template) && str_contains($template, 'bg-danger-subtle text-danger-emphasis') diff --git a/web/tests/CloudAdminInstanceServiceTest.php b/web/tests/CloudAdminInstanceServiceTest.php index f053c551..6bf7e846 100644 --- a/web/tests/CloudAdminInstanceServiceTest.php +++ b/web/tests/CloudAdminInstanceServiceTest.php @@ -164,8 +164,13 @@ namespace { $schema->create('cloud_jobs', static function (Blueprint $table): void { $table->increments('id'); $table->string('operation_id'); + $table->string('request_idempotency_key'); + $table->string('request_fingerprint'); + $table->integer('parent_job_id')->nullable(); $table->integer('instance_id')->nullable(); $table->integer('order_id')->nullable(); + $table->integer('invoice_id')->nullable(); + $table->integer('snapshot_id')->nullable(); $table->integer('user_id'); $table->integer('host_id')->default(7); $table->string('kind'); @@ -174,14 +179,21 @@ namespace { $table->string('outcome')->nullable(); $table->string('status'); $table->integer('attempts')->default(0); + $table->integer('dispatch_attempts')->nullable()->default(0); + $table->integer('dispatch_deadline_at')->default(0); + $table->integer('dispatch_started_at')->nullable(); + $table->integer('agent_accepted_at')->nullable(); $table->integer('dispatched_at')->nullable(); + $table->integer('receipt_deadline_at')->nullable(); $table->boolean('effect_may_have_applied')->nullable(); $table->boolean('safe_to_resubmit')->nullable(); $table->string('effect_resolution')->default('not_applicable'); $table->integer('terminal_at')->nullable(); + $table->string('completion_event_id')->nullable(); $table->string('error_code')->nullable(); $table->boolean('finalization_incident')->default(0); $table->string('finalization_error_code')->nullable(); + $table->integer('available_at')->default(0); $table->text('sealed_payload')->default('must-not-expose-job-payload'); $table->text('result_json')->nullable(); $table->integer('created_at'); @@ -269,7 +281,19 @@ namespace { $insertJob = static function (int $id, array $overrides = []) use ($now): void { $values = array_replace([ 'id' => $id, 'operation_id' => sprintf('%032d', $id), + 'request_idempotency_key' => sprintf('%032d', $id), + 'request_fingerprint' => hash('sha256', (string) $id), + 'parent_job_id' => null, + 'order_id' => null, 'invoice_id' => null, 'snapshot_id' => null, 'instance_id' => 206, 'user_id' => 99, 'kind' => 'action', + 'execution_mode' => 'agent', 'dispatch_attempts' => 1, + 'attempts' => 1, + 'dispatch_deadline_at' => $now - 90, + 'dispatch_started_at' => $now - 80, + 'agent_accepted_at' => $now - 70, + 'dispatched_at' => $now - 75, + 'receipt_deadline_at' => $now - 60, + 'completion_event_id' => null, 'phase' => 'terminal', 'outcome' => 'succeeded', 'created_at' => $now - 100, 'updated_at' => $now, 'result_json' => json_encode([ @@ -277,6 +301,17 @@ namespace { 'unreviewed_note' => 'must-not-expose-unknown-job-result', ]), ], $overrides); + if (($values['execution_mode'] ?? '') === 'agent' + && (int) ($values['dispatch_attempts'] ?? -1) === 0) { + foreach (['attempts' => 0, 'dispatch_started_at' => null, + 'agent_accepted_at' => null, 'dispatched_at' => null, + 'receipt_deadline_at' => null, 'completion_event_id' => null] + as $field => $value) { + if (!array_key_exists($field, $overrides)) { + $values[$field] = $value; + } + } + } if ($values['phase'] === 'terminal') { if (!in_array($values['outcome'], ['succeeded', 'failed'], true)) { throw new RuntimeException('Terminal job fixtures require a supported outcome.'); @@ -421,6 +456,9 @@ namespace { 'instance_id' => 213, 'outcome' => 'failed', 'effect_may_have_applied' => true, 'safe_to_resubmit' => false, 'effect_resolution' => 'unknown', + 'finalization_incident' => true, + 'finalization_error_code' => 'recovery_state_invalid', + 'available_at' => $now + 30, 'dispatched_at' => $now - 20, ]); $insertJob(32, [ @@ -431,9 +469,9 @@ namespace { // the older active task that still owns the resource mutation fence. $insertJob(33, [ 'instance_id' => 214, 'outcome' => 'failed', + 'dispatch_attempts' => 0, 'effect_may_have_applied' => false, 'safe_to_resubmit' => false, 'effect_resolution' => 'not_applicable', - 'dispatched_at' => null, ]); $attentionDetail = CloudAdminInstanceService::detail($admin, '213'); $activeDetail = CloudAdminInstanceService::detail($admin, '214'); @@ -441,10 +479,141 @@ namespace { && $attentionDetail['instance']['active_job']['completed'] === true && $attentionDetail['instance']['active_job']['status'] === 'failed' && $attentionDetail['instance']['active_job']['blocks_mutation'] === true + && ($attentionDetail['instance']['active_job']['recovery']['pending'] + ?? null) === true + && str_contains( + (string) ($attentionDetail['instance']['active_job']['recovery']['message'] + ?? ''), + '仍会继续自动核对' + ) && (int) $activeDetail['instance']['active_job']['id'] === 32 && $activeDetail['instance']['active_job']['completed'] === false && $activeDetail['instance']['active_job']['status'] === 'active', 'Administrator detail omitted an active task or terminal failed safety fence.'); + $insertJob(34, [ + 'instance_id' => 204, + 'dispatch_attempts' => 2, + 'outcome' => 'succeeded', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'effect_resolution' => 'applied', + 'finalization_incident' => false, + 'finalization_error_code' => null, + ]); + $invalidSucceededDetail = CloudAdminInstanceService::detail( + $admin, + '204' + ); + $assert((int) $invalidSucceededDetail['instance']['active_job']['id'] === 34 + && $invalidSucceededDetail['instance']['active_job']['completed'] === true + && $invalidSucceededDetail['instance']['active_job']['status'] === 'succeeded' + && $invalidSucceededDetail['instance']['active_job']['blocks_mutation'] === true + && ($invalidSucceededDetail['instance']['active_job']['recovery']['pending'] + ?? null) === true, + 'A succeeded task with an invalid dispatch ledger did not retain the administrator mutation fence.'); + $insertJob(35, [ + 'instance_id' => 203, + 'outcome' => 'succeeded', + 'dispatch_attempts' => 1, + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'effect_resolution' => 'applied', + 'finalization_incident' => true, + 'finalization_error_code' => 'recovery_dispatch_ledger_conflict', + ]); + $insertJob(36, [ + 'instance_id' => 202, + 'outcome' => 'failed', + 'dispatch_attempts' => 0, + 'dispatched_at' => null, + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'effect_resolution' => 'not_applied', + 'finalization_incident' => true, + 'finalization_error_code' => 'recovery_ledger_conflict', + ]); + $insertJob(37, [ + 'instance_id' => 201, + 'outcome' => 'succeeded', + 'dispatch_attempts' => null, + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'effect_resolution' => 'applied', + 'finalization_incident' => false, + 'finalization_error_code' => null, + ]); + $insertJob(38, [ + 'instance_id' => 200, + 'outcome' => 'succeeded', + 'dispatch_attempts' => 1, + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'effect_resolution' => 'not_applied', + 'finalization_incident' => false, + 'finalization_error_code' => null, + ]); + $insertJob(39, [ + 'instance_id' => 199, + 'outcome' => 'succeeded', + 'dispatch_attempts' => 1, + 'receipt_deadline_at' => null, + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'effect_resolution' => 'applied', + 'finalization_incident' => false, + 'finalization_error_code' => null, + ]); + $stickyDetail = CloudAdminInstanceService::detail($admin, '203'); + $localFinalizerDetail = CloudAdminInstanceService::detail($admin, '202'); + $nullLedgerDetail = CloudAdminInstanceService::detail($admin, '201'); + $resolvedConflictDetail = CloudAdminInstanceService::detail($admin, '200'); + $envelopeConflictDetail = CloudAdminInstanceService::detail($admin, '199'); + $assert((int) $stickyDetail['instance']['active_job']['id'] === 35 + && $stickyDetail['instance']['active_job']['status'] === 'succeeded' + && $stickyDetail['instance']['active_job']['blocks_mutation'] === true + && ($stickyDetail['instance']['active_job']['recovery']['code'] ?? null) + === 'recovery_dispatch_ledger_conflict', + 'A repaired succeeded task was presented as unlocked before sticky validation.'); + $assert((int) $localFinalizerDetail['instance']['active_job']['id'] === 36 + && $localFinalizerDetail['instance']['active_job']['status'] === 'failed' + && $localFinalizerDetail['instance']['active_job']['blocks_mutation'] === true + && str_contains( + (string) ($localFinalizerDetail['instance']['active_job']['recovery']['message'] + ?? ''), + '面板账本' + ), + 'A zero-dispatch PHP finalizer failure was omitted from the active safety fence.'); + $assert((int) $nullLedgerDetail['instance']['active_job']['id'] === 37 + && $nullLedgerDetail['instance']['active_job']['status'] === 'succeeded' + && $nullLedgerDetail['instance']['active_job']['blocks_mutation'] === true + && ($nullLedgerDetail['instance']['active_job']['recovery']['code'] ?? null) + === 'recovery_dispatch_ledger_conflict', + 'A NULL dispatch counter was presented as an ordinary succeeded task.'); + $assert((int) $resolvedConflictDetail['instance']['active_job']['id'] === 38 + && $resolvedConflictDetail['instance']['active_job']['status'] + === 'succeeded' + && $resolvedConflictDetail['instance']['active_job']['blocks_mutation'] + === true + && ($resolvedConflictDetail['instance']['active_job']['recovery']['code'] + ?? null) === 'recovery_instance_state_conflict', + 'A succeeded/not_applied terminal contradiction escaped the instance safety fence.'); + $assert((int) $envelopeConflictDetail['instance']['active_job']['id'] === 39 + && $envelopeConflictDetail['instance']['active_job']['status'] + === 'succeeded' + && $envelopeConflictDetail['instance']['active_job']['blocks_mutation'] + === true + && ($envelopeConflictDetail['instance']['active_job']['recovery']['code'] + ?? null) === 'recovery_instance_state_conflict', + 'A resolved Agent envelope with no receipt deadline escaped the instance safety fence.'); + $jobAttentionIds = $ids(CloudAdminInstanceService::page( + $admin, + ['attention' => 'jobs'] + )['items']); + foreach ([204, 203, 202, 201, 200, 199] as $expectedAttentionId) { + $assert(in_array($expectedAttentionId, $jobAttentionIds, true), + 'Administrator job-attention filter omitted recovery-fenced instance ' + . $expectedAttentionId . '.'); + } $unsupported = CloudAdminInstanceService::detail($admin, '214'); $assert($unsupported['instance']['network_change_supported'] === false && $unsupported['instance']['instance_settings_supported'] === false, diff --git a/web/tests/CloudAdminOperationRecoveryServiceTest.php b/web/tests/CloudAdminOperationRecoveryServiceTest.php index 7bc3d3fb..9b9c68d5 100644 --- a/web/tests/CloudAdminOperationRecoveryServiceTest.php +++ b/web/tests/CloudAdminOperationRecoveryServiceTest.php @@ -1,6 +1,27 @@ increments('id'); $table->string('operation_id'); + $table->string('request_idempotency_key'); + $table->string('request_fingerprint'); $table->integer('host_id'); $table->string('kind'); $table->string('execution_mode')->default('agent'); @@ -124,11 +150,16 @@ namespace { $table->integer('user_id')->default(99); $table->integer('instance_id')->nullable(); $table->integer('order_id')->nullable(); + $table->integer('parent_job_id')->nullable(); $table->integer('snapshot_id')->nullable(); $table->integer('attempts')->default(1); $table->integer('dispatch_attempts')->default(1); $table->integer('dispatch_deadline_at')->default(1); + $table->integer('dispatch_started_at')->nullable(); + $table->integer('agent_accepted_at')->nullable(); $table->integer('dispatched_at')->nullable(); + $table->integer('receipt_deadline_at')->nullable(); + $table->string('completion_event_id')->nullable(); $table->integer('terminal_at')->nullable(); $table->boolean('effect_may_have_applied')->nullable(); $table->boolean('safe_to_resubmit')->nullable(); @@ -145,6 +176,14 @@ namespace { $table->integer('created_at')->nullable(); $table->integer('updated_at')->nullable(); }); + $capsule->schema('default')->create('cloud_instances', + static function (Blueprint $table): void { + $table->increments('id'); + $table->string('uuid'); + $table->integer('host_id'); + $table->integer('user_id'); + $table->string('status'); + }); $now = time(); foreach ([ 41 => 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', @@ -154,25 +193,77 @@ namespace { ] as $id => $operationId) { Capsule::table('cloud_jobs')->insert([ 'id' => $id, 'operation_id' => $operationId, 'host_id' => 7, + 'request_idempotency_key' => $operationId, + 'request_fingerprint' => hash('sha256', $operationId), 'kind' => 'create', 'order_id' => 100, 'phase' => 'terminal', 'outcome' => 'failed', 'status' => 'failed', 'dispatched_at' => $now - 90, + 'dispatch_started_at' => $now - 100, + 'agent_accepted_at' => $now - 95, + 'receipt_deadline_at' => $now + 30, 'terminal_at' => $now - 30, 'effect_may_have_applied' => true, 'safe_to_resubmit' => false, 'effect_resolution' => 'unknown', + 'sealed_payload' => CloudSecrets::encrypt([ + 'method' => 'POST', + 'request_target' => '/v1/vms', + 'body' => [ + 'source' => 'cloud', + 'name' => 'vm-recovery-' . $id, + 'vcpu' => 2, + 'memory_mib' => 2048, + 'disk_gib' => 40, + 'bandwidth_mbps' => 100, + 'network' => 'bridge:br0', + 'template_id' => 'debian-13', + 'template_revision' => 1, + 'template_generation_token' => str_repeat('1', 32), + 'root_password' => 'StrongPassword!123', + 'public_pool_key' => str_repeat('2', 32), + 'public_pool_cidr' => '203.0.113.0/24', + 'public_ip_cidr' => '203.0.113.41/24', + 'gateway' => '203.0.113.1', + 'dns_servers' => ['1.1.1.1'], + 'platform_network_policy_snapshot' => [ + 'schema_version' => 1, + ], + ], + 'template_metadata' => [ + 'template_id' => 'debian-13', + 'os_source' => 'cloud_template', + 'os_name' => 'Debian 13', + 'login_name' => 'root', + ], + ], 'job-payload'), 'created_at' => $now - 120, 'updated_at' => $now - 30, ]); } + Capsule::table('cloud_instances')->insert([ + 'id' => 45, + 'uuid' => '123e4567-e89b-42d3-a456-426614174000', + 'host_id' => 7, + 'user_id' => 99, + 'status' => 'active', + ]); Capsule::table('cloud_jobs')->insert([ 'id' => 45, 'operation_id' => 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', + 'request_idempotency_key' => + 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', + 'request_fingerprint' => hash( + 'sha256', + 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' + ), 'host_id' => 7, 'kind' => 'instance_settings', 'phase' => 'terminal', 'outcome' => 'failed', 'status' => 'failed', 'dispatched_at' => $now - 90, + 'dispatch_started_at' => $now - 100, + 'agent_accepted_at' => $now - 95, + 'receipt_deadline_at' => $now + 30, 'terminal_at' => $now - 30, 'effect_may_have_applied' => true, 'safe_to_resubmit' => false, @@ -181,10 +272,31 @@ namespace { . ($now - 60) . ':1:prepared:automatic_applied_failed_fence:' . str_repeat('a', 64) . ':' . str_repeat('b', 64), + 'instance_id' => 45, + 'sealed_payload' => CloudSecrets::encrypt([ + 'method' => 'POST', + 'request_target' => '/v1/vms/' + . '123e4567-e89b-42d3-a456-426614174000/settings', + 'body' => [ + 'operation_id' => 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', + 'hostname' => 'safe.example', + 'confirm_restart' => true, + ], + 'owner_id' => 99, + 'can_manage' => false, + 'settings_fields' => ['hostname'], + 'credential' => null, + ], 'job-payload'), 'created_at' => $now - 120, 'updated_at' => $now - 30, ]); + $identityA = CloudOperationRecoveryIdentity::expected(CloudJob::find(41)); + $identityB = CloudOperationRecoveryIdentity::expected(CloudJob::find(42)); + $identityC = CloudOperationRecoveryIdentity::expected(CloudJob::find(43)); + $identityD = CloudOperationRecoveryIdentity::expected(CloudJob::find(44)); + $identityE = CloudOperationRecoveryIdentity::expected(CloudJob::find(45)); + $admin = ['user_id' => 99, 'is_admin' => true, 'is_super_admin' => true, 'can_manage' => true]; $readonly = ['user_id' => 98, 'is_admin' => true, @@ -192,6 +304,64 @@ namespace { $client = new RecoveryTestAgentClient(); CloudAgentSettingsService::$client = $client; + $before = count($client->requests); + $beforeClientBuilds = count(CloudAgentSettingsService::$calls); + Capsule::table('cloud_jobs')->where('id', 41)->update([ + 'execution_mode' => 'local', + 'phase' => 'accepted', + 'outcome' => null, + 'status' => 'queued', + ]); + $reject(static fn () => Recovery::inspect($admin, '41'), 409); + $assert(count($client->requests) === $before + && count(CloudAgentSettingsService::$calls) === $beforeClientBuilds, + 'A nonterminal supported Agent kind with a damaged execution mode reached the Agent client.'); + Capsule::table('cloud_jobs')->where('id', 41)->update([ + 'kind' => 'template_import', + 'execution_mode' => 'agent', + ]); + $reject(static fn () => Recovery::inspect($admin, '41'), 409); + $assert(count($client->requests) === $before + && count(CloudAgentSettingsService::$calls) === $beforeClientBuilds, + 'A malformed aggregate identity reached the Agent client.'); + Capsule::table('cloud_jobs')->where('id', 41)->update([ + 'kind' => 'create', + 'execution_mode' => 'agent', + 'phase' => 'terminal', + 'outcome' => 'failed', + 'status' => 'failed', + ]); + Capsule::table('cloud_jobs')->where('id', 45)->update([ + 'receipt_deadline_at' => null, + ]); + $reject(static fn () => Recovery::inspect($admin, '45'), 409); + $assert(count($client->requests) === $before + && count(CloudAgentSettingsService::$calls) === $beforeClientBuilds, + 'A terminal Agent task with a damaged immutable envelope reached the Agent client.'); + Capsule::table('cloud_jobs')->where('id', 45)->update([ + 'receipt_deadline_at' => $now + 30, + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'effect_resolution' => 'applied', + 'finalization_incident' => true, + 'finalization_error_code' => 'recovery_ledger_conflict', + ]); + $reject(static fn () => Recovery::inspect($admin, '45'), 409); + $assert(count($client->requests) === $before + && count(CloudAgentSettingsService::$calls) === $beforeClientBuilds, + 'A resolved sticky recovery incident reached the Agent client.'); + Capsule::table('cloud_jobs')->where('id', 45)->update([ + 'outcome' => 'failed', + 'status' => 'failed', + 'effect_may_have_applied' => true, + 'safe_to_resubmit' => false, + 'effect_resolution' => 'unknown', + 'finalization_incident' => false, + 'finalization_error_code' => null, + ]); + $before = count($client->requests); $reject(static fn () => Recovery::inspectForRecovery('41'), 409); $reject(static fn () => Recovery::resolveFenceForRecovery( @@ -231,10 +401,13 @@ namespace { ], 'abort_job' => ['available' => false], 'cleanup' => ['available' => false], - ]; + ] + $identityA; $inspection = Recovery::inspect($admin, '41'); $assert($inspection === [ 'operation_id' => $operationA, + 'action' => $identityA['action'], + 'resource_id' => $identityA['resource_id'], + 'request_fingerprint' => $identityA['request_fingerprint'], 'journal_status' => 'failed', 'checked_at' => $now, 'outcome' => 'failed', @@ -280,7 +453,7 @@ namespace { 'abort_job' => ['available' => false], 'cleanup' => ['available' => false], 'raw_error' => '/srv/private/secret.qcow2', - ]; + ] + $identityA; $reject(static fn () => Recovery::inspect($admin, '41'), 502, 'agent_invalid_inspection'); @@ -302,7 +475,7 @@ namespace { 'effect_projection' => $safeProjection, 'abort_job' => ['available' => false], 'cleanup' => ['available' => false], - ]; + ] + $identityE; $before = count($client->requests); $systemInspection = Recovery::inspectForRecovery('45'); $requests = array_slice($client->requests, $before); @@ -321,6 +494,33 @@ namespace { ], 'Internal inspection lost its bounded recovery evidence or actor.'); + $client->responses[] = [ + 'operation_id' => $operationE, + 'operation_status' => 'failed', + 'checked_at' => $now, + 'outcome' => 'succeeded', + 'summary_code' => 'operation_succeeded', + 'effect_resolution' => 'applied', + 'fence_resolution_required' => true, + 'fence_state' => 'active', + 'completion_delivery_state' => 'quarantined', + 'completion_delivery_error_code' => + 'completion_receipt_invalid', + 'effect_projection' => $safeProjection, + 'abort_job' => ['available' => false], + 'cleanup' => ['available' => false], + ] + $identityE; + $poisonedInspection = Recovery::inspectForRecovery('45'); + $assert(($poisonedInspection['completion_delivery_state'] ?? null) + === 'quarantined' + && ($poisonedInspection['completion_delivery_error_code'] ?? null) + === 'completion_receipt_invalid' + && str_contains( + (string) ($poisonedInspection['completion_delivery_error'] ?? ''), + '完成回执内容无效' + ), + 'A quarantined completion did not retain its bounded Chinese cause.'); + $client->responses[] = [ 'operation_id' => $operationE, 'operation_status' => 'failed', @@ -333,7 +533,7 @@ namespace { 'effect_projection' => $safeProjection, 'abort_job' => ['available' => false], 'cleanup' => ['available' => false], - ]; + ] + $identityE; $resolvedInspection = Recovery::inspectForRecovery('45'); $assert(($resolvedInspection['effect_resolution'] ?? null) === 'applied' && ($resolvedInspection['fence_state'] ?? null) === 'resolved' @@ -359,6 +559,13 @@ namespace { 'hostname' => str_repeat('x', 65537), 'settings_changed' => true, ]], + ['effect_resolution' => 'applied', + 'effect_projection' => $safeProjection, + 'completion_delivery_state' => 'quarantined', + 'completion_delivery_error_code' => 'future_poison_reason'], + ['effect_resolution' => 'applied', + 'effect_projection' => $safeProjection, + 'completion_delivery_state' => 'quarantined'], ] as $unsafeEvidence) { $client->responses[] = [ 'operation_id' => $operationE, @@ -370,13 +577,30 @@ namespace { 'fence_state' => 'active', 'abort_job' => ['available' => false], 'cleanup' => ['available' => false], - ] + $unsafeEvidence; + ] + $unsafeEvidence + $identityE; $reject(static fn () => Recovery::inspectForRecovery('45'), 502, 'agent_invalid_inspection'); } $reason = '已人工只读核对虚拟机、磁盘与网络状态,确认原操作效果已经发生。'; $reasonDigest = hash('sha256', $reason); + $poisonedManualInspection = $inspection + [ + 'completion_delivery_state' => 'quarantined', + 'completion_delivery_error_code' => + 'completion_operation_invalid', + 'completion_delivery_error' => + 'Agent 完成回执对应的原操作记录无效,当前结果不能采信', + ]; + $before = count($client->requests); + $reject(static fn () => Recovery::resolveFence( + $admin, + '41', + 'not_applied', + $reason, + $poisonedManualInspection + ), 409); + $assert(count($client->requests) === $before, + 'A quarantined completion reached the Agent fence resolver.'); $oldReceipt = [ 'operation_id' => $operationA, 'resolution_id' => str_repeat('1', 32), @@ -468,7 +692,7 @@ namespace { 'operation_id' => $operationB, 'checked_at' => $now, 'outcome' => 'failed', 'summary_code' => 'operation_failed', 'error_code' => 'creation_absent', - ]; + ] + $identityB; $client->responses[] = $notFound(); $client->responses[] = static function (array $request) use ( $operationB, $now @@ -503,7 +727,7 @@ namespace { 'operation_id' => $operationC, 'checked_at' => $now, 'outcome' => 'failed', 'summary_code' => 'operation_failed', 'error_code' => 'creation_absent', - ]; + ] + $identityC; $client->responses[] = $notFound(); $client->responses[] = new CloudAgentError( 'lost response', 503, 'agent_disconnected', true, 503 @@ -540,7 +764,7 @@ namespace { 'operation_id' => $operationD, 'checked_at' => $now, 'outcome' => 'failed', 'summary_code' => 'operation_failed', 'error_code' => 'creation_absent', - ]; + ] + $identityD; $client->responses[] = array_replace($oldReceipt, [ 'operation_id' => $operationD, 'resolved_by' => 0, @@ -573,7 +797,7 @@ namespace { 'operation_id' => $operationA, 'checked_at' => $now - 121, 'outcome' => 'failed', 'summary_code' => 'operation_failed', 'error_code' => 'creation_absent', - ] + ] + $identityA ), 409); $assert(count($client->requests) === $before, 'Unauthorized or stale resolution reached the Agent.'); diff --git a/web/tests/CloudAdminOperationsServiceTest.php b/web/tests/CloudAdminOperationsServiceTest.php index 173b7ed2..58990658 100644 --- a/web/tests/CloudAdminOperationsServiceTest.php +++ b/web/tests/CloudAdminOperationsServiceTest.php @@ -73,23 +73,29 @@ namespace { $schema->create('cloud_jobs', static function (Blueprint $table): void { $table->increments('id'); $table->string('operation_id'); + $table->string('request_idempotency_key'); + $table->string('request_fingerprint'); $table->integer('parent_job_id')->nullable(); $table->integer('order_id')->nullable(); $table->integer('invoice_id')->nullable(); $table->integer('instance_id')->nullable(); + $table->integer('snapshot_id')->nullable(); $table->integer('user_id'); - $table->integer('host_id'); + $table->integer('host_id')->nullable(); $table->string('kind'); $table->string('execution_mode')->default('agent'); $table->string('phase'); $table->string('outcome')->nullable(); $table->string('status'); $table->integer('attempts')->default(0); - $table->integer('dispatch_attempts')->default(0); + $table->integer('dispatch_attempts')->nullable()->default(0); $table->integer('dispatch_deadline_at'); + $table->integer('dispatch_started_at')->nullable(); + $table->integer('agent_accepted_at')->nullable(); $table->integer('receipt_deadline_at')->nullable(); $table->integer('dispatched_at')->nullable(); $table->integer('terminal_at')->nullable(); + $table->string('completion_event_id')->nullable(); $table->boolean('effect_may_have_applied')->nullable(); $table->boolean('safe_to_resubmit')->nullable(); $table->string('effect_resolution')->default('not_applicable'); @@ -130,15 +136,21 @@ namespace { $insert = static function (int $id, array $values = []) use ($now): void { Capsule::table('cloud_jobs')->insert(array_replace([ 'id' => $id, 'operation_id' => sprintf('%032x', $id), + 'request_idempotency_key' => sprintf('%032x', $id), + 'request_fingerprint' => hash('sha256', (string) $id), 'order_id' => 100, 'instance_id' => 10, + 'snapshot_id' => null, 'user_id' => 99, 'host_id' => 7, 'kind' => 'action', 'phase' => 'terminal', 'outcome' => 'succeeded', 'status' => 'succeeded', 'attempts' => 1, 'dispatch_attempts' => 1, 'dispatch_deadline_at' => $now - 100, + 'dispatch_started_at' => $now - 95, + 'agent_accepted_at' => $now - 92, 'receipt_deadline_at' => $now - 50, 'dispatched_at' => $now - 90, 'terminal_at' => $now - 40, + 'completion_event_id' => null, 'effect_may_have_applied' => false, 'safe_to_resubmit' => false, 'effect_resolution' => 'not_applicable', @@ -161,12 +173,18 @@ namespace { 'outcome' => 'failed', 'status' => 'failed', 'effect_may_have_applied' => true, 'safe_to_resubmit' => false, 'effect_resolution' => 'unknown', 'error_code' => 'transport_lost', + 'finalization_incident' => true, + 'finalization_error_code' => 'recovery_evidence_conflict', + 'available_at' => $now + 45, 'result_json' => json_encode(['cause_code' => 'transport_lost'], JSON_THROW_ON_ERROR), ]); $insert(4, [ 'outcome' => 'failed', 'status' => 'failed', 'error_code' => 'operation_failed', + 'finalization_incident' => true, + 'finalization_error_code' => + 'PDOException: password=must-not-expose-server-error', ]); $insert(5, [ 'outcome' => 'failed', 'status' => 'failed', @@ -202,6 +220,15 @@ namespace { $assert($ids($page['items']) === $expected, 'Status filter diverged from task receipt state: ' . $status); } + $unsafeIncident = array_values(array_filter( + $all['items'], + static fn (array $item): bool => $item['id'] === '4' + ))[0]; + $assert($unsafeIncident['finalization_error_code'] + === 'finalization_failed' + && !str_contains(json_encode($unsafeIncident, + JSON_UNESCAPED_UNICODE), 'must-not-expose-server-error'), + 'Administrator DTO leaked an unreviewed server finalization error.'); foreach (["tenant's", '100%_vm', '11111111-1111-4111-8111-111111111110'] as $search) { $assert(Operations::page($admin, @@ -220,9 +247,23 @@ namespace { && $detail['effect_resolution'] === 'unknown' && $detail['can_inspect'] === true && $detail['can_resolve_effect'] === false + && ($detail['recovery']['pending'] ?? null) === true + && ($detail['recovery']['code'] ?? null) + === 'recovery_evidence_conflict' + && ($detail['recovery']['next_check_at'] ?? null) === $now + 45 + && str_contains((string) ($detail['recovery']['message'] ?? ''), + '仍会继续自动核对') && str_contains($detail['resolve_effect_reason'], '尚无可原子收敛业务账本'), 'Unknown-effect terminal failure lost its immutable outcome or safety fence.'); + $detailPayload = Operations::detail($admin, '3'); + $assert(str_contains(implode(' ', $detailPayload['notes']), + '绝不会重放原操作') + && str_contains(implode(' ', $detailPayload['notes']), + '仍会继续自动核对') + && !str_contains(implode(' ', $detailPayload['notes']), + '失败后不会自动核对'), + 'Administrator detail still described recoverable work as permanently manual.'); $active = Operations::detail($admin, '1')['job']; $assert($active['completed'] === false && $active['status'] === 'active', 'Accepted task was exposed as a fabricated terminal result.'); @@ -240,6 +281,185 @@ namespace { '不会更换已有池路径'), 'Storage failure was still presented as a durable resource blocker.'); + $insert(7, [ + 'outcome' => 'succeeded', 'status' => 'succeeded', + 'dispatch_attempts' => 1, + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'effect_resolution' => 'applied', + 'finalization_incident' => true, + 'finalization_error_code' => 'recovery_dispatch_ledger_conflict', + ]); + $insert(8, [ + 'outcome' => 'failed', 'status' => 'failed', + 'attempts' => 0, + 'dispatch_attempts' => 0, + 'dispatch_started_at' => null, + 'agent_accepted_at' => null, + 'dispatched_at' => null, + 'receipt_deadline_at' => null, + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'effect_resolution' => 'not_applied', + 'finalization_incident' => true, + 'finalization_error_code' => 'recovery_ledger_conflict', + ]); + $insert(9, [ + 'outcome' => 'succeeded', 'status' => 'succeeded', + 'dispatch_attempts' => null, + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'effect_resolution' => 'applied', + 'finalization_incident' => false, + 'finalization_error_code' => null, + ]); + $insert(10, [ + 'outcome' => 'succeeded', 'status' => 'succeeded', + 'dispatch_attempts' => 1, + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'effect_resolution' => 'not_applied', + 'finalization_incident' => false, + 'finalization_error_code' => null, + ]); + $insert(11, [ + 'outcome' => 'succeeded', 'status' => 'succeeded', + 'dispatch_attempts' => 1, + 'receipt_deadline_at' => null, + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'effect_resolution' => 'applied', + 'finalization_incident' => false, + 'finalization_error_code' => null, + ]); + $insert(12, [ + 'order_id' => null, 'instance_id' => null, 'host_id' => null, + 'kind' => 'template_import', 'execution_mode' => 'aggregate', + 'outcome' => 'succeeded', 'status' => 'succeeded', + 'attempts' => 0, 'dispatch_attempts' => 0, + 'dispatch_started_at' => null, 'agent_accepted_at' => null, + 'dispatched_at' => null, 'receipt_deadline_at' => null, + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'effect_resolution' => 'applied', + 'finalization_incident' => false, + 'finalization_error_code' => null, + ]); + $recoveryInventory = Operations::page($admin, ['status' => 'all']); + $assert($recoveryInventory['summary'] === [ + 'total' => 12, 'active' => 1, 'succeeded' => 6, + 'failed' => 5, 'unresolved_effect' => 7, + ] + && $ids(Operations::page($admin, ['status' => 'attention'])['items']) + === [12, 11, 10, 9, 8, 7, 6, 5, 4, 3] + && $ids(Operations::page($admin, ['status' => 'succeeded'])['items']) + === [12, 11, 10, 9, 7, 2], + 'Administrator summary/filtering omitted succeeded recovery incidents or local finalizers.'); + + $stickyRepair = Operations::detail($admin, '7')['job']; + $assert($stickyRepair['status'] === 'succeeded' + && $stickyRepair['display']['status'] === '恢复处理中' + && str_contains($stickyRepair['display']['effect'], '终态保持不变') + && ($stickyRepair['recovery']['code'] ?? null) + === 'recovery_dispatch_ledger_conflict' + && $stickyRepair['can_inspect'] === false + && $stickyRepair['can_resolve_effect'] === false + && str_contains($stickyRepair['inspect_reason'], '恢复账本'), + 'A repaired succeeded task appeared successful or exposed controls before sticky validation.'); + $localFinalizer = Operations::detail($admin, '8')['job']; + $assert($localFinalizer['dispatch_state'] === 'not_dispatched' + && $localFinalizer['display']['status'] === '恢复处理中' + && ($localFinalizer['recovery']['code'] ?? null) + === 'recovery_ledger_conflict' + && str_contains($localFinalizer['display']['effect'], 'PHP') + && str_contains($localFinalizer['display']['effect'], '不会联系 Agent') + && $localFinalizer['can_inspect'] === false + && $localFinalizer['can_resolve_effect'] === false, + 'A zero-dispatch PHP finalizer recovery was described as an Agent operation or unlocked.'); + $nullLedger = Operations::detail($admin, '9')['job']; + $assert($nullLedger['status'] === 'succeeded' + && $nullLedger['dispatch_attempts'] === null + && $nullLedger['dispatch_state'] === 'invalid' + && $nullLedger['display']['status'] === '恢复处理中' + && ($nullLedger['recovery']['code'] ?? null) + === 'recovery_dispatch_ledger_conflict' + && $nullLedger['can_inspect'] === false, + 'A NULL dispatch ledger was normalized to zero or shown as ordinary success.'); + $resolvedConflict = Operations::detail($admin, '10')['job']; + $assert($resolvedConflict['status'] === 'succeeded' + && $resolvedConflict['display']['status'] === '恢复处理中' + && ($resolvedConflict['recovery']['code'] ?? null) + === 'recovery_instance_state_conflict' + && $resolvedConflict['can_inspect'] === false, + 'A succeeded/not_applied terminal contradiction escaped administrator attention.'); + $envelopeConflict = Operations::detail($admin, '11')['job']; + $assert($envelopeConflict['status'] === 'succeeded' + && $envelopeConflict['display']['status'] === '恢复处理中' + && ($envelopeConflict['recovery']['code'] ?? null) + === 'recovery_instance_state_conflict' + && $envelopeConflict['can_inspect'] === false, + 'A resolved Agent task with an invalid receipt deadline escaped administrator attention.'); + $aggregateConflict = Operations::detail($admin, '12')['job']; + $assert($aggregateConflict['status'] === 'succeeded' + && $aggregateConflict['display']['status'] === '恢复处理中' + && ($aggregateConflict['recovery']['code'] ?? null) + === 'recovery_aggregate_state_conflict' + && $aggregateConflict['can_inspect'] === false, + 'A published aggregate with a missing receipt deadline escaped administrator attention.'); + + $insert(13, [ + 'kind' => 'delete', + 'outcome' => 'failed', 'status' => 'failed', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'effect_resolution' => 'not_applied', + 'error_code' => 'force_required', + ]); + $insert(14, [ + 'kind' => 'delete', + 'outcome' => 'failed', 'status' => 'failed', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'effect_resolution' => 'not_applied', + 'error_code' => 'force_required', + 'finalization_incident' => true, + 'finalization_error_code' => 'recovery_ledger_conflict', + ]); + $forceReady = Operations::detail($admin, '13')['job']; + $forceBlocked = Operations::detail($admin, '14')['job']; + $assert($forceReady['can_force_delete'] === true + && $forceBlocked['can_force_delete'] === false + && str_contains( + (string) $forceBlocked['force_delete_reason'], + '恢复账本异常' + ), + 'A sticky recovery incident exposed the destructive force-delete control.'); + $insert(15, [ + 'kind' => 'instance_settings', + 'execution_mode' => 'local', + 'phase' => 'accepted', + 'outcome' => null, + 'status' => 'queued', + 'dispatch_deadline_at' => $now + 100, + 'dispatch_attempts' => 0, + 'attempts' => 0, + 'dispatch_started_at' => null, + 'agent_accepted_at' => null, + 'dispatched_at' => null, + 'receipt_deadline_at' => null, + 'terminal_at' => null, + 'effect_may_have_applied' => null, + 'safe_to_resubmit' => null, + ]); + $wrongModeActive = Operations::detail($admin, '15')['job']; + $assert($wrongModeActive['completed'] === false + && $wrongModeActive['can_inspect'] === false + && str_contains( + (string) $wrongModeActive['inspect_reason'], + 'PHP 本地恢复' + ), + 'A nonterminal supported kind with a damaged mode exposed Agent inspection.'); + $reason = '已在宿主机只读核对虚拟机与磁盘,确认原操作效果已经发生。'; $operationId = sprintf('%032x', 3); $freshInspection = [ diff --git a/web/tests/CloudAgentMutationIdentityTest.php b/web/tests/CloudAgentMutationIdentityTest.php new file mode 100644 index 00000000..1f3bc032 --- /dev/null +++ b/web/tests/CloudAgentMutationIdentityTest.php @@ -0,0 +1,650 @@ +httpStatus === $status, + 'Unexpected CloudError status.'); + return; + } + throw new RuntimeException('Expected CloudError was not thrown.'); + }; + + $capsule = new Capsule(); + $capsule->addConnection([ + 'driver' => 'sqlite', 'database' => ':memory:', + ], 'default'); + $capsule->setAsGlobal(); + $capsule->bootEloquent(); + $schema = $capsule->schema('default'); + $schema->create('cloud_jobs', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('host_id'); + $table->integer('user_id'); + $table->integer('order_id')->nullable(); + $table->integer('instance_id')->nullable(); + $table->integer('snapshot_id')->nullable(); + $table->string('operation_id')->unique(); + $table->string('execution_mode'); + $table->string('kind'); + $table->string('phase'); + $table->string('outcome')->nullable(); + $table->string('status'); + $table->integer('dispatch_attempts')->default(1); + $table->integer('terminal_at')->nullable(); + $table->boolean('effect_may_have_applied')->nullable(); + $table->boolean('safe_to_resubmit')->nullable(); + $table->string('effect_resolution')->default('not_applicable'); + $table->text('sealed_payload'); + $table->string('completion_event_id')->nullable(); + $table->boolean('finalization_incident')->default(0); + $table->string('finalization_error_code')->nullable(); + $table->integer('read_at')->nullable(); + $table->string('lease_token')->nullable(); + $table->integer('lease_until')->default(0); + $table->integer('available_at')->default(0); + $table->string('error_code')->nullable(); + $table->integer('created_at'); + $table->integer('updated_at'); + }); + $schema->create('cloud_agent_completion_events', + static function (Blueprint $table): void { + $table->string('event_id')->primary(); + $table->integer('host_id'); + $table->string('operation_id'); + $table->string('payload_sha256'); + $table->string('outcome'); + $table->boolean('effect_may_have_applied'); + $table->boolean('safe_to_resubmit'); + $table->string('error_code')->default(''); + $table->text('result_json')->nullable(); + $table->string('disposition')->default('received'); + $table->integer('received_at'); + $table->integer('applied_at')->nullable(); + $table->unique(['host_id', 'operation_id']); + }); + $schema->create('cloud_host_storage_configurations', + static function (Blueprint $table): void { + $table->integer('host_id')->primary(); + $table->integer('revision'); + foreach (['managed', 'template', 'seed', 'user_iso', 'rescue'] + as $role) { + $table->text($role . '_directory'); + } + $table->string('state'); + $table->string('operation_id')->nullable(); + $table->integer('job_id')->nullable(); + $table->integer('created_at'); + $table->integer('updated_at'); + }); + + $now = time(); + $createBody = static function (string $operationId, int $suffix): array { + return [ + 'operation_id' => $operationId, + 'source' => 'cloud', + 'name' => 'identity-vm-' . $suffix, + 'vcpu' => 2, + 'memory_mib' => 2048, + 'disk_gib' => 40, + 'bandwidth_mbps' => 100, + 'network' => 'bridge:br0', + 'template_id' => 'debian-13', + 'template_revision' => 1, + 'template_generation_token' => str_repeat('1', 32), + 'root_password' => 'Identity-test9!Pass', + 'public_pool_key' => str_repeat('2', 32), + 'public_pool_cidr' => '203.0.113.0/24', + 'public_ip_cidr' => '203.0.113.' . $suffix . '/24', + 'gateway' => '203.0.113.1', + 'dns_servers' => ['1.1.1.1'], + 'platform_network_policy_snapshot' => ['schema_version' => 1], + ]; + }; + $insertCreate = static function ( + int $id, + string $operationId + ) use ($createBody, $now): void { + Capsule::table('cloud_jobs')->insert([ + 'id' => $id, + 'host_id' => 7, + 'user_id' => 11, + 'order_id' => 1000 + $id, + 'operation_id' => $operationId, + 'execution_mode' => 'agent', + 'kind' => 'create', + 'phase' => 'awaiting_receipt', + 'outcome' => null, + 'status' => 'running', + 'dispatch_attempts' => 1, + 'effect_resolution' => 'not_applicable', + 'sealed_payload' => CloudSecrets::encrypt([ + 'method' => 'POST', + 'request_target' => '/v1/vms', + 'body' => $createBody($operationId, 20 + $id), + 'credential' => [ + 'password' => 'Identity-test9!Pass', + 'login_name' => 'root', + 'auth_mode' => 'password', + ], + 'template_metadata' => [ + 'template_id' => 'debian-13', + 'os_source' => 'cloud_template', + 'os_name' => 'Debian 13', + 'login_name' => 'root', + ], + ], 'job-payload'), + 'created_at' => $now - 30, + 'updated_at' => $now - 10, + ]); + }; + + $createOperation = str_repeat('1a', 16); + $storageOperation = str_repeat('2b', 16); + $invalidCreateOperation = str_repeat('3c', 16); + $hashCreateOperation = str_repeat('4d', 16); + $secretCreateOperation = str_repeat('5e', 16); + $activeLedgerConflictOperation = str_repeat('6f', 16); + $terminalLedgerConflictOperation = str_repeat('70', 16); + $repairedDuringDeferOperation = str_repeat('81', 16); + $insertCreate(1, $createOperation); + $insertCreate(3, $invalidCreateOperation); + $insertCreate(4, $hashCreateOperation); + $insertCreate(5, $secretCreateOperation); + $insertCreate(6, $activeLedgerConflictOperation); + $insertCreate(7, $terminalLedgerConflictOperation); + $insertCreate(8, $repairedDuringDeferOperation); + $storageBody = [ + 'operation_id' => $storageOperation, + 'managed_directory' => '/srv/virt/managed', + 'template_directory' => '/srv/virt/templates', + 'seed_directory' => '/srv/virt/seeds', + 'user_iso_directory' => '/srv/virt/user-isos', + 'rescue_directory' => '/srv/virt/rescue', + ]; + Capsule::table('cloud_jobs')->insert([ + 'id' => 2, + 'host_id' => 8, + 'user_id' => 11, + 'operation_id' => $storageOperation, + 'execution_mode' => 'agent', + 'kind' => 'host_storage_configure', + 'phase' => 'dispatching', + 'outcome' => null, + 'status' => 'running', + 'dispatch_attempts' => 1, + 'effect_resolution' => 'not_applicable', + 'sealed_payload' => CloudSecrets::encrypt([ + 'method' => 'POST', + 'request_target' => '/v1/storage/configuration', + 'body' => $storageBody, + 'owner_id' => 11, + 'can_manage' => true, + 'storage_revision' => 4, + ], 'job-payload'), + 'created_at' => $now - 30, + 'updated_at' => $now - 10, + ]); + Capsule::table('cloud_host_storage_configurations')->insert([ + 'host_id' => 8, + 'revision' => 4, + 'managed_directory' => $storageBody['managed_directory'], + 'template_directory' => $storageBody['template_directory'], + 'seed_directory' => $storageBody['seed_directory'], + 'user_iso_directory' => $storageBody['user_iso_directory'], + 'rescue_directory' => $storageBody['rescue_directory'], + 'state' => 'applying', + 'operation_id' => $storageOperation, + 'job_id' => 2, + 'created_at' => $now - 30, + 'updated_at' => $now - 10, + ]); + + $createJob = CloudJob::findOrFail(1); + $storageJob = CloudJob::findOrFail(2); + $createIdentity = CloudOperationRecoveryIdentity::expected($createJob); + $storageIdentity = CloudOperationRecoveryIdentity::expected($storageJob); + $assert(CloudOperationRecoveryIdentity::supports('create') + && CloudOperationRecoveryIdentity::supports( + 'host_storage_configure' + ) + && !CloudOperationRecoveryPolicy::supports('create') + && !CloudOperationRecoveryPolicy::supports( + 'host_storage_configure' + ) + && $createIdentity['action'] === 'create-vm' + && preg_match( + '/^[a-f0-9]{8}-[a-f0-9]{4}-5[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/D', + $createIdentity['resource_id'] + ) === 1 + && $storageIdentity['action'] === 'configure-storage' + && $storageIdentity['resource_id'] === 'host-storage', + 'Agent identity support was incorrectly coupled to recovery policy.'); + + $operationForJob = new ReflectionMethod( + CloudWorkerService::class, + 'operationForJob' + ); + $validSync = [ + 'operation_id' => $createOperation, + 'status' => 'succeeded', + ] + $createIdentity; + $assert($operationForJob->invoke(null, $createJob, $validSync) + === $validSync, + 'A correctly bound synchronous create response was rejected.'); + $wrongSync = $validSync; + $wrongSync['resource_id'] = 'different-create-resource'; + try { + $operationForJob->invoke(null, $createJob, $wrongSync); + throw new RuntimeException( + 'A cross-operation synchronous create response was accepted.' + ); + } catch (CloudRecoveryOperationIdentityConflict $expected) { + // Expected: no result from the mismatched response can reach ledgers. + } + $validStorageSync = [ + 'operation_id' => $storageOperation, + 'status' => 'succeeded', + ] + $storageIdentity; + $wrongStorageSync = $validStorageSync; + $wrongStorageSync['request_fingerprint'] = str_repeat('f', 64); + try { + $operationForJob->invoke(null, $storageJob, $wrongStorageSync); + throw new RuntimeException( + 'A cross-operation synchronous storage response was accepted.' + ); + } catch (CloudRecoveryOperationIdentityConflict $expected) { + // Expected. + } + + $receipt = static function ( + string $eventId, + int $hostId, + string $operationId, + array $identity + ): array { + return [ + 'type' => 'completion', + 'id' => $eventId, + 'agent_id' => (string) $hostId, + 'operation_id' => $operationId, + 'action' => $identity['action'], + 'resource_id' => $identity['resource_id'], + 'request_fingerprint' => $identity['request_fingerprint'], + 'status' => 'succeeded', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'error_code' => '', + 'result' => [], + ]; + }; + + // Completion ingestion may persist evidence for a corrupt dispatch + // ledger, but it must not ACK/consume that evidence. Both an active task + // and an apparently settled terminal task stay visibly repairable until + // dispatch_attempts is restored to one of its only valid states (0/1). + Capsule::table('cloud_jobs')->where('id', 6)->update([ + 'dispatch_attempts' => 2, + ]); + $activeLedgerConflictJob = CloudJob::findOrFail(6); + $activeLedgerConflictReceipt = $receipt( + 'active-dispatch-ledger-conflict', + 7, + $activeLedgerConflictOperation, + CloudOperationRecoveryIdentity::expected( + $activeLedgerConflictJob, + true + ) + ); + $activeLedgerConflictAccepted = + CloudOperationCompletionService::accept( + $activeLedgerConflictReceipt + ); + $activeLedgerConflictJob->refresh(); + $activeLedgerConflictEvent = Capsule::table( + 'cloud_agent_completion_events' + )->where( + 'event_id', + $activeLedgerConflictReceipt['id'] + )->first(); + $assert($activeLedgerConflictAccepted === [ + 'accepted' => true, + 'disposition' => 'received', + ] + && (string) $activeLedgerConflictJob->phase === 'terminal' + && (string) $activeLedgerConflictJob->outcome === 'failed' + && (bool) $activeLedgerConflictJob->effect_may_have_applied + && !(bool) $activeLedgerConflictJob->safe_to_resubmit + && (string) $activeLedgerConflictJob->effect_resolution === 'unknown' + && (bool) $activeLedgerConflictJob->finalization_incident + && (string) $activeLedgerConflictJob->finalization_error_code + === 'recovery_dispatch_ledger_conflict' + && (string) $activeLedgerConflictEvent->disposition === 'received' + && $activeLedgerConflictEvent->applied_at === null, + 'An active invalid dispatch ledger consumed its immutable completion: ' + . json_encode([ + 'accepted' => $activeLedgerConflictAccepted, + 'job' => $activeLedgerConflictJob->toArray(), + 'event' => (array) $activeLedgerConflictEvent, + ], JSON_THROW_ON_ERROR)); + + $terminalLedgerConflictEventId = + 'terminal-dispatch-ledger-conflict'; + Capsule::table('cloud_jobs')->where('id', 7)->update([ + 'phase' => 'terminal', + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'dispatch_attempts' => 2, + 'terminal_at' => time(), + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'completion_event_id' => $terminalLedgerConflictEventId, + ]); + $terminalLedgerConflictJob = CloudJob::findOrFail(7); + $terminalLedgerConflictTerminalAt = + (int) $terminalLedgerConflictJob->terminal_at; + $terminalLedgerConflictReceipt = $receipt( + $terminalLedgerConflictEventId, + 7, + $terminalLedgerConflictOperation, + CloudOperationRecoveryIdentity::expected( + $terminalLedgerConflictJob, + true + ) + ); + $terminalLedgerConflictAccepted = + CloudOperationCompletionService::accept( + $terminalLedgerConflictReceipt + ); + $terminalLedgerConflictJob->refresh(); + $terminalLedgerConflictEvent = + \App\Models\CloudAgentCompletionEvent::where( + 'event_id', + $terminalLedgerConflictEventId + )->firstOrFail(); + $assert($terminalLedgerConflictAccepted === [ + 'accepted' => true, + 'disposition' => 'received', + ] + && (string) $terminalLedgerConflictJob->phase === 'terminal' + && (string) $terminalLedgerConflictJob->outcome === 'succeeded' + && (string) $terminalLedgerConflictJob->status === 'succeeded' + && !(bool) $terminalLedgerConflictJob->effect_may_have_applied + && !(bool) $terminalLedgerConflictJob->safe_to_resubmit + && (string) $terminalLedgerConflictJob->effect_resolution === 'applied' + && $terminalLedgerConflictJob->error_code === null + && (int) $terminalLedgerConflictJob->terminal_at + === $terminalLedgerConflictTerminalAt + && (string) $terminalLedgerConflictJob->completion_event_id + === $terminalLedgerConflictEventId + && (bool) $terminalLedgerConflictJob->finalization_incident + && (string) $terminalLedgerConflictJob->finalization_error_code + === 'recovery_dispatch_ledger_conflict' + && (string) $terminalLedgerConflictEvent->disposition === 'received' + && $terminalLedgerConflictEvent->applied_at === null + && !CloudOperationCompletionService::settledTaskWithEvent( + $terminalLedgerConflictJob, + $terminalLedgerConflictEvent + ), + 'A terminal invalid dispatch ledger ACKed a received completion.'); + + // Simulate an operator repairing the counter after a worker observed the + // invalid value but before deferDispatchLedgerConflict acquired its lock. + // The repaired value must remain sticky until background validation. + Capsule::table('cloud_jobs')->where('id', 8)->update([ + 'dispatch_attempts' => 2, + ]); + $repairedDuringDefer = CloudJob::findOrFail(8); + Capsule::table('cloud_jobs')->where('id', 8)->update([ + 'dispatch_attempts' => 1, + ]); + CloudOperationCompletionService::deferDispatchLedgerConflict( + $repairedDuringDefer + ); + $repairedDuringDefer->refresh(); + $assert((int) $repairedDuringDefer->dispatch_attempts === 1 + && (string) $repairedDuringDefer->phase === 'terminal' + && (string) $repairedDuringDefer->outcome === 'failed' + && (bool) $repairedDuringDefer->effect_may_have_applied + && (string) $repairedDuringDefer->effect_resolution === 'unknown' + && (bool) $repairedDuringDefer->finalization_incident + && (string) $repairedDuringDefer->finalization_error_code + === 'recovery_dispatch_ledger_conflict', + 'A lock-window dispatch repair bypassed the sticky safety incident.'); + + $wrongCreate = $receipt( + 'create-wrong-identity-event', + 7, + $createOperation, + $createIdentity + ); + $wrongCreate['resource_id'] = 'different-create-resource'; + $createAccepted = CloudOperationCompletionService::accept($wrongCreate); + $wrongStorage = $receipt( + 'storage-wrong-identity-event', + 8, + $storageOperation, + $storageIdentity + ); + $wrongStorage['request_fingerprint'] = str_repeat('f', 64); + $storageAccepted = CloudOperationCompletionService::accept($wrongStorage); + $createAfterWrong = CloudJob::findOrFail(1); + $storageAfterWrong = CloudJob::findOrFail(2); + $assert($createAccepted === [ + 'accepted' => true, 'disposition' => 'rejected', + ] + && $storageAccepted === [ + 'accepted' => true, 'disposition' => 'rejected', + ] + && (string) $createAfterWrong->phase === 'awaiting_receipt' + && $createAfterWrong->outcome === null + && (string) $createAfterWrong->effect_resolution === 'not_applicable' + && (string) $storageAfterWrong->phase === 'dispatching' + && $storageAfterWrong->outcome === null + && (string) $storageAfterWrong->effect_resolution + === 'not_applicable' + && (string) Capsule::table('cloud_host_storage_configurations') + ->where('host_id', 8)->value('state') === 'applying', + 'A wrong identity bypassed create or storage deadline finalization.'); + + $invalidCreate = $receipt( + 'create-invalid-receipt-event', + 7, + $invalidCreateOperation, + CloudOperationRecoveryIdentity::expected(CloudJob::findOrFail(3)) + ); + unset($invalidCreate['action']); + $expectCloudError( + static fn () => CloudOperationCompletionService::accept( + $invalidCreate + ), + 400 + ); + $invalidStorage = $receipt( + 'storage-invalid-receipt-event', + 8, + $storageOperation, + $storageIdentity + ); + unset($invalidStorage['action']); + $expectCloudError( + static fn () => CloudOperationCompletionService::accept( + $invalidStorage + ), + 400 + ); + $invalidCreateJob = CloudJob::findOrFail(3); + $invalidStorageJob = CloudJob::findOrFail(2); + $assert((string) $invalidCreateJob->phase === 'awaiting_receipt' + && $invalidCreateJob->outcome === null + && (bool) $invalidCreateJob->finalization_incident + && (string) $invalidCreateJob->finalization_error_code + === 'recovery_receipt_invalid' + && (string) $invalidStorageJob->phase === 'dispatching' + && $invalidStorageJob->outcome === null + && (bool) $invalidStorageJob->finalization_incident + && (string) $invalidStorageJob->finalization_error_code + === 'recovery_receipt_invalid' + && (string) Capsule::table('cloud_host_storage_configurations') + ->where('host_id', 8)->value('state') === 'applying', + 'An attributable invalid receipt bypassed create/storage finalizers.'); + + $hashIdentity = CloudOperationRecoveryIdentity::expected( + CloudJob::findOrFail(4) + ); + $hashReceipt = $receipt( + 'create-hash-conflict-event', + 7, + $hashCreateOperation, + $hashIdentity + ); + Capsule::table('cloud_agent_completion_events')->insert([ + 'event_id' => $hashReceipt['id'], + 'host_id' => 7, + 'operation_id' => $hashCreateOperation, + 'payload_sha256' => str_repeat('0', 64), + 'outcome' => 'failed', + 'effect_may_have_applied' => 1, + 'safe_to_resubmit' => 0, + 'error_code' => 'old_conflicting_receipt', + 'result_json' => null, + 'disposition' => 'rejected', + 'received_at' => $now - 5, + 'applied_at' => null, + ]); + $expectCloudError( + static fn () => CloudOperationCompletionService::accept($hashReceipt), + 409 + ); + $hashJob = CloudJob::findOrFail(4); + $assert((string) $hashJob->phase === 'awaiting_receipt' + && $hashJob->outcome === null + && (bool) $hashJob->finalization_incident + && (string) $hashJob->finalization_error_code + === 'recovery_operation_identity_conflict', + 'A payload-hash conflict was invisible or bypassed create finalization.'); + + $secretReceipt = $receipt( + 'create-secret-result-event', + 7, + $secretCreateOperation, + CloudOperationRecoveryIdentity::expected( + CloudJob::findOrFail(5), + true + ) + ); + $secretReceipt['result'] = [ + 'vm' => ['ssh_private_key' => 'must-never-be-persisted'], + ]; + $expectCloudError( + static fn () => CloudOperationCompletionService::accept( + $secretReceipt + ), + 400 + ); + $secretJob = CloudJob::findOrFail(5); + $assert(!Capsule::table('cloud_agent_completion_events') + ->where('event_id', $secretReceipt['id'])->exists() + && (string) $secretJob->phase === 'awaiting_receipt' + && $secretJob->outcome === null + && (bool) $secretJob->finalization_incident + && (string) $secretJob->finalization_error_code + === 'recovery_receipt_invalid', + 'A create completion secret was persisted or bypassed its finalizer.'); + + $unknownSecretCases = [ + 'unknown-generated-password' => [ + 'generatedPassword' => 'must-never-persist', + ], + 'unknown-root-password' => [ + 'nested' => ['root-password' => 'must-never-persist'], + ], + 'unknown-access-token' => [ + 'access_token' => 'must-never-persist', + ], + 'unknown-passphrase' => [ + 'diskPassphrase' => 'must-never-persist', + ], + 'unknown-plain-token' => [ + 'token' => 'must-never-persist', + ], + ]; + $unknownIndex = 0; + foreach ($unknownSecretCases as $eventId => $secretResult) { + $unknownIndex++; + $unknownOperation = substr(hash( + 'sha256', + 'unknown-secret-operation:' . $unknownIndex + ), 0, 32); + $unknownReceipt = $receipt( + $eventId . '-event', + 77, + $unknownOperation, + $createIdentity + ); + $unknownReceipt['result'] = $secretResult; + $expectCloudError( + static fn () => CloudOperationCompletionService::accept( + $unknownReceipt + ), + 400 + ); + $assert(!Capsule::table('cloud_agent_completion_events') + ->where('event_id', $unknownReceipt['id'])->exists(), + 'An unknown-operation secret completion was persisted.'); + } + + echo "Agent mutation identity binding tests passed.\n"; +} diff --git a/web/tests/CloudAgentProtocolTest.php b/web/tests/CloudAgentProtocolTest.php index ed993249..85055b75 100644 --- a/web/tests/CloudAgentProtocolTest.php +++ b/web/tests/CloudAgentProtocolTest.php @@ -187,6 +187,9 @@ $handler = new MockHandler([ 'retryable' => false, 'operation' => [ 'operation_id' => 'operation_12345678', + 'action' => 'create-vm', + 'resource_id' => 'operation-resource-12345678', + 'fingerprint' => str_repeat('a', 64), 'status' => 'reserved', ], ]], JSON_THROW_ON_ERROR)), @@ -197,6 +200,9 @@ $handler = new MockHandler([ 'retryable' => false, 'operation' => [ 'operation_id' => 'operation_12345678', + 'action' => 'create-vm', + 'resource_id' => 'operation-resource-12345678', + 'fingerprint' => str_repeat('a', 64), 'status' => 'failed', 'cause_code' => 'storage_clone_failed', 'error' => ['code' => 'creation_absent'], @@ -209,6 +215,9 @@ $handler = new MockHandler([ 'retryable' => false, 'operation' => [ 'operation_id' => 'operation_12345678', + 'action' => 'create-vm', + 'resource_id' => 'operation-resource-12345678', + 'fingerprint' => str_repeat('a', 64), 'status' => 'failed', 'cause_code' => 'StorageCloneFailed', 'error' => ['code' => 'creation_absent'], @@ -221,6 +230,9 @@ $handler = new MockHandler([ 'retryable' => false, 'operation' => [ 'operation_id' => 'operation_12345678', + 'action' => 'create-vm', + 'resource_id' => 'operation-resource-12345678', + 'fingerprint' => str_repeat('a', 64), 'status' => 'failed', 'error' => ['code' => 'operation_not_dispatched'], ], @@ -354,6 +366,11 @@ $assert(($starting['status'] ?? null) === 'reserved' $journalFailure = $client->request('POST', '/v1/vms', $actor, ['operation_id' => 'operation_12345678']); $assert(($journalFailure['status'] ?? null) === 'failed' + && ($journalFailure['action'] ?? null) === 'create-vm' + && ($journalFailure['resource_id'] ?? null) + === 'operation-resource-12345678' + && ($journalFailure['request_fingerprint'] ?? null) + === str_repeat('a', 64) && ($journalFailure['cause_code'] ?? null) === 'storage_clone_failed' && ($journalFailure['error']['code'] ?? null) === 'creation_absent' && !isset($journalFailure['message']), diff --git a/web/tests/CloudAggregateRecoveryConvergenceTest.php b/web/tests/CloudAggregateRecoveryConvergenceTest.php new file mode 100644 index 00000000..480d37a2 --- /dev/null +++ b/web/tests/CloudAggregateRecoveryConvergenceTest.php @@ -0,0 +1,3279 @@ +value('parent_job_id')") + && $parentLock !== false + && $catalogLock !== false + && $leafLock !== false + && $parentLock < $catalogLock + && $catalogLock < $leafLock + && str_contains( + $lockMethod, + "(int) (\$job->parent_job_id ?? 0)\n" + . ' !== $aggregateParentId' + ), + 'Fence commit does not preserve aggregate parent-before-child lock order.'); + + $capsule = new Capsule(); + $capsule->addConnection([ + 'driver' => 'sqlite', 'database' => ':memory:', + ], 'default'); + $capsule->setAsGlobal(); + $capsule->bootEloquent(); + $schema = $capsule->schema('default'); + $schema->create('user', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('enable')->default(1); + $table->integer('is_admin')->default(0); + }); + $schema->create('cloud_jobs', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('operation_id')->unique(); + $table->string('request_idempotency_key')->unique(); + $table->string('request_fingerprint'); + $table->integer('parent_job_id')->nullable(); + $table->integer('order_id')->nullable(); + $table->integer('invoice_id')->nullable(); + $table->integer('instance_id')->nullable(); + $table->integer('snapshot_id')->nullable(); + $table->integer('user_id'); + $table->integer('host_id')->nullable(); + $table->string('kind'); + $table->string('execution_mode'); + $table->string('phase'); + $table->string('outcome')->nullable(); + $table->string('status'); + $table->text('sealed_payload'); + $table->integer('attempts')->default(0); + $table->integer('dispatch_attempts')->default(0); + $table->integer('dispatch_deadline_at'); + $table->integer('dispatch_started_at')->nullable(); + $table->integer('agent_accepted_at')->nullable(); + $table->integer('receipt_deadline_at')->nullable(); + $table->integer('terminal_at')->nullable(); + $table->boolean('effect_may_have_applied')->nullable(); + $table->boolean('safe_to_resubmit')->nullable(); + $table->string('effect_resolution'); + $table->integer('effect_resolved_at')->nullable(); + $table->integer('effect_resolved_by')->nullable(); + $table->string('effect_resolution_reason')->default(''); + $table->string('completion_event_id')->nullable(); + $table->integer('read_at')->nullable(); + $table->integer('dispatched_at')->nullable(); + $table->string('lease_token')->nullable(); + $table->integer('lease_until')->default(0); + $table->integer('available_at')->default(0); + $table->string('error_code')->nullable(); + $table->boolean('finalization_incident')->default(0); + $table->string('finalization_error_code')->nullable(); + $table->text('result_json')->nullable(); + $table->integer('created_at'); + $table->integer('updated_at'); + }); + $schema->create('cloud_agent_completion_events', + static function (Blueprint $table): void { + $table->string('event_id')->primary(); + $table->integer('host_id'); + $table->string('operation_id'); + $table->string('payload_sha256'); + $table->string('outcome'); + $table->boolean('effect_may_have_applied'); + $table->boolean('safe_to_resubmit'); + $table->string('error_code')->default(''); + $table->text('result_json')->nullable(); + $table->string('disposition')->default('received'); + $table->integer('received_at'); + $table->integer('applied_at')->nullable(); + $table->unique(['host_id', 'operation_id']); + }); + $schema->create('cloud_templates', + static function (Blueprint $table): void { + $table->string('id')->primary(); + $table->string('name'); + $table->string('os_family'); + $table->string('os_version'); + $table->string('source_type'); + $table->text('sealed_source_url'); + $table->integer('image_bytes'); + $table->string('sha256'); + $table->text('startup_script'); + $table->integer('revision'); + $table->string('generation_token'); + $table->string('state'); + $table->integer('active_job_id')->nullable(); + $table->integer('created_at'); + $table->integer('updated_at'); + }); + $schema->create('cloud_template_replicas', + static function (Blueprint $table): void { + $table->integer('host_id'); + $table->string('template_id'); + $table->integer('revision'); + $table->string('generation_token'); + $table->string('state'); + $table->integer('image_bytes'); + $table->string('sha256'); + $table->string('operation_id'); + $table->integer('job_id')->nullable(); + $table->string('error_code'); + $table->integer('created_at'); + $table->integer('updated_at'); + $table->primary(['host_id', 'template_id']); + }); + $schema->create('cloud_user_isos', + static function (Blueprint $table): void { + $table->string('id')->primary(); + $table->integer('user_id'); + $table->string('name'); + $table->text('sealed_source_url'); + $table->integer('size_bytes')->default(0); + $table->string('sha256')->default(''); + $table->string('state')->default('importing'); + $table->string('import_operation_id'); + $table->integer('active_job_id')->nullable(); + $table->integer('created_at'); + $table->integer('updated_at'); + }); + $schema->create('cloud_user_iso_replicas', + static function (Blueprint $table): void { + $table->integer('host_id'); + $table->string('user_iso_id'); + $table->integer('user_id'); + $table->string('state')->default('pending'); + $table->integer('size_bytes')->default(0); + $table->string('sha256')->default(''); + $table->string('operation_id'); + $table->integer('job_id')->nullable(); + $table->string('error_code')->default(''); + $table->integer('created_at'); + $table->integer('updated_at'); + $table->primary(['host_id', 'user_iso_id']); + }); + Capsule::table('user')->insert([ + 'id' => 1, 'enable' => 1, 'is_admin' => 0, + ]); + + $now = time(); + $nextId = 1; + $insertParent = static function ( + string $kind = 'template_import', + int $userId = 1 + ) use (&$nextId, $now): int { + $id = $nextId++; + $operationId = md5('aggregate-parent:' . $id); + Capsule::table('cloud_jobs')->insert([ + 'id' => $id, + 'operation_id' => $operationId, + 'request_idempotency_key' => $operationId, + 'request_fingerprint' => hash('sha256', $operationId), + 'parent_job_id' => null, + 'order_id' => null, + 'invoice_id' => null, + 'instance_id' => null, + 'snapshot_id' => null, + 'user_id' => $userId, + 'host_id' => null, + 'kind' => $kind, + 'execution_mode' => 'aggregate', + 'phase' => 'terminal', + 'outcome' => 'failed', + 'status' => 'failed', + 'sealed_payload' => CloudSecrets::encrypt([], 'job-payload'), + 'attempts' => 0, + 'dispatch_attempts' => 0, + 'dispatch_deadline_at' => $now - 600, + 'dispatch_started_at' => null, + 'agent_accepted_at' => null, + 'receipt_deadline_at' => $now - 1, + 'terminal_at' => $now - 1, + 'effect_may_have_applied' => 1, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'unknown', + 'effect_resolved_at' => null, + 'effect_resolved_by' => null, + 'effect_resolution_reason' => '', + 'completion_event_id' => null, + 'read_at' => $now - 1, + 'dispatched_at' => null, + 'lease_token' => str_repeat('a', 32), + 'lease_until' => $now + 300, + 'available_at' => $now + 300, + 'error_code' => 'aggregate_deadline_exceeded', + 'finalization_incident' => 1, + 'finalization_error_code' => 'recovery_child_convergence', + 'result_json' => null, + 'created_at' => $now - 900, + 'updated_at' => $now - 1, + ]); + return $id; + }; + $insertResolvedChild = static function ( + int $parentId, + string $resolution, + string $kind = 'action', + int $userId = 1, + string $executionMode = 'agent' + ) use (&$nextId, $now): int { + $id = $nextId++; + $operationId = md5('resolved-child:' . $id); + Capsule::table('cloud_jobs')->insert([ + 'id' => $id, + 'operation_id' => $operationId, + 'request_idempotency_key' => $operationId, + 'request_fingerprint' => hash('sha256', $operationId), + 'parent_job_id' => $parentId, + 'order_id' => null, + 'invoice_id' => null, + 'instance_id' => null, + 'snapshot_id' => null, + 'user_id' => $userId, + 'host_id' => 7, + 'kind' => $kind, + 'execution_mode' => $executionMode, + 'phase' => 'terminal', + 'outcome' => $resolution === 'applied' ? 'succeeded' : 'failed', + 'status' => $resolution === 'applied' ? 'succeeded' : 'failed', + 'sealed_payload' => CloudSecrets::encrypt([], 'job-payload'), + 'attempts' => 1, + 'dispatch_attempts' => 1, + 'dispatch_deadline_at' => $now - 600, + 'dispatch_started_at' => $now - 500, + 'agent_accepted_at' => $now - 490, + 'receipt_deadline_at' => $now - 1, + 'terminal_at' => $now - 1, + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => $resolution === 'not_applied' ? 1 : 0, + 'effect_resolution' => $resolution, + 'effect_resolved_at' => $now - 1, + 'effect_resolved_by' => null, + 'effect_resolution_reason' => 'normal_completion', + 'completion_event_id' => null, + 'read_at' => null, + 'dispatched_at' => $now - 490, + 'lease_token' => null, + 'lease_until' => 0, + 'available_at' => 0, + 'error_code' => $resolution === 'not_applied' + ? 'operation_rejected' : null, + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'result_json' => null, + 'created_at' => $now - 600, + 'updated_at' => $now - 1, + ]); + return $id; + }; + $insertProjectionForParent = static function (int $parentId) use ($now): string { + $parent = CloudJob::findOrFail($parentId); + $children = CloudJob::where('parent_job_id', $parentId) + ->orderBy('id')->get(); + if ($children->isEmpty()) { + throw new RuntimeException('Projection fixture requires children.'); + } + foreach ($children as $index => $child) { + $hostId = 1000 + (int) $child->id; + Capsule::table('cloud_jobs')->where('id', (int) $child->id) + ->update(['host_id' => $hostId]); + $child->host_id = $hostId; + } + if (str_starts_with((string) $parent->kind, 'template_')) { + $resourceId = 'aggregate-projection-' . $parentId; + $generation = md5('projection-generation:' . $parentId); + $sha256 = hash('sha256', 'projection-sha:' . $parentId); + $state = match ((string) $parent->kind) { + 'template_import' => 'error', + 'template_metadata_sync' => 'active', + 'template_delete' => 'delete_failed', + }; + Capsule::table('cloud_templates')->insert([ + 'id' => $resourceId, + 'name' => 'Aggregate projection ' . $parentId, + 'os_family' => 'Debian', + 'os_version' => '13', + 'source_type' => 'qcow2', + 'sealed_source_url' => 'test-only', + 'image_bytes' => 4096, + 'sha256' => $sha256, + 'startup_script' => '', + 'revision' => (string) $parent->kind + === 'template_metadata_sync' ? 2 : 1, + 'generation_token' => $generation, + 'state' => $state, + 'active_job_id' => $parentId, + 'created_at' => $now - 60, + 'updated_at' => $now, + ]); + foreach ($children as $child) { + $applied = (string) $child->effect_resolution === 'applied'; + $replicaState = match ((string) $parent->kind) { + 'template_import' => $applied ? 'active' : 'failed', + 'template_metadata_sync' => $applied ? 'active' : 'stale', + 'template_delete' => $applied + ? 'delete_succeeded' : 'delete_failed', + }; + Capsule::table('cloud_template_replicas')->insert([ + 'host_id' => (int) $child->host_id, + 'template_id' => $resourceId, + 'revision' => (string) $parent->kind + === 'template_metadata_sync' + ? ($applied ? 2 : 1) : 1, + 'generation_token' => $generation, + 'state' => $replicaState, + 'image_bytes' => (string) $parent->kind + === 'template_import' && !$applied + ? 0 : 4096, + 'sha256' => $sha256, + 'operation_id' => (string) $child->operation_id, + 'job_id' => (int) $child->id, + 'error_code' => $applied ? '' : 'operation_not_applied', + 'created_at' => $now - 60, + 'updated_at' => $now, + ]); + } + return $resourceId; + } + + $resourceId = md5('aggregate-iso-projection:' . $parentId); + $sha256 = hash('sha256', 'projection-iso-sha:' . $parentId); + Capsule::table('cloud_user_isos')->insert([ + 'id' => $resourceId, + 'user_id' => (int) $parent->user_id, + 'name' => 'Aggregate ISO ' . $parentId, + 'sealed_source_url' => 'test-only', + 'size_bytes' => 4096, + 'sha256' => $sha256, + 'state' => (string) $parent->kind === 'user_iso_import' + ? 'import_failed' : 'delete_failed', + 'import_operation_id' => (string) $parent->operation_id, + 'active_job_id' => $parentId, + 'created_at' => $now - 60, + 'updated_at' => $now, + ]); + foreach ($children as $child) { + $applied = (string) $child->effect_resolution === 'applied'; + $replicaState = (string) $parent->kind === 'user_iso_import' + ? ($applied ? 'active' : 'failed') + : ($applied ? 'delete_succeeded' : 'delete_failed'); + Capsule::table('cloud_user_iso_replicas')->insert([ + 'host_id' => (int) $child->host_id, + 'user_iso_id' => $resourceId, + 'user_id' => (int) $parent->user_id, + 'state' => $replicaState, + 'size_bytes' => (string) $parent->kind === 'user_iso_delete' + || $applied ? 4096 : 0, + 'sha256' => $sha256, + 'operation_id' => (string) $child->operation_id, + 'job_id' => (int) $child->id, + 'error_code' => $applied ? '' : 'operation_not_applied', + 'created_at' => $now - 60, + 'updated_at' => $now, + ]); + } + return $resourceId; + }; + $settleLastChild = static function ( + string $firstResolution + ) use ( + $insertParent, + $insertResolvedChild, + $insertProjectionForParent, + $assert + ): CloudJob { + $parentId = $insertParent(); + $insertResolvedChild( + $parentId, + $firstResolution, + 'template_import_replica' + ); + $lastChildId = $insertResolvedChild( + $parentId, + 'not_applied', + 'template_import_replica' + ); + $insertProjectionForParent($parentId); + Capsule::table('cloud_jobs')->where('id', $lastChildId)->update([ + 'phase' => 'awaiting_receipt', + 'outcome' => null, + 'status' => 'running', + 'effect_may_have_applied' => null, + 'safe_to_resubmit' => null, + 'effect_resolution' => 'not_applicable', + 'effect_resolved_at' => null, + 'effect_resolution_reason' => '', + 'terminal_at' => null, + ]); + + $before = CloudJob::find($parentId); + $assert($before !== null + && CloudJobService::recoveryPresentation($before, true) !== null, + 'The aggregate fixture was not fenced before its last child.'); + + Capsule::table('cloud_jobs')->where('id', $lastChildId)->update([ + 'phase' => 'terminal', + 'outcome' => 'failed', + 'status' => 'failed', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 1, + 'effect_resolution' => 'not_applied', + 'effect_resolved_at' => time(), + 'effect_resolution_reason' => 'normal_completion', + 'terminal_at' => time(), + ]); + $completed = CloudJob::find($lastChildId); + CloudJobService::reconcileAggregateParentEffectLocked( + $completed, + null + ); + $assert((string) $completed->phase === 'terminal' + && (string) $completed->outcome === 'failed' + && (string) $completed->effect_resolution === 'not_applied', + 'The last leaf did not enter its normal terminal state.'); + + return CloudJob::find($parentId); + }; + + $allAbsent = $settleLastChild('not_applied'); + $assert($allAbsent !== null + && (string) $allAbsent->phase === 'terminal' + && (string) $allAbsent->outcome === 'failed' + && (string) $allAbsent->status === 'failed' + && (string) $allAbsent->effect_resolution === 'not_applied' + && (int) $allAbsent->effect_resolved_at > 0 + && $allAbsent->effect_resolved_by === null + && str_starts_with( + (string) $allAbsent->effect_resolution_reason, + 'child_effects_resolved:' + ) + && !(bool) $allAbsent->finalization_incident + && $allAbsent->finalization_error_code === null + && $allAbsent->lease_token === null + && (int) $allAbsent->lease_until === 0 + && (int) $allAbsent->available_at === 0 + && $allAbsent->read_at === null + && (string) Capsule::table('cloud_templates') + ->where('active_job_id', (int) $allAbsent->id) + ->value('state') === 'retired' + && !Capsule::table('cloud_template_replicas') + ->whereIn('template_id', static function ($query) use ($allAbsent) { + $query->select('id')->from('cloud_templates') + ->where('active_job_id', (int) $allAbsent->id); + })->exists() + && CloudJobService::recoveryPresentation($allAbsent, true) === null, + 'All-not-applied import children did not retire their placeholder.'); + + $partial = $settleLastChild('applied'); + $assert($partial !== null + && (string) $partial->phase === 'terminal' + && (string) $partial->outcome === 'failed' + && (string) $partial->status === 'failed' + && (string) $partial->effect_resolution === 'unknown' + && (bool) $partial->finalization_incident + && (string) $partial->finalization_error_code + === 'recovery_aggregate_state_conflict' + && $partial->lease_token === null + && (int) $partial->available_at >= time() + 290 + && (CloudJobService::recoveryPresentation( + $partial, + true + )['code'] ?? null) === 'recovery_aggregate_state_conflict', + 'Mixed child effects were falsely published as a settled aggregate.'); + + // A zero-dispatch child can know its host effect is not-applied while its + // PHP replica/catalog finalizer is still rolled back. Neither the realtime + // sibling hook nor the legacy sweep may publish the parent until that + // independent local incident has committed and cleared. + $localIncidentParentId = $insertParent('template_import'); + $localIncidentChildId = $insertResolvedChild( + $localIncidentParentId, + 'not_applied', + 'template_import_replica' + ); + $insertProjectionForParent($localIncidentParentId); + Capsule::table('cloud_jobs')->where( + 'id', + $localIncidentChildId + )->update([ + 'attempts' => 0, + 'dispatch_attempts' => 0, + 'dispatch_started_at' => null, + 'agent_accepted_at' => null, + 'dispatched_at' => null, + 'receipt_deadline_at' => null, + 'completion_event_id' => null, + 'safe_to_resubmit' => 0, + 'finalization_incident' => 1, + 'finalization_error_code' => 'recovery_ledger_conflict', + ]); + CloudJobService::reconcileAggregateParentEffectLocked( + CloudJob::findOrFail($localIncidentChildId), + null + ); + $localIncidentParent = CloudJob::findOrFail($localIncidentParentId); + $assert((string) $localIncidentParent->effect_resolution === 'unknown' + && (bool) $localIncidentParent->finalization_incident, + 'A local-finalizer child prematurely released its aggregate parent.'); + Capsule::table('cloud_jobs')->where( + 'id', + $localIncidentChildId + )->update([ + 'safe_to_resubmit' => 1, + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'effect_resolved_at' => time(), + 'effect_resolution_reason' => 'automatic_local_not_dispatched', + ]); + CloudJobService::reconcileAggregateParentEffectLocked( + CloudJob::findOrFail($localIncidentChildId), + null + ); + $localIncidentParent->refresh(); + $assert((string) $localIncidentParent->effect_resolution + === 'not_applied' + && !(bool) $localIncidentParent->finalization_incident, + 'The aggregate parent stayed fenced after its local child converged.'); + + $makeLegacyEligible = static function (int $parentId): void { + Capsule::table('cloud_jobs')->where('id', $parentId)->update([ + 'lease_token' => null, + 'lease_until' => 0, + 'available_at' => 0, + 'finalization_incident' => 1, + 'finalization_error_code' => 'recovery_child_convergence', + ]); + }; + + $legacyLocalIncidentParentId = $insertParent('template_import'); + $makeLegacyEligible($legacyLocalIncidentParentId); + $legacyLocalIncidentChildId = $insertResolvedChild( + $legacyLocalIncidentParentId, + 'not_applied', + 'template_import_replica' + ); + $insertProjectionForParent($legacyLocalIncidentParentId); + Capsule::table('cloud_jobs')->where( + 'id', + $legacyLocalIncidentChildId + )->update([ + 'attempts' => 0, + 'dispatch_attempts' => 0, + 'dispatch_started_at' => null, + 'agent_accepted_at' => null, + 'dispatched_at' => null, + 'receipt_deadline_at' => null, + 'completion_event_id' => null, + 'safe_to_resubmit' => 0, + 'finalization_incident' => 1, + 'finalization_error_code' => 'recovery_ledger_conflict', + ]); + $assert(CloudJobService::reconcileOneLegacyAggregateEffect(), + 'The legacy sweep did not inspect a local-finalizer child incident.'); + $legacyLocalIncidentParent = CloudJob::findOrFail( + $legacyLocalIncidentParentId + ); + $assert((string) $legacyLocalIncidentParent->effect_resolution + === 'unknown' + && (string) $legacyLocalIncidentParent->finalization_error_code + === 'recovery_child_convergence', + 'The legacy sweep prematurely released a local-finalizer child.'); + Capsule::table('cloud_jobs')->where( + 'id', + $legacyLocalIncidentChildId + )->update([ + 'safe_to_resubmit' => 1, + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'effect_resolved_at' => time(), + 'effect_resolution_reason' => 'automatic_local_not_dispatched', + ]); + $makeLegacyEligible($legacyLocalIncidentParentId); + $assert(CloudJobService::reconcileOneLegacyAggregateEffect(), + 'The legacy sweep did not resume after local finalizer convergence.'); + $legacyLocalIncidentParent->refresh(); + $assert((string) $legacyLocalIncidentParent->effect_resolution + === 'not_applied' + && !(bool) $legacyLocalIncidentParent->finalization_incident, + 'The legacy parent stayed fenced after local finalizer convergence.'); + + // The realtime hook applies the same topology rules to both the child that + // triggered it and every sibling. A wrong link is an incident, never + // evidence that the aggregate effect can be published. + $liveWrongCurrentParent = $insertParent('template_delete'); + $makeLegacyEligible($liveWrongCurrentParent); + $liveWrongCurrent = $insertResolvedChild( + $liveWrongCurrentParent, + 'applied', + 'template_import_replica' + ); + $insertResolvedChild( + $liveWrongCurrentParent, + 'not_applied', + 'template_delete_replica' + ); + CloudJobService::reconcileAggregateParentEffectLocked( + CloudJob::find($liveWrongCurrent), + null + ); + + $liveWrongSiblingParent = $insertParent('user_iso_delete'); + $makeLegacyEligible($liveWrongSiblingParent); + $liveValidCurrent = $insertResolvedChild( + $liveWrongSiblingParent, + 'applied', + 'user_iso_delete_replica' + ); + $insertResolvedChild( + $liveWrongSiblingParent, + 'not_applied', + 'user_iso_import_replica' + ); + CloudJobService::reconcileAggregateParentEffectLocked( + CloudJob::find($liveValidCurrent), + null + ); + + foreach ([ + $liveWrongCurrentParent => 'current child', + $liveWrongSiblingParent => 'sibling child', + ] as $parentId => $description) { + $conflict = CloudJob::find($parentId); + $display = CloudJobService::recoveryPresentation($conflict, true); + $assert((string) $conflict->effect_resolution === 'unknown' + && (bool) $conflict->finalization_incident + && (string) $conflict->finalization_error_code + === 'recovery_aggregate_state_conflict' + && (int) $conflict->available_at >= time() + 290 + && $conflict->read_at === null + && ($display['code'] ?? null) + === 'recovery_aggregate_state_conflict', + 'The live hook released a parent with a wrong ' + . $description . ' relationship.'); + } + + foreach ([ + 'missing parent' => static function () use ( + $insertResolvedChild + ): CloudJob { + return CloudJob::findOrFail($insertResolvedChild( + 999999, + 'applied', + 'template_import_replica' + )); + }, + 'non-aggregate parent' => static function () use ( + $insertParent, + $insertResolvedChild + ): CloudJob { + $parentId = $insertParent('template_import'); + Capsule::table('cloud_jobs')->where('id', $parentId)->update([ + 'execution_mode' => 'local', + ]); + return CloudJob::findOrFail($insertResolvedChild( + $parentId, + 'applied', + 'template_import_replica' + )); + }, + ] as $description => $fixture) { + $thrown = false; + try { + CloudJobService::reconcileAggregateParentEffectLocked( + $fixture(), + null + ); + } catch (CloudRecoveryAggregateStateConflict $error) { + $thrown = true; + } + $assert($thrown, + 'A child with a ' . $description + . ' could be silently acknowledged.'); + } + + // A damaged aggregate relationship must be rejected before the recovery + // coordinator writes the Agent journal fence. Cover both parent-envelope + // and child-kind corruption at the private transaction boundary. + $resolveFence = new ReflectionMethod( + CloudAutomaticOperationRecoveryService::class, + 'resolveFenceAndCommit' + ); + $preparedFence = [ + 'resolution' => 'applied', + 'journal_status' => 'failed', + 'fence_resolution_required' => true, + 'source' => 'host_inspection', + 'operation' => [], + ]; + foreach ([ + 'bad parent mode' => static function () use ( + $insertParent, + $insertResolvedChild + ): CloudJob { + $parentId = $insertParent('template_import'); + $childId = $insertResolvedChild( + $parentId, + 'applied', + 'template_import_replica' + ); + Capsule::table('cloud_jobs')->where('id', $parentId)->update([ + 'execution_mode' => 'local', + ]); + Capsule::table('cloud_jobs')->where('id', $childId)->update([ + 'effect_resolution' => 'unknown', + 'lease_token' => str_repeat('f', 32), + 'lease_until' => time() + 300, + ]); + return CloudJob::findOrFail($childId); + }, + 'wrong child kind' => static function () use ( + $insertParent, + $insertResolvedChild, + $insertProjectionForParent + ): CloudJob { + $parentId = $insertParent('template_delete'); + $childId = $insertResolvedChild( + $parentId, + 'applied', + 'template_import_replica' + ); + $insertProjectionForParent($parentId); + Capsule::table('cloud_jobs')->where('id', $childId)->update([ + 'effect_resolution' => 'unknown', + 'lease_token' => str_repeat('e', 32), + 'lease_until' => time() + 300, + ]); + return CloudJob::findOrFail($childId); + }, + ] as $description => $fixture) { + $beforeFenceRequests = CloudAgentSettingsService::$requests; + $blocked = false; + try { + $resolveFence->invoke( + null, + $fixture(), + $preparedFence, + 'test-only', + [] + ); + } catch (CloudRecoveryAggregateStateConflict $error) { + $blocked = true; + } + $assert( + $blocked + && CloudAgentSettingsService::$requests === $beforeFenceRequests, + 'A ' . $description . ' reached an Agent fence write.' + ); + } + + // Upgrade sweep: these parents were already terminal failed/unknown before + // the realtime leaf hook existed. Each tick may converge exactly one local + // parent from already-known children and must never need an Agent client. + $legacyMappings = [ + 'template_import' => 'template_import_replica', + 'template_metadata_sync' => 'template_metadata_replica', + 'template_delete' => 'template_delete_replica', + 'user_iso_import' => 'user_iso_import_replica', + 'user_iso_delete' => 'user_iso_delete_replica', + ]; + $legacyParents = []; + foreach ($legacyMappings as $parentKind => $childKind) { + $parentId = $insertParent($parentKind); + $makeLegacyEligible($parentId); + $firstResolution = $parentKind === 'template_import' + ? 'not_applied' : 'applied'; + $insertResolvedChild( + $parentId, + $firstResolution, + $childKind + ); + $insertResolvedChild($parentId, $firstResolution, $childKind); + $resourceId = $insertProjectionForParent($parentId); + $legacyParents[$parentId] = [ + 'kind' => $parentKind, + 'resolution' => $firstResolution === 'applied' + ? 'applied' : 'not_applied', + 'resource_id' => $resourceId, + ]; + } + $automatic = new CloudAutomaticOperationRecoveryService(); + $resolvedLegacyCount = 0; + foreach ($legacyParents as $parentId => $expectation) { + $assert($automatic->tick(), + 'The local legacy aggregate sweep did not claim a parent.'); + $resolved = CloudJob::whereIn('id', array_keys($legacyParents)) + ->whereIn('effect_resolution', ['applied', 'not_applied']) + ->count(); + $resolvedLegacyCount++; + $current = CloudJob::find($parentId); + $assert($resolved === $resolvedLegacyCount + && $current !== null + && (string) $current->effect_resolution + === $expectation['resolution'] + && (string) $current->outcome === 'failed' + && !(bool) $current->finalization_incident + && $current->finalization_error_code === null + && CloudJobService::recoveryPresentation( + $current, + true + ) === null, + 'A tick handled multiple legacy parents or mapped children incorrectly.'); + $resourceId = $expectation['resource_id']; + $projectionOkay = match ($expectation['kind']) { + 'template_import' => + (string) Capsule::table('cloud_templates') + ->where('id', $resourceId)->value('state') === 'retired' + && !Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId)->exists(), + 'template_metadata_sync' => + (string) Capsule::table('cloud_templates') + ->where('id', $resourceId)->value('state') === 'active' + && !Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId) + ->where('state', '<>', 'active')->exists(), + 'template_delete' => + (string) Capsule::table('cloud_templates') + ->where('id', $resourceId)->value('state') === 'retired' + && !Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId)->exists(), + 'user_iso_import' => + (string) Capsule::table('cloud_user_isos') + ->where('id', $resourceId)->value('state') === 'active', + 'user_iso_delete' => + (string) Capsule::table('cloud_user_isos') + ->where('id', $resourceId)->value('state') === 'retired' + && !Capsule::table('cloud_user_iso_replicas') + ->where('user_iso_id', $resourceId)->exists(), + }; + $assert($projectionOkay, + 'A legacy terminal parent did not recompute its resource projection: ' + . $expectation['kind']); + } + + $waitingParent = $insertParent('template_import'); + $makeLegacyEligible($waitingParent); + $waitingChild = $insertResolvedChild( + $waitingParent, + 'not_applied', + 'template_import_replica' + ); + $insertProjectionForParent($waitingParent); + Capsule::table('cloud_jobs')->where('id', $waitingChild)->update([ + 'phase' => 'awaiting_receipt', + 'outcome' => null, + 'status' => 'running', + 'effect_resolution' => 'not_applicable', + 'effect_resolved_at' => null, + 'effect_resolution_reason' => '', + ]); + + // Receipt handling must run before a legacy aggregate that can remain in + // child-convergence for an arbitrarily long time. Use an invalid durable + // event here so the scheduler must quarantine it without touching Agent + // or catalog state; the aggregate remains immediately eligible for the + // following tick instead of starving the receipt forever. + $priorityChild = $insertResolvedChild( + 0, + 'not_applied', + 'template_import_replica' + ); + Capsule::table('cloud_jobs')->where('id', $priorityChild)->update([ + 'outcome' => 'failed', + 'status' => 'failed', + 'effect_may_have_applied' => 1, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'unknown', + 'effect_resolved_at' => null, + 'effect_resolution_reason' => '', + 'available_at' => 0, + 'dispatched_at' => $now - 20, + ]); + $priorityOperation = (string) CloudJob::findOrFail( + $priorityChild + )->operation_id; + Capsule::table('cloud_agent_completion_events')->insert([ + 'event_id' => 'aggregate-priority-receipt', + 'host_id' => 7, + 'operation_id' => $priorityOperation, + 'payload_sha256' => str_repeat('0', 64), + 'outcome' => 'succeeded', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'error_code' => '', + 'result_json' => null, + 'disposition' => 'received', + 'received_at' => $now, + 'applied_at' => null, + ]); + $makeLegacyEligible($waitingParent); + $assert($automatic->tick(), + 'A durable receipt was not prioritised over a waiting aggregate.'); + $priorityEvent = Capsule::table('cloud_agent_completion_events') + ->where('event_id', 'aggregate-priority-receipt')->first(); + $stillEligibleParent = CloudJob::findOrFail($waitingParent); + $assert((string) $priorityEvent->disposition === 'rejected' + && (int) $stillEligibleParent->available_at === 0, + 'A waiting legacy aggregate starved receipt validation.'); + + $assert($automatic->tick(), + 'A legacy aggregate with an active child was not inspected locally.'); + $waiting = CloudJob::find($waitingParent); + $waitingDisplay = CloudJobService::recoveryPresentation($waiting, true); + $assert((string) $waiting->effect_resolution === 'unknown' + && (string) $waiting->finalization_error_code + === 'recovery_child_convergence' + && (int) $waiting->available_at >= time() + 290 + && ($waitingDisplay['code'] ?? null) + === 'recovery_child_convergence', + 'An unresolved but valid child released or corrupted its parent fence.'); + + // Corrupt aggregate relationships remain fenced and retryable. Cover every + // structural invariant independently so a future relaxed query cannot turn + // a wrong child into evidence for releasing its parent. + $conflictFixtures = []; + + $missingChildParent = $insertParent('template_import'); + $makeLegacyEligible($missingChildParent); + $conflictFixtures[$missingChildParent] = 'missing child'; + + $wrongParentMode = $insertParent('template_import'); + $makeLegacyEligible($wrongParentMode); + $insertResolvedChild( + $wrongParentMode, + 'applied', + 'template_import_replica' + ); + Capsule::table('cloud_jobs')->where('id', $wrongParentMode)->update([ + 'execution_mode' => 'local', + ]); + $conflictFixtures[$wrongParentMode] = 'wrong parent execution mode'; + + $wrongParentKind = $insertParent('template_import'); + $makeLegacyEligible($wrongParentKind); + $insertResolvedChild( + $wrongParentKind, + 'applied', + 'template_import_replica' + ); + Capsule::table('cloud_jobs')->where('id', $wrongParentKind)->update([ + 'kind' => 'corrupt_aggregate_kind', + ]); + $conflictFixtures[$wrongParentKind] = 'wrong parent kind'; + + $wrongKindParent = $insertParent('template_delete'); + $makeLegacyEligible($wrongKindParent); + $insertResolvedChild( + $wrongKindParent, + 'applied', + 'template_import_replica' + ); + $conflictFixtures[$wrongKindParent] = 'wrong child kind'; + + $wrongUserParent = $insertParent('user_iso_import'); + $makeLegacyEligible($wrongUserParent); + $insertResolvedChild( + $wrongUserParent, + 'applied', + 'user_iso_import_replica', + 2 + ); + $conflictFixtures[$wrongUserParent] = 'wrong child owner'; + + $wrongModeParent = $insertParent('user_iso_delete'); + $makeLegacyEligible($wrongModeParent); + $insertResolvedChild( + $wrongModeParent, + 'not_applied', + 'user_iso_delete_replica', + 1, + 'local' + ); + $conflictFixtures[$wrongModeParent] = 'wrong child execution mode'; + + $nestedParent = $insertParent('template_metadata_sync'); + $makeLegacyEligible($nestedParent); + Capsule::table('cloud_jobs')->where('id', $nestedParent)->update([ + // The parent only needs to be non-null to exercise the invalid + // aggregate nesting invariant. Do not attach it to an earlier valid + // aggregate fixture: doing so also (correctly) corrupts that parent's + // already-published child topology and changes the next claimed row. + 'parent_job_id' => 999999, + ]); + $insertResolvedChild( + $nestedParent, + 'applied', + 'template_metadata_replica' + ); + $conflictFixtures[$nestedParent] = 'non-top-level aggregate parent'; + + // A malformed Agent child is itself a higher-priority PHP-only leaf + // repair, so it may be claimed before an earlier aggregate parent. Drain + // the bounded fixture set, then verify every parent retained its fence. + $beforeConflictRequests = CloudAgentSettingsService::$requests; + for ($attempt = 0; $attempt < count($conflictFixtures) * 3; $attempt++) { + $remaining = CloudJob::whereIn('id', array_keys($conflictFixtures)) + ->where(static function ($pending): void { + $pending->where('finalization_incident', 0) + ->orWhereNull('finalization_error_code') + ->orWhere( + 'finalization_error_code', + '<>', + 'recovery_aggregate_state_conflict' + ); + })->exists(); + if (!$remaining) { + break; + } + $assert($automatic->tick(), + 'The aggregate conflict fixture queue stopped before convergence.'); + } + foreach ($conflictFixtures as $parentId => $description) { + $conflict = CloudJob::find($parentId); + $display = $conflict === null ? null + : CloudJobService::recoveryPresentation($conflict, true); + $assert($conflict !== null + && (string) $conflict->effect_resolution === 'unknown' + && (string) $conflict->outcome === 'failed' + && (bool) $conflict->finalization_incident + && (string) $conflict->finalization_error_code + === 'recovery_aggregate_state_conflict' + && (int) $conflict->available_at >= time() + 290 + && $conflict->lease_token === null + && (int) $conflict->lease_until === 0 + && $conflict->read_at === null + && ($display['code'] ?? null) + === 'recovery_aggregate_state_conflict' + && str_contains( + (string) ($display['message'] ?? ''), + '关系异常' + ) + && CloudAgentSettingsService::$requests + === $beforeConflictRequests, + 'A ' . $description + . ' relationship released or concealed its aggregate fence.'); + } + + // prepareRecoveredEffect updates a replica before the external Agent fence + // write. Simulate that exact local prepare seam: the public parent must + // remain visibly recovering until the child effect commit runs, then the + // same transaction may publish the aggregate success. + $preparedParentId = $nextId++; + $preparedParentOperation = md5( + 'aggregate-prepared-parent:' . $preparedParentId + ); + Capsule::table('cloud_jobs')->insert([ + 'id' => $preparedParentId, + 'operation_id' => $preparedParentOperation, + 'request_idempotency_key' => $preparedParentOperation, + 'request_fingerprint' => hash('sha256', $preparedParentOperation), + 'parent_job_id' => null, + 'user_id' => 1, + 'host_id' => null, + 'kind' => 'template_import', + 'execution_mode' => 'aggregate', + 'phase' => 'awaiting_receipt', + 'outcome' => null, + 'status' => 'running', + 'sealed_payload' => CloudSecrets::encrypt([], 'job-payload'), + 'attempts' => 0, + 'dispatch_attempts' => 0, + 'dispatch_deadline_at' => $now + 300, + 'receipt_deadline_at' => $now + 900, + 'effect_resolution' => 'not_applicable', + 'effect_resolution_reason' => '', + 'lease_until' => 0, + 'available_at' => $now, + 'finalization_incident' => 0, + 'created_at' => $now - 60, + 'updated_at' => $now, + ]); + $preparedChildId = $insertResolvedChild( + $preparedParentId, + 'not_applied', + 'template_import_replica' + ); + Capsule::table('cloud_jobs')->where('id', $preparedChildId)->update([ + 'outcome' => 'failed', + 'status' => 'failed', + 'effect_may_have_applied' => 1, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'unknown', + 'effect_resolved_at' => null, + 'effect_resolution_reason' => + 'automatic_recovery:v1:1:1:prepared:test', + 'finalization_incident' => 1, + 'finalization_error_code' => 'recovery_payload_unavailable', + ]); + $preparedTemplateId = 'prepared-import-template'; + $preparedGeneration = str_repeat('c', 32); + $preparedSha = str_repeat('d', 64); + Capsule::table('cloud_templates')->insert([ + 'id' => $preparedTemplateId, + 'name' => 'Prepared import', + 'os_family' => 'Debian', + 'os_version' => '13', + 'source_type' => 'qcow2', + 'sealed_source_url' => 'test-only', + 'image_bytes' => 4096, + 'sha256' => $preparedSha, + 'startup_script' => '', + 'revision' => 1, + 'generation_token' => $preparedGeneration, + 'state' => 'importing', + 'active_job_id' => $preparedParentId, + 'created_at' => $now - 60, + 'updated_at' => $now, + ]); + Capsule::table('cloud_template_replicas')->insert([ + 'host_id' => 7, + 'template_id' => $preparedTemplateId, + 'revision' => 1, + 'generation_token' => $preparedGeneration, + 'state' => 'failed', + 'image_bytes' => 0, + 'sha256' => $preparedSha, + 'operation_id' => (string) CloudJob::findOrFail( + $preparedChildId + )->operation_id, + 'job_id' => $preparedChildId, + 'error_code' => 'aggregate_deadline_exceeded', + 'created_at' => $now - 60, + 'updated_at' => $now, + ]); + $preparedOperation = [ + 'operation_id' => (string) CloudJob::findOrFail( + $preparedChildId + )->operation_id, + 'status' => 'succeeded', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'error_code' => '', + ]; + CloudTemplateCatalogService::finishJobLocked( + CloudJob::findOrFail($preparedChildId), + 'succeeded', + [ + 'id' => $preparedTemplateId, + 'revision' => 1, + 'generation_token' => $preparedGeneration, + 'size_bytes' => 4096, + 'sha256' => $preparedSha, + ], + ['template_id' => $preparedTemplateId], + $preparedOperation, + true + ); + $preparedParent = CloudJob::findOrFail($preparedParentId); + $preparedParentDisplay = CloudJobService::display( + $preparedParent, + true + ); + $assert((string) $preparedParent->phase === 'awaiting_receipt' + && (string) Capsule::table('cloud_templates') + ->where('id', $preparedTemplateId)->value('state') === 'importing' + && (string) Capsule::table('cloud_template_replicas') + ->where('template_id', $preparedTemplateId) + ->value('state') === 'active' + && ($preparedParentDisplay['recovery']['pending'] ?? null) === true + && ($preparedParentDisplay['recovery']['code'] ?? null) + === 'recovery_payload_unavailable', + 'A recovered child prepare prematurely completed or hid its parent.'); + + Capsule::table('cloud_jobs')->where('id', $preparedChildId)->update([ + 'effect_resolution' => 'applied', + 'effect_resolved_at' => time(), + 'effect_resolution_reason' => 'agent_inspection:test', + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'available_at' => 0, + ]); + CloudJobService::reconcileAggregateParentEffectLocked( + CloudJob::findOrFail($preparedChildId), + null + ); + $preparedParent->refresh(); + $assert((string) $preparedParent->phase === 'terminal' + && (string) $preparedParent->outcome === 'succeeded' + && (string) $preparedParent->effect_resolution === 'applied' + && (string) Capsule::table('cloud_templates') + ->where('id', $preparedTemplateId)->value('state') === 'active' + && CloudJobService::recoveryPresentation( + $preparedParent, + true + ) === null, + 'The aggregate parent did not settle after the child effect commit.'); + + $immutableParentAudit = static fn (CloudJob $job): array => [ + 'phase' => (string) $job->phase, + 'outcome' => $job->outcome === null ? null : (string) $job->outcome, + 'status' => (string) $job->status, + 'terminal_at' => $job->terminal_at === null + ? null : (int) $job->terminal_at, + 'error_code' => $job->error_code === null + ? null : (string) $job->error_code, + 'result_json' => $job->result_json === null + ? null : (string) $job->result_json, + ]; + $markDeadlineAudit = static function (int $parentId): CloudJob { + Capsule::table('cloud_jobs')->where('id', $parentId)->update([ + 'result_json' => json_encode( + ['deadline_parent' => $parentId], + JSON_THROW_ON_ERROR + ), + ]); + return CloudJob::findOrFail($parentId); + }; + + // A parent deadline is an immutable failed audit, not the final catalog + // projection. Once every late child resolves, imports become usable and + // deletes become retired without rewriting that original failed task. + $deadlineImportParentId = $insertParent('template_import'); + $deadlineImportParent = $markDeadlineAudit($deadlineImportParentId); + $deadlineImportAudit = $immutableParentAudit($deadlineImportParent); + $deadlineImportChildId = $insertResolvedChild( + $deadlineImportParentId, + 'applied', + 'template_import_replica' + ); + $deadlineImportTemplateId = 'deadline-import-template'; + $deadlineImportGeneration = str_repeat('5', 32); + $deadlineImportSha = str_repeat('6', 64); + Capsule::table('cloud_templates')->insert([ + 'id' => $deadlineImportTemplateId, + 'name' => 'Deadline import', + 'os_family' => 'Debian', + 'os_version' => '13', + 'source_type' => 'qcow2', + 'sealed_source_url' => 'test-only', + 'image_bytes' => 4096, + 'sha256' => $deadlineImportSha, + 'startup_script' => '', + 'revision' => 1, + 'generation_token' => $deadlineImportGeneration, + 'state' => 'error', + 'active_job_id' => $deadlineImportParentId, + 'created_at' => $now - 60, + 'updated_at' => $now, + ]); + Capsule::table('cloud_template_replicas')->insert([ + 'host_id' => 7, + 'template_id' => $deadlineImportTemplateId, + 'revision' => 1, + 'generation_token' => $deadlineImportGeneration, + 'state' => 'active', + 'image_bytes' => 4096, + 'sha256' => $deadlineImportSha, + 'operation_id' => (string) CloudJob::findOrFail( + $deadlineImportChildId + )->operation_id, + 'job_id' => $deadlineImportChildId, + 'error_code' => '', + 'created_at' => $now - 60, + 'updated_at' => $now, + ]); + CloudJobService::reconcileAggregateParentEffectLocked( + CloudJob::findOrFail($deadlineImportChildId), + null + ); + $deadlineImportParent->refresh(); + $deadlinePublicIds = array_column( + CloudTemplateCatalogService::publicCatalog()['templates'], + 'id' + ); + $assert($immutableParentAudit($deadlineImportParent) + === $deadlineImportAudit + && (string) $deadlineImportParent->effect_resolution === 'applied' + && (string) Capsule::table('cloud_templates') + ->where('id', $deadlineImportTemplateId)->value('state') + === 'active' + && in_array($deadlineImportTemplateId, $deadlinePublicIds, true), + 'A recovered deadline import did not publish its catalog projection ' + . 'without rewriting the failed task.'); + + $deadlineDeleteParentId = $insertParent('template_delete'); + $deadlineDeleteParent = $markDeadlineAudit($deadlineDeleteParentId); + $deadlineDeleteAudit = $immutableParentAudit($deadlineDeleteParent); + $deadlineDeleteChildId = $insertResolvedChild( + $deadlineDeleteParentId, + 'applied', + 'template_delete_replica' + ); + $deadlineDeleteTemplateId = 'deadline-delete-template'; + $deadlineDeleteGeneration = str_repeat('7', 32); + $deadlineDeleteSha = str_repeat('8', 64); + Capsule::table('cloud_templates')->insert([ + 'id' => $deadlineDeleteTemplateId, + 'name' => 'Deadline delete', + 'os_family' => 'Debian', + 'os_version' => '13', + 'source_type' => 'qcow2', + 'sealed_source_url' => 'test-only', + 'image_bytes' => 4096, + 'sha256' => $deadlineDeleteSha, + 'startup_script' => '', + 'revision' => 1, + 'generation_token' => $deadlineDeleteGeneration, + 'state' => 'delete_failed', + 'active_job_id' => $deadlineDeleteParentId, + 'created_at' => $now - 60, + 'updated_at' => $now, + ]); + Capsule::table('cloud_template_replicas')->insert([ + 'host_id' => 7, + 'template_id' => $deadlineDeleteTemplateId, + 'revision' => 1, + 'generation_token' => $deadlineDeleteGeneration, + 'state' => 'delete_succeeded', + 'image_bytes' => 4096, + 'sha256' => $deadlineDeleteSha, + 'operation_id' => (string) CloudJob::findOrFail( + $deadlineDeleteChildId + )->operation_id, + 'job_id' => $deadlineDeleteChildId, + 'error_code' => '', + 'created_at' => $now - 60, + 'updated_at' => $now, + ]); + CloudJobService::reconcileAggregateParentEffectLocked( + CloudJob::findOrFail($deadlineDeleteChildId), + null + ); + $deadlineDeleteParent->refresh(); + $assert($immutableParentAudit($deadlineDeleteParent) + === $deadlineDeleteAudit + && (string) $deadlineDeleteParent->effect_resolution === 'applied' + && (string) Capsule::table('cloud_templates') + ->where('id', $deadlineDeleteTemplateId)->value('state') + === 'retired' + && (int) Capsule::table('cloud_templates') + ->where('id', $deadlineDeleteTemplateId)->value('revision') === 2 + && !Capsule::table('cloud_template_replicas') + ->where('template_id', $deadlineDeleteTemplateId)->exists(), + 'A recovered deadline delete did not retire its catalog projection ' + . 'without rewriting the failed task.'); + + $deadlineIsoParentId = $insertParent('user_iso_import'); + $deadlineIsoParent = $markDeadlineAudit($deadlineIsoParentId); + $deadlineIsoAudit = $immutableParentAudit($deadlineIsoParent); + $deadlineIsoChildId = $insertResolvedChild( + $deadlineIsoParentId, + 'applied', + 'user_iso_import_replica' + ); + $deadlineIsoId = str_repeat('9', 32); + $deadlineIsoSha = str_repeat('a', 64); + Capsule::table('cloud_user_isos')->insert([ + 'id' => $deadlineIsoId, + 'user_id' => 1, + 'name' => 'Deadline ISO', + 'sealed_source_url' => 'test-only', + 'size_bytes' => 4096, + 'sha256' => $deadlineIsoSha, + 'state' => 'import_failed', + 'import_operation_id' => (string) $deadlineIsoParent->operation_id, + 'active_job_id' => $deadlineIsoParentId, + 'created_at' => $now - 60, + 'updated_at' => $now, + ]); + Capsule::table('cloud_user_iso_replicas')->insert([ + 'host_id' => 7, + 'user_iso_id' => $deadlineIsoId, + 'user_id' => 1, + 'state' => 'active', + 'size_bytes' => 4096, + 'sha256' => $deadlineIsoSha, + 'operation_id' => (string) CloudJob::findOrFail( + $deadlineIsoChildId + )->operation_id, + 'job_id' => $deadlineIsoChildId, + 'error_code' => '', + 'created_at' => $now - 60, + 'updated_at' => $now, + ]); + CloudJobService::reconcileAggregateParentEffectLocked( + CloudJob::findOrFail($deadlineIsoChildId), + null + ); + $deadlineIsoParent->refresh(); + $assert($immutableParentAudit($deadlineIsoParent) === $deadlineIsoAudit + && (string) $deadlineIsoParent->effect_resolution === 'applied' + && (string) Capsule::table('cloud_user_isos') + ->where('id', $deadlineIsoId)->value('state') === 'active', + 'A recovered deadline ISO import did not publish its catalog ' + . 'projection without rewriting the failed task.'); + + $delayedConflictBefore = CloudJob::findOrFail((int) $partial->id); + $delayedConflictUpdatedAt = (int) $delayedConflictBefore->updated_at; + $automatic->tick(); + $delayedConflictAfter = CloudJob::findOrFail((int) $partial->id); + $assert((int) $delayedConflictAfter->updated_at + === $delayedConflictUpdatedAt + && (int) $delayedConflictAfter->available_at > time(), + 'A delayed aggregate conflict hot-looped within its retry window.'); + $assert(CloudAgentSettingsService::$requests === 0, + 'Aggregate recovery contacted an Agent instead of local ledgers.'); + + // A corrupt replica dispatch ledger must not be interpreted as an + // undispatched/no-effect child. Doing so would fail the replica and + // release the public template aggregate even though the Agent boundary is + // unknown. Keep the catalog, child escrow and parent fence intact instead. + $invalidDispatchParentId = $insertParent('template_import'); + Capsule::table('cloud_jobs')->where( + 'id', + $invalidDispatchParentId + )->update([ + 'phase' => 'awaiting_receipt', + 'outcome' => null, + 'status' => 'running', + 'terminal_at' => null, + 'effect_may_have_applied' => null, + 'safe_to_resubmit' => null, + 'effect_resolution' => 'not_applicable', + 'effect_resolved_at' => null, + 'effect_resolution_reason' => '', + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'lease_token' => null, + 'lease_until' => 0, + 'available_at' => 0, + 'receipt_deadline_at' => $now + 600, + ]); + $invalidDispatchChildId = $insertResolvedChild( + $invalidDispatchParentId, + 'not_applied', + 'template_import_replica' + ); + $invalidDispatchTemplateId = 'invalid-dispatch-template'; + $invalidDispatchGeneration = str_repeat('e', 32); + $invalidDispatchSha = str_repeat('f', 64); + $invalidDispatchPayload = CloudSecrets::encrypt([ + 'method' => 'POST', + 'request_target' => '/v1/templates/import', + 'body' => [], + 'template_id' => $invalidDispatchTemplateId, + 'owner_id' => 1, + 'can_manage' => true, + ], 'job-payload'); + Capsule::table('cloud_jobs')->where( + 'id', + $invalidDispatchChildId + )->update([ + 'phase' => 'awaiting_receipt', + 'outcome' => null, + 'status' => 'running', + 'sealed_payload' => $invalidDispatchPayload, + 'attempts' => 2, + 'dispatch_attempts' => 2, + 'dispatch_started_at' => $now - 30, + 'agent_accepted_at' => $now - 29, + 'receipt_deadline_at' => $now - 1, + 'terminal_at' => null, + 'effect_may_have_applied' => null, + 'safe_to_resubmit' => null, + 'effect_resolution' => 'not_applicable', + 'effect_resolved_at' => null, + 'effect_resolution_reason' => '', + 'completion_event_id' => null, + 'dispatched_at' => $now - 29, + 'lease_token' => null, + 'lease_until' => 0, + 'available_at' => 0, + 'error_code' => null, + 'finalization_incident' => 0, + 'finalization_error_code' => null, + ]); + Capsule::table('cloud_templates')->insert([ + 'id' => $invalidDispatchTemplateId, + 'name' => 'Invalid dispatch template', + 'os_family' => 'Debian', + 'os_version' => '13', + 'source_type' => 'qcow2', + 'sealed_source_url' => 'test-only', + 'image_bytes' => 4096, + 'sha256' => $invalidDispatchSha, + 'startup_script' => '', + 'revision' => 1, + 'generation_token' => $invalidDispatchGeneration, + 'state' => 'importing', + 'active_job_id' => $invalidDispatchParentId, + 'created_at' => $now - 60, + 'updated_at' => $now, + ]); + Capsule::table('cloud_template_replicas')->insert([ + 'host_id' => 7, + 'template_id' => $invalidDispatchTemplateId, + 'revision' => 1, + 'generation_token' => $invalidDispatchGeneration, + 'state' => 'importing', + 'image_bytes' => 0, + 'sha256' => $invalidDispatchSha, + 'operation_id' => (string) CloudJob::findOrFail( + $invalidDispatchChildId + )->operation_id, + 'job_id' => $invalidDispatchChildId, + 'error_code' => '', + 'created_at' => $now - 60, + 'updated_at' => $now, + ]); + $assert(CloudWorkerService::expireDueTasksForOwner( + 1, + $invalidDispatchChildId, + 1 + ) === 1, 'The invalid template child deadline was not claimed.'); + $invalidDispatchChild = CloudJob::findOrFail( + $invalidDispatchChildId + ); + $invalidDispatchParent = CloudJob::findOrFail( + $invalidDispatchParentId + ); + $invalidDispatchParentRecovery = CloudJobService::recoveryPresentation( + $invalidDispatchParent, + true + ); + $assert((string) $invalidDispatchChild->effect_resolution === 'unknown' + && (bool) $invalidDispatchChild->effect_may_have_applied + && !(bool) $invalidDispatchChild->safe_to_resubmit + && (bool) $invalidDispatchChild->finalization_incident + && (string) $invalidDispatchChild->finalization_error_code + === 'recovery_dispatch_ledger_conflict' + && (string) $invalidDispatchChild->sealed_payload + === $invalidDispatchPayload + && (string) $invalidDispatchParent->effect_resolution + !== 'not_applied' + && (string) Capsule::table('cloud_templates') + ->where('id', $invalidDispatchTemplateId)->value('state') + === 'importing' + && (string) Capsule::table('cloud_template_replicas') + ->where('template_id', $invalidDispatchTemplateId) + ->value('state') === 'importing' + && ($invalidDispatchParentRecovery['code'] ?? null) + === 'recovery_dispatch_ledger_conflict', + 'An invalid template child released its catalog or aggregate as no-effect.'); + + // Ordinary receipt finalization runs before the currently completing child + // is made terminal. That current transition is allowed, but a different + // sibling with an invalid recovery ledger must keep the public catalog and + // aggregate parent fenced. Once the sibling is repaired, the normal child + // recovery hook publishes the already-prepared replicas. + $normalGateParentId = $insertParent('template_import'); + Capsule::table('cloud_jobs')->where('id', $normalGateParentId)->update([ + 'phase' => 'awaiting_receipt', + 'outcome' => null, + 'status' => 'running', + 'terminal_at' => null, + 'effect_may_have_applied' => null, + 'safe_to_resubmit' => null, + 'effect_resolution' => 'not_applicable', + 'effect_resolved_at' => null, + 'effect_resolution_reason' => '', + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'lease_token' => null, + 'lease_until' => 0, + 'available_at' => 0, + 'receipt_deadline_at' => $now + 600, + ]); + $normalGateSiblingId = $insertResolvedChild( + $normalGateParentId, + 'applied', + 'template_import_replica' + ); + Capsule::table('cloud_jobs')->where( + 'id', + $normalGateSiblingId + )->update(['dispatch_attempts' => 2]); + $normalGateCurrentId = $insertResolvedChild( + $normalGateParentId, + 'applied', + 'template_import_replica' + ); + Capsule::table('cloud_jobs')->where('id', $normalGateCurrentId)->update([ + 'host_id' => 8, + 'phase' => 'awaiting_receipt', + 'outcome' => null, + 'status' => 'running', + 'terminal_at' => null, + 'effect_may_have_applied' => null, + 'safe_to_resubmit' => null, + 'effect_resolution' => 'not_applicable', + 'effect_resolved_at' => null, + 'effect_resolution_reason' => '', + ]); + $normalGateTemplateId = 'normal-settle-gated-template'; + $normalGateGeneration = str_repeat('1', 32); + $normalGateSha = str_repeat('2', 64); + Capsule::table('cloud_templates')->insert([ + 'id' => $normalGateTemplateId, + 'name' => 'Normal settle gated', + 'os_family' => 'Debian', + 'os_version' => '13', + 'source_type' => 'qcow2', + 'sealed_source_url' => 'test-only', + 'image_bytes' => 8192, + 'sha256' => $normalGateSha, + 'startup_script' => '', + 'revision' => 1, + 'generation_token' => $normalGateGeneration, + 'state' => 'importing', + 'active_job_id' => $normalGateParentId, + 'created_at' => $now - 60, + 'updated_at' => $now, + ]); + foreach ([ + [7, $normalGateSiblingId, 'active', 8192], + [8, $normalGateCurrentId, 'importing', 0], + ] as [$hostId, $jobId, $state, $imageBytes]) { + Capsule::table('cloud_template_replicas')->insert([ + 'host_id' => $hostId, + 'template_id' => $normalGateTemplateId, + 'revision' => 1, + 'generation_token' => $normalGateGeneration, + 'state' => $state, + 'image_bytes' => $imageBytes, + 'sha256' => $normalGateSha, + 'operation_id' => (string) CloudJob::findOrFail($jobId) + ->operation_id, + 'job_id' => $jobId, + 'error_code' => '', + 'created_at' => $now - 60, + 'updated_at' => $now, + ]); + } + CloudTemplateCatalogService::finishJobLocked( + CloudJob::findOrFail($normalGateCurrentId), + 'succeeded', + [ + 'id' => $normalGateTemplateId, + 'revision' => 1, + 'generation_token' => $normalGateGeneration, + 'size_bytes' => 8192, + 'sha256' => $normalGateSha, + ], + ['template_id' => $normalGateTemplateId], + [ + 'status' => 'succeeded', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'error_code' => '', + ] + ); + $normalGateParent = CloudJob::findOrFail($normalGateParentId); + $assert((string) $normalGateParent->phase === 'awaiting_receipt' + && (string) Capsule::table('cloud_templates') + ->where('id', $normalGateTemplateId)->value('state') + === 'importing' + && Capsule::table('cloud_template_replicas') + ->where('template_id', $normalGateTemplateId) + ->where('state', 'active')->count() === 2, + 'Normal completion published a parent with an unsafe sibling.'); + Capsule::table('cloud_jobs')->where('id', $normalGateSiblingId)->update([ + 'dispatch_attempts' => 1, + ]); + Capsule::table('cloud_jobs')->where('id', $normalGateCurrentId)->update([ + 'phase' => 'terminal', + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'terminal_at' => time(), + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'effect_resolved_at' => time(), + 'effect_resolution_reason' => 'normal_completion', + ]); + CloudJobService::reconcileAggregateParentEffectLocked( + CloudJob::findOrFail($normalGateSiblingId), + null + ); + $normalGateParent->refresh(); + $assert((string) $normalGateParent->phase === 'terminal' + && (string) $normalGateParent->outcome === 'succeeded' + && (string) $normalGateParent->effect_resolution === 'applied' + && (string) Capsule::table('cloud_templates') + ->where('id', $normalGateTemplateId)->value('state') === 'active', + 'The recovery hook did not publish a safe repaired aggregate.'); + + // The normal last-child receipt must use the same strict projection gate + // as late recovery. Missing, extra or cross-wired sibling replicas may be + // projected locally, but can never publish the aggregate parent. + foreach ([ + 'missing sibling replica' => [ + 'mutation' => 'missing', + 'exception' => CloudRecoveryAggregateStateConflict::class, + ], + 'extra sibling replica' => [ + 'mutation' => 'extra', + 'exception' => CloudRecoveryAggregateStateConflict::class, + ], + 'cross-wired sibling operation' => [ + 'mutation' => 'mapping', + 'exception' => CloudRecoveryOperationIdentityConflict::class, + ], + ] as $description => $fixture) { + $parentId = $insertParent('template_import'); + $siblingId = $insertResolvedChild( + $parentId, + 'applied', + 'template_import_replica' + ); + $currentId = $insertResolvedChild( + $parentId, + 'applied', + 'template_import_replica' + ); + $resourceId = $insertProjectionForParent($parentId); + Capsule::table('cloud_jobs')->where('id', $parentId)->update([ + 'phase' => 'awaiting_receipt', + 'outcome' => null, + 'status' => 'running', + 'terminal_at' => null, + 'effect_may_have_applied' => null, + 'safe_to_resubmit' => null, + 'effect_resolution' => 'not_applicable', + 'effect_resolved_at' => null, + 'effect_resolution_reason' => '', + 'error_code' => null, + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'lease_token' => null, + 'lease_until' => 0, + 'available_at' => 0, + ]); + Capsule::table('cloud_jobs')->where('id', $currentId)->update([ + 'phase' => 'awaiting_receipt', + 'outcome' => null, + 'status' => 'running', + 'terminal_at' => null, + 'effect_may_have_applied' => null, + 'safe_to_resubmit' => null, + 'effect_resolution' => 'not_applicable', + 'effect_resolved_at' => null, + 'effect_resolution_reason' => '', + ]); + Capsule::table('cloud_templates')->where('id', $resourceId)->update([ + 'state' => 'importing', + ]); + Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId) + ->where('job_id', $currentId)->update([ + 'state' => 'importing', + 'image_bytes' => 0, + ]); + $template = Capsule::table('cloud_templates') + ->where('id', $resourceId)->first(); + CloudTemplateCatalogService::finishJobLocked( + CloudJob::findOrFail($currentId), + 'succeeded', + [ + 'id' => $resourceId, + 'revision' => (int) $template->revision, + 'generation_token' => (string) $template->generation_token, + 'size_bytes' => (int) $template->image_bytes, + 'sha256' => (string) $template->sha256, + ], + ['template_id' => $resourceId], + [] + ); + if ($fixture['mutation'] === 'missing') { + Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId) + ->where('job_id', $siblingId)->delete(); + } elseif ($fixture['mutation'] === 'extra') { + $extra = (array) Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId) + ->where('job_id', $siblingId)->first(); + $extra['host_id'] = 900000 + $parentId; + $extra['job_id'] = null; + $extra['operation_id'] = md5('normal-extra:' . $parentId); + Capsule::table('cloud_template_replicas')->insert($extra); + } else { + Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId) + ->where('job_id', $siblingId)->update([ + 'operation_id' => md5('normal-cross-wire:' . $parentId), + ]); + } + Capsule::table('cloud_jobs')->where('id', $currentId)->update([ + 'phase' => 'terminal', + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'terminal_at' => time(), + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'effect_resolved_at' => time(), + 'effect_resolution_reason' => 'normal_completion', + ]); + try { + CloudJobService::reconcileAggregateParentEffectLocked( + CloudJob::findOrFail($currentId), + null + ); + throw new RuntimeException( + 'Normal aggregate accepted ' . $description . '.' + ); + } catch (CloudError $error) { + $assert($error instanceof $fixture['exception'], + 'Normal aggregate reported the wrong conflict for ' + . $description . '.'); + } + $assert((string) CloudJob::findOrFail($parentId)->phase + === 'awaiting_receipt' + && (string) Capsule::table('cloud_templates') + ->where('id', $resourceId)->value('state') === 'importing', + 'Normal aggregate published after ' . $description . '.'); + } + + // Exercise the actual ordinary completion order for all five catalog + // aggregates: project the final failed replica, persist its terminal + // no-effect conclusion, then let the shared strict reconciler restore the + // safe resource boundary. + foreach ([ + 'template_import' => 'template_import_replica', + 'template_metadata_sync' => 'template_metadata_replica', + 'template_delete' => 'template_delete_replica', + 'user_iso_import' => 'user_iso_import_replica', + 'user_iso_delete' => 'user_iso_delete_replica', + ] as $parentKind => $childKind) { + $parentId = $insertParent($parentKind); + $childId = $insertResolvedChild( + $parentId, + 'not_applied', + $childKind + ); + $resourceId = $insertProjectionForParent($parentId); + Capsule::table('cloud_jobs')->where('id', $parentId)->update([ + 'phase' => 'awaiting_receipt', + 'outcome' => null, + 'status' => 'running', + 'terminal_at' => null, + 'effect_may_have_applied' => null, + 'safe_to_resubmit' => null, + 'effect_resolution' => 'not_applicable', + 'effect_resolved_at' => null, + 'effect_resolution_reason' => '', + 'error_code' => null, + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'lease_token' => null, + 'lease_until' => 0, + 'available_at' => 0, + ]); + Capsule::table('cloud_jobs')->where('id', $childId)->update([ + 'phase' => 'awaiting_receipt', + 'outcome' => null, + 'status' => 'running', + 'terminal_at' => null, + 'effect_may_have_applied' => null, + 'safe_to_resubmit' => null, + 'effect_resolution' => 'not_applicable', + 'effect_resolved_at' => null, + 'effect_resolution_reason' => '', + ]); + if (str_starts_with($parentKind, 'template_')) { + $resourceState = $parentKind === 'template_delete' + ? 'deleting' : ($parentKind === 'template_import' + ? 'importing' : 'active'); + $replicaState = match ($parentKind) { + 'template_import' => 'importing', + 'template_metadata_sync' => 'syncing', + 'template_delete' => 'deleting', + }; + Capsule::table('cloud_templates')->where('id', $resourceId) + ->update(['state' => $resourceState]); + Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId)->update([ + 'state' => $replicaState, + ]); + $template = Capsule::table('cloud_templates') + ->where('id', $resourceId)->first(); + CloudTemplateCatalogService::finishJobLocked( + CloudJob::findOrFail($childId), + 'failed', + null, + ['template_id' => $resourceId], + [ + 'status' => 'failed', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => true, + 'error_code' => 'operation_not_applied', + ] + ); + } else { + $resourceState = $parentKind === 'user_iso_delete' + ? 'deleting' : 'importing'; + $replicaState = $parentKind === 'user_iso_delete' + ? 'deleting' : 'importing'; + Capsule::table('cloud_user_isos')->where('id', $resourceId) + ->update(['state' => $resourceState]); + Capsule::table('cloud_user_iso_replicas') + ->where('user_iso_id', $resourceId)->update([ + 'state' => $replicaState, + ]); + CloudUserIsoService::finishJobLocked( + CloudJob::findOrFail($childId), + 'failed', + null, + ['user_iso_id' => $resourceId], + [ + 'status' => 'failed', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => true, + 'error_code' => 'operation_not_applied', + ] + ); + } + Capsule::table('cloud_jobs')->where('id', $childId)->update([ + 'phase' => 'terminal', + 'outcome' => 'failed', + 'status' => 'failed', + 'terminal_at' => time(), + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 1, + 'effect_resolution' => 'not_applied', + 'effect_resolved_at' => time(), + 'effect_resolution_reason' => 'normal_completion', + 'error_code' => 'operation_rejected', + ]); + CloudJobService::reconcileAggregateParentEffectLocked( + CloudJob::findOrFail($childId), + null + ); + $parent = CloudJob::findOrFail($parentId); + $projectionOkay = match ($parentKind) { + 'template_import' => + (string) Capsule::table('cloud_templates') + ->where('id', $resourceId)->value('state') === 'retired' + && !Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId)->exists(), + 'template_metadata_sync' => + (string) Capsule::table('cloud_templates') + ->where('id', $resourceId)->value('state') === 'active' + && (string) Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId)->value('state') + === 'stale', + 'template_delete' => + (string) Capsule::table('cloud_templates') + ->where('id', $resourceId)->value('state') === 'active' + && (string) Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId)->value('state') + === 'active', + 'user_iso_import' => + (string) Capsule::table('cloud_user_isos') + ->where('id', $resourceId)->value('state') === 'retired' + && !Capsule::table('cloud_user_iso_replicas') + ->where('user_iso_id', $resourceId)->exists(), + 'user_iso_delete' => + (string) Capsule::table('cloud_user_isos') + ->where('id', $resourceId)->value('state') === 'active' + && (string) Capsule::table('cloud_user_iso_replicas') + ->where('user_iso_id', $resourceId)->value('state') + === 'active', + }; + if ($parentKind === 'template_metadata_sync') { + $publicIds = array_column( + CloudTemplateCatalogService::publicCatalog()['templates'], + 'id' + ); + $projectionOkay = $projectionOkay + && !in_array($resourceId, $publicIds, true); + } + $assert((string) $parent->phase === 'terminal' + && (string) $parent->outcome === 'failed' + && (string) $parent->effect_resolution === 'not_applied' + && !(bool) $parent->finalization_incident + && $projectionOkay, + 'Normal all-not-applied completion did not restore ' + . $parentKind . '.'); + } + + // The ordinary last-child path must lock the one-and-only main catalog + // record before publishing its aggregate parent. A duplicate binding is + // data corruption, not permission to complete one arbitrary record. + foreach ([ + 'template_import' => 'template_import_replica', + 'user_iso_import' => 'user_iso_import_replica', + ] as $parentKind => $childKind) { + $parentId = $insertParent($parentKind); + $childId = $insertResolvedChild($parentId, 'applied', $childKind); + $resourceId = $insertProjectionForParent($parentId); + Capsule::table('cloud_jobs')->where('id', $parentId)->update([ + 'phase' => 'awaiting_receipt', + 'outcome' => null, + 'status' => 'running', + 'terminal_at' => null, + 'effect_may_have_applied' => null, + 'safe_to_resubmit' => null, + 'effect_resolution' => 'not_applicable', + 'effect_resolved_at' => null, + 'effect_resolution_reason' => '', + 'error_code' => null, + 'finalization_incident' => 0, + 'finalization_error_code' => null, + ]); + Capsule::table('cloud_jobs')->where('id', $childId)->update([ + 'phase' => 'awaiting_receipt', + 'outcome' => null, + 'status' => 'running', + 'terminal_at' => null, + 'effect_may_have_applied' => null, + 'safe_to_resubmit' => null, + 'effect_resolution' => 'not_applicable', + 'effect_resolved_at' => null, + 'effect_resolution_reason' => '', + ]); + if ($parentKind === 'template_import') { + Capsule::table('cloud_templates')->where('id', $resourceId) + ->update(['state' => 'importing']); + Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId)->update([ + 'state' => 'importing', + 'image_bytes' => 0, + ]); + $duplicate = (array) Capsule::table('cloud_templates') + ->where('id', $resourceId)->first(); + $duplicate['id'] = $resourceId . '-normal-duplicate'; + Capsule::table('cloud_templates')->insert($duplicate); + $template = Capsule::table('cloud_templates') + ->where('id', $resourceId)->first(); + CloudTemplateCatalogService::finishJobLocked( + CloudJob::findOrFail($childId), + 'succeeded', + [ + 'id' => $resourceId, + 'revision' => (int) $template->revision, + 'generation_token' => + (string) $template->generation_token, + 'size_bytes' => (int) $template->image_bytes, + 'sha256' => (string) $template->sha256, + ], + ['template_id' => $resourceId], + [] + ); + } else { + Capsule::table('cloud_user_isos')->where('id', $resourceId) + ->update(['state' => 'importing']); + Capsule::table('cloud_user_iso_replicas') + ->where('user_iso_id', $resourceId)->update([ + 'state' => 'importing', + 'size_bytes' => 0, + ]); + $duplicate = (array) Capsule::table('cloud_user_isos') + ->where('id', $resourceId)->first(); + $duplicate['id'] = md5('normal-duplicate:' . $parentId); + Capsule::table('cloud_user_isos')->insert($duplicate); + $iso = Capsule::table('cloud_user_isos') + ->where('id', $resourceId)->first(); + CloudUserIsoService::finishJobLocked( + CloudJob::findOrFail($childId), + 'succeeded', + [ + 'id' => $resourceId, + 'owner_id' => (int) $iso->user_id, + 'name' => (string) $iso->name, + 'size_bytes' => (int) $iso->size_bytes, + 'sha256' => (string) $iso->sha256, + ], + ['user_iso_id' => $resourceId], + [] + ); + } + Capsule::table('cloud_jobs')->where('id', $childId)->update([ + 'phase' => 'terminal', + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'terminal_at' => time(), + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'effect_resolved_at' => time(), + 'effect_resolution_reason' => 'normal_completion', + ]); + try { + CloudJobService::reconcileAggregateParentEffectLocked( + CloudJob::findOrFail($childId), + null + ); + throw new RuntimeException( + 'Normal catalog settle accepted duplicate main records.' + ); + } catch (CloudRecoveryAggregateStateConflict $expected) { + // Expected: the child projection exists, but the parent remains + // fenced until its one-and-only main record is repairable. + } + $assert((string) CloudJob::findOrFail($parentId)->phase + === 'awaiting_receipt', + 'A duplicate main record completed its normal aggregate parent.'); + } + foreach ([ + 'template_delete' => [ + CloudTemplateCatalogService::class, + 'template_delete_replica', + 'cloud_templates', + ], + 'user_iso_delete' => [ + CloudUserIsoService::class, + 'user_iso_delete_replica', + 'cloud_user_isos', + ], + ] as $parentKind => [$service, $childKind, $table]) { + $parentId = $insertParent($parentKind); + $childId = $insertResolvedChild($parentId, 'applied', $childKind); + $resourceId = $insertProjectionForParent($parentId); + Capsule::table('cloud_jobs')->where('id', $parentId)->update([ + 'phase' => 'awaiting_receipt', + 'outcome' => null, + 'status' => 'running', + 'terminal_at' => null, + 'effect_may_have_applied' => null, + 'safe_to_resubmit' => null, + 'effect_resolution' => 'not_applicable', + 'effect_resolved_at' => null, + 'effect_resolution_reason' => '', + 'error_code' => null, + 'finalization_incident' => 0, + 'finalization_error_code' => null, + ]); + Capsule::table('cloud_jobs')->where('id', $childId)->update([ + 'phase' => 'awaiting_receipt', + 'outcome' => null, + 'status' => 'running', + 'terminal_at' => null, + 'effect_may_have_applied' => null, + 'safe_to_resubmit' => null, + 'effect_resolution' => 'not_applicable', + 'effect_resolved_at' => null, + 'effect_resolution_reason' => '', + ]); + $duplicate = (array) Capsule::table($table) + ->where('id', $resourceId)->first(); + $duplicate['id'] = $parentKind === 'template_delete' + ? $resourceId . '-normal-duplicate' + : md5('normal-delete-duplicate:' . $parentId); + Capsule::table($table)->insert($duplicate); + $resource = $parentKind === 'template_delete' + ? \App\Models\CloudTemplate::findOrFail($resourceId) + : \App\Models\CloudUserIso::findOrFail($resourceId); + $settleDelete = new ReflectionMethod($service, 'settleDeleteParent'); + try { + $settleDelete->invoke( + null, + $resource, + $parentId, + ['effect_may_have_applied' => true], + $childId + ); + throw new RuntimeException( + 'Normal delete settle accepted duplicate main records.' + ); + } catch (CloudRecoveryAggregateStateConflict $expected) { + // Expected. + } + $assert((string) CloudJob::findOrFail($parentId)->phase + === 'awaiting_receipt', + 'A duplicate main record completed its normal delete parent.'); + } + + // ISO identity reconstruction must bind both import and delete children to + // the expected aggregate root, owner and active main record before any + // normal receipt can reach catalog finalization. + $expectIsoIdentityConflict = static function ( + CloudJob $child, + array $payload + ): void { + try { + CloudOperationRecoveryIdentity::expectedFromPayload( + $child, + $payload + ); + throw new RuntimeException( + 'Cross-wired ISO aggregate identity was accepted.' + ); + } catch (CloudRecoveryInstanceStateConflict $expected) { + // Expected. + } + }; + $identityImportParent = $insertParent('user_iso_import'); + $identityImportChild = $insertResolvedChild( + $identityImportParent, + 'applied', + 'user_iso_import_replica' + ); + $identityImportIso = $insertProjectionForParent($identityImportParent); + Capsule::table('cloud_user_isos')->where('id', $identityImportIso) + ->update(['active_job_id' => $identityImportParent + 900000]); + $identityImportRow = Capsule::table('cloud_user_isos') + ->where('id', $identityImportIso)->first(); + $expectIsoIdentityConflict( + CloudJob::findOrFail($identityImportChild), + [ + 'method' => 'POST', + 'request_target' => '/v1/user-isos', + 'body' => [ + 'id' => $identityImportIso, + 'owner_id' => 1, + 'name' => (string) $identityImportRow->name, + ], + 'user_iso_id' => $identityImportIso, + 'owner_id' => 1, + ] + ); + + $identityDeleteParent = $insertParent('user_iso_delete'); + $identityDeleteChild = $insertResolvedChild( + $identityDeleteParent, + 'applied', + 'user_iso_delete_replica' + ); + $identityDeleteIso = $insertProjectionForParent($identityDeleteParent); + Capsule::table('cloud_jobs')->where('id', $identityDeleteParent) + ->update(['user_id' => 2]); + $expectIsoIdentityConflict( + CloudJob::findOrFail($identityDeleteChild), + [ + 'method' => 'DELETE', + 'request_target' => '/v1/user-isos/' + . rawurlencode($identityDeleteIso) . '?owner_id=1', + 'body' => [], + 'user_iso_id' => $identityDeleteIso, + 'owner_id' => 1, + ] + ); + + // A historical fail-open parent can already say succeeded/applied while a + // child remains unsafe. Such a template must disappear from the public + // catalog and be rejected by every provisioning metadata boundary until + // the child ledger is repaired. + $historicalParentId = $insertParent('template_import'); + Capsule::table('cloud_jobs')->where('id', $historicalParentId)->update([ + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'effect_resolved_at' => $now - 1, + 'effect_resolution_reason' => 'historical_fail_open', + 'error_code' => null, + 'finalization_incident' => 0, + 'finalization_error_code' => null, + ]); + $historicalChildId = $insertResolvedChild( + $historicalParentId, + 'applied', + 'template_import_replica' + ); + Capsule::table('cloud_jobs')->where('id', $historicalChildId)->update([ + 'dispatch_attempts' => 2, + ]); + $historicalTemplateId = 'historical-fail-open-template'; + $historicalGeneration = str_repeat('3', 32); + $historicalSha = str_repeat('4', 64); + Capsule::table('cloud_templates')->insert([ + 'id' => $historicalTemplateId, + 'name' => 'Historical fail open', + 'os_family' => 'Debian', + 'os_version' => '13', + 'source_type' => 'qcow2', + 'sealed_source_url' => 'test-only', + 'image_bytes' => 4096, + 'sha256' => $historicalSha, + 'startup_script' => '', + 'revision' => 1, + 'generation_token' => $historicalGeneration, + 'state' => 'active', + 'active_job_id' => $historicalParentId, + 'created_at' => $now - 60, + 'updated_at' => $now, + ]); + Capsule::table('cloud_template_replicas')->insert([ + 'host_id' => 7, + 'template_id' => $historicalTemplateId, + 'revision' => 1, + 'generation_token' => $historicalGeneration, + 'state' => 'active', + 'image_bytes' => 4096, + 'sha256' => $historicalSha, + 'operation_id' => (string) CloudJob::findOrFail($historicalChildId) + ->operation_id, + 'job_id' => $historicalChildId, + 'error_code' => '', + 'created_at' => $now - 60, + 'updated_at' => $now, + ]); + $publicIds = array_column( + CloudTemplateCatalogService::publicCatalog()['templates'], + 'id' + ); + $assert(!in_array($historicalTemplateId, $publicIds, true), + 'A fail-open template remained visible in the public catalog.'); + $expectUnsafeTemplate = static function ( + callable $callable, + string $message + ) use ($assert): void { + try { + $callable(); + } catch (CloudError $error) { + $assert($error->httpStatus === 409, $message); + return; + } + throw new RuntimeException($message); + }; + $expectUnsafeTemplate( + static fn (): array => + CloudTemplateCatalogService::applyProvisioningSnapshot([ + 'template_id' => $historicalTemplateId, + ]), + 'Provisioning consumed a fail-open template.' + ); + $expectUnsafeTemplate( + static fn (): array => + CloudTemplateCatalogService::templateMetadataSnapshot([ + 'template_id' => $historicalTemplateId, + 'template_revision' => 1, + 'template_generation_token' => $historicalGeneration, + ]), + 'Metadata validation consumed a fail-open template.' + ); + $expectUnsafeTemplate( + static function () use ($historicalTemplateId): void { + CloudTemplateCatalogService::assertProvisionable( + $historicalTemplateId + ); + }, + 'Provisionability accepted a fail-open template.' + ); + Capsule::table('cloud_jobs')->where('id', $historicalChildId)->update([ + 'dispatch_attempts' => 1, + ]); + $publicIds = array_column( + CloudTemplateCatalogService::publicCatalog()['templates'], + 'id' + ); + $snapshot = CloudTemplateCatalogService::applyProvisioningSnapshot([ + 'template_id' => $historicalTemplateId, + ]); + $metadata = CloudTemplateCatalogService::templateMetadataSnapshot([ + 'template_id' => $historicalTemplateId, + 'template_revision' => 1, + 'template_generation_token' => $historicalGeneration, + ]); + CloudTemplateCatalogService::assertProvisionable($historicalTemplateId); + $assert(in_array($historicalTemplateId, $publicIds, true) + && ($snapshot['template_id'] ?? null) === $historicalTemplateId + && ($metadata['template_id'] ?? null) === $historicalTemplateId, + 'A safely repaired template remained unavailable.'); + + // Uniform not-applied evidence is a safe rollback boundary. Imports retire + // their unused placeholders; deletes restore their prior usable records; + // metadata keeps the panel revision while old host revisions remain stale. + foreach ([ + 'template_import' => 'template_import_replica', + 'template_metadata_sync' => 'template_metadata_replica', + 'template_delete' => 'template_delete_replica', + 'user_iso_import' => 'user_iso_import_replica', + 'user_iso_delete' => 'user_iso_delete_replica', + ] as $parentKind => $childKind) { + $parentId = $insertParent($parentKind); + $childId = $insertResolvedChild( + $parentId, + 'not_applied', + $childKind + ); + $resourceId = $insertProjectionForParent($parentId); + $parent = $markDeadlineAudit($parentId); + $audit = $immutableParentAudit($parent); + CloudJobService::reconcileAggregateParentEffectLocked( + CloudJob::findOrFail($childId), + null + ); + $parent->refresh(); + $projectionOkay = match ($parentKind) { + 'template_import' => + (string) Capsule::table('cloud_templates') + ->where('id', $resourceId)->value('state') === 'retired' + && !Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId)->exists(), + 'template_metadata_sync' => + (string) Capsule::table('cloud_templates') + ->where('id', $resourceId)->value('state') === 'active' + && (string) Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId)->value('state') + === 'stale' + && (int) Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId)->value('revision') + < (int) Capsule::table('cloud_templates') + ->where('id', $resourceId)->value('revision'), + 'template_delete' => + (string) Capsule::table('cloud_templates') + ->where('id', $resourceId)->value('state') === 'active' + && (string) Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId)->value('state') + === 'active', + 'user_iso_import' => + (string) Capsule::table('cloud_user_isos') + ->where('id', $resourceId)->value('state') === 'retired' + && (int) Capsule::table('cloud_user_isos') + ->where('id', $resourceId)->value('size_bytes') === 0 + && (string) Capsule::table('cloud_user_isos') + ->where('id', $resourceId)->value('name') === '' + && !Capsule::table('cloud_user_iso_replicas') + ->where('user_iso_id', $resourceId)->exists(), + 'user_iso_delete' => + (string) Capsule::table('cloud_user_isos') + ->where('id', $resourceId)->value('state') === 'active' + && (string) Capsule::table('cloud_user_iso_replicas') + ->where('user_iso_id', $resourceId)->value('state') + === 'active', + }; + if ($parentKind === 'template_metadata_sync') { + $publicIds = array_column( + CloudTemplateCatalogService::publicCatalog()['templates'], + 'id' + ); + $snapshotBlocked = false; + try { + CloudTemplateCatalogService::applyProvisioningSnapshot([ + 'template_id' => $resourceId, + ]); + } catch (CloudError $error) { + $snapshotBlocked = $error->httpStatus === 409; + } + $assertBlocked = false; + try { + CloudTemplateCatalogService::assertProvisionable($resourceId); + } catch (CloudError $error) { + $assertBlocked = $error->httpStatus === 409; + } + $projectionOkay = $projectionOkay + && !in_array($resourceId, $publicIds, true) + && $snapshotBlocked + && $assertBlocked; + } + $assert($immutableParentAudit($parent) === $audit + && (string) $parent->effect_resolution === 'not_applied' + && !(bool) $parent->finalization_incident + && (int) $parent->available_at === 0 + && $projectionOkay, + 'Uniform not-applied recovery did not unlock ' . $parentKind . '.'); + } + + $insertMixedMetadata = static function ( + bool $terminal, + bool $legacy + ) use ( + $insertParent, + $insertResolvedChild, + $insertProjectionForParent, + $makeLegacyEligible, + $now + ): array { + $parentId = $insertParent('template_metadata_sync'); + if (!$terminal) { + Capsule::table('cloud_jobs')->where('id', $parentId)->update([ + 'phase' => 'awaiting_receipt', + 'outcome' => null, + 'status' => 'running', + 'terminal_at' => null, + 'effect_may_have_applied' => null, + 'safe_to_resubmit' => null, + 'effect_resolution' => 'not_applicable', + 'effect_resolved_at' => null, + 'effect_resolution_reason' => '', + 'error_code' => null, + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'lease_token' => null, + 'lease_until' => 0, + 'available_at' => $now, + ]); + } elseif ($legacy) { + $makeLegacyEligible($parentId); + } + $appliedId = $insertResolvedChild( + $parentId, + 'applied', + 'template_metadata_replica' + ); + $notAppliedId = $insertResolvedChild( + $parentId, + 'not_applied', + 'template_metadata_replica' + ); + $resourceId = $insertProjectionForParent($parentId); + return [$parentId, $appliedId, $notAppliedId, $resourceId]; + }; + $assertMixedMetadata = static function ( + int $parentId, + string $resourceId, + string $context + ) use ($assert): void { + $parent = CloudJob::findOrFail($parentId); + $replicas = Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId)->orderBy('host_id')->get(); + $publicIds = array_column( + CloudTemplateCatalogService::publicCatalog()['templates'], + 'id' + ); + $snapshot = CloudTemplateCatalogService::applyProvisioningSnapshot([ + 'template_id' => $resourceId, + ]); + CloudTemplateCatalogService::assertProvisionable($resourceId); + $assert((string) $parent->phase === 'terminal' + && (string) $parent->outcome === 'failed' + && (string) $parent->effect_resolution === 'applied' + && !(bool) $parent->finalization_incident + && (string) Capsule::table('cloud_templates') + ->where('id', $resourceId)->value('state') === 'active' + && $replicas->count() === 2 + && $replicas->contains(static fn ($replica): bool => + (string) $replica->state === 'active' + && (int) $replica->revision === 2) + && $replicas->contains(static fn ($replica): bool => + (string) $replica->state === 'stale' + && (int) $replica->revision === 1) + && in_array($resourceId, $publicIds, true) + && ($snapshot['template_id'] ?? null) === $resourceId, + 'Mixed metadata did not converge at the ' . $context . ' seam.'); + }; + + [$realtimeMetadataParent, $realtimeMetadataApplied, + $_realtimeMetadataAbsent, $realtimeMetadataResource] = + $insertMixedMetadata(false, false); + CloudJobService::reconcileAggregateParentEffectLocked( + CloudJob::findOrFail($realtimeMetadataApplied), + null + ); + $assertMixedMetadata( + $realtimeMetadataParent, + $realtimeMetadataResource, + 'realtime' + ); + + [$terminalMetadataParent, $terminalMetadataApplied, + $_terminalMetadataAbsent, $terminalMetadataResource] = + $insertMixedMetadata(true, false); + $terminalMetadataAudit = $immutableParentAudit( + $markDeadlineAudit($terminalMetadataParent) + ); + CloudJobService::reconcileAggregateParentEffectLocked( + CloudJob::findOrFail($terminalMetadataApplied), + null + ); + $assertMixedMetadata( + $terminalMetadataParent, + $terminalMetadataResource, + 'terminal deadline' + ); + $assert($immutableParentAudit( + CloudJob::findOrFail($terminalMetadataParent) + ) === $terminalMetadataAudit, + 'Mixed metadata recovery rewrote the deadline parent audit.'); + + [$legacyMetadataParent, $_legacyMetadataApplied, + $_legacyMetadataAbsent, $legacyMetadataResource] = + $insertMixedMetadata(true, true); + $assert(CloudJobService::reconcileOneLegacyAggregateEffect(), + 'Legacy mixed metadata was not inspected.'); + $assertMixedMetadata( + $legacyMetadataParent, + $legacyMetadataResource, + 'legacy sweep' + ); + + // An all-applied import can exceed quota only after host work finished. + // Keep it unavailable, expose an explicit cleanup capability, and reserve + // a brand-new delete aggregate instead of replaying an import child. + $quotaExistingIsoId = md5('quota-existing-active-iso'); + Capsule::table('cloud_user_isos')->insert([ + 'id' => $quotaExistingIsoId, + 'user_id' => 1, + 'name' => 'Existing quota usage', + 'sealed_source_url' => 'test-only', + 'size_bytes' => 6 * 1024 * 1024 * 1024, + 'sha256' => hash('sha256', 'existing-quota-iso'), + 'state' => 'active', + 'import_operation_id' => md5('existing-quota-operation'), + 'active_job_id' => null, + 'created_at' => $now - 120, + 'updated_at' => $now, + ]); + $quotaParentId = $insertParent('user_iso_import'); + Capsule::table('cloud_jobs')->where('id', $quotaParentId)->update([ + 'phase' => 'awaiting_receipt', + 'outcome' => null, + 'status' => 'running', + 'terminal_at' => null, + 'effect_may_have_applied' => null, + 'safe_to_resubmit' => null, + 'effect_resolution' => 'not_applicable', + 'effect_resolved_at' => null, + 'effect_resolution_reason' => '', + 'error_code' => null, + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'lease_token' => null, + 'lease_until' => 0, + 'available_at' => $now, + 'receipt_deadline_at' => $now + 600, + ]); + $quotaChildId = $insertResolvedChild( + $quotaParentId, + 'applied', + 'user_iso_import_replica' + ); + $quotaIsoId = $insertProjectionForParent($quotaParentId); + $quotaRecoveredBytes = 5 * 1024 * 1024 * 1024; + Capsule::table('cloud_user_isos')->where('id', $quotaIsoId)->update([ + 'size_bytes' => $quotaRecoveredBytes, + ]); + Capsule::table('cloud_user_iso_replicas') + ->where('user_iso_id', $quotaIsoId)->update([ + 'size_bytes' => $quotaRecoveredBytes, + ]); + CloudJobService::reconcileAggregateParentEffectLocked( + CloudJob::findOrFail($quotaChildId), + null + ); + $quotaParent = CloudJob::findOrFail($quotaParentId); + $quotaIso = Capsule::table('cloud_user_isos') + ->where('id', $quotaIsoId)->first(); + $quotaDto = collect(CloudUserIsoService::listing(1)['isos']) + ->firstWhere('id', $quotaIsoId); + $assert((string) $quotaParent->phase === 'terminal' + && (string) $quotaParent->outcome === 'failed' + && (string) $quotaParent->error_code + === 'user_iso_quota_exceeded' + && (string) $quotaParent->effect_resolution === 'applied' + && !(bool) $quotaParent->finalization_incident + && $quotaIso !== null + && (string) $quotaIso->state === 'import_failed' + && is_array($quotaDto) + && ($quotaDto['can_delete'] ?? false) === true + && ($quotaDto['cleanup_reason'] ?? null) + === 'quota_exceeded_after_import', + 'Quota-rejected applied ISO import was not exposed for safe cleanup.'); + $cleanup = CloudUserIsoService::delete($quotaIsoId, ['user_id' => 1]); + $cleanupParentId = (int) ($cleanup['task_id'] ?? 0); + $cleanupParent = CloudJob::findOrFail($cleanupParentId); + $quotaIso = Capsule::table('cloud_user_isos') + ->where('id', $quotaIsoId)->first(); + $cleanupChild = CloudJob::where('parent_job_id', $cleanupParentId)->first(); + $assert($cleanupParentId > 0 && $cleanupParentId !== $quotaParentId + && (string) $cleanupParent->kind === 'user_iso_delete' + && (string) $cleanupParent->phase === 'awaiting_receipt' + && $quotaIso !== null + && (string) $quotaIso->state === 'deleting' + && (int) $quotaIso->active_job_id === $cleanupParentId + && $cleanupChild !== null + && (string) $cleanupChild->kind === 'user_iso_delete_replica' + && (string) Capsule::table('cloud_user_iso_replicas') + ->where('user_iso_id', $quotaIsoId)->value('state') === 'deleting', + 'Quota cleanup did not reserve an independent delete operation.'); + $nextId = max( + $nextId, + (int) Capsule::table('cloud_jobs')->max('id') + 1 + ); + + // A deadline keeps its immutable aggregate_deadline_exceeded audit even + // when every late host later proves the import applied. If quota prevented + // publication, that exact all-active projection must still be removable + // by a new delete operation without relying on the parent's old error. + $deadlineQuotaParentId = $insertParent('user_iso_import'); + $deadlineQuotaAudit = $immutableParentAudit( + $markDeadlineAudit($deadlineQuotaParentId) + ); + $deadlineQuotaChildId = $insertResolvedChild( + $deadlineQuotaParentId, + 'applied', + 'user_iso_import_replica' + ); + $deadlineQuotaIsoId = $insertProjectionForParent( + $deadlineQuotaParentId + ); + Capsule::table('cloud_user_isos')->where( + 'id', + $deadlineQuotaIsoId + )->update(['size_bytes' => $quotaRecoveredBytes]); + Capsule::table('cloud_user_iso_replicas')->where( + 'user_iso_id', + $deadlineQuotaIsoId + )->update(['size_bytes' => $quotaRecoveredBytes]); + CloudJobService::reconcileAggregateParentEffectLocked( + CloudJob::findOrFail($deadlineQuotaChildId), + null + ); + $deadlineQuotaParent = CloudJob::findOrFail($deadlineQuotaParentId); + $deadlineQuotaDto = collect(CloudUserIsoService::listing(1)['isos']) + ->firstWhere('id', $deadlineQuotaIsoId); + $assert($immutableParentAudit($deadlineQuotaParent) + === $deadlineQuotaAudit + && (string) $deadlineQuotaParent->error_code + === 'aggregate_deadline_exceeded' + && (string) $deadlineQuotaParent->effect_resolution === 'applied' + && !(bool) $deadlineQuotaParent->finalization_incident + && (string) Capsule::table('cloud_user_isos') + ->where('id', $deadlineQuotaIsoId)->value('state') + === 'import_failed' + && is_array($deadlineQuotaDto) + && ($deadlineQuotaDto['can_delete'] ?? false) === true + && ($deadlineQuotaDto['cleanup_reason'] ?? null) + === 'quota_exceeded_after_import', + 'Deadline quota recovery lost its audit or safe cleanup capability.'); + + // Projection failure rolls back atomically and delays only that parent. A + // later valid parent is claimed by the next tick instead of being starved. + $missingCatalogParentId = $insertParent('template_import'); + $missingCatalogChildId = $insertResolvedChild( + $missingCatalogParentId, + 'applied', + 'template_import_replica' + ); + $makeLegacyEligible($missingCatalogParentId); + $missingCatalogAudit = $immutableParentAudit( + CloudJob::findOrFail($missingCatalogParentId) + ); + $validAfterDamageParentId = $insertParent('template_import'); + $insertResolvedChild( + $validAfterDamageParentId, + 'applied', + 'template_import_replica' + ); + $validAfterDamageResource = $insertProjectionForParent( + $validAfterDamageParentId + ); + $makeLegacyEligible($validAfterDamageParentId); + $assert($automatic->tick(), + 'The damaged projection was not isolated by the legacy sweep.'); + $missingCatalogParent = CloudJob::findOrFail($missingCatalogParentId); + $assert($immutableParentAudit($missingCatalogParent) + === $missingCatalogAudit + && (string) $missingCatalogParent->effect_resolution === 'unknown' + && (bool) $missingCatalogParent->finalization_incident + && (string) $missingCatalogParent->finalization_error_code + === 'recovery_instance_state_conflict' + && (int) $missingCatalogParent->available_at >= time() + 290 + && CloudJob::findOrFail($missingCatalogChildId)->effect_resolution + === 'applied', + 'A missing catalog escaped or rewrote the terminal parent audit.'); + $assert($automatic->tick(), + 'A damaged projection starved the following valid aggregate.'); + $validAfterDamageParent = CloudJob::findOrFail( + $validAfterDamageParentId + ); + $assert((string) $validAfterDamageParent->effect_resolution === 'applied' + && !(bool) $validAfterDamageParent->finalization_incident + && (string) Capsule::table('cloud_templates') + ->where('id', $validAfterDamageResource)->value('state') + === 'active', + 'The valid aggregate after a damaged parent did not converge.'); + + $projectionConflictFixtures = []; + foreach ([ + 'missing replica' => 'missing', + 'extra replica' => 'extra', + 'residual importing replica' => 'pending', + 'cross-wired operation' => 'mapping', + ] as $description => $mutation) { + $parentId = $insertParent('template_import'); + $insertResolvedChild( + $parentId, + 'applied', + 'template_import_replica' + ); + $resourceId = $insertProjectionForParent($parentId); + if ($mutation === 'missing') { + Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId)->delete(); + } elseif ($mutation === 'extra') { + $extra = (array) Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId)->first(); + $extra['host_id'] = 999000 + $parentId; + $extra['job_id'] = null; + $extra['operation_id'] = md5('extra-replica:' . $parentId); + Capsule::table('cloud_template_replicas')->insert($extra); + } elseif ($mutation === 'pending') { + Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId) + ->update(['state' => 'importing']); + } else { + Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId)->update([ + 'operation_id' => md5('wrong-operation:' . $parentId), + ]); + } + $makeLegacyEligible($parentId); + $projectionConflictFixtures[$parentId] = [ + 'description' => $description, + 'code' => in_array($mutation, ['missing', 'extra'], true) + ? 'recovery_aggregate_state_conflict' + : ($mutation === 'mapping' + ? 'recovery_operation_identity_conflict' + : 'recovery_instance_state_conflict'), + ]; + } + + foreach ([ + 'template generation mismatch' => 'generation', + 'template import content mismatch' => 'content', + ] as $description => $mutation) { + $parentId = $insertParent('template_import'); + $insertResolvedChild( + $parentId, + 'applied', + 'template_import_replica' + ); + $resourceId = $insertProjectionForParent($parentId); + Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId)->update( + $mutation === 'generation' + ? ['generation_token' => str_repeat('f', 32)] + : [ + 'image_bytes' => 1, + 'sha256' => str_repeat('0', 64), + ] + ); + $makeLegacyEligible($parentId); + $projectionConflictFixtures[$parentId] = [ + 'description' => $description, + 'code' => 'recovery_instance_state_conflict', + ]; + } + + $metadataContentParent = $insertParent('template_metadata_sync'); + $insertResolvedChild( + $metadataContentParent, + 'applied', + 'template_metadata_replica' + ); + $insertResolvedChild( + $metadataContentParent, + 'not_applied', + 'template_metadata_replica' + ); + $metadataContentResource = $insertProjectionForParent( + $metadataContentParent + ); + Capsule::table('cloud_template_replicas') + ->where('template_id', $metadataContentResource) + ->where('state', 'active')->update([ + 'image_bytes' => 1, + 'sha256' => str_repeat('0', 64), + ]); + $makeLegacyEligible($metadataContentParent); + $projectionConflictFixtures[$metadataContentParent] = [ + 'description' => 'template metadata mixed content mismatch', + 'code' => 'recovery_instance_state_conflict', + ]; + + $templateDeleteContentParent = $insertParent('template_delete'); + $insertResolvedChild( + $templateDeleteContentParent, + 'not_applied', + 'template_delete_replica' + ); + $templateDeleteContentResource = $insertProjectionForParent( + $templateDeleteContentParent + ); + Capsule::table('cloud_template_replicas') + ->where('template_id', $templateDeleteContentResource)->update([ + 'image_bytes' => 1, + 'sha256' => str_repeat('0', 64), + ]); + $makeLegacyEligible($templateDeleteContentParent); + $projectionConflictFixtures[$templateDeleteContentParent] = [ + 'description' => 'template delete not-applied content mismatch', + 'code' => 'recovery_instance_state_conflict', + ]; + + foreach ([ + 'ISO import parent operation mismatch' => 'parent_operation', + 'ISO import content mismatch' => 'content', + 'ISO active job cross-user binding' => 'user', + ] as $description => $mutation) { + $parentId = $insertParent('user_iso_import'); + $insertResolvedChild( + $parentId, + 'applied', + 'user_iso_import_replica' + ); + $resourceId = $insertProjectionForParent($parentId); + if ($mutation === 'parent_operation') { + Capsule::table('cloud_user_isos')->where('id', $resourceId) + ->update([ + 'import_operation_id' => md5( + 'wrong-import-parent:' . $parentId + ), + ]); + } elseif ($mutation === 'content') { + Capsule::table('cloud_user_iso_replicas') + ->where('user_iso_id', $resourceId)->update([ + 'size_bytes' => 1, + 'sha256' => str_repeat('0', 64), + ]); + } else { + Capsule::table('cloud_user_isos')->where('id', $resourceId) + ->update(['user_id' => 2]); + } + $makeLegacyEligible($parentId); + $projectionConflictFixtures[$parentId] = [ + 'description' => $description, + 'code' => in_array( + $mutation, + ['parent_operation', 'user'], + true + ) + ? 'recovery_operation_identity_conflict' + : 'recovery_instance_state_conflict', + ]; + } + + $isoDeleteContentParent = $insertParent('user_iso_delete'); + $insertResolvedChild( + $isoDeleteContentParent, + 'not_applied', + 'user_iso_delete_replica' + ); + $isoDeleteContentResource = $insertProjectionForParent( + $isoDeleteContentParent + ); + Capsule::table('cloud_user_iso_replicas') + ->where('user_iso_id', $isoDeleteContentResource)->update([ + 'size_bytes' => 1, + 'sha256' => str_repeat('0', 64), + ]); + $makeLegacyEligible($isoDeleteContentParent); + $projectionConflictFixtures[$isoDeleteContentParent] = [ + 'description' => 'ISO delete not-applied content mismatch', + 'code' => 'recovery_instance_state_conflict', + ]; + + foreach ([ + 'template duplicate main binding' => 'template_import', + 'ISO duplicate main binding' => 'user_iso_import', + ] as $description => $parentKind) { + $childKind = $parentKind === 'template_import' + ? 'template_import_replica' : 'user_iso_import_replica'; + $parentId = $insertParent($parentKind); + $insertResolvedChild($parentId, 'applied', $childKind); + $resourceId = $insertProjectionForParent($parentId); + if ($parentKind === 'template_import') { + $duplicate = (array) Capsule::table('cloud_templates') + ->where('id', $resourceId)->first(); + $duplicate['id'] = $resourceId . '-duplicate'; + $duplicate['state'] = 'error'; + Capsule::table('cloud_templates')->insert($duplicate); + } else { + $duplicate = (array) Capsule::table('cloud_user_isos') + ->where('id', $resourceId)->first(); + $duplicate['id'] = md5('duplicate-main:' . $parentId); + $duplicate['state'] = 'retired'; + Capsule::table('cloud_user_isos')->insert($duplicate); + } + $makeLegacyEligible($parentId); + $projectionConflictFixtures[$parentId] = [ + 'description' => $description, + 'code' => 'recovery_aggregate_state_conflict', + ]; + } + + foreach ([ + 'template mixed effects forged all-success' => [ + 'parent' => 'template_import', + 'child' => 'template_import_replica', + ], + 'ISO delete mixed effects forged all-success' => [ + 'parent' => 'user_iso_delete', + 'child' => 'user_iso_delete_replica', + ], + ] as $description => $kinds) { + $parentId = $insertParent($kinds['parent']); + $insertResolvedChild($parentId, 'applied', $kinds['child']); + $insertResolvedChild($parentId, 'not_applied', $kinds['child']); + $resourceId = $insertProjectionForParent($parentId); + if ($kinds['parent'] === 'template_import') { + Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId)->update([ + 'state' => 'active', + 'image_bytes' => 4096, + ]); + } else { + Capsule::table('cloud_user_iso_replicas') + ->where('user_iso_id', $resourceId)->update([ + 'state' => 'delete_succeeded', + ]); + } + $makeLegacyEligible($parentId); + $projectionConflictFixtures[$parentId] = [ + 'description' => $description, + 'code' => 'recovery_instance_state_conflict', + ]; + } + foreach ($projectionConflictFixtures as $parentId => $expectation) { + $assert($automatic->tick(), + 'The projection conflict was not inspected: ' + . $expectation['description']); + $parent = CloudJob::findOrFail($parentId); + $assert((string) $parent->effect_resolution === 'unknown' + && (bool) $parent->finalization_incident + && (string) $parent->finalization_error_code + === $expectation['code'] + && (int) $parent->available_at >= time() + 290, + 'The projection conflict escaped its recovery fence: ' + . $expectation['description']); + } + $assert(CloudAgentSettingsService::$requests === 0, + 'Aggregate projection recovery replayed an Agent mutation.'); + + // Published parents with no pre-existing incident are still audited while + // they remain the catalog's current active_job_id. Damage introduced + // after the original settlement must become a sticky local incident; the + // immutable parent/child audit is not rewritten and Agent is never called. + foreach ([ + 'mapping' => 'recovery_operation_identity_conflict', + 'content' => 'recovery_instance_state_conflict', + 'state' => 'recovery_instance_state_conflict', + ] as $mutation => $expectedCode) { + $parentId = $insertParent('template_import'); + $childId = $insertResolvedChild( + $parentId, + 'applied', + 'template_import_replica' + ); + $resourceId = $insertProjectionForParent($parentId); + CloudJobService::reconcileAggregateParentEffectLocked( + CloudJob::findOrFail($childId), + null + ); + $publishedAudit = $immutableParentAudit( + CloudJob::findOrFail($parentId) + ); + $damage = match ($mutation) { + 'mapping' => [ + 'operation_id' => md5('published-wrong-op:' . $parentId), + ], + 'content' => [ + 'image_bytes' => 1, + 'sha256' => str_repeat('0', 64), + ], + 'state' => ['state' => 'stale'], + }; + Capsule::table('cloud_template_replicas') + ->where('template_id', $resourceId)->update($damage); + Capsule::table('cloud_jobs')->where('id', '<>', $parentId)->update([ + 'available_at' => time() + 3600, + 'lease_until' => time() + 3600, + ]); + Capsule::table('cloud_jobs')->where('id', $parentId)->update([ + 'available_at' => 0, + 'lease_until' => 0, + ]); + $beforePublishedAuditRequests = CloudAgentSettingsService::$requests; + $assert($automatic->tick(), + 'A current published projection was not audited: ' . $mutation); + $damaged = CloudJob::findOrFail($parentId); + $assert($immutableParentAudit($damaged) === $publishedAudit + && (string) $damaged->effect_resolution === 'applied' + && (bool) $damaged->finalization_incident + && (string) $damaged->finalization_error_code === $expectedCode + && (int) $damaged->available_at >= time() + 290 + && CloudAgentSettingsService::$requests + === $beforePublishedAuditRequests, + 'Published projection damage rewrote audit, disappeared, or contacted Agent: ' + . $mutation); + } + + // A resolved child in a nonterminal phase is a PHP-ledger contradiction, + // not ordinary child convergence. It stays in the same 300-second local + // loop with the concrete aggregate-state code. + $phaseConflictParentId = $insertParent('template_import'); + $phaseConflictChildId = $insertResolvedChild( + $phaseConflictParentId, + 'applied', + 'template_import_replica' + ); + $insertProjectionForParent($phaseConflictParentId); + CloudJobService::reconcileAggregateParentEffectLocked( + CloudJob::findOrFail($phaseConflictChildId), + null + ); + Capsule::table('cloud_jobs')->where('id', $phaseConflictChildId)->update([ + 'phase' => 'awaiting_receipt', + 'outcome' => null, + 'status' => 'running', + 'terminal_at' => null, + ]); + Capsule::table('cloud_jobs')->where( + 'id', + '<>', + $phaseConflictParentId + )->update([ + 'available_at' => time() + 3600, + 'lease_until' => time() + 3600, + ]); + Capsule::table('cloud_jobs')->where('id', $phaseConflictParentId)->update([ + 'available_at' => 0, + 'lease_until' => 0, + ]); + $phaseBefore = CloudJobService::recoveryPresentation( + CloudJob::findOrFail($phaseConflictParentId), + true + ); + $beforePhaseRequests = CloudAgentSettingsService::$requests; + $assert(($phaseBefore['code'] ?? null) + === 'recovery_aggregate_state_conflict' + && $automatic->tick(), + 'A nonterminal child with a final effect was not retained locally.'); + $phaseConflict = CloudJob::findOrFail($phaseConflictParentId); + $assert((bool) $phaseConflict->finalization_incident + && (string) $phaseConflict->finalization_error_code + === 'recovery_aggregate_state_conflict' + && (int) $phaseConflict->available_at >= time() + 290 + && CloudAgentSettingsService::$requests === $beforePhaseRequests, + 'A nonterminal/final child lost its concrete conflict or contacted Agent.'); + + // Ordinary leaf recovery has priority over healthy periodic catalog audit, + // and a successful audit advances available_at so it cannot hot-loop. + $healthyParentId = $insertParent('template_import'); + $healthyChildId = $insertResolvedChild( + $healthyParentId, + 'applied', + 'template_import_replica' + ); + $insertProjectionForParent($healthyParentId); + CloudJobService::reconcileAggregateParentEffectLocked( + CloudJob::findOrFail($healthyChildId), + null + ); + $priorityLeafId = $insertResolvedChild( + 0, + 'applied', + 'template_import_replica' + ); + Capsule::table('cloud_jobs')->where('id', $priorityLeafId)->update([ + 'dispatch_attempts' => 0, + 'dispatched_at' => null, + 'phase' => 'terminal', + 'outcome' => 'failed', + 'status' => 'failed', + 'effect_may_have_applied' => 1, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'unknown', + 'finalization_incident' => 0, + 'finalization_error_code' => null, + ]); + Capsule::table('cloud_jobs')->update([ + 'available_at' => time() + 3600, + 'lease_until' => time() + 3600, + ]); + Capsule::table('cloud_jobs')->whereIn('id', [ + $healthyParentId, + $priorityLeafId, + ])->update(['available_at' => 0, 'lease_until' => 0]); + $assert($automatic->tick(), + 'The ordinary invalid leaf was not preferred over healthy catalog audit.'); + $priorityLeaf = CloudJob::findOrFail($priorityLeafId); + $healthyBeforeAudit = CloudJob::findOrFail($healthyParentId); + $assert((string) $priorityLeaf->finalization_error_code + === 'recovery_instance_state_conflict' + && !(bool) $healthyBeforeAudit->finalization_incident + && (int) $healthyBeforeAudit->available_at === 0, + 'Healthy aggregate audit starved an ordinary leaf recovery claim.'); + $assert($automatic->tick(), + 'The healthy current aggregate was not periodically audited.'); + $healthyAfterAudit = CloudJob::findOrFail($healthyParentId); + $assert(!(bool) $healthyAfterAudit->finalization_incident + && (int) $healthyAfterAudit->available_at >= time() + 290, + 'A healthy published aggregate audit hot-looped or created an incident.'); + + echo "Cloud aggregate recovery convergence tests passed.\n"; +} diff --git a/web/tests/CloudAutomaticOperationRecoveryServiceTest.php b/web/tests/CloudAutomaticOperationRecoveryServiceTest.php index bd482f93..51510294 100644 --- a/web/tests/CloudAutomaticOperationRecoveryServiceTest.php +++ b/web/tests/CloudAutomaticOperationRecoveryServiceTest.php @@ -83,9 +83,13 @@ namespace { use App\Services\Cloud\CloudAgentError; use App\Services\Cloud\CloudAgentSettingsService; use App\Services\Cloud\CloudAutomaticOperationRecoveryService; + use App\Services\Cloud\CloudError; use App\Services\Cloud\CloudJobService; use App\Services\Cloud\CloudOperationCompletionService; + use App\Services\Cloud\CloudOperationRecoveryIdentity; use App\Services\Cloud\CloudOperationRecoveryService; + use App\Services\Cloud\CloudRecoveryInstanceStateConflict; + use App\Services\Cloud\CloudRecoveryOperationIdentityConflict; use App\Services\Cloud\CloudSecrets; use App\Services\Cloud\CloudWorkerService; use Illuminate\Database\Capsule\Manager as Capsule; @@ -201,6 +205,58 @@ namespace { $table->integer('applied_at')->nullable(); $table->unique(['host_id', 'operation_id']); }); + $schema->create('cloud_instance_snapshots', + static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('instance_id'); + $table->string('state'); + $table->string('last_operation_id')->default(''); + $table->integer('deleted_at')->nullable(); + $table->integer('updated_at'); + }); + $schema->create('cloud_templates', + static function (Blueprint $table): void { + $table->string('id')->primary(); + $table->integer('active_job_id')->nullable(); + $table->string('state')->default('active'); + }); + $schema->create('cloud_user_isos', + static function (Blueprint $table): void { + $table->string('id')->primary(); + $table->integer('active_job_id')->nullable(); + $table->string('state')->default('active'); + }); + $schema->create('cloud_template_replicas', + static function (Blueprint $table): void { + $table->integer('host_id'); + $table->string('template_id'); + $table->integer('revision')->default(0); + $table->string('generation_token')->default(''); + $table->string('state')->default('pending'); + $table->integer('image_bytes')->default(0); + $table->string('sha256')->default(''); + $table->string('operation_id')->default(''); + $table->integer('job_id')->nullable(); + $table->string('error_code')->default(''); + $table->integer('created_at')->default(0); + $table->integer('updated_at')->default(0); + $table->primary(['host_id', 'template_id']); + }); + $schema->create('cloud_user_iso_replicas', + static function (Blueprint $table): void { + $table->integer('host_id'); + $table->string('user_iso_id'); + $table->integer('user_id'); + $table->string('state')->default('pending'); + $table->integer('size_bytes')->default(0); + $table->string('sha256')->default(''); + $table->string('operation_id')->default(''); + $table->integer('job_id')->nullable(); + $table->string('error_code')->default(''); + $table->integer('created_at')->default(0); + $table->integer('updated_at')->default(0); + $table->primary(['host_id', 'user_iso_id']); + }); Capsule::table('user')->insert([ 'id' => 1, 'enable' => 1, 'is_admin' => 0, ]); @@ -433,7 +489,10 @@ namespace { ?? $journalStatus === 'failed') ? 'active' : 'not_required'), 'abort_job' => ['available' => false], 'cleanup' => ['available' => false], - ]; + ] + CloudOperationRecoveryIdentity::expected( + CloudJob::where('operation_id', $operationId)->firstOrFail(), + $applied + ); if ($projection !== null) { $value['effect_projection'] = $projection; } @@ -466,23 +525,199 @@ namespace { $client = new AutomaticRecoveryTestAgentClient(); CloudAgentSettingsService::$client = $client; - // The recovery worker is a kind-specific finalizer, not a generic way to - // clear unknown effects. A fully eligible non-settings task must remain - // byte-for-byte untouched and must not contact the Agent. - [$nonSettingsId] = $insertSettingsJob( + // An immutable received receipt must outrank a legacy aggregate whose + // child can remain active indefinitely. This prevents the aggregate sweep + // from starving both PHP convergence and the Agent outbox ACK. + [$receiptPriorityId, $receiptPriorityUuid] = $insertSettingsJob( + str_repeat('0a', 16), + ['hostname' => 'receipt-priority.example'] + ); + $receiptPriorityJob = CloudJob::findOrFail($receiptPriorityId); + $receiptPriorityIdentity = CloudOperationRecoveryIdentity::expected( + $receiptPriorityJob, + true + ); + $receiptPriorityResult = [ + 'uuid' => $receiptPriorityUuid, + 'hostname' => 'receipt-priority.example', + 'settings_changed' => true, + ]; + $receiptPriorityWire = [ + 'event_id' => 'automatic-priority-receipt', + 'host_id' => 7, + 'operation_id' => (string) $receiptPriorityJob->operation_id, + 'action' => $receiptPriorityIdentity['action'], + 'resource_id' => $receiptPriorityIdentity['resource_id'], + 'request_fingerprint' => + $receiptPriorityIdentity['request_fingerprint'], + 'status' => 'succeeded', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'error_code' => '', + 'result' => $receiptPriorityResult, + ]; + Capsule::table('cloud_agent_completion_events')->insert([ + 'event_id' => $receiptPriorityWire['event_id'], + 'host_id' => 7, + 'operation_id' => $receiptPriorityWire['operation_id'], + 'payload_sha256' => hash('sha256', json_encode( + $receiptPriorityWire, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + | JSON_UNESCAPED_UNICODE + )), + 'outcome' => 'succeeded', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'error_code' => '', + 'result_json' => json_encode([ + 'schema' => 'virt_cloud_completion_event', + 'version' => 1, + 'identity' => $receiptPriorityIdentity, + 'result' => $receiptPriorityResult, + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + | JSON_UNESCAPED_UNICODE), + 'disposition' => 'received', + 'received_at' => $now, + 'applied_at' => null, + ]); + [$legacyParentId] = $insertSettingsJob( + str_repeat('0b', 16), + ['hostname' => 'legacy-parent.example'] + ); + Capsule::table('cloud_jobs')->where('id', $legacyParentId)->update([ + 'kind' => 'template_import', + 'execution_mode' => 'aggregate', + 'host_id' => null, + 'instance_id' => null, + 'dispatch_attempts' => 0, + 'dispatched_at' => null, + 'available_at' => 0, + 'lease_until' => 0, + ]); + [$legacyChildId] = $insertSettingsJob( + str_repeat('0c', 16), + ['hostname' => 'legacy-child.example'] + ); + Capsule::table('cloud_jobs')->where('id', $legacyChildId)->update([ + 'parent_job_id' => $legacyParentId, + 'kind' => 'template_import_replica', + 'phase' => 'awaiting_receipt', + 'outcome' => null, + 'status' => 'running', + 'effect_may_have_applied' => null, + 'safe_to_resubmit' => null, + 'effect_resolution' => 'not_applicable', + 'terminal_at' => null, + ]); + $beforePriorityRequests = count($client->requests); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'An exact completion receipt was not claimed ahead of legacy sweep.'); + $priorityEvent = Capsule::table('cloud_agent_completion_events') + ->where('event_id', 'automatic-priority-receipt')->first(); + $assert((string) CloudJob::findOrFail($receiptPriorityId) + ->effect_resolution === 'applied' + && (string) $priorityEvent->disposition === 'applied' + && (int) CloudJob::findOrFail($legacyParentId)->available_at === 0 + && count($client->requests) === $beforePriorityRequests, + 'A waiting aggregate starved or contaminated an exact receipt.'); + Capsule::table('cloud_jobs')->whereIn( + 'id', + [$legacyParentId, $legacyChildId] + )->delete(); + Capsule::table('cloud_instances')->whereIn( + 'id', + [$legacyParentId, $legacyChildId] + )->delete(); + + // Every explicitly registered Agent leaf remains eligible. Inconclusive + // evidence keeps the exact operation fenced and schedules another check. + [$nonSettingsId, $nonSettingsUuid] = $insertSettingsJob( str_repeat('0f', 16), ['hostname' => 'not-a-settings-recovery.example'] ); Capsule::table('cloud_jobs')->where('id', $nonSettingsId)->update([ 'kind' => 'network_change', + 'sealed_payload' => CloudSecrets::encrypt([ + 'method' => 'POST', + 'request_target' => '/v1/vms/' . $nonSettingsUuid . '/network', + 'body' => [ + 'operation_id' => str_repeat('0f', 16), + 'network' => 'bridge:br0', + 'public_pool_key' => str_repeat('a', 32), + 'public_pool_cidr' => '203.0.113.0/24', + 'public_ip_cidr' => '203.0.113.10/24', + 'gateway' => '203.0.113.1', + 'dns_servers' => ['1.1.1.1'], + 'confirm_restart' => true, + ], + 'owner_id' => 1, + 'can_manage' => false, + ], 'job-payload'), ]); - $nonSettingsBefore = CloudJob::find($nonSettingsId)->getAttributes(); $beforeNonSettingsRequests = count($client->requests); - $assert(!(new CloudAutomaticOperationRecoveryService())->tick() - && CloudJob::find($nonSettingsId)->getAttributes() - === $nonSettingsBefore - && count($client->requests) === $beforeNonSettingsRequests, - 'The settings recovery worker claimed a different operation kind.'); + $client->responses[] = $inspection( + str_repeat('0f', 16), + 'failed', + 'inconclusive' + ); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'The recovery worker did not claim a registered non-settings kind.'); + $nonSettings = CloudJob::find($nonSettingsId); + $assert((string) $nonSettings->effect_resolution === 'unknown' + && (string) $nonSettings->finalization_error_code + === 'recovery_evidence_inconclusive' + && (int) $nonSettings->available_at >= time() + 290 + && count($client->requests) === $beforeNonSettingsRequests + 1, + 'Inconclusive non-settings evidence did not stay recoverable.'); + + // A poisoned Agent completion outbox is never evidence for either effect + // verdict. Even a syntactically complete not-applied projection remains + // fenced and the reviewed cause is visible without exposing raw data. + [$quarantinedId] = $insertSettingsJob( + str_repeat('0e', 16), + ['hostname' => 'quarantined-receipt.example'] + ); + $quarantinedInspection = $inspection( + str_repeat('0e', 16), + 'failed', + 'not_applied', + null, + true, + 'settings_not_committed' + ); + $quarantinedInspection['completion_delivery_state'] = 'quarantined'; + $quarantinedInspection['completion_delivery_error_code'] = + 'completion_identity_mismatch'; + $client->responses[] = $quarantinedInspection; + $beforeQuarantinedRequests = count($client->requests); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'The recovery worker did not inspect a quarantined completion.'); + $quarantined = CloudJob::findOrFail($quarantinedId); + $quarantinedUser = CloudJobService::recoveryPresentation( + $quarantined, + false + ); + $quarantinedAdmin = CloudJobService::recoveryPresentation( + $quarantined, + true + ); + $assert((string) $quarantined->effect_resolution === 'unknown' + && (string) $quarantined->finalization_error_code + === 'recovery_completion_identity_mismatch' + && (int) $quarantined->available_at >= time() + 290 + && count($client->requests) === $beforeQuarantinedRequests + 1 + && ($quarantinedAdmin['code'] ?? null) + === 'recovery_completion_identity_mismatch' + && str_contains( + (string) ($quarantinedAdmin['message'] ?? ''), + '身份与原操作记录不匹配' + ) + && str_contains( + (string) ($quarantinedUser['message'] ?? ''), + '身份与原操作记录不匹配' + ) + && !array_key_exists('code', $quarantinedUser), + 'A quarantined completion was trusted or its safe cause was hidden.'); // A journal success is immutable exact evidence and has no active fence. [$succeededId, $succeededUuid] = $insertSettingsJob( @@ -518,6 +753,7 @@ namespace { && count($client->requests) === $beforeDispatchRequests, 'Automatic recovery ran before an ordinary dispatchable task.'); $queuedBehindRecovery = $insertDispatchableJob(str_repeat('b', 32)); + $beforeSucceededRecovery = count($client->requests); $assert((new CloudAutomaticOperationRecoveryService())->tick(), 'The dedicated recovery service did not claim a recoverable task.'); $assert((string) CloudJob::find($queuedBehindRecovery)->phase @@ -546,13 +782,16 @@ namespace { && !CloudJobService::blockingQueryForInstance( $succeededId )->exists() - && count($client->requests) === 1 - && str_ends_with($client->requests[0]['target'], '/inspect'), + && count($client->requests) === $beforeSucceededRecovery + 1 + && str_ends_with( + $client->requests[array_key_last($client->requests)]['target'], + '/inspect' + ), 'Journal-success recovery did not converge without a fence write.'); - // Receipt proof is validated before comparing it with an existing - // automatic prepared marker. Otherwise a malformed success receipt would - // be misclassified as a conflict with sound automatic evidence. + // A malformed or contradictory receipt is isolated from an existing + // prepared intent. The job itself remains scheduled for a fresh Agent + // inspection instead of treating the incident as a permanent stop. $invalidProofRequests = count($client->requests); $invalidProofCases = [ [ @@ -597,9 +836,13 @@ namespace { if (array_key_exists('hostname', $case['body'])) { $preparedResult['hostname'] = $case['body']['hostname']; } + $operationIdentity = CloudOperationRecoveryIdentity::expected( + CloudJob::findOrFail($invalidProofId), + true + ); CloudOperationRecoveryService::prepareApplied( $invalidProofId, - [ + $operationIdentity + [ 'operation_id' => $case['operation_id'], 'status' => 'succeeded', 'effect_may_have_applied' => false, @@ -621,6 +864,10 @@ namespace { 'id' => $eventId, 'agent_id' => '7', 'operation_id' => $case['operation_id'], + 'action' => $operationIdentity['action'], + 'resource_id' => $operationIdentity['resource_id'], + 'request_fingerprint' => + $operationIdentity['request_fingerprint'], 'status' => 'succeeded', 'effect_may_have_applied' => false, 'safe_to_resubmit' => false, @@ -639,18 +886,109 @@ namespace { && (string) $invalidProofJob->effect_resolution_reason === $preparedMarker && (bool) $invalidProofJob->finalization_incident - && (string) $invalidProofJob->finalization_error_code - === 'recovery_receipt_invalid' + && in_array( + (string) $invalidProofJob->finalization_error_code, + [ + 'recovery_receipt_invalid', + 'recovery_evidence_conflict', + ], + true + ) + && (int) $invalidProofJob->available_at >= time() + 290 && (string) $invalidProofEvent->disposition === 'late' && CloudJobService::blockingQueryForInstance( $invalidProofId )->exists(), 'A success receipt with ' . $case['message'] - . ' was not parked as invalid.'); + . ' was not isolated while leaving inspection retryable.'); } $assert(count($client->requests) === $invalidProofRequests, 'Invalid late receipt proof unexpectedly contacted the Agent.'); + // A well-formed completion for a different immutable Agent request is a + // bad event, not a reason to strand the already-prepared PHP convergence. + // Quarantine it, then let the normal prepared crash-resume path finish. + [$wrongIdentityId, $wrongIdentityUuid] = $insertSettingsJob( + str_repeat('e3', 16), + ['hostname' => 'prepared-identity.example'] + ); + $expectedIdentity = CloudOperationRecoveryIdentity::expected( + CloudJob::findOrFail($wrongIdentityId), + true + ); + CloudOperationRecoveryService::prepareApplied( + $wrongIdentityId, + $expectedIdentity + [ + 'operation_id' => str_repeat('e3', 16), + 'status' => 'succeeded', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'error_code' => '', + 'result' => [ + 'uuid' => $wrongIdentityUuid, + 'hostname' => 'prepared-identity.example', + 'settings_changed' => true, + ], + ], + 'automatic_applied_succeeded_nofence:' . str_repeat('9', 64) + ); + $preparedWrongIdentity = CloudJob::findOrFail($wrongIdentityId); + $preparedWrongIdentityMarker = (string) $preparedWrongIdentity + ->effect_resolution_reason; + $wrongIdentityEventId = 'automatic-wrong-identity'; + $acceptedWrongIdentity = CloudOperationCompletionService::accept([ + 'type' => 'completion', + 'id' => $wrongIdentityEventId, + 'agent_id' => '7', + 'operation_id' => str_repeat('e3', 16), + 'action' => $expectedIdentity['action'], + 'resource_id' => '00000000-0000-4000-8000-000000009999', + 'request_fingerprint' => $expectedIdentity['request_fingerprint'], + 'status' => 'succeeded', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'error_code' => '', + 'result' => [ + 'uuid' => $wrongIdentityUuid, + 'hostname' => 'prepared-identity.example', + 'settings_changed' => true, + ], + ]); + $preparedWrongIdentity = CloudJob::findOrFail($wrongIdentityId); + $wrongIdentityEvent = Capsule::table( + 'cloud_agent_completion_events' + )->where('event_id', $wrongIdentityEventId)->first(); + $assert($acceptedWrongIdentity === [ + 'accepted' => true, + 'disposition' => 'rejected', + ] + && (string) $wrongIdentityEvent->disposition === 'rejected' + && (string) $preparedWrongIdentity->effect_resolution === 'unknown' + && (string) $preparedWrongIdentity->effect_resolution_reason + === $preparedWrongIdentityMarker + && (bool) $preparedWrongIdentity->finalization_incident + && (string) $preparedWrongIdentity->finalization_error_code + === 'recovery_operation_identity_conflict', + 'A definitive wrong-operation receipt was not isolated from prepared recovery.'); + Capsule::table('cloud_jobs')->where('id', $wrongIdentityId)->update([ + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + $beforeWrongIdentityResume = count($client->requests); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'Prepared recovery did not resume after quarantining a wrong receipt.'); + $preparedWrongIdentity = CloudJob::findOrFail($wrongIdentityId); + $wrongIdentityEvent = Capsule::table( + 'cloud_agent_completion_events' + )->where('event_id', $wrongIdentityEventId)->first(); + $assert((string) $preparedWrongIdentity->effect_resolution === 'applied' + && !(bool) $preparedWrongIdentity->finalization_incident + && $preparedWrongIdentity->finalization_error_code === null + && (string) $wrongIdentityEvent->disposition === 'rejected' + && count($client->requests) === $beforeWrongIdentityResume, + 'The quarantined wrong receipt starved or contaminated prepared convergence.'); + // Failed journal + dual settings markers: prepare first, then resolve the // fence. Simulate a lost POST response and prove one GET recovers it. [$lostId, $lostUuid] = $insertSettingsJob( @@ -801,7 +1139,7 @@ namespace { $beforeExternallyResolved ); $assert((string) $externallyResolved->effect_resolution === 'unknown' - && (int) $externallyResolved->available_at >= time() + 590 + && (int) $externallyResolved->available_at >= time() + 290 && CloudJobService::blockingQueryForInstance( $externallyResolvedId )->exists() @@ -812,7 +1150,7 @@ namespace { ), 'An unprepared externally resolved fence bypassed PHP recovery intent.'); - // Partial and inconclusive evidence stay blocked and receive a 10-minute + // Partial and inconclusive evidence stay blocked and receive a five-minute // retry delay. Two tasks also prove each worker tick handles only one. [$partialId] = $insertSettingsJob( str_repeat('4', 32), @@ -837,7 +1175,7 @@ namespace { $partial = CloudJob::find($partialId); $notYetClaimed = CloudJob::find($inconclusiveId); $assert((string) $partial->effect_resolution === 'unknown' - && (int) $partial->available_at >= time() + 590 + && (int) $partial->available_at >= time() + 290 && CloudJobService::blockingQueryForInstance($partialId)->exists() && (int) $notYetClaimed->available_at === 0, 'One worker tick did not stop after one inconclusive recovery.'); @@ -845,7 +1183,7 @@ namespace { 'The inconclusive-evidence task was not inspected.'); $inconclusive = CloudJob::find($inconclusiveId); $assert((string) $inconclusive->effect_resolution === 'unknown' - && (int) $inconclusive->available_at >= time() + 590 + && (int) $inconclusive->available_at >= time() + 290 && CloudJobService::blockingQueryForInstance( $inconclusiveId )->exists(), @@ -901,15 +1239,14 @@ namespace { 'available_at' => time() + 300, ]); - // Automatic read-only recovery has the same durable 12-attempt / six-hour - // safety bound as other reconciliation loops. Once exhausted it must stop - // contacting the Agent while preserving both the blocker and escrow. + // Attempt count is audit metadata only. The same operation remains in the + // recovery queue beyond the former 12-attempt boundary. [$limitedId] = $insertSettingsJob( str_repeat('c', 32), ['hostname' => 'retry-limit.example'] ); $beforeLimitedRequests = count($client->requests); - for ($attempt = 1; $attempt <= 12; $attempt++) { + for ($attempt = 1; $attempt <= 13; $attempt++) { Capsule::table('cloud_jobs')->where('id', $limitedId)->update([ 'available_at' => 0, 'lease_until' => 0, @@ -919,26 +1256,24 @@ namespace { 'offline', 503, 'agent_unavailable', true, 503 ); $assert((new CloudAutomaticOperationRecoveryService())->tick(), - 'A bounded recovery attempt was not claimed.'); + 'A persistent recovery attempt was not claimed.'); } $limited = CloudJob::find($limitedId); $limitedPayloadBefore = (string) $limited->sealed_payload; $limitedRequestCount = count($client->requests); $assert((bool) $limited->finalization_incident && (string) $limited->finalization_error_code - === 'recovery_limit_reached' + === 'recovery_waiting_connection' && preg_match( - '/^automatic_recovery:v1:[1-9][0-9]{0,10}:12:pending$/D', + '/^automatic_recovery:v1:[1-9][0-9]{0,10}:13:pending$/D', (string) $limited->effect_resolution_reason ) === 1 && (string) $limited->effect_resolution === 'unknown' && (string) $limited->sealed_payload === $limitedPayloadBefore && CloudJobService::blockingQueryForInstance($limitedId)->exists() - && $limitedRequestCount - $beforeLimitedRequests === 12, - 'Recovery exhaustion did not stop safely with durable audit state.'); - $assert(!(new CloudAutomaticOperationRecoveryService())->tick() - && count($client->requests) === $limitedRequestCount, - 'An exhausted recovery continued contacting the Agent.'); + && $limitedRequestCount - $beforeLimitedRequests === 13 + && (int) $limited->available_at >= time() + 290, + 'Recovery did not remain queued beyond the former attempt limit.'); // First pass prepares PHP, commits the Agent fence, then loses both the // POST response and its verification GET. A later pass must read that @@ -1029,10 +1364,7 @@ namespace { ), 'Prepared recovery re-inspected/replayed or failed to commit.'); - // The prepared crash-resume stage is independently bounded. If its - // Agent fence read remains unavailable for all 12 attempts, automatic - // network traffic stops while the blocker, escrow and prepared intent - // remain available for a later exact receipt or explicit repair. + // Prepared crash-resume also remains eligible beyond the former limit. [$preparedLimitId] = $insertSettingsJob( str_repeat('e', 32), ['hostname' => 'prepared-limit.example'] @@ -1062,7 +1394,7 @@ namespace { (string) $preparedLimitFirst->effect_resolution_reason ) === 1, 'Preparing did not reset the independent resume budget.'); - for ($attempt = 2; $attempt <= 12; $attempt++) { + for ($attempt = 2; $attempt <= 13; $attempt++) { Capsule::table('cloud_jobs')->where('id', $preparedLimitId)->update([ 'available_at' => 0, 'lease_until' => 0, @@ -1076,32 +1408,211 @@ namespace { 503 ); $assert((new CloudAutomaticOperationRecoveryService())->tick(), - 'A bounded prepared-resume attempt was not claimed.'); + 'A persistent prepared-resume attempt was not claimed.'); } $preparedLimited = CloudJob::find($preparedLimitId); $preparedLimitRequestCount = count($client->requests); $preparedLimitPayload = (string) $preparedLimited->sealed_payload; + $preparedLimitEscrow = CloudSecrets::decrypt( + $preparedLimitPayload, + 'job-payload' + ); + $preparedLimitRequests = array_slice( + $client->requests, + $beforePreparedLimit + ); + $preparedLimitFenceWrite = null; + foreach ($preparedLimitRequests as $request) { + if ($request['method'] === 'POST' + && str_ends_with($request['target'], '/resolve-fence')) { + $preparedLimitFenceWrite = $request; + break; + } + } $assert((bool) $preparedLimited->finalization_incident && (string) $preparedLimited->finalization_error_code - === 'recovery_limit_reached' + === 'recovery_waiting_connection' && preg_match( - '/^automatic_recovery:v1:[1-9][0-9]{0,10}:12:prepared:/D', + '/^automatic_recovery:v1:[1-9][0-9]{0,10}:13:prepared:/D', (string) $preparedLimited->effect_resolution_reason ) === 1 && (string) $preparedLimited->effect_resolution === 'unknown' && CloudJobService::blockingQueryForInstance( $preparedLimitId )->exists() - && count($client->requests) - $beforePreparedLimit === 15, - 'Prepared-resume exhaustion did not stop with durable safety state.'); - $assert(!(new CloudAutomaticOperationRecoveryService())->tick() - && count($client->requests) === $preparedLimitRequestCount - && (string) CloudJob::find($preparedLimitId)->sealed_payload - === $preparedLimitPayload, - 'An exhausted prepared recovery continued contacting the Agent.'); + && count($client->requests) - $beforePreparedLimit === 16 + && is_array($preparedLimitEscrow['_operation_recovery'] ?? null) + && ($preparedLimitEscrow['_operation_recovery']['operation'] + ['operation_id'] ?? null) === str_repeat('e', 32) + && ($preparedLimitEscrow['_operation_recovery']['operation'] + ['status'] ?? null) === 'failed' + && is_array($preparedLimitFenceWrite) + && (int) $preparedLimited->available_at >= time() + 290, + 'Prepared recovery did not remain queued beyond the former limit.'); - // The wall-clock limit is independent of attempt count and is evaluated - // before any network call. + // A fourteenth pass can still finish the original crash-resume protocol. + // The retry marker contains only hashes, so this succeeds only if the + // worker reconstructs the exact failed operation from the encrypted + // _operation_recovery envelope retained across attempts 1 through 13. + Capsule::table('cloud_jobs')->where('id', $preparedLimitId)->update([ + 'available_at' => 0, + 'lease_until' => 0, + 'lease_token' => null, + ]); + $client->responses[] = static fn (): array => + $fenceResponse($preparedLimitFenceWrite, time()); + $beforePreparedLimitResume = count($client->requests); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'Prepared recovery was not claimable after attempt thirteen.'); + $preparedLimitResumeRequests = array_slice( + $client->requests, + $beforePreparedLimitResume + ); + $preparedLimitResolved = CloudJob::find($preparedLimitId); + $preparedLimitFinalPayload = CloudSecrets::decrypt( + (string) $preparedLimitResolved->sealed_payload, + 'job-payload' + ); + $assert((string) $preparedLimitResolved->effect_resolution + === 'not_applied' + && !(bool) $preparedLimitResolved->finalization_incident + && $preparedLimitResolved->finalization_error_code === null + && !array_key_exists( + '_operation_recovery', + $preparedLimitFinalPayload + ) + && !CloudJobService::blockingQueryForInstance( + $preparedLimitId + )->exists() + && count($preparedLimitResumeRequests) === 1 + && $preparedLimitResumeRequests[0]['method'] === 'GET' + && str_ends_with( + $preparedLimitResumeRequests[0]['target'], + '/fence-resolution' + ), + 'Attempt thirteen stranded encrypted prepared recovery state.'); + + // A timed-out graceful delete may later be proven not applied because the + // Agent requires an explicitly authorized force generation. Recovery must + // preserve that exact business error: it is the immutable authorization + // anchor for enqueueForceDelete(), not an instance-state contradiction. + [$forceRequiredId, $forceRequiredUuid] = $insertSettingsJob( + str_repeat('ab', 16), + ['hostname' => 'delete-force-required.example'] + ); + Capsule::table('cloud_jobs')->where('id', $forceRequiredId)->update([ + 'kind' => 'delete', + 'sealed_payload' => CloudSecrets::encrypt([ + 'method' => 'DELETE', + 'request_target' => '/v1/vms/' . $forceRequiredUuid, + 'body' => ['remove_managed_disks' => true], + 'owner_id' => 1, + 'can_manage' => false, + ], 'job-payload'), + ]); + $beforeForceRequiredRecovery = count($client->requests); + $client->responses[] = $inspection( + str_repeat('ab', 16), + 'failed', + 'not_applied', + null, + false, + 'force_required', + 'not_required' + ); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'The force-required delete recovery was not claimed.'); + $forceRequired = CloudJob::find($forceRequiredId); + $forceRequiredInstance = \App\Models\CloudInstance::find( + $forceRequiredId + ); + $assert((string) $forceRequired->effect_resolution === 'not_applied' + && (string) $forceRequired->error_code === 'force_required' + && (string) $forceRequired->phase === 'terminal' + && (string) $forceRequired->outcome === 'failed' + && $forceRequired->dispatched_at !== null, + 'Force-required inspection did not converge into its authorization anchor: ' + . json_encode($forceRequired->toArray(), JSON_THROW_ON_ERROR)); + $beforeForceJobCount = CloudJob::count(); + Capsule::table('cloud_jobs')->where('id', $forceRequiredId)->update([ + 'finalization_incident' => 1, + 'finalization_error_code' => 'recovery_ledger_conflict', + ]); + try { + CloudJobService::enqueueForceDelete( + $forceRequired->fresh(), + [ + 'user_id' => 99, + 'is_admin' => true, + 'is_super_admin' => true, + 'can_manage' => true, + ] + ); + throw new RuntimeException( + 'A sticky recovery incident created a force-delete generation.' + ); + } catch (CloudError $error) { + $assert($error->httpStatus === 409 + && CloudJob::count() === $beforeForceJobCount, + 'Sticky force-delete rejection changed the immutable job ledger.'); + } + Capsule::table('cloud_jobs')->where('id', $forceRequiredId)->update([ + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'receipt_deadline_at' => null, + ]); + try { + CloudJobService::enqueueForceDelete( + $forceRequired->fresh(), + [ + 'user_id' => 99, + 'is_admin' => true, + 'is_super_admin' => true, + 'can_manage' => true, + ] + ); + throw new RuntimeException( + 'A damaged Agent envelope created a force-delete generation.' + ); + } catch (CloudError $error) { + $assert($error->httpStatus === 409 + && CloudJob::count() === $beforeForceJobCount, + 'Envelope force-delete rejection changed the immutable job ledger.'); + } + Capsule::table('cloud_jobs')->where('id', $forceRequiredId)->update([ + 'receipt_deadline_at' => $now + 120, + ]); + $forceRequired->refresh(); + $forceDelete = CloudJobService::enqueueForceDelete( + $forceRequired, + [ + 'user_id' => 99, + 'is_admin' => true, + 'is_super_admin' => true, + 'can_manage' => true, + ] + ); + $nextId = max($nextId, (int) $forceDelete->id + 1); + $forceDeletePayload = CloudSecrets::decrypt( + (string) $forceDelete->sealed_payload, + 'job-payload' + ); + $assert((string) $forceRequired->effect_resolution === 'not_applied' + && (string) $forceRequired->error_code === 'force_required' + && (string) $forceRequiredInstance->status === 'active' + && !(bool) $forceRequired->finalization_incident + && (string) $forceDelete->kind === 'delete_force' + && ($forceDeletePayload['prior_job_id'] ?? null) + === $forceRequiredId + && ($forceDeletePayload['prior_operation_id'] ?? null) + === str_repeat('ab', 16) + && count($client->requests) === $beforeForceRequiredRecovery + 1 + && $client->requests[array_key_last($client->requests)]['method'] + === 'GET', + 'Recovered force-required evidence did not preserve the separately authorized force-delete path.'); + + // Age is also audit metadata only; a six-hour-old operation is still + // inspected with the original operation ID. [$agedId] = $insertSettingsJob( str_repeat('f', 32), ['hostname' => 'age-limit.example'] @@ -1111,16 +1622,1274 @@ namespace { . (time() - 21601) . ':1:pending', ]); $beforeAged = count($client->requests); - $assert(!(new CloudAutomaticOperationRecoveryService())->tick(), - 'An aged recovery was unexpectedly claimed for network work.'); + $client->responses[] = new CloudAgentError( + 'offline', 503, 'agent_unavailable', true, 503 + ); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'A six-hour-old recovery was not claimed.'); $aged = CloudJob::find($agedId); $assert((bool) $aged->finalization_incident && (string) $aged->finalization_error_code - === 'recovery_limit_reached' + === 'recovery_waiting_connection' + && preg_match( + '/^automatic_recovery:v1:[1-9][0-9]{0,10}:2:pending$/D', + (string) $aged->effect_resolution_reason + ) === 1 && (string) $aged->effect_resolution === 'unknown' && CloudJobService::blockingQueryForInstance($agedId)->exists() - && count($client->requests) === $beforeAged, - 'The wall-clock recovery bound contacted Agent or released safety.'); + && count($client->requests) === $beforeAged + 1, + 'An aged recovery stopped retrying or released safety.'); + + // A corrupt dispatch ledger remains a recovery candidate forever, but it + // cannot authorize either an Agent read or consumption of even an exact + // received completion. The only safe automatic action is to record the + // concrete incident and back off until an operator repairs the 0/1 fence. + [$invalidDispatchId, $invalidDispatchUuid] = $insertSettingsJob( + str_repeat('dc', 16), + ['hostname' => 'invalid-dispatch-ledger.example'] + ); + $invalidDispatchEventId = 'automatic-invalid-dispatch-ledger'; + Capsule::table('cloud_jobs')->where('id', $invalidDispatchId)->update([ + 'dispatch_attempts' => 2, + // Simulate a historical fail-open release which mistook the corrupt + // non-zero counter for a fully settled successful Agent mutation. + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'error_code' => null, + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'completion_event_id' => $invalidDispatchEventId, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + 'finalization_incident' => 0, + 'finalization_error_code' => null, + ]); + $invalidDispatchJob = CloudJob::findOrFail($invalidDispatchId); + $invalidDispatchEnvelope = (string) $invalidDispatchJob->sealed_payload; + $invalidDispatchTerminalAt = (int) $invalidDispatchJob->terminal_at; + $invalidDispatchResultJson = (string) $invalidDispatchJob->result_json; + $invalidDispatchIdentity = CloudOperationRecoveryIdentity::expected( + $invalidDispatchJob, + true + ); + $invalidDispatchResult = [ + 'uuid' => $invalidDispatchUuid, + 'hostname' => 'invalid-dispatch-ledger.example', + 'settings_changed' => true, + ]; + $invalidDispatchWire = [ + 'event_id' => $invalidDispatchEventId, + 'host_id' => 7, + 'operation_id' => (string) $invalidDispatchJob->operation_id, + 'action' => $invalidDispatchIdentity['action'], + 'resource_id' => $invalidDispatchIdentity['resource_id'], + 'request_fingerprint' => + $invalidDispatchIdentity['request_fingerprint'], + 'status' => 'succeeded', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'error_code' => '', + 'result' => $invalidDispatchResult, + ]; + Capsule::table('cloud_agent_completion_events')->insert([ + 'event_id' => $invalidDispatchWire['event_id'], + 'host_id' => 7, + 'operation_id' => $invalidDispatchWire['operation_id'], + 'payload_sha256' => hash('sha256', json_encode( + $invalidDispatchWire, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + | JSON_UNESCAPED_UNICODE + )), + 'outcome' => 'succeeded', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'error_code' => '', + 'result_json' => json_encode([ + 'schema' => 'virt_cloud_completion_event', + 'version' => 1, + 'identity' => $invalidDispatchIdentity, + 'result' => $invalidDispatchResult, + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + | JSON_UNESCAPED_UNICODE), + 'disposition' => 'received', + 'received_at' => time(), + 'applied_at' => null, + ]); + $beforeInvalidDispatchRequests = count($client->requests); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'An invalid dispatch ledger permanently left the recovery queue.'); + $invalidDispatchJob = CloudJob::findOrFail($invalidDispatchId); + $invalidDispatchEvent = Capsule::table( + 'cloud_agent_completion_events' + )->where( + 'event_id', + $invalidDispatchWire['event_id'] + )->first(); + $assert((string) $invalidDispatchJob->phase === 'terminal' + && (string) $invalidDispatchJob->outcome === 'succeeded' + && (string) $invalidDispatchJob->status === 'succeeded' + && $invalidDispatchJob->error_code === null + && !(bool) $invalidDispatchJob->effect_may_have_applied + && (string) $invalidDispatchJob->effect_resolution === 'applied' + && !(bool) $invalidDispatchJob->safe_to_resubmit + && (int) $invalidDispatchJob->terminal_at + === $invalidDispatchTerminalAt + && (string) $invalidDispatchJob->result_json + === $invalidDispatchResultJson + && (string) $invalidDispatchJob->completion_event_id + === $invalidDispatchEventId + && (bool) $invalidDispatchJob->finalization_incident + && (string) $invalidDispatchJob->finalization_error_code + === 'recovery_dispatch_ledger_conflict' + && (string) $invalidDispatchJob->sealed_payload + === $invalidDispatchEnvelope + && $invalidDispatchJob->lease_token === null + && (int) $invalidDispatchJob->lease_until === 0 + && (int) $invalidDispatchJob->available_at >= time() + 290 + && (string) $invalidDispatchEvent->disposition === 'received' + && $invalidDispatchEvent->applied_at === null + && count($client->requests) === $beforeInvalidDispatchRequests, + 'Invalid dispatch recovery contacted Agent, consumed evidence, or released its fence.'); + + // Once the durable ledger is repaired to the only valid dispatched state, + // the same unconsumed receipt must resume convergence without waiting for + // an Agent retransmission or issuing any Agent request. + Capsule::table('cloud_jobs')->where('id', $invalidDispatchId)->update([ + 'dispatch_attempts' => 1, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'A repaired dispatch ledger could not resume its queued receipt.'); + $repairedDispatchJob = CloudJob::findOrFail($invalidDispatchId); + $repairedDispatchEvent = Capsule::table( + 'cloud_agent_completion_events' + )->where( + 'event_id', + $invalidDispatchWire['event_id'] + )->first(); + $assert((string) $repairedDispatchJob->phase === 'terminal' + && (string) $repairedDispatchJob->outcome === 'succeeded' + && (string) $repairedDispatchJob->status === 'succeeded' + && (int) $repairedDispatchJob->terminal_at + === $invalidDispatchTerminalAt + && $repairedDispatchJob->error_code === null + && (string) $repairedDispatchJob->result_json + === $invalidDispatchResultJson + && (string) $repairedDispatchJob->effect_resolution === 'applied' + && !(bool) $repairedDispatchJob->finalization_incident + && $repairedDispatchJob->finalization_error_code === null + && (string) $repairedDispatchEvent->disposition === 'applied' + && (int) $repairedDispatchEvent->applied_at > 0 + && count($client->requests) === $beforeInvalidDispatchRequests, + 'Repairing the dispatch ledger did not resume the exact stored completion.'); + + // An exact immutable receipt cannot authorize convergence when any other + // field in the dispatched Agent envelope is damaged. Claiming must keep + // the receipt untouched and record a local-only state conflict without an + // Agent request. + [$corruptReceiptEnvelopeId, $corruptReceiptEnvelopeUuid] = + $insertSettingsJob( + str_repeat('b1', 16), + ['hostname' => 'corrupt-receipt-envelope.example'] + ); + $corruptReceiptEnvelopeJob = CloudJob::findOrFail( + $corruptReceiptEnvelopeId + ); + $corruptReceiptEnvelopeIdentity = + CloudOperationRecoveryIdentity::expected( + $corruptReceiptEnvelopeJob, + true + ); + $corruptReceiptEnvelopeResult = [ + 'uuid' => $corruptReceiptEnvelopeUuid, + 'hostname' => 'corrupt-receipt-envelope.example', + 'settings_changed' => true, + ]; + $corruptReceiptEnvelopeWire = [ + 'event_id' => 'automatic-corrupt-receipt-envelope', + 'host_id' => 7, + 'operation_id' => (string) $corruptReceiptEnvelopeJob->operation_id, + 'action' => $corruptReceiptEnvelopeIdentity['action'], + 'resource_id' => $corruptReceiptEnvelopeIdentity['resource_id'], + 'request_fingerprint' => + $corruptReceiptEnvelopeIdentity['request_fingerprint'], + 'status' => 'succeeded', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'error_code' => '', + 'result' => $corruptReceiptEnvelopeResult, + ]; + Capsule::table('cloud_agent_completion_events')->insert([ + 'event_id' => $corruptReceiptEnvelopeWire['event_id'], + 'host_id' => 7, + 'operation_id' => $corruptReceiptEnvelopeWire['operation_id'], + 'payload_sha256' => hash('sha256', json_encode( + $corruptReceiptEnvelopeWire, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + | JSON_UNESCAPED_UNICODE + )), + 'outcome' => 'succeeded', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'error_code' => '', + 'result_json' => json_encode([ + 'schema' => 'virt_cloud_completion_event', + 'version' => 1, + 'identity' => $corruptReceiptEnvelopeIdentity, + 'result' => $corruptReceiptEnvelopeResult, + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + | JSON_UNESCAPED_UNICODE), + 'disposition' => 'received', + 'received_at' => time(), + 'applied_at' => null, + ]); + Capsule::table('cloud_jobs')->where( + 'id', + $corruptReceiptEnvelopeId + )->update([ + 'request_idempotency_key' => 'bad-receipt-key', + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + Capsule::table('cloud_templates')->insert([ + 'id' => 'identity-priority-template', + 'active_job_id' => $corruptReceiptEnvelopeId, + 'state' => 'active', + ]); + $beforeCorruptReceiptEnvelopeRequests = count($client->requests); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'A damaged envelope with an exact receipt left recovery.'); + $corruptReceiptEnvelopeJob = CloudJob::findOrFail( + $corruptReceiptEnvelopeId + ); + $corruptReceiptEnvelopeEvent = Capsule::table( + 'cloud_agent_completion_events' + )->where( + 'event_id', + $corruptReceiptEnvelopeWire['event_id'] + )->first(); + $assert((string) $corruptReceiptEnvelopeJob->effect_resolution + === 'unknown' + && (bool) $corruptReceiptEnvelopeJob->finalization_incident + && (string) $corruptReceiptEnvelopeJob->finalization_error_code + === 'recovery_operation_identity_conflict' + && (int) $corruptReceiptEnvelopeJob->available_at >= time() + 290 + && (int) $corruptReceiptEnvelopeJob->lease_until >= time() + 290 + && (string) $corruptReceiptEnvelopeEvent->disposition === 'received' + && $corruptReceiptEnvelopeEvent->applied_at === null + && (int) Capsule::table('cloud_templates')->where( + 'id', + 'identity-priority-template' + )->value('active_job_id') === $corruptReceiptEnvelopeId + && CloudJobService::blockingQueryForInstance( + $corruptReceiptEnvelopeId + )->exists() + && count($client->requests) + === $beforeCorruptReceiptEnvelopeRequests, + 'A damaged envelope consumed its receipt, contacted Agent, or falsely unlocked.'); + Capsule::table('cloud_templates')->where( + 'id', + 'identity-priority-template' + )->delete(); + + // A prepared no-fence conclusion must revalidate the complete envelope at + // the locked publication boundary. This protects direct callers and the + // crash-resume path even if claim-time validation is bypassed or races. + [$preparedStateConflictId, $preparedStateConflictUuid] = + $insertSettingsJob( + str_repeat('b2', 16), + ['hostname' => 'prepared-state-conflict.example'] + ); + $preparedStateConflictIdentity = + CloudOperationRecoveryIdentity::expected( + CloudJob::findOrFail($preparedStateConflictId), + true + ); + $preparedStateConflictOperation = $preparedStateConflictIdentity + [ + 'operation_id' => str_repeat('b2', 16), + 'status' => 'succeeded', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'error_code' => '', + 'result' => [ + 'uuid' => $preparedStateConflictUuid, + 'hostname' => 'prepared-state-conflict.example', + 'settings_changed' => true, + ], + ]; + $preparedStateConflictSource = + 'automatic_applied_succeeded_nofence:' . str_repeat('2', 64); + CloudOperationRecoveryService::prepareApplied( + $preparedStateConflictId, + $preparedStateConflictOperation, + $preparedStateConflictSource + ); + $preparedStateConflictMarker = (string) CloudJob::findOrFail( + $preparedStateConflictId + )->effect_resolution_reason; + Capsule::table('cloud_jobs')->where( + 'id', + $preparedStateConflictId + )->update([ + 'receipt_deadline_at' => 0, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + try { + CloudOperationRecoveryService::commitApplied( + $preparedStateConflictId, + $preparedStateConflictOperation, + $preparedStateConflictSource, + 0 + ); + throw new RuntimeException( + 'A direct applied commit published a damaged Agent envelope.' + ); + } catch (CloudRecoveryInstanceStateConflict $error) { + $assert($error->httpStatus === 409, + 'The applied envelope guard returned the wrong status.'); + } + $preparedStateConflict = CloudJob::findOrFail( + $preparedStateConflictId + ); + $assert((string) $preparedStateConflict->effect_resolution === 'unknown' + && (string) $preparedStateConflict->effect_resolution_reason + === $preparedStateConflictMarker, + 'A rejected applied commit changed its prepared recovery intent.'); + $beforePreparedStateConflictRequests = count($client->requests); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'A prepared no-fence envelope conflict left recovery.'); + $preparedStateConflict = CloudJob::findOrFail( + $preparedStateConflictId + ); + $assert((string) $preparedStateConflict->effect_resolution === 'unknown' + && (string) $preparedStateConflict->effect_resolution_reason + === $preparedStateConflictMarker + && (bool) $preparedStateConflict->finalization_incident + && (string) $preparedStateConflict->finalization_error_code + === 'recovery_instance_state_conflict' + && CloudJobService::blockingQueryForInstance( + $preparedStateConflictId + )->exists() + && count($client->requests) + === $beforePreparedStateConflictRequests, + 'A prepared no-fence conflict contacted Agent, published, or unlocked.'); + + // The not-applied publication boundary applies the same immutable identity + // guard. A prepared proof cannot rely only on its encrypted escrow after + // the durable request fingerprint column has been damaged. + [$preparedIdentityConflictId] = $insertSettingsJob( + str_repeat('b3', 16), + ['hostname' => 'prepared-identity-conflict.example'] + ); + $preparedIdentityConflictIdentity = + CloudOperationRecoveryIdentity::expected( + CloudJob::findOrFail($preparedIdentityConflictId), + false + ); + $preparedIdentityConflictOperation = $preparedIdentityConflictIdentity + [ + 'operation_id' => str_repeat('b3', 16), + 'status' => 'failed', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => true, + 'error_code' => 'settings_not_committed', + 'result' => ['agent_detail' => 'bounded'], + ]; + $preparedIdentityConflictSource = + 'automatic_not_applied_failed_nofence:' . str_repeat('3', 64); + CloudOperationRecoveryService::prepareNotApplied( + $preparedIdentityConflictId, + $preparedIdentityConflictOperation, + $preparedIdentityConflictSource + ); + $preparedIdentityConflictMarker = (string) CloudJob::findOrFail( + $preparedIdentityConflictId + )->effect_resolution_reason; + Capsule::table('cloud_jobs')->where( + 'id', + $preparedIdentityConflictId + )->update([ + 'request_fingerprint' => 'bad-fingerprint', + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + try { + CloudOperationRecoveryService::commitNotApplied( + $preparedIdentityConflictId, + $preparedIdentityConflictOperation, + $preparedIdentityConflictSource, + 0 + ); + throw new RuntimeException( + 'A direct not-applied commit published damaged request identity.' + ); + } catch (CloudRecoveryOperationIdentityConflict $error) { + $assert($error->httpStatus === 409, + 'The not-applied identity guard returned the wrong status.'); + } + $preparedIdentityConflict = CloudJob::findOrFail( + $preparedIdentityConflictId + ); + $assert((string) $preparedIdentityConflict->effect_resolution === 'unknown' + && (string) $preparedIdentityConflict->effect_resolution_reason + === $preparedIdentityConflictMarker, + 'A rejected not-applied commit changed its prepared recovery intent.'); + $beforePreparedIdentityConflictRequests = count($client->requests); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'A prepared request-identity conflict left recovery.'); + $preparedIdentityConflict = CloudJob::findOrFail( + $preparedIdentityConflictId + ); + $assert((string) $preparedIdentityConflict->effect_resolution === 'unknown' + && (string) $preparedIdentityConflict->effect_resolution_reason + === $preparedIdentityConflictMarker + && (bool) $preparedIdentityConflict->finalization_incident + && (string) $preparedIdentityConflict->finalization_error_code + === 'recovery_operation_identity_conflict' + && CloudJobService::blockingQueryForInstance( + $preparedIdentityConflictId + )->exists() + && count($client->requests) + === $beforePreparedIdentityConflictRequests, + 'A prepared identity conflict contacted Agent, published, or unlocked.'); + + // A previously published effect with an older incident is not exempt from + // envelope validation. The immutable terminal audit remains resolved, but + // the concrete envelope conflict becomes visible and the resource remains + // blocked without consulting Agent state. + [$resolvedEnvelopeConflictId] = $insertSettingsJob( + str_repeat('b4', 16), + ['hostname' => 'resolved-envelope-conflict.example'] + ); + Capsule::table('cloud_jobs')->where( + 'id', + $resolvedEnvelopeConflictId + )->update([ + 'effect_resolution' => 'applied', + 'effect_resolved_at' => time() - 5, + 'effect_resolved_by' => 0, + 'effect_resolution_reason' => 'prior_exact_evidence', + 'receipt_deadline_at' => 0, + 'finalization_incident' => 1, + 'finalization_error_code' => 'recovery_waiting_connection', + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + $beforeResolvedEnvelopeConflictRequests = count($client->requests); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'A resolved task with a damaged envelope left local recovery.'); + $resolvedEnvelopeConflict = CloudJob::findOrFail( + $resolvedEnvelopeConflictId + ); + $assert((string) $resolvedEnvelopeConflict->effect_resolution === 'applied' + && (string) $resolvedEnvelopeConflict->effect_resolution_reason + === 'prior_exact_evidence' + && (bool) $resolvedEnvelopeConflict->finalization_incident + && (string) $resolvedEnvelopeConflict->finalization_error_code + === 'recovery_instance_state_conflict' + && (int) $resolvedEnvelopeConflict->available_at >= time() + 290 + && CloudJobService::blockingQueryForInstance( + $resolvedEnvelopeConflictId + )->exists() + && count($client->requests) + === $beforeResolvedEnvelopeConflictRequests, + 'A resolved envelope conflict contacted Agent, hid its cause, or falsely unlocked.'); + + // Repairing a failed row to the dispatched state is not enough when the + // immutable host/operation/time envelope is still damaged. Keep it in the + // local envelope-conflict queue instead of publishing a recovery that can + // never satisfy the normal Agent claim. + [$incompleteRepairId] = $insertSettingsJob( + str_repeat('bd', 16), + ['hostname' => 'incomplete-dispatch-repair.example'] + ); + Capsule::table('cloud_jobs')->where('id', $incompleteRepairId)->update([ + 'dispatch_attempts' => 2, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + CloudOperationCompletionService::deferDispatchLedgerConflict( + CloudJob::findOrFail($incompleteRepairId) + ); + Capsule::table('cloud_jobs')->where('id', $incompleteRepairId)->update([ + 'dispatch_attempts' => 1, + 'dispatched_at' => null, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + $beforeIncompleteRepairRequests = count($client->requests); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'An incomplete repaired dispatch envelope was not checked.'); + $incompleteRepair = CloudJob::findOrFail($incompleteRepairId); + $assert((string) $incompleteRepair->effect_resolution === 'unknown' + && (bool) $incompleteRepair->finalization_incident + && (string) $incompleteRepair->finalization_error_code + === 'recovery_dispatch_repair_instance_state_conflict' + && (int) $incompleteRepair->lease_until >= time() + 290 + && (int) $incompleteRepair->available_at >= time() + 290 + && count($client->requests) === $beforeIncompleteRepairRequests, + 'An incomplete repaired dispatch envelope left its sticky queue.'); + + // A pre-existing dispatched/unknown row with a damaged immutable envelope + // must still be claimed forever, but without attempting an Agent request. + [$malformedEnvelopeId] = $insertSettingsJob( + str_repeat('bc', 16), + ['hostname' => 'malformed-envelope.example'] + ); + Capsule::table('cloud_jobs')->where('id', $malformedEnvelopeId)->update([ + 'dispatched_at' => null, + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + $beforeMalformedEnvelopeRequests = count($client->requests); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'A damaged dispatched recovery envelope fell out of the queue.'); + $malformedEnvelope = CloudJob::findOrFail($malformedEnvelopeId); + $assert((bool) $malformedEnvelope->finalization_incident + && (string) $malformedEnvelope->finalization_error_code + === 'recovery_instance_state_conflict' + && (string) $malformedEnvelope->effect_resolution === 'unknown' + && (int) $malformedEnvelope->lease_until >= time() + 290 + && (int) $malformedEnvelope->available_at >= time() + 290 + && count($client->requests) === $beforeMalformedEnvelopeRequests, + 'A damaged dispatched recovery envelope contacted Agent or lost its concrete incident.'); + + [$invalidOperationIdJob] = $insertSettingsJob( + str_repeat('G', 32), + ['hostname' => 'invalid-operation-id.example'] + ); + Capsule::table('cloud_jobs')->where('id', $invalidOperationIdJob)->update([ + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + $beforeInvalidOperationIdRequests = count($client->requests); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'A malformed Agent operation ID fell out of recovery.'); + $invalidOperationIdentity = CloudJob::findOrFail( + $invalidOperationIdJob + ); + $assert((bool) $invalidOperationIdentity->finalization_incident + && (string) $invalidOperationIdentity->finalization_error_code + === 'recovery_operation_identity_conflict' + && (string) $invalidOperationIdentity->effect_resolution === 'unknown' + && (int) $invalidOperationIdentity->available_at >= time() + 290 + && count($client->requests) === $beforeInvalidOperationIdRequests, + 'A malformed operation ID lost its concrete identity-conflict status or contacted Agent.'); + + // A historical succeeded row without a bound completion event must still + // prove the immutable dispatched envelope before its sticky repair + // incident can be cleared. Otherwise repairing only the numeric counter + // would release the instance while host/time identity remained corrupt. + [$incompleteSucceededRepairId] = $insertSettingsJob( + str_repeat('be', 16), + ['hostname' => 'incomplete-succeeded-repair.example'] + ); + $incompleteSucceededResult = json_encode([ + 'hostname' => 'incomplete-succeeded-repair.example', + 'settings_changed' => true, + ], JSON_THROW_ON_ERROR); + Capsule::table('cloud_jobs')->where( + 'id', + $incompleteSucceededRepairId + )->update([ + 'dispatch_attempts' => 2, + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'error_code' => null, + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'completion_event_id' => null, + 'result_json' => $incompleteSucceededResult, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + $incompleteSucceededBefore = $audit($incompleteSucceededRepairId); + $incompleteSucceededBefore['dispatch_attempts'] = 1; + $incompleteSucceededEnvelope = (string) CloudJob::findOrFail( + $incompleteSucceededRepairId + )->sealed_payload; + CloudOperationCompletionService::deferDispatchLedgerConflict( + CloudJob::findOrFail($incompleteSucceededRepairId) + ); + Capsule::table('cloud_jobs')->where( + 'id', + $incompleteSucceededRepairId + )->update([ + 'dispatch_attempts' => 1, + 'dispatched_at' => null, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + $beforeIncompleteSucceededRequests = count($client->requests); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'An incomplete succeeded dispatch envelope was not checked.'); + $incompleteSucceededRepair = CloudJob::findOrFail( + $incompleteSucceededRepairId + ); + $assert((bool) $incompleteSucceededRepair->finalization_incident + && (string) $incompleteSucceededRepair->finalization_error_code + === 'recovery_dispatch_repair_instance_state_conflict' + && (int) $incompleteSucceededRepair->lease_until >= time() + 290 + && (int) $incompleteSucceededRepair->available_at >= time() + 290 + && count($client->requests) === $beforeIncompleteSucceededRequests, + 'A succeeded task cleared its repair incident without a complete dispatched envelope.'); + $assert($audit($incompleteSucceededRepairId) + === $incompleteSucceededBefore, + 'Checking an incomplete succeeded envelope rewrote terminal audit data: ' + . json_encode([ + 'expected' => $incompleteSucceededBefore, + 'actual' => $audit($incompleteSucceededRepairId), + ], JSON_THROW_ON_ERROR)); + Capsule::table('cloud_jobs')->where( + 'id', + $incompleteSucceededRepairId + )->update([ + 'dispatched_at' => time() - 980, + 'sealed_payload' => 'automatic-recovery-test:missing', + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'A succeeded repair with a damaged identity escrow was not checked.'); + $damagedSucceededRepair = CloudJob::findOrFail( + $incompleteSucceededRepairId + ); + $assert((bool) $damagedSucceededRepair->finalization_incident + && (string) $damagedSucceededRepair->finalization_error_code + === 'recovery_dispatch_repair_payload_unavailable' + && (int) $damagedSucceededRepair->lease_until >= time() + 290 + && (int) $damagedSucceededRepair->available_at >= time() + 290, + 'A succeeded repair cleared its sticky incident without validating the immutable identity.'); + Capsule::table('cloud_jobs')->where( + 'id', + $incompleteSucceededRepairId + )->update([ + 'sealed_payload' => $incompleteSucceededEnvelope, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'A completed succeeded dispatch envelope did not resume repair.'); + $completedSucceededRepair = CloudJob::findOrFail( + $incompleteSucceededRepairId + ); + $assert(!(bool) $completedSucceededRepair->finalization_incident + && $completedSucceededRepair->finalization_error_code === null + && $audit($incompleteSucceededRepairId) + === $incompleteSucceededBefore + && count($client->requests) === $beforeIncompleteSucceededRequests, + 'A complete succeeded dispatch envelope was not unlocked without rewriting its terminal audit.'); + + // Repairing a corrupt counter to zero cannot erase already durable Agent + // evidence. The sticky repair queue must outrank the PHP-only finalizer; + // after the operator chooses one, the same receipt resumes convergence. + [$zeroCounterConflictId, $zeroCounterConflictUuid] = $insertSettingsJob( + str_repeat('bf', 16), + ['hostname' => 'zero-counter-conflict.example'] + ); + $zeroCounterConflictJob = CloudJob::findOrFail($zeroCounterConflictId); + $zeroCounterIdentity = CloudOperationRecoveryIdentity::expected( + $zeroCounterConflictJob, + true + ); + $zeroCounterEventId = 'zero-counter-proof-01'; + $zeroCounterWire = [ + 'type' => 'completion', + 'id' => $zeroCounterEventId, + 'agent_id' => '7', + 'operation_id' => (string) $zeroCounterConflictJob->operation_id, + 'action' => $zeroCounterIdentity['action'], + 'resource_id' => $zeroCounterIdentity['resource_id'], + 'request_fingerprint' => + $zeroCounterIdentity['request_fingerprint'], + 'status' => 'succeeded', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'error_code' => '', + 'result' => [ + 'uuid' => $zeroCounterConflictUuid, + 'hostname' => 'zero-counter-conflict.example', + 'settings_changed' => true, + ], + ]; + Capsule::table('cloud_jobs')->where( + 'id', + $zeroCounterConflictId + )->update([ + 'dispatch_attempts' => 2, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + $beforeZeroCounterRequests = count($client->requests); + $acceptedZeroCounter = CloudOperationCompletionService::accept( + $zeroCounterWire + ); + $zeroCounterEnvelope = (string) CloudJob::findOrFail( + $zeroCounterConflictId + )->sealed_payload; + $zeroCounterTerminalAt = (int) CloudJob::findOrFail( + $zeroCounterConflictId + )->terminal_at; + Capsule::table('cloud_jobs')->where( + 'id', + $zeroCounterConflictId + )->update([ + 'dispatch_attempts' => 0, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'A repaired-zero ledger with Agent evidence was not checked.'); + $zeroCounterConflict = CloudJob::findOrFail($zeroCounterConflictId); + $zeroCounterEvent = Capsule::table( + 'cloud_agent_completion_events' + )->where('event_id', $zeroCounterEventId)->first(); + $assert($acceptedZeroCounter === [ + 'accepted' => true, + 'disposition' => 'received', + ] + && (bool) $zeroCounterConflict->finalization_incident + && (string) $zeroCounterConflict->finalization_error_code + === 'recovery_dispatch_repair_instance_state_conflict' + && (string) $zeroCounterConflict->effect_resolution === 'unknown' + && (string) $zeroCounterConflict->sealed_payload + === $zeroCounterEnvelope + && (string) $zeroCounterEvent->disposition === 'received' + && $zeroCounterEvent->applied_at === null + && (int) $zeroCounterConflict->lease_until >= time() + 290 + && (int) $zeroCounterConflict->available_at >= time() + 290 + && count($client->requests) === $beforeZeroCounterRequests, + 'Repairing a dispatched operation to zero ran the PHP-only finalizer or consumed its receipt.'); + Capsule::table('cloud_jobs')->where( + 'id', + $zeroCounterConflictId + )->update([ + 'dispatch_attempts' => 1, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + $assert(CloudOperationCompletionService::accept($zeroCounterWire) === [ + 'accepted' => true, + 'disposition' => 'received', + ] + && (string) Capsule::table('cloud_agent_completion_events') + ->where('event_id', $zeroCounterEventId)->value('disposition') + === 'received', + 'A retransmitted receipt bypassed the sticky dispatch-repair coordinator.'); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'The repaired dispatched ledger did not re-enter Agent recovery.'); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'The repaired dispatched ledger did not consume its retained receipt.'); + $zeroCounterResolved = CloudJob::findOrFail($zeroCounterConflictId); + $zeroCounterResolvedEvent = Capsule::table( + 'cloud_agent_completion_events' + )->where('event_id', $zeroCounterEventId)->first(); + $assert((string) $zeroCounterResolved->phase === 'terminal' + && (string) $zeroCounterResolved->outcome === 'failed' + && (string) $zeroCounterResolved->status === 'failed' + && (int) $zeroCounterResolved->terminal_at + === $zeroCounterTerminalAt + && (string) $zeroCounterResolved->effect_resolution === 'applied' + && !(bool) $zeroCounterResolved->finalization_incident + && $zeroCounterResolved->finalization_error_code === null + && (string) $zeroCounterResolvedEvent->disposition === 'applied' + && (int) $zeroCounterResolvedEvent->applied_at > 0 + && count($client->requests) === $beforeZeroCounterRequests, + 'Repairing the counter to one did not safely resume the retained Agent receipt.'); + + // The same contradiction on an active generation-zero task must move the + // row to a sticky terminal fence before the ordinary worker can dispatch. + [$activeZeroConflictId] = $insertSettingsJob( + str_repeat('c0', 16), + ['hostname' => 'active-zero-conflict.example'] + ); + Capsule::table('cloud_jobs')->where('id', $activeZeroConflictId)->update([ + 'phase' => 'accepted', + 'outcome' => null, + 'status' => 'queued', + 'attempts' => 0, + 'dispatch_attempts' => 0, + 'dispatch_started_at' => null, + 'agent_accepted_at' => null, + 'receipt_deadline_at' => null, + 'terminal_at' => null, + 'effect_may_have_applied' => null, + 'safe_to_resubmit' => null, + 'effect_resolution' => 'not_applicable', + 'dispatched_at' => null, + 'error_code' => null, + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'result_json' => null, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + $activeZeroJob = CloudJob::findOrFail($activeZeroConflictId); + $activeZeroIdentity = CloudOperationRecoveryIdentity::expected( + $activeZeroJob, + true + ); + $activeZeroEventId = 'active-zero-proof-01'; + $activeZeroAccepted = CloudOperationCompletionService::accept([ + 'type' => 'completion', + 'id' => $activeZeroEventId, + 'agent_id' => '7', + 'operation_id' => (string) $activeZeroJob->operation_id, + 'action' => $activeZeroIdentity['action'], + 'resource_id' => $activeZeroIdentity['resource_id'], + 'request_fingerprint' => $activeZeroIdentity['request_fingerprint'], + 'status' => 'succeeded', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'error_code' => '', + 'result' => [ + 'hostname' => 'active-zero-conflict.example', + 'settings_changed' => true, + ], + ]); + $activeZeroConflict = CloudJob::findOrFail($activeZeroConflictId); + $activeZeroEvent = Capsule::table( + 'cloud_agent_completion_events' + )->where('event_id', $activeZeroEventId)->first(); + $assert($activeZeroAccepted === [ + 'accepted' => true, + 'disposition' => 'received', + ] + && (string) $activeZeroConflict->phase === 'terminal' + && (string) $activeZeroConflict->outcome === 'failed' + && (string) $activeZeroConflict->status === 'failed' + && (string) $activeZeroConflict->effect_resolution === 'unknown' + && (bool) $activeZeroConflict->finalization_incident + && (string) $activeZeroConflict->finalization_error_code + === 'recovery_dispatch_repair_instance_state_conflict' + && (string) $activeZeroEvent->disposition === 'received' + && !CloudJob::where('id', $activeZeroConflictId) + ->where('phase', 'accepted') + ->where('dispatch_attempts', 0)->exists() + && count($client->requests) === $beforeZeroCounterRequests, + 'An active zero-counter task retained a replayable mutation after Agent completion evidence arrived.'); + // Defence in depth for a pre-upgrade/crash snapshot where only the event + // became durable: the ordinary worker query itself excludes any Agent job + // with same-operation completion evidence. + Capsule::table('cloud_jobs')->where('id', $activeZeroConflictId)->update([ + 'phase' => 'accepted', + 'outcome' => null, + 'status' => 'queued', + 'attempts' => 0, + 'dispatch_attempts' => 0, + 'dispatch_deadline_at' => time() + 300, + 'dispatch_started_at' => null, + 'agent_accepted_at' => null, + 'receipt_deadline_at' => null, + 'terminal_at' => null, + 'effect_may_have_applied' => null, + 'safe_to_resubmit' => null, + 'effect_resolution' => 'not_applicable', + 'dispatched_at' => null, + 'error_code' => null, + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + $beforeCrashWindowRequests = count($client->requests); + (new CloudWorkerService())->tick(); + $crashWindowJob = CloudJob::findOrFail($activeZeroConflictId); + $assert((string) $crashWindowJob->phase === 'accepted' + && (int) $crashWindowJob->dispatch_attempts === 0 + && count($client->requests) === $beforeCrashWindowRequests, + 'The ordinary worker replayed a mutation after durable same-operation completion evidence.'); + + // A repaired ledger with a corrupt bound receipt stays visible but obeys + // the same retry gate on both ordinary and receipt-priority passes. Without + // the lease clock this exact event would be reclaimed on every tick. + [$repairBackoffId, $repairBackoffUuid] = $insertSettingsJob( + str_repeat('ce', 16), + ['hostname' => 'dispatch-repair-backoff.example'] + ); + $repairBackoffEventId = 'dispatch-repair-invalid-event'; + Capsule::table('cloud_jobs')->where('id', $repairBackoffId)->update([ + 'dispatch_attempts' => 2, + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'error_code' => null, + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'completion_event_id' => $repairBackoffEventId, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + $repairBackoffJob = CloudJob::findOrFail($repairBackoffId); + $repairBackoffIdentity = CloudOperationRecoveryIdentity::expected( + $repairBackoffJob, + true + ); + Capsule::table('cloud_agent_completion_events')->insert([ + 'event_id' => $repairBackoffEventId, + 'host_id' => 7, + 'operation_id' => (string) $repairBackoffJob->operation_id, + // Valid shape but deliberately not the hash of the immutable receipt. + 'payload_sha256' => str_repeat('0', 64), + 'outcome' => 'succeeded', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'error_code' => '', + 'result_json' => json_encode([ + 'schema' => 'virt_cloud_completion_event', + 'version' => 1, + 'identity' => $repairBackoffIdentity, + 'result' => [ + 'uuid' => $repairBackoffUuid, + 'hostname' => 'dispatch-repair-backoff.example', + 'settings_changed' => true, + ], + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + | JSON_UNESCAPED_UNICODE), + 'disposition' => 'received', + 'received_at' => time(), + 'applied_at' => null, + ]); + CloudOperationCompletionService::deferDispatchLedgerConflict( + $repairBackoffJob + ); + Capsule::table('cloud_jobs')->where('id', $repairBackoffId)->update([ + 'dispatch_attempts' => 1, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + $beforeRepairBackoffRequests = count($client->requests); + $repairBackoffService = new CloudAutomaticOperationRecoveryService(); + $assert($repairBackoffService->tick(), + 'A repaired ledger with an invalid bound receipt was not checked.'); + $repairBackoffJob = CloudJob::findOrFail($repairBackoffId); + $repairBackoffUpdatedAt = (int) $repairBackoffJob->updated_at; + $assert((bool) $repairBackoffJob->finalization_incident + && (string) $repairBackoffJob->finalization_error_code + === 'recovery_dispatch_repair_receipt_invalid' + && (int) $repairBackoffJob->lease_until >= time() + 290 + && (int) $repairBackoffJob->available_at >= time() + 290 + && count($client->requests) === $beforeRepairBackoffRequests, + 'An invalid repaired-ledger receipt did not enter bounded backoff.'); + Capsule::table('cloud_jobs')->where('id', '<>', $repairBackoffId) + ->update([ + 'lease_until' => time() + 3600, + 'available_at' => time() + 3600, + ]); + $assert(!$repairBackoffService->tick() + && (int) CloudJob::findOrFail($repairBackoffId)->updated_at + === $repairBackoffUpdatedAt + && count($client->requests) === $beforeRepairBackoffRequests, + 'Receipt-priority recovery ignored the repaired-ledger retry gate.'); + + // Contradictory terminal/unknown safety tuples are PHP-only incidents. + // They must remain scheduled forever without inspection, fence writes, or + // any replay of the original mutation. Cover both legal dispatch counters + // and each independent part of the canonical terminal tuple. + $stateCases = [ + [str_repeat('f1', 16), [ + 'effect_may_have_applied' => 1, + 'safe_to_resubmit' => 1, + ]], + [str_repeat('f2', 16), [ + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + ]], + [str_repeat('f3', 16), [ + 'outcome' => 'succeeded', + 'status' => 'succeeded', + ]], + [str_repeat('f4', 16), [ + 'dispatch_attempts' => 0, + 'dispatched_at' => null, + 'dispatch_started_at' => null, + 'agent_accepted_at' => null, + 'receipt_deadline_at' => null, + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + ]], + // The safety booleans look canonical for an unknown dispatched + // operation, but generation zero proves no Agent mutation crossed the + // boundary. Without an undispatched-finalizer incident this is a + // contradictory historical row, not an Agent recovery candidate. + [str_repeat('f8', 16), [ + 'dispatch_attempts' => 0, + 'dispatched_at' => null, + 'dispatch_started_at' => null, + 'agent_accepted_at' => null, + 'receipt_deadline_at' => null, + 'effect_may_have_applied' => 1, + 'safe_to_resubmit' => 0, + ]], + ]; + foreach ($stateCases as [$operationId, $overrides]) { + [$stateId] = $insertSettingsJob( + $operationId, + ['hostname' => 'damaged-state.example'] + ); + Capsule::table('cloud_jobs')->where('id', $stateId)->update( + $overrides + [ + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ] + ); + $beforeStateRequests = count($client->requests); + $stateService = new CloudAutomaticOperationRecoveryService(); + $assert($stateService->tick(), + 'A damaged leaf terminal tuple left the recovery queue.'); + $stateJob = CloudJob::findOrFail($stateId); + $assert((bool) $stateJob->finalization_incident + && (string) $stateJob->finalization_error_code + === 'recovery_instance_state_conflict' + && (int) $stateJob->available_at >= time() + 290 + && (int) $stateJob->lease_until >= time() + 290 + && count($client->requests) === $beforeStateRequests, + 'A damaged leaf terminal tuple contacted Agent or lost backoff.'); + Capsule::table('cloud_jobs')->where('id', $stateId)->update([ + 'available_at' => time() + 3600, + 'lease_until' => time() + 3600, + ]); + } + + // A completed Agent effect can still carry a sticky PHP projection + // incident. Both resolved outcomes remain in the local retry queue, retain + // their concrete code, and must never trigger another Agent request. + $resolvedIncidentCases = [ + [ + str_repeat('f9', 16), + 'applied', + 'succeeded', + 'recovery_payload_unavailable', + ], + [ + str_repeat('fa', 16), + 'not_applied', + 'failed', + 'recovery_operation_identity_conflict', + ], + ]; + foreach ($resolvedIncidentCases as [ + $operationId, + $resolution, + $outcome, + $incidentCode, + ]) { + [$resolvedIncidentId] = $insertSettingsJob( + $operationId, + ['hostname' => 'resolved-local-incident.example'] + ); + Capsule::table('cloud_jobs') + ->where('id', $resolvedIncidentId)->update([ + 'outcome' => $outcome, + 'status' => $outcome, + 'dispatch_attempts' => 1, + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => $resolution, + 'effect_resolved_at' => time() - 1, + 'finalization_incident' => 1, + 'finalization_error_code' => $incidentCode, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + $beforeResolvedIncidentRequests = count($client->requests); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'A resolved sticky incident left the local recovery queue.'); + $resolvedIncident = CloudJob::findOrFail($resolvedIncidentId); + $assert((bool) $resolvedIncident->finalization_incident + && (string) $resolvedIncident->finalization_error_code + === $incidentCode + && (string) $resolvedIncident->effect_resolution === $resolution + && (int) $resolvedIncident->available_at >= time() + 290 + && (int) $resolvedIncident->lease_until >= time() + 290 + && count($client->requests) === $beforeResolvedIncidentRequests, + 'A resolved sticky incident contacted Agent, lost its code, ' + . 'or failed to enter local backoff.'); + } + + // The same rule applies to a replica child below an already-resolved + // aggregate. Child ancestry must not turn a local finalization incident + // back into an Agent recovery or remove its concrete cause. + [$resolvedIncidentParentId] = $insertSettingsJob( + str_repeat('fb', 16), + ['hostname' => 'resolved-incident-parent.example'] + ); + Capsule::table('cloud_jobs') + ->where('id', $resolvedIncidentParentId)->update([ + 'instance_id' => null, + 'host_id' => null, + 'kind' => 'template_import', + 'execution_mode' => 'aggregate', + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'attempts' => 0, + 'dispatch_attempts' => 0, + 'dispatch_started_at' => null, + 'agent_accepted_at' => null, + 'dispatched_at' => null, + 'completion_event_id' => null, + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'effect_resolved_at' => time() - 1, + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'available_at' => time() + 3600, + 'lease_token' => null, + 'lease_until' => time() + 3600, + ]); + [$resolvedIncidentChildId] = $insertSettingsJob( + str_repeat('fc', 16), + ['hostname' => 'resolved-incident-child.example'] + ); + Capsule::table('cloud_jobs') + ->where('id', $resolvedIncidentChildId)->update([ + 'parent_job_id' => $resolvedIncidentParentId, + 'kind' => 'template_import_replica', + 'outcome' => 'failed', + 'status' => 'failed', + 'dispatch_attempts' => 1, + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'not_applied', + 'effect_resolved_at' => time() - 1, + 'finalization_incident' => 1, + 'finalization_error_code' => 'recovery_payload_unavailable', + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + $beforeResolvedIncidentChildRequests = count($client->requests); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'A resolved sticky aggregate child left the local recovery queue.'); + $resolvedIncidentChild = CloudJob::findOrFail( + $resolvedIncidentChildId + ); + $assert((bool) $resolvedIncidentChild->finalization_incident + && (string) $resolvedIncidentChild->finalization_error_code + === 'recovery_payload_unavailable' + && (string) $resolvedIncidentChild->effect_resolution + === 'not_applied' + && (int) $resolvedIncidentChild->available_at >= time() + 290 + && (int) $resolvedIncidentChild->lease_until >= time() + 290 + && count($client->requests) + === $beforeResolvedIncidentChildRequests, + 'A resolved sticky aggregate child contacted Agent, lost its code, ' + . 'or failed to enter local backoff.'); + + [$aggregateStateId] = $insertSettingsJob( + str_repeat('f5', 16), + ['hostname' => 'aggregate-state.example'] + ); + Capsule::table('cloud_jobs')->where('id', $aggregateStateId)->update([ + 'instance_id' => null, + 'host_id' => null, + 'kind' => 'template_import', + 'execution_mode' => 'aggregate', + 'dispatch_attempts' => 0, + 'dispatched_at' => null, + 'dispatch_started_at' => null, + 'agent_accepted_at' => null, + 'receipt_deadline_at' => null, + 'safe_to_resubmit' => 1, + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + $beforeAggregateStateRequests = count($client->requests); + $aggregateStateService = new CloudAutomaticOperationRecoveryService(); + $assert($aggregateStateService->tick(), + 'A damaged aggregate-parent tuple left the recovery queue.'); + $aggregateStateJob = CloudJob::findOrFail($aggregateStateId); + $assert((bool) $aggregateStateJob->finalization_incident + && (string) $aggregateStateJob->finalization_error_code + === 'recovery_aggregate_state_conflict' + && (int) $aggregateStateJob->available_at >= time() + 290 + && (int) $aggregateStateJob->lease_until >= time() + 290 + && count($client->requests) === $beforeAggregateStateRequests, + 'A damaged aggregate-parent tuple contacted Agent or lost backoff.'); + Capsule::table('cloud_jobs')->where('id', $aggregateStateId)->update([ + 'available_at' => time() + 3600, + 'lease_until' => time() + 3600, + ]); + + // A resolved aggregate parent must still surface and retain an anomalous + // Agent child; only the child enters the PHP-only incident loop. + [$resolvedParentId] = $insertSettingsJob( + str_repeat('f6', 16), + ['hostname' => 'resolved-parent.example'] + ); + Capsule::table('cloud_jobs')->where('id', $resolvedParentId)->update([ + 'instance_id' => null, + 'host_id' => null, + 'kind' => 'template_import', + 'execution_mode' => 'aggregate', + 'dispatch_attempts' => 0, + 'dispatched_at' => null, + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'available_at' => time() + 3600, + 'lease_until' => time() + 3600, + ]); + [$stateChildId] = $insertSettingsJob( + str_repeat('f7', 16), + ['hostname' => 'damaged-child.example'] + ); + Capsule::table('cloud_jobs')->where('id', $stateChildId)->update([ + 'parent_job_id' => $resolvedParentId, + 'kind' => 'template_import_replica', + 'safe_to_resubmit' => 1, + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + $beforeStateChildRequests = count($client->requests); + $stateChildService = new CloudAutomaticOperationRecoveryService(); + $assert($stateChildService->tick(), + 'An anomalous aggregate child left the recovery queue.'); + $stateChild = CloudJob::findOrFail($stateChildId); + $assert((bool) $stateChild->finalization_incident + && (string) $stateChild->finalization_error_code + === 'recovery_instance_state_conflict' + && count($client->requests) === $beforeStateChildRequests, + 'An anomalous aggregate child contacted Agent or lost its incident.'); foreach ($client->requests as $request) { $allowed = preg_match( diff --git a/web/tests/CloudCatalogActiveJobPointerRecoveryTest.php b/web/tests/CloudCatalogActiveJobPointerRecoveryTest.php new file mode 100644 index 00000000..0a8c4adb --- /dev/null +++ b/web/tests/CloudCatalogActiveJobPointerRecoveryTest.php @@ -0,0 +1,1028 @@ + $assert ?? null, + 'insertParent' => $insertParent ?? null, + 'insertResolvedChild' => $insertResolvedChild ?? null, + 'insertProjectionForParent' => $insertProjectionForParent ?? null, + 'makeLegacyEligible' => $makeLegacyEligible ?? null, +] as $fixture => $callable) { + if (!is_callable($callable)) { + throw new RuntimeException( + 'Missing aggregate pointer recovery fixture: ' . $fixture + ); + } +} + +$parkOtherParents = static function (int $parentId): void { + $future = time() + 3600; + Capsule::table('cloud_jobs') + ->whereNull('parent_job_id') + ->where('id', '<>', $parentId) + ->update([ + 'available_at' => $future, + 'lease_until' => $future, + ]); +}; + +$runLegacySweep = static function (int $parentId) use ( + $parkOtherParents, + $makeLegacyEligible, + $assert +): void { + $parkOtherParents($parentId); + $makeLegacyEligible($parentId); + $assert( + CloudJobService::reconcileOneLegacyAggregateEffect(), + 'The catalog pointer recovery sweep did not claim its exact parent.' + ); +}; + +$runPublishedSweep = static function (int $parentId) use ( + $parkOtherParents, + $assert +): void { + $parkOtherParents($parentId); + Capsule::table('cloud_jobs')->where('id', $parentId)->update([ + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + $assert( + CloudJobService::reconcileOneLegacyAggregateEffect(), + 'The published catalog pointer anomaly stayed outside the local sweep.' + ); +}; + +// A NULL template pointer is repairable only because the immutable child and +// replica ledgers name the same host, operation and resource exactly once. +$templateParentId = $insertParent('template_import'); +$insertResolvedChild( + $templateParentId, + 'applied', + 'template_import_replica' +); +$templateId = $insertProjectionForParent($templateParentId); +Capsule::table('cloud_templates')->where('id', $templateId)->update([ + 'state' => 'importing', + 'active_job_id' => null, +]); +$runLegacySweep($templateParentId); +$templateParent = CloudJob::findOrFail($templateParentId); +$assert( + (int) Capsule::table('cloud_templates') + ->where('id', $templateId) + ->value('active_job_id') === $templateParentId + && (string) Capsule::table('cloud_templates') + ->where('id', $templateId) + ->value('state') === 'active' + && (string) $templateParent->effect_resolution === 'applied' + && !(bool) $templateParent->finalization_incident, + 'A uniquely proven NULL template active_job_id did not recover.' +); + +// The same proof must recover an integer-zero ISO delete pointer without +// replaying the already completed Agent deletion. +$isoParentId = $insertParent('user_iso_delete'); +$insertResolvedChild( + $isoParentId, + 'applied', + 'user_iso_delete_replica' +); +$isoId = $insertProjectionForParent($isoParentId); +Capsule::table('cloud_user_isos')->where('id', $isoId)->update([ + 'state' => 'deleting', + 'active_job_id' => 0, +]); +$runLegacySweep($isoParentId); +$isoParent = CloudJob::findOrFail($isoParentId); +$assert( + (int) Capsule::table('cloud_user_isos') + ->where('id', $isoId) + ->value('active_job_id') === $isoParentId + && (string) Capsule::table('cloud_user_isos') + ->where('id', $isoId) + ->value('state') === 'retired' + && !Capsule::table('cloud_user_iso_replicas') + ->where('user_iso_id', $isoId) + ->exists() + && (string) $isoParent->effect_resolution === 'applied' + && !(bool) $isoParent->finalization_incident, + 'A uniquely proven zero ISO active_job_id did not recover locally.' +); + +// Deadline/finalizer failure states are application-reachable before the +// parent-first sweep runs. Clearing the pointer in that window must not strand +// the resource outside recovery. +$errorTemplateParentId = $insertParent('template_import'); +$insertResolvedChild( + $errorTemplateParentId, + 'applied', + 'template_import_replica' +); +$errorTemplateId = $insertProjectionForParent($errorTemplateParentId); +Capsule::table('cloud_templates')->where('id', $errorTemplateId)->update([ + 'active_job_id' => null, +]); +$runLegacySweep($errorTemplateParentId); +$errorTemplateParent = CloudJob::findOrFail($errorTemplateParentId); +$assert( + (int) Capsule::table('cloud_templates') + ->where('id', $errorTemplateId) + ->value('active_job_id') === $errorTemplateParentId + && (string) Capsule::table('cloud_templates') + ->where('id', $errorTemplateId)->value('state') === 'active' + && (string) $errorTemplateParent->effect_resolution === 'applied' + && !(bool) $errorTemplateParent->finalization_incident, + 'A NULL pointer in template import error state was not recovered.' +); + +$failedTemplateDeleteParentId = $insertParent('template_delete'); +$insertResolvedChild( + $failedTemplateDeleteParentId, + 'not_applied', + 'template_delete_replica' +); +$failedTemplateDeleteId = $insertProjectionForParent( + $failedTemplateDeleteParentId +); +Capsule::table('cloud_templates') + ->where('id', $failedTemplateDeleteId) + ->update(['active_job_id' => 0]); +$runLegacySweep($failedTemplateDeleteParentId); +$failedTemplateDeleteParent = CloudJob::findOrFail( + $failedTemplateDeleteParentId +); +$assert( + (int) Capsule::table('cloud_templates') + ->where('id', $failedTemplateDeleteId) + ->value('active_job_id') === $failedTemplateDeleteParentId + && (string) Capsule::table('cloud_templates') + ->where('id', $failedTemplateDeleteId)->value('state') === 'active' + && (string) Capsule::table('cloud_template_replicas') + ->where('template_id', $failedTemplateDeleteId) + ->value('state') === 'active' + && (string) $failedTemplateDeleteParent->effect_resolution + === 'not_applied' + && !(bool) $failedTemplateDeleteParent->finalization_incident, + 'A zero pointer in template delete_failed state was not recovered.' +); + +$failedIsoImportParentId = $insertParent('user_iso_import'); +$insertResolvedChild( + $failedIsoImportParentId, + 'applied', + 'user_iso_import_replica' +); +$failedIsoImportId = $insertProjectionForParent($failedIsoImportParentId); +Capsule::table('cloud_user_isos')->where('id', $failedIsoImportId)->update([ + 'active_job_id' => null, +]); +$runLegacySweep($failedIsoImportParentId); +$failedIsoImportParent = CloudJob::findOrFail($failedIsoImportParentId); +$assert( + (int) Capsule::table('cloud_user_isos') + ->where('id', $failedIsoImportId) + ->value('active_job_id') === $failedIsoImportParentId + && (string) Capsule::table('cloud_user_isos') + ->where('id', $failedIsoImportId)->value('state') === 'active' + && (string) $failedIsoImportParent->effect_resolution === 'applied' + && !(bool) $failedIsoImportParent->finalization_incident, + 'A NULL pointer in ISO import_failed state was not recovered.' +); + +$failedIsoDeleteParentId = $insertParent('user_iso_delete'); +$insertResolvedChild( + $failedIsoDeleteParentId, + 'not_applied', + 'user_iso_delete_replica' +); +$failedIsoDeleteId = $insertProjectionForParent($failedIsoDeleteParentId); +Capsule::table('cloud_user_isos')->where('id', $failedIsoDeleteId)->update([ + 'active_job_id' => 0, +]); +$runLegacySweep($failedIsoDeleteParentId); +$failedIsoDeleteParent = CloudJob::findOrFail($failedIsoDeleteParentId); +$assert( + (int) Capsule::table('cloud_user_isos') + ->where('id', $failedIsoDeleteId) + ->value('active_job_id') === $failedIsoDeleteParentId + && (string) Capsule::table('cloud_user_isos') + ->where('id', $failedIsoDeleteId)->value('state') === 'active' + && (string) Capsule::table('cloud_user_iso_replicas') + ->where('user_iso_id', $failedIsoDeleteId) + ->value('state') === 'active' + && (string) $failedIsoDeleteParent->effect_resolution === 'not_applied' + && !(bool) $failedIsoDeleteParent->finalization_incident, + 'A zero pointer in ISO delete_failed state was not recovered.' +); + +// Two resources claiming the same immutable child are deliberately not +// guessed. The parent remains fenced and the task center gets an identity code. +$ambiguousParentId = $insertParent('template_import'); +$insertResolvedChild( + $ambiguousParentId, + 'applied', + 'template_import_replica' +); +$firstTemplateId = $insertProjectionForParent($ambiguousParentId); +$secondTemplateId = $firstTemplateId . '-duplicate'; +$firstTemplate = (array) Capsule::table('cloud_templates') + ->where('id', $firstTemplateId) + ->first(); +$firstTemplate['id'] = $secondTemplateId; +$firstTemplate['state'] = 'importing'; +$firstTemplate['active_job_id'] = null; +Capsule::table('cloud_templates')->insert($firstTemplate); +$firstReplica = (array) Capsule::table('cloud_template_replicas') + ->where('template_id', $firstTemplateId) + ->first(); +$firstReplica['template_id'] = $secondTemplateId; +Capsule::table('cloud_template_replicas')->insert($firstReplica); +Capsule::table('cloud_templates')->where('id', $firstTemplateId)->update([ + 'state' => 'importing', + 'active_job_id' => null, +]); +$runLegacySweep($ambiguousParentId); +$ambiguousParent = CloudJob::findOrFail($ambiguousParentId); +$ambiguousRecovery = CloudJobService::recoveryPresentation( + $ambiguousParent, + true +); +$assert( + (string) $ambiguousParent->effect_resolution === 'unknown' + && (bool) $ambiguousParent->finalization_incident + && (string) $ambiguousParent->finalization_error_code + === 'recovery_operation_identity_conflict' + && ($ambiguousRecovery['code'] ?? null) + === 'recovery_operation_identity_conflict' + && Capsule::table('cloud_templates') + ->whereIn('id', [$firstTemplateId, $secondTemplateId]) + ->whereNotNull('active_job_id') + ->count() === 0, + 'An ambiguous template pointer was guessed or not shown as an identity conflict.' +); + +// Already-published parents normally avoid the legacy sweep. A lost pointer +// plus an in-flight catalog state is an explicit exception: repair the unique +// pointer, then keep the contradictory projection fenced and visible. +$publishedTemplateParentId = $insertParent('template_import'); +$insertResolvedChild( + $publishedTemplateParentId, + 'applied', + 'template_import_replica' +); +$publishedTemplateId = $insertProjectionForParent( + $publishedTemplateParentId +); +Capsule::table('cloud_templates') + ->where('id', $publishedTemplateId) + ->update(['state' => 'importing', 'active_job_id' => null]); +Capsule::table('cloud_jobs')->where('id', $publishedTemplateParentId)->update([ + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'effect_resolved_at' => time(), + 'effect_resolution_reason' => 'normal_completion', + 'error_code' => null, + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +$runPublishedSweep($publishedTemplateParentId); +$publishedTemplateParent = CloudJob::findOrFail( + $publishedTemplateParentId +); +$assert( + (int) Capsule::table('cloud_templates') + ->where('id', $publishedTemplateId) + ->value('active_job_id') === $publishedTemplateParentId + && (string) Capsule::table('cloud_templates') + ->where('id', $publishedTemplateId) + ->value('state') === 'importing' + && (bool) $publishedTemplateParent->finalization_incident + && (string) $publishedTemplateParent->finalization_error_code + === 'recovery_instance_state_conflict' + && (CloudJobService::recoveryPresentation( + $publishedTemplateParent, + true + )['code'] ?? null) === 'recovery_instance_state_conflict', + 'A published template with a lost pointer stayed invisible or was falsely unlocked.' +); + +$publishedIsoParentId = $insertParent('user_iso_delete'); +$insertResolvedChild( + $publishedIsoParentId, + 'applied', + 'user_iso_delete_replica' +); +$publishedIsoId = $insertProjectionForParent($publishedIsoParentId); +Capsule::table('cloud_user_isos')->where('id', $publishedIsoId)->update([ + 'state' => 'deleting', + 'active_job_id' => 0, +]); +Capsule::table('cloud_jobs')->where('id', $publishedIsoParentId)->update([ + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'effect_resolved_at' => time(), + 'effect_resolution_reason' => 'normal_completion', + 'error_code' => null, + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +$runPublishedSweep($publishedIsoParentId); +$publishedIsoParent = CloudJob::findOrFail($publishedIsoParentId); +$assert( + (int) Capsule::table('cloud_user_isos') + ->where('id', $publishedIsoId) + ->value('active_job_id') === $publishedIsoParentId + && (string) Capsule::table('cloud_user_isos') + ->where('id', $publishedIsoId) + ->value('state') === 'deleting' + && (bool) $publishedIsoParent->finalization_incident + && (string) $publishedIsoParent->finalization_error_code + === 'recovery_instance_state_conflict' + && (CloudJobService::recoveryPresentation( + $publishedIsoParent, + true + )['code'] ?? null) === 'recovery_instance_state_conflict', + 'A published ISO with a lost pointer stayed invisible or was falsely unlocked.' +); + +// Metadata sync keeps the main template state active, so recovery needs an +// additional in-flight proof. A failed/unknown parent plus the exact current +// child/replica identity is sufficient and must still fence new mutations. +$metadataParentId = $insertParent('template_metadata_sync'); +$insertResolvedChild( + $metadataParentId, + 'applied', + 'template_metadata_replica' +); +$metadataTemplateId = $insertProjectionForParent($metadataParentId); +Capsule::table('cloud_templates') + ->where('id', $metadataTemplateId) + ->update(['active_job_id' => null]); +$metadataBoundary = new ReflectionMethod( + \App\Services\Cloud\CloudTemplateCatalogService::class, + 'activeJobSafelySettled' +); +$assert( + $metadataBoundary->invoke( + null, + \App\Models\CloudTemplate::findOrFail($metadataTemplateId), + true + ) === false, + 'A missing metadata pointer allowed a new overlapping template mutation.' +); +$assert( + Capsule::table('cloud_templates') + ->where('id', $metadataTemplateId) + ->whereNull('active_job_id') + ->exists(), + 'The mutation boundary repaired the pointer in reverse lock order.' +); +$runLegacySweep($metadataParentId); +$metadataParent = CloudJob::findOrFail($metadataParentId); +$assert( + (int) Capsule::table('cloud_templates') + ->where('id', $metadataTemplateId) + ->value('active_job_id') === $metadataParentId + && (string) Capsule::table('cloud_templates') + ->where('id', $metadataTemplateId) + ->value('state') === 'active' + && (string) $metadataParent->effect_resolution === 'applied' + && !(bool) $metadataParent->finalization_incident, + 'A uniquely proven metadata-sync pointer did not recover.' +); + +// A healthy, already-published metadata history with only active replicas is +// not evidence of an in-flight operation and must never be rebound by guess. +$healthyMetadataParentId = $insertParent('template_metadata_sync'); +$insertResolvedChild( + $healthyMetadataParentId, + 'applied', + 'template_metadata_replica' +); +$healthyMetadataTemplateId = $insertProjectionForParent( + $healthyMetadataParentId +); +Capsule::table('cloud_templates') + ->where('id', $healthyMetadataTemplateId) + ->update(['active_job_id' => null]); +Capsule::table('cloud_jobs')->where('id', $healthyMetadataParentId)->update([ + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'effect_resolved_at' => time(), + 'effect_resolution_reason' => 'normal_completion', + 'error_code' => null, + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, +]); +$parkOtherParents($healthyMetadataParentId); +$assert( + !CloudJobService::reconcileOneLegacyAggregateEffect(), + 'A healthy metadata history was incorrectly selected for pointer repair.' +); +$healthyRepairRejected = false; +try { + \App\Services\Cloud\CloudTemplateCatalogService:: + repairMissingParentBindingLocked( + CloudJob::findOrFail($healthyMetadataParentId) + ); +} catch (\App\Services\Cloud\CloudRecoveryInstanceStateConflict $error) { + $healthyRepairRejected = true; +} +$assert( + $healthyRepairRejected + && Capsule::table('cloud_templates') + ->where('id', $healthyMetadataTemplateId) + ->whereNull('active_job_id') + ->exists(), + 'A healthy metadata history was rebound without in-flight evidence.' +); +$assert( + $metadataBoundary->invoke( + null, + \App\Models\CloudTemplate::findOrFail($healthyMetadataTemplateId), + true + ) === true, + 'A healthy, fully settled metadata history permanently blocked mutations.' +); + +// The same pre-mutation fence applies to an ISO whose visible state was +// already changed back to active while its uniquely linked parent is still +// unresolved. This is the exact window before the parent-first sweep runs. +$isoBoundaryParentId = $insertParent('user_iso_import'); +$insertResolvedChild( + $isoBoundaryParentId, + 'applied', + 'user_iso_import_replica' +); +$isoBoundaryId = $insertProjectionForParent($isoBoundaryParentId); +Capsule::table('cloud_user_isos')->where('id', $isoBoundaryId)->update([ + 'state' => 'active', + 'active_job_id' => null, +]); +$isoBoundary = new ReflectionMethod( + \App\Services\Cloud\CloudUserIsoService::class, + 'activeJobSafelySettled' +); +$assert( + $isoBoundary->invoke( + null, + \App\Models\CloudUserIso::findOrFail($isoBoundaryId), + true + ) === false + && Capsule::table('cloud_user_isos') + ->where('id', $isoBoundaryId) + ->whereNull('active_job_id') + ->exists(), + 'A lost ISO pointer allowed a second mutation before recovery.' +); + +// Even with a failed/unknown parent, two current metadata resources remain an +// identity conflict. Neither pointer may be written. +$ambiguousMetadataParentId = $insertParent('template_metadata_sync'); +$insertResolvedChild( + $ambiguousMetadataParentId, + 'applied', + 'template_metadata_replica' +); +$firstMetadataId = $insertProjectionForParent($ambiguousMetadataParentId); +$secondMetadataId = $firstMetadataId . '-duplicate'; +$firstMetadata = (array) Capsule::table('cloud_templates') + ->where('id', $firstMetadataId) + ->first(); +$firstMetadata['id'] = $secondMetadataId; +$firstMetadata['active_job_id'] = null; +Capsule::table('cloud_templates')->insert($firstMetadata); +$firstMetadataReplica = (array) Capsule::table('cloud_template_replicas') + ->where('template_id', $firstMetadataId) + ->first(); +$firstMetadataReplica['template_id'] = $secondMetadataId; +Capsule::table('cloud_template_replicas')->insert($firstMetadataReplica); +Capsule::table('cloud_templates')->where('id', $firstMetadataId)->update([ + 'active_job_id' => null, +]); +$runLegacySweep($ambiguousMetadataParentId); +$ambiguousMetadataParent = CloudJob::findOrFail( + $ambiguousMetadataParentId +); +$assert( + (string) $ambiguousMetadataParent->effect_resolution === 'unknown' + && (bool) $ambiguousMetadataParent->finalization_incident + && (string) $ambiguousMetadataParent->finalization_error_code + === 'recovery_operation_identity_conflict' + && Capsule::table('cloud_templates') + ->whereIn('id', [$firstMetadataId, $secondMetadataId]) + ->whereNotNull('active_job_id') + ->count() === 0, + 'An ambiguous metadata-sync pointer was guessed or falsely released.' +); + +$publishParent = static function (int $parentId): void { + Capsule::table('cloud_jobs')->where('id', $parentId)->update([ + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'effect_resolved_at' => time(), + 'effect_resolution_reason' => 'normal_completion', + 'error_code' => null, + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); +}; + +// A quota-rejected import is a legitimate published failed/applied projection: +// its active replicas remain for explicit cleanup. A lost pointer must be +// repaired without turning that state into a generic incident. +$quotaIsoParentId = $insertParent('user_iso_import'); +$insertResolvedChild( + $quotaIsoParentId, + 'applied', + 'user_iso_import_replica' +); +$quotaIsoId = $insertProjectionForParent($quotaIsoParentId); +Capsule::table('cloud_user_isos')->where('id', $quotaIsoId)->update([ + 'active_job_id' => null, +]); +Capsule::table('cloud_jobs')->where('id', $quotaIsoParentId)->update([ + 'outcome' => 'failed', + 'status' => 'failed', + 'effect_may_have_applied' => 1, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'effect_resolved_at' => time(), + 'effect_resolution_reason' => 'normal_completion', + 'error_code' => 'user_iso_quota_exceeded', + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, +]); +$runPublishedSweep($quotaIsoParentId); +$quotaIsoParent = CloudJob::findOrFail($quotaIsoParentId); +$assert( + (int) Capsule::table('cloud_user_isos')->where('id', $quotaIsoId) + ->value('active_job_id') === $quotaIsoParentId + && (string) Capsule::table('cloud_user_isos')->where('id', $quotaIsoId) + ->value('state') === 'import_failed' + && (string) $quotaIsoParent->outcome === 'failed' + && (string) $quotaIsoParent->effect_resolution === 'applied' + && !(bool) $quotaIsoParent->finalization_incident + && $isoBoundary->invoke( + null, + \App\Models\CloudUserIso::findOrFail($quotaIsoId), + false + ) === true, + 'A settled quota cleanup projection was not uniquely rebound.' +); + +// A published not-applied delete may legitimately retain an older stale +// replica. It is already safe before pointer repair and remains strictly +// verifiable after the parent-first sweep restores the pointer. +$staleDeleteParentId = $insertParent('template_delete'); +$insertResolvedChild( + $staleDeleteParentId, + 'not_applied', + 'template_delete_replica' +); +$staleDeleteTemplateId = $insertProjectionForParent($staleDeleteParentId); +Capsule::table('cloud_templates')->where('id', $staleDeleteTemplateId)->update([ + 'state' => 'active', + 'active_job_id' => null, +]); +Capsule::table('cloud_template_replicas') + ->where('template_id', $staleDeleteTemplateId)->update([ + 'state' => 'stale', + 'revision' => 0, + ]); +Capsule::table('cloud_jobs')->where('id', $staleDeleteParentId)->update([ + 'outcome' => 'failed', + 'status' => 'failed', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 1, + 'effect_resolution' => 'not_applied', + 'effect_resolved_at' => time(), + 'effect_resolution_reason' => 'normal_completion', + 'error_code' => 'template_delete_not_applied', + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, +]); +$assert( + $metadataBoundary->invoke( + null, + \App\Models\CloudTemplate::findOrFail($staleDeleteTemplateId), + false + ) === true, + 'A valid not-applied delete with a stale replica stayed falsely fenced.' +); +$runPublishedSweep($staleDeleteParentId); +$staleDeleteParent = CloudJob::findOrFail($staleDeleteParentId); +$assert( + (int) Capsule::table('cloud_templates') + ->where('id', $staleDeleteTemplateId) + ->value('active_job_id') === $staleDeleteParentId + && (string) Capsule::table('cloud_template_replicas') + ->where('template_id', $staleDeleteTemplateId) + ->value('state') === 'stale' + && !(bool) $staleDeleteParent->finalization_incident, + 'A valid not-applied delete pointer was not repaired safely.' +); + +// Published healthy resources with a positive wrong pointer remain eligible +// for diagnosis, but the positive value is never overwritten automatically. +$publishedWrongTemplateParentId = $insertParent('template_import'); +$insertResolvedChild( + $publishedWrongTemplateParentId, + 'applied', + 'template_import_replica' +); +$publishedWrongTemplateId = $insertProjectionForParent( + $publishedWrongTemplateParentId +); +Capsule::table('cloud_templates') + ->where('id', $publishedWrongTemplateId)->update([ + 'state' => 'active', + 'active_job_id' => 999999991, + ]); +$publishParent($publishedWrongTemplateParentId); +$runPublishedSweep($publishedWrongTemplateParentId); +$publishedWrongTemplateParent = CloudJob::findOrFail( + $publishedWrongTemplateParentId +); +$assert( + (int) Capsule::table('cloud_templates') + ->where('id', $publishedWrongTemplateId) + ->value('active_job_id') === 999999991 + && (string) $publishedWrongTemplateParent->finalization_error_code + === 'recovery_operation_identity_conflict' + && (int) $publishedWrongTemplateParent->available_at >= time() + 290, + 'A published template positive pointer was overwritten or not queued.' +); + +$publishedWrongIsoParentId = $insertParent('user_iso_import'); +$insertResolvedChild( + $publishedWrongIsoParentId, + 'applied', + 'user_iso_import_replica' +); +$publishedWrongIsoId = $insertProjectionForParent($publishedWrongIsoParentId); +Capsule::table('cloud_user_isos') + ->where('id', $publishedWrongIsoId)->update([ + 'state' => 'active', + 'active_job_id' => 999999992, + ]); +$publishParent($publishedWrongIsoParentId); +$runPublishedSweep($publishedWrongIsoParentId); +$publishedWrongIsoParent = CloudJob::findOrFail($publishedWrongIsoParentId); +$assert( + (int) Capsule::table('cloud_user_isos') + ->where('id', $publishedWrongIsoId) + ->value('active_job_id') === 999999992 + && (string) $publishedWrongIsoParent->finalization_error_code + === 'recovery_operation_identity_conflict' + && (int) $publishedWrongIsoParent->available_at >= time() + 290, + 'A published ISO positive pointer was overwritten or not queued.' +); + +// Full content is part of the binding proof. A NULL pointer plus a matching +// identity chain must stay fenced and visible when bytes or hashes diverge. +$corruptTemplateParentId = $insertParent('template_import'); +$insertResolvedChild( + $corruptTemplateParentId, + 'applied', + 'template_import_replica' +); +$corruptTemplateId = $insertProjectionForParent($corruptTemplateParentId); +Capsule::table('cloud_templates')->where('id', $corruptTemplateId)->update([ + 'state' => 'active', + 'active_job_id' => null, +]); +Capsule::table('cloud_template_replicas') + ->where('template_id', $corruptTemplateId)->update([ + 'sha256' => str_repeat('f', 64), + ]); +$publishParent($corruptTemplateParentId); +$assert( + $metadataBoundary->invoke( + null, + \App\Models\CloudTemplate::findOrFail($corruptTemplateId), + false + ) === false, + 'A NULL template pointer with corrupt content falsely unlocked mutation.' +); +$runPublishedSweep($corruptTemplateParentId); +$corruptTemplateParent = CloudJob::findOrFail($corruptTemplateParentId); +$corruptTemplatePointer = Capsule::table('cloud_templates') + ->where('id', $corruptTemplateId)->value('active_job_id'); +$assert( + (int) $corruptTemplatePointer === $corruptTemplateParentId + && (string) $corruptTemplateParent->finalization_error_code + === 'recovery_instance_state_conflict', + 'Corrupt template content was unlocked or dropped from recovery: pointer=' + . var_export($corruptTemplatePointer, true) . ', code=' + . (string) $corruptTemplateParent->finalization_error_code +); + +$corruptIsoParentId = $insertParent('user_iso_import'); +$insertResolvedChild( + $corruptIsoParentId, + 'applied', + 'user_iso_import_replica' +); +$corruptIsoId = $insertProjectionForParent($corruptIsoParentId); +Capsule::table('cloud_user_isos')->where('id', $corruptIsoId)->update([ + 'state' => 'active', + 'active_job_id' => 0, +]); +Capsule::table('cloud_user_iso_replicas') + ->where('user_iso_id', $corruptIsoId)->update([ + 'size_bytes' => 8192, + ]); +$publishParent($corruptIsoParentId); +$assert( + $isoBoundary->invoke( + null, + \App\Models\CloudUserIso::findOrFail($corruptIsoId), + false + ) === false, + 'A zero ISO pointer with corrupt content falsely unlocked mutation.' +); +$runPublishedSweep($corruptIsoParentId); +$corruptIsoParent = CloudJob::findOrFail($corruptIsoParentId); +$assert( + (int) Capsule::table('cloud_user_isos')->where('id', $corruptIsoId) + ->value('active_job_id') === $corruptIsoParentId + && (string) $corruptIsoParent->finalization_error_code + === 'recovery_instance_state_conflict', + 'Corrupt ISO content was unlocked or dropped from recovery.' +); + +// The same child id cannot belong to both catalog domains. Cross-table reuse +// is an identity incident and may not authorize a NULL-pointer repair. +$crossTableTemplateParentId = $insertParent('template_import'); +$crossTableTemplateChildId = $insertResolvedChild( + $crossTableTemplateParentId, + 'applied', + 'template_import_replica' +); +$crossTableTemplateId = $insertProjectionForParent( + $crossTableTemplateParentId +); +Capsule::table('cloud_templates') + ->where('id', $crossTableTemplateId) + ->update(['active_job_id' => null]); +$crossTableTemplateChild = CloudJob::findOrFail($crossTableTemplateChildId); +Capsule::table('cloud_user_iso_replicas')->insert([ + 'host_id' => 800000 + $crossTableTemplateChildId, + 'user_iso_id' => md5('cross-table-iso:' . $crossTableTemplateChildId), + 'user_id' => 1, + 'state' => 'active', + 'size_bytes' => 4096, + 'sha256' => str_repeat('a', 64), + 'operation_id' => (string) $crossTableTemplateChild->operation_id, + 'job_id' => $crossTableTemplateChildId, + 'error_code' => '', + 'created_at' => time(), + 'updated_at' => time(), +]); +$runLegacySweep($crossTableTemplateParentId); +$crossTableTemplateParent = CloudJob::findOrFail( + $crossTableTemplateParentId +); +$assert( + Capsule::table('cloud_templates')->where('id', $crossTableTemplateId) + ->whereNull('active_job_id')->exists() + && (string) $crossTableTemplateParent->finalization_error_code + === 'recovery_operation_identity_conflict', + 'A template child duplicated in the ISO ledger repaired its pointer.' +); + +$crossTableIsoParentId = $insertParent('user_iso_import'); +$crossTableIsoChildId = $insertResolvedChild( + $crossTableIsoParentId, + 'applied', + 'user_iso_import_replica' +); +$crossTableIsoId = $insertProjectionForParent($crossTableIsoParentId); +Capsule::table('cloud_user_isos')->where('id', $crossTableIsoId)->update([ + 'active_job_id' => null, +]); +$crossTableIsoChild = CloudJob::findOrFail($crossTableIsoChildId); +Capsule::table('cloud_template_replicas')->insert([ + 'host_id' => 900000 + $crossTableIsoChildId, + 'template_id' => 'cross-table-template-' . $crossTableIsoChildId, + 'revision' => 1, + 'generation_token' => md5( + 'cross-table-template:' . $crossTableIsoChildId + ), + 'state' => 'active', + 'image_bytes' => 4096, + 'sha256' => str_repeat('b', 64), + 'operation_id' => (string) $crossTableIsoChild->operation_id, + 'job_id' => $crossTableIsoChildId, + 'error_code' => '', + 'created_at' => time(), + 'updated_at' => time(), +]); +$runLegacySweep($crossTableIsoParentId); +$crossTableIsoParent = CloudJob::findOrFail($crossTableIsoParentId); +$assert( + Capsule::table('cloud_user_isos')->where('id', $crossTableIsoId) + ->whereNull('active_job_id')->exists() + && (string) $crossTableIsoParent->finalization_error_code + === 'recovery_operation_identity_conflict', + 'An ISO child duplicated in the template ledger repaired its pointer.' +); + +// A unique positive pointer is not sufficient: swapping two otherwise valid +// parents must fail closed when their children and replicas belong elsewhere. +$crossTemplateParentA = $insertParent('template_metadata_sync'); +$insertResolvedChild( + $crossTemplateParentA, + 'applied', + 'template_metadata_replica' +); +$crossTemplateA = $insertProjectionForParent($crossTemplateParentA); +$publishParent($crossTemplateParentA); +$crossTemplateParentB = $insertParent('template_metadata_sync'); +$insertResolvedChild( + $crossTemplateParentB, + 'applied', + 'template_metadata_replica' +); +$crossTemplateB = $insertProjectionForParent($crossTemplateParentB); +$publishParent($crossTemplateParentB); +Capsule::table('cloud_templates')->where('id', $crossTemplateA)->update([ + 'active_job_id' => $crossTemplateParentB, +]); +Capsule::table('cloud_templates')->where('id', $crossTemplateB)->update([ + 'active_job_id' => $crossTemplateParentA, +]); +$assert( + $metadataBoundary->invoke( + null, + \App\Models\CloudTemplate::findOrFail($crossTemplateA), + false + ) === false + && $metadataBoundary->invoke( + null, + \App\Models\CloudTemplate::findOrFail($crossTemplateB), + false + ) === false, + 'Cross-wired template parents falsely unlocked both resources.' +); +$runPublishedSweep($crossTemplateParentA); +$runPublishedSweep($crossTemplateParentB); +$assert( + (int) Capsule::table('cloud_templates')->where('id', $crossTemplateA) + ->value('active_job_id') === $crossTemplateParentB + && (int) Capsule::table('cloud_templates')->where('id', $crossTemplateB) + ->value('active_job_id') === $crossTemplateParentA + && (string) CloudJob::findOrFail($crossTemplateParentA) + ->finalization_error_code === 'recovery_operation_identity_conflict' + && (string) CloudJob::findOrFail($crossTemplateParentB) + ->finalization_error_code === 'recovery_operation_identity_conflict', + 'Cross-wired template pointers were rewritten or removed from recovery.' +); + +$crossIsoParentA = $insertParent('user_iso_import'); +$insertResolvedChild( + $crossIsoParentA, + 'applied', + 'user_iso_import_replica' +); +$crossIsoA = $insertProjectionForParent($crossIsoParentA); +$publishParent($crossIsoParentA); +$crossIsoParentB = $insertParent('user_iso_import'); +$insertResolvedChild( + $crossIsoParentB, + 'applied', + 'user_iso_import_replica' +); +$crossIsoB = $insertProjectionForParent($crossIsoParentB); +$publishParent($crossIsoParentB); +Capsule::table('cloud_user_isos')->whereIn( + 'id', + [$crossIsoA, $crossIsoB] +)->update(['state' => 'active']); +Capsule::table('cloud_user_isos')->where('id', $crossIsoA)->update([ + 'active_job_id' => $crossIsoParentB, +]); +Capsule::table('cloud_user_isos')->where('id', $crossIsoB)->update([ + 'active_job_id' => $crossIsoParentA, +]); +$assert( + $isoBoundary->invoke( + null, + \App\Models\CloudUserIso::findOrFail($crossIsoA), + false + ) === false + && $isoBoundary->invoke( + null, + \App\Models\CloudUserIso::findOrFail($crossIsoB), + false + ) === false, + 'Cross-wired ISO parents falsely unlocked both resources.' +); +$runPublishedSweep($crossIsoParentA); +$runPublishedSweep($crossIsoParentB); +$assert( + (int) Capsule::table('cloud_user_isos')->where('id', $crossIsoA) + ->value('active_job_id') === $crossIsoParentB + && (int) Capsule::table('cloud_user_isos')->where('id', $crossIsoB) + ->value('active_job_id') === $crossIsoParentA + && (string) CloudJob::findOrFail($crossIsoParentA) + ->finalization_error_code === 'recovery_operation_identity_conflict' + && (string) CloudJob::findOrFail($crossIsoParentB) + ->finalization_error_code === 'recovery_operation_identity_conflict', + 'Cross-wired ISO pointers were rewritten or removed from recovery.' +); + +// Positive damage is never overwritten automatically. Even a unique replica +// chain only proves the expected parent; it cannot authorize replacing a +// positive pointer that may represent a separate damaged generation. +$danglingTemplateParentId = $insertParent('template_metadata_sync'); +$insertResolvedChild( + $danglingTemplateParentId, + 'applied', + 'template_metadata_replica' +); +$danglingTemplateId = $insertProjectionForParent( + $danglingTemplateParentId +); +Capsule::table('cloud_templates')->where('id', $danglingTemplateId)->update([ + 'active_job_id' => 999999999, +]); +$runLegacySweep($danglingTemplateParentId); +$danglingTemplateParent = CloudJob::findOrFail($danglingTemplateParentId); +$assert( + (int) Capsule::table('cloud_templates') + ->where('id', $danglingTemplateId) + ->value('active_job_id') === 999999999 + && (string) $danglingTemplateParent->effect_resolution === 'unknown' + && (bool) $danglingTemplateParent->finalization_incident + && (string) $danglingTemplateParent->finalization_error_code + === 'recovery_operation_identity_conflict' + && (int) $danglingTemplateParent->available_at >= time() + 290, + 'A positive dangling template pointer was overwritten or left invisible.' +); + +$wrongIsoParentId = $insertParent('user_iso_delete'); +$wrongIsoChildId = $insertResolvedChild( + $wrongIsoParentId, + 'applied', + 'user_iso_delete_replica' +); +$wrongIsoId = $insertProjectionForParent($wrongIsoParentId); +Capsule::table('cloud_user_isos')->where('id', $wrongIsoId)->update([ + 'state' => 'deleting', + 'active_job_id' => $wrongIsoChildId, +]); +$runLegacySweep($wrongIsoParentId); +$wrongIsoParent = CloudJob::findOrFail($wrongIsoParentId); +$assert( + (int) Capsule::table('cloud_user_isos') + ->where('id', $wrongIsoId) + ->value('active_job_id') === $wrongIsoChildId + && (string) $wrongIsoParent->effect_resolution === 'unknown' + && (bool) $wrongIsoParent->finalization_incident + && (string) $wrongIsoParent->finalization_error_code + === 'recovery_operation_identity_conflict' + && (int) $wrongIsoParent->available_at >= time() + 290, + 'An ISO pointer to a leaf job was overwritten or left invisible.' +); + +echo "Cloud catalog active-job pointer recovery checks passed.\n"; diff --git a/web/tests/CloudCatalogDispatchLedgerSafetyTest.php b/web/tests/CloudCatalogDispatchLedgerSafetyTest.php new file mode 100644 index 00000000..32cb9bba --- /dev/null +++ b/web/tests/CloudCatalogDispatchLedgerSafetyTest.php @@ -0,0 +1,585 @@ + false, + 1 => true, + 2 => true, + -1 => true, +] as $attempts => $mayHaveDispatched) { + $job = (object) ['dispatch_attempts' => $attempts]; + $assert( + CloudDispatchLedger::mayHaveDispatched($job) === $mayHaveDispatched, + 'The dispatch ledger did not treat only zero as proof of no dispatch.' + ); +} + +$capsule = new Capsule(); +$capsule->addConnection([ + 'driver' => 'sqlite', + 'database' => ':memory:', +], 'default'); +$capsule->setAsGlobal(); +$capsule->bootEloquent(); +$capsule->schema('default')->create( + 'cloud_jobs', + static function (Blueprint $table): void { + $table->increments('id'); + $table->string('operation_id')->default( + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + ); + $table->string('request_idempotency_key')->default( + 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' + ); + $table->string('request_fingerprint')->default( + 'cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc' + ); + $table->integer('parent_job_id')->nullable(); + $table->integer('order_id')->nullable(); + $table->integer('invoice_id')->nullable(); + $table->integer('instance_id')->nullable(); + $table->integer('snapshot_id')->nullable(); + $table->integer('user_id')->default(1); + $table->integer('host_id')->nullable(); + $table->string('kind')->default('template_import'); + $table->string('execution_mode')->default('aggregate'); + $table->integer('attempts')->default(0); + $table->integer('dispatch_attempts'); + $table->integer('dispatch_deadline_at')->default(1); + $table->integer('dispatch_started_at')->nullable(); + $table->integer('agent_accepted_at')->nullable(); + $table->integer('dispatched_at')->nullable(); + $table->integer('receipt_deadline_at')->nullable()->default(1); + $table->string('phase'); + $table->string('outcome')->nullable(); + $table->string('status')->default('succeeded'); + $table->integer('terminal_at')->nullable()->default(1); + $table->string('completion_event_id')->nullable(); + $table->boolean('effect_may_have_applied')->nullable(); + $table->boolean('safe_to_resubmit')->nullable(); + $table->string('effect_resolution'); + $table->string('error_code')->nullable(); + $table->text('result_json')->nullable(); + $table->boolean('finalization_incident')->default(0); + $table->string('finalization_error_code')->nullable(); + } +); + +$agentEnvelope = [ + 'host_id' => 7, + 'attempts' => 1, + 'dispatch_deadline_at' => 1, + 'dispatch_started_at' => 1, + 'agent_accepted_at' => 1, + 'dispatched_at' => 1, + 'receipt_deadline_at' => 1, + 'terminal_at' => 1, +]; +$capsule->schema('default')->create( + 'cloud_templates', + static function (Blueprint $table): void { + $table->string('id')->primary(); + $table->integer('active_job_id')->nullable(); + } +); +$capsule->schema('default')->create( + 'cloud_user_isos', + static function (Blueprint $table): void { + $table->string('id')->primary(); + $table->integer('user_id'); + $table->integer('active_job_id')->nullable(); + } +); + +foreach ([ + [1, 0, 'terminal', 'succeeded', 'applied'], + [2, 1, 'terminal', 'succeeded', 'applied'], + [3, 2, 'terminal', 'succeeded', 'applied'], + [4, -1, 'terminal', 'succeeded', 'applied'], + [5, 1, 'awaiting_receipt', null, 'unknown'], +] as [$id, $attempts, $phase, $outcome, $resolution]) { + Capsule::table('cloud_jobs')->insert([ + 'id' => $id, + 'parent_job_id' => null, + 'dispatch_attempts' => $attempts, + 'phase' => $phase, + 'outcome' => $outcome, + 'status' => $outcome ?? 'running', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => $resolution, + ]); +} +foreach ([1, 2] as $parentId) { + Capsule::table('cloud_jobs')->insert([ + ...$agentEnvelope, + 'id' => 100 + $parentId, + 'parent_job_id' => $parentId, + 'user_id' => 1, + 'kind' => 'template_import_replica', + 'execution_mode' => 'agent', + 'dispatch_attempts' => 1, + 'phase' => 'terminal', + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'finalization_incident' => 0, + 'finalization_error_code' => null, + ]); +} +foreach ([ + [201, 0, 'terminal', 'succeeded', 'applied'], + [202, 1, 'terminal', 'succeeded', 'applied'], + [203, 2, 'terminal', 'succeeded', 'applied'], + [204, -1, 'terminal', 'succeeded', 'applied'], + [205, 1, 'awaiting_receipt', null, 'unknown'], +] as [$id, $attempts, $phase, $outcome, $resolution]) { + Capsule::table('cloud_jobs')->insert([ + 'id' => $id, + 'parent_job_id' => null, + 'user_id' => 1, + 'kind' => 'user_iso_import', + 'execution_mode' => 'aggregate', + 'dispatch_attempts' => $attempts, + 'phase' => $phase, + 'outcome' => $outcome, + 'status' => $outcome ?? 'running', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => $resolution, + 'finalization_incident' => 0, + 'finalization_error_code' => null, + ]); +} +foreach ([201, 202] as $parentId) { + Capsule::table('cloud_jobs')->insert([ + ...$agentEnvelope, + 'id' => 100 + $parentId, + 'parent_job_id' => $parentId, + 'user_id' => 1, + 'kind' => 'user_iso_import_replica', + 'execution_mode' => 'agent', + 'dispatch_attempts' => 1, + 'phase' => 'terminal', + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'finalization_incident' => 0, + 'finalization_error_code' => null, + ]); +} + +$invokeBoundary = static function ( + string $service, + object $resource, + bool $shouldBlock +) use ($assert): void { + $method = new ReflectionMethod($service, 'assertMutationBoundaryLocked'); + $jobId = (int) ($resource->active_job_id ?? 0); + $parent = $jobId > 0 ? CloudJob::find($jobId) : null; + $validKinds = $service === CloudTemplateCatalogService::class + ? ['template_import', 'template_metadata_sync', 'template_delete'] + : ['user_iso_import', 'user_iso_delete']; + if ($parent === null + || (string) $parent->execution_mode !== 'aggregate' + || $parent->parent_job_id !== null + || !in_array((string) $parent->kind, $validKinds, true)) { + $parent = null; + } + try { + $method->invoke(null, $resource, $parent); + } catch (CloudError $error) { + $assert($shouldBlock && $error->httpStatus === 409, + $service . ' rejected a valid settled job boundary.'); + return; + } + $assert(!$shouldBlock, + $service . ' released an unsafe prior job boundary.'); +}; + +// This focused fixture intentionally has no replica tables. Exercise the +// parent/child dispatch-ledger predicate directly; full catalog projection +// ownership is covered by CloudCatalogActiveJobPointerRecoveryTest. +$parentSafelySettled = static function ( + string $service, + object $resource, + int $jobId +): bool { + $method = new ReflectionMethod($service, 'aggregateParentSafelySettled'); + $parent = CloudJob::find($jobId); + if ($parent === null) { + return false; + } + return $service === CloudTemplateCatalogService::class + ? $method->invoke(null, $parent, false) + : $method->invoke(null, $resource, $parent, false); +}; + +foreach ([ + 1 => false, + 2 => true, + 3 => true, + 4 => true, + 5 => true, + 999 => true, +] as $jobId => $shouldBlock) { + $template = new CloudTemplate(); + $template->active_job_id = $jobId; + $assert( + $parentSafelySettled( + CloudTemplateCatalogService::class, + $template, + $jobId + ) === !$shouldBlock, + 'The template aggregate dispatch ledger boundary was misclassified.' + ); +} + +foreach ([ + 201 => false, + 202 => true, + 203 => true, + 204 => true, + 205 => true, + 999 => true, +] as $jobId => $shouldBlock) { + $iso = new CloudUserIso(); + $iso->active_job_id = $jobId; + $iso->user_id = 1; + $assert( + $parentSafelySettled( + CloudUserIsoService::class, + $iso, + $jobId + ) === !$shouldBlock, + 'The ISO aggregate dispatch ledger boundary was misclassified.' + ); +} + +// A fail-open aggregate parent may already say succeeded/applied while one of +// its Agent children still needs recovery. Both template and ISO mutation +// boundaries must follow the child fence rather than trusting the parent row. +Capsule::table('cloud_jobs')->insert([ + 'id' => 6, + 'parent_job_id' => null, + 'user_id' => 1, + 'kind' => 'template_import', + 'execution_mode' => 'aggregate', + 'dispatch_attempts' => 0, + 'phase' => 'terminal', + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +Capsule::table('cloud_jobs')->insert([ + ...$agentEnvelope, + 'id' => 106, + 'parent_job_id' => 6, + 'user_id' => 1, + 'kind' => 'template_import_replica', + 'execution_mode' => 'agent', + 'dispatch_attempts' => 2, + 'phase' => 'terminal', + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +Capsule::table('cloud_jobs')->insert([ + 'id' => 206, + 'parent_job_id' => null, + 'user_id' => 1, + 'kind' => 'user_iso_import', + 'execution_mode' => 'aggregate', + 'dispatch_attempts' => 0, + 'phase' => 'terminal', + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +Capsule::table('cloud_jobs')->insert([ + ...$agentEnvelope, + 'id' => 306, + 'parent_job_id' => 206, + 'user_id' => 1, + 'kind' => 'user_iso_import_replica', + 'execution_mode' => 'agent', + 'dispatch_attempts' => 2, + 'phase' => 'terminal', + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +$failOpenTemplate = new CloudTemplate(); +$failOpenTemplate->active_job_id = 6; +$failOpenIso = new CloudUserIso(); +$failOpenIso->active_job_id = 206; +$failOpenIso->user_id = 1; +$assertBothBoundaries = static function (bool $shouldBlock) use ( + $assert, + $parentSafelySettled, + $failOpenTemplate, + $failOpenIso +): void { + $assert( + $parentSafelySettled( + CloudTemplateCatalogService::class, + $failOpenTemplate, + 6 + ) === !$shouldBlock, + 'The template child dispatch ledger boundary was misclassified.' + ); + $assert( + $parentSafelySettled( + CloudUserIsoService::class, + $failOpenIso, + 206 + ) === !$shouldBlock, + 'The ISO child dispatch ledger boundary was misclassified.' + ); +}; +$assertBothBoundaries(true); +Capsule::table('cloud_jobs')->whereIn('id', [106, 306])->update([ + 'dispatch_attempts' => 1, + 'finalization_incident' => 1, + 'finalization_error_code' => 'recovery_dispatch_ledger_conflict', +]); +$assertBothBoundaries(true); +Capsule::table('cloud_jobs')->whereIn('id', [106, 306])->update([ + 'dispatch_attempts' => 0, + 'outcome' => 'failed', + 'status' => 'failed', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'not_applied', + 'finalization_incident' => 1, + 'finalization_error_code' => 'recovery_ledger_conflict', +]); +$assertBothBoundaries(true); +Capsule::table('cloud_jobs')->whereIn('id', [106, 306])->update([ + 'dispatch_attempts' => 1, + 'effect_may_have_applied' => 1, + 'effect_resolution' => 'unknown', + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +$assertBothBoundaries(true); +Capsule::table('cloud_jobs')->whereIn('id', [106, 306])->update([ + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', +]); +$assertBothBoundaries(false); + +// A settled-looking row is not a valid catalog boundary unless its active job +// is the exact aggregate root for that resource type and identity, and exactly +// one main record owns that job. +foreach ([ + [20, 'user_iso_import', 1], + [21, 'user_iso_import', 2], + [22, 'template_import', 1], + [23, 'user_iso_import', 1], +] as [$id, $kind, $userId]) { + Capsule::table('cloud_jobs')->insert([ + 'id' => $id, + 'parent_job_id' => null, + 'user_id' => $userId, + 'kind' => $kind, + 'execution_mode' => 'aggregate', + 'dispatch_attempts' => 0, + 'phase' => 'terminal', + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'effect_may_have_applied' => 1, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'finalization_incident' => 0, + 'finalization_error_code' => null, + ]); +} +Capsule::table('cloud_templates')->insert([ + ['id' => 'wrong-kind-template', 'active_job_id' => 20], + ['id' => 'duplicate-template-a', 'active_job_id' => 22], + ['id' => 'duplicate-template-b', 'active_job_id' => 22], +]); +Capsule::table('cloud_user_isos')->insert([ + ['id' => 'cross-user-iso', 'user_id' => 1, 'active_job_id' => 21], + ['id' => 'duplicate-iso-a', 'user_id' => 1, 'active_job_id' => 23], + ['id' => 'duplicate-iso-b', 'user_id' => 1, 'active_job_id' => 23], +]); +$invokeBoundary( + CloudTemplateCatalogService::class, + CloudTemplate::findOrFail('wrong-kind-template'), + true +); +$invokeBoundary( + CloudUserIsoService::class, + CloudUserIso::findOrFail('cross-user-iso'), + true +); +foreach (['duplicate-template-a', 'duplicate-template-b'] as $id) { + $invokeBoundary( + CloudTemplateCatalogService::class, + CloudTemplate::findOrFail($id), + true + ); +} +foreach (['duplicate-iso-a', 'duplicate-iso-b'] as $id) { + $invokeBoundary( + CloudUserIsoService::class, + CloudUserIso::findOrFail($id), + true + ); +} + +// The current receipt is still nonterminal while its catalog projection is +// finalized. It is the sole allowed exception; sibling and current ledger +// corruption remain blockers. +Capsule::table('cloud_jobs')->insert([ + 'id' => 7, + 'parent_job_id' => null, + 'user_id' => 1, + 'kind' => 'template_import', + 'execution_mode' => 'aggregate', + 'dispatch_attempts' => 0, + 'phase' => 'awaiting_receipt', + 'outcome' => null, + 'status' => 'running', + 'effect_may_have_applied' => null, + 'safe_to_resubmit' => null, + 'effect_resolution' => 'not_applicable', + 'terminal_at' => null, + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +Capsule::table('cloud_jobs')->insert([ + array_replace($agentEnvelope, [ + 'id' => 107, + 'parent_job_id' => 7, + 'user_id' => 1, + 'kind' => 'template_import_replica', + 'execution_mode' => 'agent', + 'dispatch_attempts' => 1, + 'phase' => 'awaiting_receipt', + 'outcome' => null, + 'status' => 'running', + 'effect_may_have_applied' => null, + 'safe_to_resubmit' => null, + 'effect_resolution' => 'not_applicable', + 'terminal_at' => null, + 'finalization_incident' => 0, + 'finalization_error_code' => null, + ]), + array_replace($agentEnvelope, [ + 'id' => 108, + 'parent_job_id' => 7, + 'user_id' => 1, + 'kind' => 'template_import_replica', + 'execution_mode' => 'agent', + 'dispatch_attempts' => 1, + 'phase' => 'terminal', + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'finalization_incident' => 0, + 'finalization_error_code' => null, + ]), +]); +$settlingParent = CloudJob::findOrFail(7); +$assert( + !CloudJobService::aggregateParentRecoveryPending( + $settlingParent, + 107 + ) + && CloudJobService::aggregateParentRecoveryPending($settlingParent), + 'The normal completing child exception was not scoped to that child.' +); +Capsule::table('cloud_jobs')->where('id', 107)->update([ + 'dispatch_attempts' => 2, +]); +$assert(CloudJobService::aggregateParentRecoveryPending( + $settlingParent, + 107 +), 'A corrupt currently completing child bypassed the aggregate gate.'); + +$root = dirname(__DIR__); +$templateSource = file_get_contents( + $root . '/app/Services/Cloud/CloudTemplateCatalogService.php' +); +$isoSource = file_get_contents( + $root . '/app/Services/Cloud/CloudUserIsoService.php' +); +$rescueImportSource = file_get_contents( + $root . '/app/Services/Cloud/CloudRescueTemplateImportService.php' +); +$rescueDeleteSource = file_get_contents( + $root . '/app/Services/Cloud/CloudRescueTemplateDeletionService.php' +); + +$assert(substr_count( + $templateSource, + 'CloudDispatchLedger::mayHaveDispatched($child)' +) === 1 && substr_count( + $isoSource, + 'CloudDispatchLedger::mayHaveDispatched($child)' +) === 1, + 'A catalog aggregate can still classify a corrupt child as undispatched.'); +$assert(substr_count( + $isoSource, + 'self::assertMutationBoundaryLocked(' +) >= 2, + 'ISO import does not reuse the unresolved-child mutation boundary.'); +$assert(str_contains($rescueImportSource, + 'CloudDispatchLedger::isInvalid($job)') + && str_contains($rescueImportSource, + 'CloudJobService::hasResolvedTerminalStateConflict($job)') + && str_contains($rescueDeleteSource, + 'CloudDispatchLedger::isInvalid($job)') + && str_contains($rescueDeleteSource, + 'CloudJobService::hasResolvedTerminalStateConflict($job)') + && str_contains($rescueDeleteSource, + '$priorJobId = (int) ($catalog->job_id ?? 0)'), + 'A rescue-template history boundary can release a corrupt prior job.'); + +echo "Catalog dispatch-ledger safety checks passed.\n"; diff --git a/web/tests/CloudCatalogLockOrderContractTest.php b/web/tests/CloudCatalogLockOrderContractTest.php new file mode 100644 index 00000000..135c0a58 --- /dev/null +++ b/web/tests/CloudCatalogLockOrderContractTest.php @@ -0,0 +1,191 @@ +parent_job_id ?? 0);', + 'private static function throwInvalidSettingsResult(' +); +$assert($ordered($finish, [ + "CloudJob::where('id', \$aggregateParentId)", + 'CloudTemplateCatalogService::lockAggregateCatalogLocked(', + 'CloudUserIsoService::lockAggregateCatalogLocked(', + "CloudJob::where('id', \$claimed->id)", + 'CloudTemplateCatalogService::finishJobLocked(', +]), 'Worker completion does not lock parent, catalog, child, replica in order.'); + +foreach (['commitApplied', 'commitNotApplied'] as $name) { + $commit = $method( + $recovery, + 'public static function ' . $name . '(', + $name === 'commitApplied' + ? 'public static function prepareNotApplied(' + : 'private static function assertResolvedBy(' + ); + $assert($ordered($commit, [ + '$aggregateParent = CloudJob::where(', + '$aggregateParentId', + 'CloudTemplateCatalogService::lockAggregateCatalogLocked(', + 'CloudUserIsoService::lockAggregateCatalogLocked(', + "CloudJob::where('id', \$jobId)", + ]), $name . ' takes a child lock before its catalog lock.'); +} + +$automaticCommit = $method( + $automatic, + 'private static function resolveFenceAndCommit(', + 'private static function assertFreshInspection(' +); +$assert($ordered($automaticCommit, [ + '$aggregateParent = CloudJob::where(', + '$aggregateParentId', + 'CloudTemplateCatalogService::lockAggregateCatalogLocked(', + 'CloudUserIsoService::lockAggregateCatalogLocked(', + "\$aggregateChildren = CloudJob::where(", + "'parent_job_id',", + '$aggregateParentId', +]), 'Automatic fence commit locks the child before its catalog.'); + +$aggregateCommit = $method( + $jobs, + 'public static function reconcileAggregateParentEffectLocked(', + 'private static function wherePublishedAggregateNeedsRecheck(' +); +$assert($ordered($aggregateCommit, [ + "CloudJob::where('id', \$parentId)", + 'CloudTemplateCatalogService::lockAggregateCatalogLocked(', + 'CloudUserIsoService::lockAggregateCatalogLocked(', + "\$children = CloudJob::where('parent_job_id', \$parentId)", +]), 'Aggregate recovery commit locks children before the catalog.'); + +$legacy = $method( + $jobs, + 'public static function reconcileOneLegacyAggregateEffect(): bool', + 'private static function aggregateRelationshipConflict(' +); +$assert($ordered($legacy, [ + '->lockForUpdate()', + 'CloudTemplateCatalogService::lockAggregateCatalogLocked(', + 'CloudUserIsoService::lockAggregateCatalogLocked(', + '$children = CloudJob::where(', + "'parent_job_id',", +]), 'Legacy aggregate sweep locks children before the catalog.'); + +$templateMutation = $method( + $templates, + 'private static function lockTemplateForMutation(', + 'private static function assertMutationBoundaryLocked(' +); +$isoMutation = $method( + $isos, + 'private static function lockIsoForMutation(', + 'private static function assertMutationBoundaryLocked(' +); +$assert($ordered($templateMutation, [ + '$parentSnapshot = $jobId > 0', + 'self::isTemplateAggregateParent($parentSnapshot)', + "? CloudJob::where('id', \$jobId)", + "->where('execution_mode', 'aggregate')", + "->whereNull('parent_job_id')", + '->lockForUpdate()->first()', + '$template = CloudTemplate::query()', + '->lockForUpdate()->first();', + 'self::assertMutationBoundaryLocked(', +]), 'Template mutation still locks the catalog before its prior parent.'); +$assert($ordered($isoMutation, [ + '$parentSnapshot = $jobId > 0', + 'self::isIsoAggregateParent($parentSnapshot)', + "? CloudJob::where('id', \$jobId)", + "->where('execution_mode', 'aggregate')", + "->whereNull('parent_job_id')", + '->lockForUpdate()->first()', + '$iso = CloudUserIso::query()', + '->lockForUpdate()->first();', + 'self::assertMutationBoundaryLocked(', +]), 'ISO mutation still locks the catalog before its prior parent.'); + +$isoImportMutation = $method( + $isos, + 'private static function lockIsoRowsForImport(', + 'private static function assertMutationBoundaryLocked(' +); +$assert($ordered($isoImportMutation, [ + '$parentSnapshots =', + '$parentIds =', + 'self::isIsoAggregateParent($job)', + '$parents =', + "->where('execution_mode', 'aggregate')", + "->whereNull('parent_job_id')", + "->orderBy('id')->lockForUpdate()->get()->keyBy('id')", + '$rows = CloudUserIso::query()', + '->lockForUpdate()->get();', +]), 'ISO import locks an invalid pointer or locks catalogs before parents.'); + +$templateDelete = $method( + $templates, + 'public static function delete(', + 'public static function finishJobLocked(' +); +$assert($ordered($templateDelete, [ + 'self::assertNoOrderReferencesLocked($id);', + 'self::lockTemplateForMutation($id);', + 'self::assertNoJobReferencesLocked($id);', +]), 'Template deletion locks its catalog before pending orders.'); + +echo "Cloud catalog lock-order contract checks passed.\n"; diff --git a/web/tests/CloudFinancialWorkflowTest.php b/web/tests/CloudFinancialWorkflowTest.php index ef3038bf..14957b0b 100644 --- a/web/tests/CloudFinancialWorkflowTest.php +++ b/web/tests/CloudFinancialWorkflowTest.php @@ -2,10 +2,21 @@ // Financial/state-machine tests only. The isolated keyring double is NOT encryption and is never loaded by production. namespace App\Services { final class Config { - public static array $values = ['super_admin' => '99']; + public static array $values = [ + 'super_admin' => '99', + 'baseUrl' => 'https://panel.example.test', + 'appName' => 'Virt Cloud Test', + ]; public static function get($name, $default = null) { return self::$values[$name] ?? $default; } } final class Auth { public static $user; public static function getUser() { return self::$user; } } + final class Mail { + public static array $sent = []; + public static function send(...$arguments): bool { + self::$sent[] = $arguments; + return true; + } + } } namespace App\Services\Cloud { final class CloudSecrets { @@ -38,16 +49,21 @@ namespace { use App\Models\CloudRegion; use App\Models\CloudResourcePool; use App\Models\CloudResourceReservation; + use App\Models\CloudServicePeriod; use App\Models\CloudTemplate; use App\Services\Cloud\CloudInvoiceService; use App\Services\Cloud\CloudInvoicePaymentService; use App\Services\Cloud\CloudAdminOperationsService; + use App\Services\Cloud\CloudAutomaticOperationRecoveryService; use App\Services\Cloud\CloudOrderService; use App\Services\Cloud\CloudWorkerService; use App\Services\Cloud\CloudAgentClient; use App\Services\Cloud\CloudAccess; use App\Services\Cloud\CloudJobService; + use App\Services\Cloud\CloudLifecycleService; use App\Services\Cloud\CloudOperationCompletionService; + use App\Services\Cloud\CloudOperationRecoveryIdentity; + use App\Services\Cloud\CloudRenewalService; use App\Services\Cloud\CloudError; use App\Services\Cloud\CloudMoney; use App\Services\Cloud\CloudPlatformTestNetworkPolicy; @@ -166,8 +182,9 @@ namespace { $schema->create('cloud_host_capacity_policies', function (Blueprint $t) { $t->integer('host_id')->primary(); foreach (['configured_cpu_cores', 'configured_memory_mib', 'configured_disk_gib', 'safety_cpu_cores', 'safety_memory_mib', 'safety_disk_gib', 'max_instances', 'created_at', 'updated_at'] as $v) { $t->integer($v)->default(0); } }); $schema->create('cloud_public_ips', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->integer('public_ip_pool_id')->nullable(); $t->string('address')->unique(); $t->integer('prefix_length'); $t->string('state'); $t->integer('reservation_id')->nullable()->unique(); $t->integer('instance_id')->nullable(); $t->string('operation_id')->nullable()->unique(); $t->integer('created_at'); $t->integer('updated_at'); }); $schema->create('cloud_offers', function (Blueprint $t) { $t->increments('id'); $t->integer('plan_id'); $t->integer('resource_pool_id'); $t->string('code')->unique(); $t->string('name'); $t->string('price'); $t->string('currency')->default('USD'); $t->integer('price_version')->default(1); $t->integer('revision')->default(1); $t->integer('status')->default(1); $t->integer('stock')->default(-1); $t->integer('sort')->default(0); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['plan_id', 'resource_pool_id']); }); - $schema->create('cloud_templates', function (Blueprint $t) { $t->string('id')->primary(); $t->string('name'); $t->string('os_family'); $t->string('os_version'); $t->string('source_type'); $t->text('sealed_source_url'); $t->integer('image_bytes'); $t->string('sha256'); $t->text('startup_script'); $t->integer('revision'); $t->string('generation_token'); $t->string('state'); $t->integer('created_at'); $t->integer('updated_at'); }); - $schema->create('cloud_template_replicas', function (Blueprint $t) { $t->integer('host_id'); $t->string('template_id'); $t->integer('revision'); $t->string('generation_token'); $t->string('state')->default('pending'); $t->integer('image_bytes')->default(0); $t->string('sha256')->default(''); $t->string('operation_id')->default(''); $t->string('error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); $t->primary(['host_id', 'template_id']); }); + $schema->create('cloud_templates', function (Blueprint $t) { $t->string('id')->primary(); $t->string('name'); $t->string('os_family'); $t->string('os_version'); $t->string('source_type'); $t->text('sealed_source_url'); $t->integer('image_bytes'); $t->string('sha256'); $t->text('startup_script'); $t->integer('revision'); $t->string('generation_token'); $t->string('state'); $t->integer('active_job_id')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); }); + $schema->create('cloud_user_isos', function (Blueprint $t) { $t->string('id')->primary(); $t->integer('active_job_id')->nullable(); }); + $schema->create('cloud_template_replicas', function (Blueprint $t) { $t->integer('host_id'); $t->string('template_id'); $t->integer('job_id')->nullable(); $t->integer('revision'); $t->string('generation_token'); $t->string('state')->default('pending'); $t->integer('image_bytes')->default(0); $t->string('sha256')->default(''); $t->string('operation_id')->default(''); $t->string('error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); $t->primary(['host_id', 'template_id']); }); $schema->create('cloud_platform_test_policy_state', function (Blueprint $t) { $t->integer('id')->primary(); $t->integer('revision')->default(0); $t->integer('updated_by')->nullable(); $t->integer('updated_at')->default(0); }); $schema->create('cloud_platform_test_policy_rules', function (Blueprint $t) { $t->increments('id'); $t->string('rule_key', 32)->unique(); $t->string('service', 120); $t->string('protocol', 8); $t->integer('port_from'); $t->integer('port_to'); $t->string('direction', 8); $t->string('reason', 500); $t->integer('created_by'); $t->integer('updated_by'); $t->integer('deleted_by')->nullable(); $t->integer('deleted_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); }); $schema->create('cloud_orders', function (Blueprint $t) { $t->increments('id'); foreach (['user_id', 'plan_id', 'offer_id', 'resource_pool_id'] as $v) { $t->integer($v); } $t->integer('host_id')->nullable(); $t->integer('reservation_id')->nullable()->unique(); $t->string('idempotency_key'); $t->string('request_hash'); $t->string('amount'); $t->string('currency')->default('USD'); $t->string('status'); $t->text('spec_json'); $t->text('sealed_payload')->nullable(); $t->integer('instance_id')->nullable(); $t->integer('refunded_at')->nullable(); $t->integer('stock_reserved_at')->nullable(); $t->integer('stock_released_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['user_id', 'idempotency_key']); }); @@ -233,6 +250,7 @@ namespace { }); $schema->create('cloud_instances', function (Blueprint $t) { $t->increments('id'); foreach (['host_id', 'user_id'] as $v) { $t->integer($v); } foreach (['order_id', 'plan_id', 'offer_id', 'resource_pool_id', 'reservation_id', 'current_period_id', 'expires_at', 'suspended_at', 'network_suspended_at'] as $v) { $t->integer($v)->nullable(); } foreach (['renewal_days', 'renewal_traffic_bytes', 'traffic_quota_bytes', 'traffic_download_bytes', 'traffic_upload_bytes', 'lifetime_download_bytes', 'lifetime_upload_bytes', 'traffic_synced_at'] as $v) { $t->integer($v)->default(0); } $t->string('renewal_price')->nullable(); $t->string('uuid'); $t->string('name'); $t->string('status'); $t->string('service_status')->default('exempt'); $t->string('network_status')->default('active'); $t->text('spec_json'); $t->text('sealed_credential')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); $t->unique(['host_id', 'uuid']); }); $schema->create('cloud_instance_snapshots', function (Blueprint $t) { $t->increments('id'); $t->string('snapshot_key')->unique(); foreach (['instance_id', 'user_id', 'host_id'] as $v) { $t->integer($v); } $t->string('name'); $t->string('state'); $t->string('consistency'); $t->integer('size_bytes')->nullable(); $t->string('last_operation_id')->nullable(); foreach (['ready_at', 'last_restored_at', 'deleted_at'] as $v) { $t->integer($v)->nullable(); } $t->integer('created_at'); $t->integer('updated_at'); }); + $schema->create('cloud_renewals', function (Blueprint $t) { $t->increments('id'); $t->integer('instance_id'); $t->integer('user_id'); $t->integer('plan_id')->nullable(); $t->integer('period_id')->nullable(); $t->string('idempotency_key'); $t->string('request_hash'); $t->string('amount'); $t->integer('validity_days'); $t->integer('traffic_bytes_added'); $t->integer('previous_expires_at'); $t->integer('new_expires_at'); $t->integer('created_at'); $t->unique(['user_id', 'idempotency_key']); }); $schema->create('cloud_service_periods', function (Blueprint $t) { $t->increments('id'); foreach (['instance_id', 'user_id'] as $v) { $t->integer($v); } foreach (['plan_id', 'order_id', 'renewal_id', 'download_base_bytes', 'upload_base_bytes', 'activated_at'] as $v) { $t->integer($v)->nullable(); } foreach (['starts_at', 'ends_at', 'traffic_quota_bytes', 'download_used_bytes', 'upload_used_bytes', 'created_at', 'updated_at'] as $v) { $t->integer($v)->default(0); } $t->string('status'); $t->unique('order_id'); $t->unique('renewal_id'); }); $schema->create('cloud_invoices', function (Blueprint $t) { $t->increments('id'); $t->string('invoice_no')->unique(); $t->string('purpose')->default('renewal'); $t->integer('instance_id')->nullable(); $t->integer('order_id')->nullable()->unique(); $t->integer('user_id'); $t->integer('plan_id')->nullable(); $t->integer('offer_id')->nullable(); $t->integer('renewal_id')->nullable(); $t->integer('renews_expires_at')->nullable(); $t->integer('due_at'); $t->string('amount'); $t->string('currency')->default('USD'); $t->integer('validity_days'); $t->integer('traffic_quota_bytes'); $t->string('status'); $t->string('paid_via')->nullable(); $t->string('payment_reference')->nullable(); $t->integer('paid_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); }); $schema->create('cloud_invoice_payments', function (Blueprint $t) { $t->increments('id'); $t->integer('invoice_id'); $t->integer('user_id'); $t->string('provider'); $t->string('provider_order_no'); $t->string('idempotency_key'); $t->string('amount'); $t->string('status'); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['provider', 'provider_order_no']); $t->unique(['user_id', 'idempotency_key']); }); @@ -241,7 +259,7 @@ namespace { $capsule->connection('default')->table( 'cloud_platform_test_policy_state' )->insert(['id' => 1, 'revision' => 0, 'updated_by' => null, 'updated_at' => 0]); - $user = new User(); $user->id = 1; $user->money = '0.00'; $user->enable = 1; $user->is_admin = false; $user->save(); $user->isLogin = true; + $user = new User(); $user->id = 1; $user->user_name = 'financial-owner'; $user->email = 'owner@example.test'; $user->money = '0.00'; $user->enable = 1; $user->is_admin = false; $user->save(); $user->isLogin = true; \App\Services\Auth::$user = $user; $now = time(); $region = new CloudRegion(); $region->code = 'test-region'; $region->name = 'Test Region'; $region->country_code = 'US'; $region->status = 'active'; $region->sort = 0; $region->created_at = $region->updated_at = $now; $region->save(); @@ -326,6 +344,19 @@ namespace { 'created_at' => $now, 'updated_at' => $now, ]); + $capsule->connection('default')->table('cloud_template_replicas')->insert([ + 'host_id' => $host->id, + 'template_id' => $reinstallTemplate->id, + 'revision' => $reinstallTemplate->revision, + 'generation_token' => $reinstallTemplate->generation_token, + 'state' => 'active', + 'image_bytes' => $reinstallTemplate->image_bytes, + 'sha256' => $reinstallTemplate->sha256, + 'operation_id' => 'fixture-reinstall-template-import', + 'error_code' => '', + 'created_at' => $now, + 'updated_at' => $now, + ]); $actor = ['user_id' => 1, 'is_admin' => false, 'is_super_admin' => false, 'can_manage' => false, 'session_id' => '']; $input = ['offer_id' => 1, 'source' => 'cloud', 'name' => 'vm-one', 'template_id' => 'alma10-1234abcd-0123456789abcdef', 'idempotency_key' => 'test-request-key-0001']; $catalogConnection = Capsule::connection('default'); @@ -547,8 +578,12 @@ namespace { $changedPlan->disk_gib = 20; $changedPlan->save(); $history = []; + $openingIdentity = CloudOperationRecoveryIdentity::expected( + $openingJob, + true + ); $createdVm = [ - 'uuid' => '11111111-1111-4111-8111-111111111111', + 'uuid' => $openingIdentity['resource_id'], 'name' => '1:vm-111111111111', 'vcpu' => 2, 'memory_mib' => 2048, @@ -570,6 +605,7 @@ namespace { new Response(200, [], json_encode([ 'operation_id' => $openingJob->operation_id, 'status' => 'succeeded', 'result' => $createdVm, + ...$openingIdentity, ])), ]); $stack = HandlerStack::create($mock); $stack->push(Middleware::history($history)); @@ -808,12 +844,271 @@ namespace { && CloudOffer::find(1)->stock === 9, 'A prior Agent fence commit was not recovered into one atomic local create settlement.'); + // A completion may be durably accepted before PHP finishes the create + // ledgers. Keep the encrypted request escrow while the effect is unknown, + // then let the exact same authenticated receipt atomically materialize the + // instance and ACK its event after the local ledger fault is repaired. + $lateCreate = CloudOrderService::purchase(array_replace($input, [ + 'name' => 'vm-late-create', + 'idempotency_key' => 'test-request-key-late-create', + ]), $actor); + $lateInvoice = CloudInvoice::where('order_id', $lateCreate->id)->first(); + CloudInvoiceService::payBalance( + $lateInvoice, + $actor, + 'provision-balance-late-create' + ); + $lateCreateJob = CloudJob::where('order_id', $lateCreate->id)->first(); + $lateCreateIdentity = CloudOperationRecoveryIdentity::expected( + $lateCreateJob, + true + ); + $lateCreatePayload = \App\Services\Cloud\CloudSecrets::decrypt( + (string) $lateCreateJob->sealed_payload, + 'job-payload' + ); + $mock->append(new Response(202, [], json_encode([ + 'operation_id' => $lateCreateJob->operation_id, + 'status' => 'reserved', + ...$lateCreateIdentity, + 'replayed' => false, + 'retryable' => false, + ]))); + $worker->tick(); + $lateCreateJob->refresh(); + $assert((string) $lateCreateJob->phase === 'awaiting_receipt', + 'Late-create fixture did not cross the Agent dispatch boundary.'); + + $lateOrder = CloudOrder::find($lateCreate->id); + $lateOrderSpec = json_decode( + (string) $lateOrder->spec_json, + true, + 64, + JSON_THROW_ON_ERROR + ); + $damagedLateOrderSpec = $lateOrderSpec; + unset($damagedLateOrderSpec['validity_days']); + $lateOrder->spec_json = json_encode( + $damagedLateOrderSpec, + JSON_THROW_ON_ERROR + ); + $lateOrder->save(); + $lateReceiptId = 'create-late-success-event-0001'; + $lateCreatedVm = array_replace($createdVm, [ + 'uuid' => $lateCreateIdentity['resource_id'], + 'name' => '1:vm-late-create', + 'public_ip_cidr' => $lateCreatePayload['body']['public_ip_cidr'], + 'public_pool_key' => $lateCreatePayload['body']['public_pool_key'], + ]); + unset($lateCreatedVm['generated_password']); + $lateReceipt = [ + 'type' => 'completion', + 'id' => $lateReceiptId, + 'agent_id' => (string) $lateCreateJob->host_id, + 'operation_id' => (string) $lateCreateJob->operation_id, + ...$lateCreateIdentity, + 'status' => 'succeeded', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'error_code' => '', + 'result' => $lateCreatedVm, + ]; + $firstLateReceipt = CloudOperationCompletionService::accept($lateReceipt); + $lateCreateJob->refresh(); + $lateEscrow = \App\Services\Cloud\CloudSecrets::decrypt( + (string) $lateCreateJob->sealed_payload, + 'job-payload' + ); + $lateEvent = \App\Models\CloudAgentCompletionEvent::where( + 'event_id', + $lateReceiptId + )->first(); + $assert($firstLateReceipt === [ + 'accepted' => true, + 'disposition' => 'received', + ] + && (string) $lateCreateJob->phase === 'terminal' + && (string) $lateCreateJob->outcome === 'failed' + && (string) $lateCreateJob->effect_resolution === 'unknown' + && ($lateEscrow['credential']['password'] ?? null) + === ($lateEscrow['body']['root_password'] ?? null) + && (string) $lateEvent->disposition === 'received' + && CloudInstance::where('order_id', $lateCreate->id)->count() === 0, + 'A failed local create finalizer lost its exact receipt or encrypted recovery escrow.'); + + $lateWalletBeforeManualResolution = (string) User::find(1)->money; + $lateReservationBeforeManualResolution = CloudResourceReservation::where( + 'order_id', + $lateCreate->id + )->first(); + try { + \App\Services\Cloud\CloudCreateFailureFinalizer::resolveNotApplied( + (int) $lateCreateJob->id, + (string) $lateCreateJob->operation_id, + 99, + 'contradictory-manual-absence', + [ + 'operation_id' => (string) $lateCreateJob->operation_id, + 'outcome' => 'failed', + 'summary_code' => 'operation_failed', + 'error_code' => 'creation_absent', + ], + time() + ); + throw new RuntimeException( + 'Manual no-effect resolution ignored a durable create success.' + ); + } catch (CloudError $error) { + $assert($error->httpStatus === 409, + 'Create success/manual absence conflict returned wrong status.'); + } + $assert((string) User::find(1)->money + === $lateWalletBeforeManualResolution + && (string) CloudOrder::find($lateCreate->id)->status === 'failed' + && (string) CloudInvoice::where('order_id', $lateCreate->id) + ->value('status') === 'paid' + && (string) CloudResourceReservation::find( + $lateReservationBeforeManualResolution->id + )->state === (string) $lateReservationBeforeManualResolution->state, + 'Conflicting manual absence resolution refunded or released a create.'); + + $lateOrder->spec_json = json_encode( + $lateOrderSpec, + JSON_THROW_ON_ERROR + ); + $lateOrder->save(); + $makeLateCreateRetryable = static function () use ( + $lateCreateJob + ): void { + Capsule::table('cloud_jobs')->where( + 'id', + (int) $lateCreateJob->id + )->update([ + 'available_at' => 0, + 'lease_token' => null, + 'lease_until' => 0, + ]); + }; + $assertLateCreateStillPending = static function ( + string $message + ) use ($assert, $lateCreate, $lateReceiptId): void { + $assert((string) \App\Models\CloudAgentCompletionEvent::where( + 'event_id', + $lateReceiptId + )->value('disposition') === 'received' + && CloudInstance::where('order_id', $lateCreate->id)->count() === 0, + $message); + }; + + $lateInvoice->purpose = 'renewal'; + $lateInvoice->save(); + $makeLateCreateRetryable(); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'Wrong-purpose create invoice was not retried safely.'); + $assertLateCreateStillPending( + 'A wrong-purpose invoice allowed late create materialisation or ACK.' + ); + + $lateInvoice->purpose = 'provision'; + $lateInvoice->status = 'refunded'; + $lateInvoice->save(); + $makeLateCreateRetryable(); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'Refunded create invoice was not retried safely.'); + $assertLateCreateStillPending( + 'A refunded invoice allowed late create materialisation or ACK.' + ); + + $lateInvoice->status = 'paid'; + $lateInvoice->save(); + $lateInvoiceRow = (array) Capsule::table('cloud_invoices') + ->where('id', (int) $lateInvoice->id)->first(); + Capsule::table('cloud_invoices')->where( + 'id', + (int) $lateInvoice->id + )->delete(); + $makeLateCreateRetryable(); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'Missing create invoice was not retried safely.'); + $assertLateCreateStillPending( + 'A missing invoice allowed late create materialisation or ACK.' + ); + Capsule::table('cloud_invoices')->insert($lateInvoiceRow); + $lateInvoice = CloudInvoice::findOrFail((int) $lateInvoice->id); + $makeLateCreateRetryable(); + $lateRecoveryTick = (new CloudAutomaticOperationRecoveryService())->tick(); + // The Agent may already have stopped retransmitting after the panel + // durably accepted the event. The recovery worker must consume that same + // stored receipt; a later duplicate is only an idempotent ACK check. + $secondLateReceipt = CloudOperationCompletionService::accept($lateReceipt); + $lateCreateJob->refresh(); + $lateOrder->refresh(); + $lateInvoice->refresh(); + $lateInstance = CloudInstance::where('order_id', $lateCreate->id)->first(); + $lateReservation = CloudResourceReservation::where( + 'order_id', + $lateCreate->id + )->first(); + $latePeriod = \App\Models\CloudServicePeriod::where( + 'order_id', + $lateCreate->id + )->first(); + $lateCredential = $lateInstance === null ? null + : \App\Services\Cloud\CloudSecrets::decrypt( + (string) $lateInstance->sealed_credential, + 'instance-credential' + ); + $lateEvent->refresh(); + $lateFinalPayload = \App\Services\Cloud\CloudSecrets::decrypt( + (string) $lateCreateJob->sealed_payload, + 'job-payload' + ); + $lateInvoiceDisplay = CloudInvoiceService::display($lateInvoice); + $lateTaskDisplay = CloudJobService::display($lateCreateJob); + $assert($lateRecoveryTick + && $secondLateReceipt === [ + 'accepted' => true, + 'disposition' => 'applied', + ] + && $lateInstance !== null + && (string) $lateCreateJob->phase === 'terminal' + && (string) $lateCreateJob->outcome === 'failed' + && (string) $lateCreateJob->status === 'failed' + && (string) $lateCreateJob->effect_resolution === 'applied' + && (string) $lateCreateJob->effect_resolution_reason + === 'late_completion_receipt:' . $lateReceiptId + && (string) $lateEvent->disposition === 'applied' + && $lateEvent->applied_at !== null + && (string) $lateOrder->status === 'succeeded' + && (int) $lateOrder->instance_id === (int) $lateInstance->id + && (int) $lateInvoice->instance_id === (int) $lateInstance->id + && (string) $lateReservation->state === 'committed' + && $latePeriod !== null + && (string) $latePeriod->status === 'active' + && (int) $latePeriod->instance_id === (int) $lateInstance->id + && (int) $lateInstance->current_period_id === (int) $latePeriod->id + && $lateCredential === $lateCreatePayload['credential'] + && !array_key_exists('credential', $lateFinalPayload) + && !array_key_exists('root_password', $lateFinalPayload['body'] ?? []) + && ($lateInvoiceDisplay['job_status'] ?? null) === 'succeeded' + && ($lateInvoiceDisplay['fulfillment_status'] ?? null) === 'succeeded' + && ($lateTaskDisplay['status'] ?? null) === 'failed' + && ($lateTaskDisplay['effect_resolution'] ?? null) === 'applied', + 'The exact late create receipt did not atomically converge PHP ledgers and public fulfillment state.'); + $assert(CloudInvoiceService::deliverReminders(20) >= 1 + && (string) CloudMailOutbox::where( + 'invoice_id', + $lateInvoice->id + )->where('kind', 'provision_succeeded')->value('status') === 'sent', + 'Recovered create success was cancelled instead of delivering its provision notice.'); + $actionJob = CloudJobService::enqueue($instance, $actor, 'action', 'POST', '/actions', ['action' => 'reboot']); $mock->append(new Response(200, [], json_encode([ 'operation_id' => $actionJob->operation_id, 'status' => 'succeeded', + ...CloudOperationRecoveryIdentity::expected($actionJob, true), 'result' => [ - 'uuid' => '11111111-1111-4111-8111-111111111111', + 'uuid' => (string) $instance->uuid, 'state' => 'running', ], ]))); $worker->tick(); @@ -837,6 +1132,7 @@ namespace { $mock->append(new Response(200, [], json_encode([ 'operation_id' => $poweroffJob->operation_id, 'status' => 'succeeded', + ...CloudOperationRecoveryIdentity::expected($poweroffJob, true), 'result' => [ 'uuid' => (string) $instance->uuid, 'state' => 'stopped', @@ -861,6 +1157,7 @@ namespace { $mock->append(new Response(200, [], json_encode([ 'operation_id' => $diagnosticJob->operation_id, 'status' => 'failed', + ...CloudOperationRecoveryIdentity::expected($diagnosticJob), 'cause_code' => 'domain_start_failed', 'error' => [ 'code' => 'libvirt_error', @@ -1083,6 +1380,10 @@ namespace { $mock->append(new Response(200, [], json_encode([ 'operation_id' => $expiredNetworkJob->operation_id, 'status' => 'succeeded', + ...CloudOperationRecoveryIdentity::expected( + $expiredNetworkJob, + true + ), 'result' => ['network_suspended' => true], ]))); $worker->tick(); @@ -1100,6 +1401,7 @@ namespace { $mock->append(new Response(200, [], json_encode([ 'operation_id' => $purgeStopJob->operation_id, 'status' => 'succeeded', + ...CloudOperationRecoveryIdentity::expected($purgeStopJob, true), 'result' => ['service_was_running' => true], ]))); $worker->tick(); @@ -1120,7 +1422,10 @@ namespace { $mock->append(new Response(409, [], json_encode([ 'operation_id' => $purgeStopFailedJob->operation_id, 'status' => 'failed', + ...CloudOperationRecoveryIdentity::expected($purgeStopFailedJob), 'error' => ['code' => 'conflict', 'message' => 'shutdown rejected'], + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => true, 'replayed' => false, 'retryable' => false, ]))); @@ -1141,6 +1446,7 @@ namespace { $mock->append(new Response(409, [], json_encode([ 'operation_id' => $purgeForcePrior->operation_id, 'status' => 'failed', + ...CloudOperationRecoveryIdentity::expected($purgeForcePrior), 'error' => ['code' => 'force_required'], 'replayed' => false, 'retryable' => false, @@ -1166,6 +1472,7 @@ namespace { $mock->append(new Response(200, [], json_encode([ 'operation_id' => $purgeForceJob->operation_id, 'status' => 'succeeded', + ...CloudOperationRecoveryIdentity::expected($purgeForceJob, true), 'result' => [ 'deleted' => true, 'managed_artifacts_absent' => true, 'forced' => true, @@ -1199,6 +1506,7 @@ namespace { $mock->append(new Response(200, [], json_encode([ 'operation_id' => $expiryDeleteJob->operation_id, 'status' => 'succeeded', + ...CloudOperationRecoveryIdentity::expected($expiryDeleteJob, true), 'result' => [ 'deleted' => true, 'managed_artifacts_absent' => true, @@ -1288,10 +1596,13 @@ namespace { $mock->append(new Response(409, [], json_encode([ 'operation_id' => $expiryDeleteFailedJob->operation_id, 'status' => 'failed', + ...CloudOperationRecoveryIdentity::expected($expiryDeleteFailedJob), 'error' => [ 'code' => 'conflict', 'message' => 'volume delete rejected before undefine', ], + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => true, 'replayed' => false, 'retryable' => false, ]))); @@ -1312,7 +1623,7 @@ namespace { && (int) $expiryDeleteFailedJob->dispatch_attempts === 1, 'Terminal expiry failure was automatically looked up, reconciled, or mutation-retried.'); - $reinstall = CloudJobService::enqueue($instance, $actor, 'reinstall', 'POST', '/reinstall', ['template_id' => $reinstallTemplate->id, 'confirmation_name' => $instance->name, 'root_password' => 'NewStrongPassword!123'], ['password' => 'NewStrongPassword!123', 'login_name' => 'root']); + $reinstall = CloudJobService::enqueue($instance, $actor, 'reinstall', 'POST', '/reinstall', ['template_id' => $reinstallTemplate->id, 'confirmation_name' => $instance->name, 'root_password' => 'NewStrongPassword!123'], ['password' => 'NewStrongPassword!123', 'login_name' => 'root', 'auth_mode' => 'password']); $oldCredential = $instance->sealed_credential; $queuedReinstall = \App\Services\Cloud\CloudSecrets::decrypt( (string) $reinstall->sealed_payload, 'job-payload' @@ -1332,6 +1643,7 @@ namespace { $mock->append(new Response(202, [], json_encode([ 'operation_id' => $reinstall->operation_id, 'status' => 'reserved', + ...CloudOperationRecoveryIdentity::expected($reinstall), 'replayed' => false, 'retryable' => false, ]))); $worker->tick(); @@ -1357,12 +1669,13 @@ namespace { 'id' => bin2hex(random_bytes(16)), 'agent_id' => (string) $instance->host_id, 'operation_id' => $reinstall->operation_id, + ...CloudOperationRecoveryIdentity::expected($reinstall, true), 'status' => 'succeeded', 'effect_may_have_applied' => false, 'safe_to_resubmit' => false, 'error_code' => '', 'result' => [ - 'generated_password' => 'never-public', + 'state' => 'running', ], ]); $reinstalled = $instance->fresh(); @@ -1373,7 +1686,6 @@ namespace { && count($history) === $beforeReinstallReceipt && CloudJob::find($reinstall->id)->status === 'succeeded' && $reinstalled->sealed_credential !== $oldCredential - && !str_contains(CloudJob::find($reinstall->id)->result_json, 'never-public') && ($reinstalledSpec['template_id'] ?? null) === $reinstallTemplate->id && ($reinstalledSpec['public_ip_cidr'] ?? null) === '203.0.113.18/28' && ($reinstalledSpec['os_source'] ?? null) === 'cloud_template' @@ -1393,10 +1705,12 @@ namespace { 'template_id' => $input['template_id'], 'confirmation_name' => $instance->name, 'root_password' => 'PartialStrongPassword!123', - ], ['password' => 'PartialStrongPassword!123', 'login_name' => 'root']); + ], ['password' => 'PartialStrongPassword!123', 'login_name' => 'root', + 'auth_mode' => 'password']); $mock->append(new Response(202, [], json_encode([ 'operation_id' => $partialReinstall->operation_id, 'status' => 'reserved', + ...CloudOperationRecoveryIdentity::expected($partialReinstall), 'replayed' => false, 'retryable' => false, ]))); @@ -1407,6 +1721,10 @@ namespace { 'id' => bin2hex(random_bytes(16)), 'agent_id' => (string) $instance->host_id, 'operation_id' => $partialReinstall->operation_id, + ...CloudOperationRecoveryIdentity::expected( + $partialReinstall, + true + ), 'status' => 'succeeded', 'effect_may_have_applied' => false, 'safe_to_resubmit' => false, @@ -1420,7 +1738,7 @@ namespace { ]); $partialJob = CloudJob::find($partialReinstall->id); $assert($partialReceipt === ['accepted' => true, - 'disposition' => 'applied'] + 'disposition' => 'received'] && count($history) === $beforePartialReceipt && $partialJob->phase === 'terminal' && $partialJob->outcome === 'failed' @@ -1430,7 +1748,7 @@ namespace { && (bool) $partialJob->safe_to_resubmit === false && $instance->fresh()->sealed_credential === $reinstalled->sealed_credential, - 'Cleanup-pending reinstall did not become a terminal fenced failure.'); + 'Cleanup-pending reinstall was acknowledged or did not become a terminal fenced failure.'); $beforePartialRetry = count($history); $worker->tick(); $assert(count($history) === $beforePartialRetry @@ -1545,6 +1863,7 @@ namespace { $mock->append(new Response(202, [], json_encode([ 'operation_id' => $networkChange->operation_id, 'status' => 'reserved', 'replayed' => false, 'retryable' => false, + ...CloudOperationRecoveryIdentity::expected($networkChange), ]))); $worker->tick(); $networkRequest = $agentRequest($history[$beforeNetwork]); @@ -1570,6 +1889,7 @@ namespace { 'id' => bin2hex(random_bytes(16)), 'agent_id' => (string) $instance->host_id, 'operation_id' => $networkChange->operation_id, + ...CloudOperationRecoveryIdentity::expected($networkChange, true), 'status' => 'succeeded', 'effect_may_have_applied' => false, 'safe_to_resubmit' => false, @@ -1609,6 +1929,7 @@ namespace { ]); $mock->append(new Response(422, [], json_encode([ 'operation_id' => $failedNetwork->operation_id, 'status' => 'failed', + ...CloudOperationRecoveryIdentity::expected($failedNetwork), 'error' => ['code' => 'invalid_request', 'message' => 'network change rejected'], 'effect_may_have_applied' => false, @@ -1638,6 +1959,7 @@ namespace { $mock->append(new Response(422, [], json_encode([ 'operation_id' => $interruptedDelete->operation_id, 'status' => 'failed', + ...CloudOperationRecoveryIdentity::expected($interruptedDelete), 'error' => ['code' => 'graceful_shutdown_unconfirmed'], 'effect_may_have_applied' => false, 'safe_to_resubmit' => true, @@ -1659,6 +1981,7 @@ namespace { $mock->append(new Response(409, [], json_encode([ 'operation_id' => $delete->operation_id, 'status' => 'failed', + ...CloudOperationRecoveryIdentity::expected($delete), 'error' => ['code' => 'force_required'], 'replayed' => false, 'retryable' => false, @@ -1683,6 +2006,7 @@ namespace { $mock->append(new Response(422, [], json_encode([ 'operation_id' => $failedForceDelete->operation_id, 'status' => 'failed', + ...CloudOperationRecoveryIdentity::expected($failedForceDelete), 'error' => ['code' => 'invalid_request'], 'effect_may_have_applied' => false, 'safe_to_resubmit' => true, @@ -1705,8 +2029,9 @@ namespace { $mock->append(new Response(200, [], json_encode([ 'operation_id' => $forceDelete->operation_id, 'status' => 'succeeded', + ...CloudOperationRecoveryIdentity::expected($forceDelete, true), 'result' => [ - 'uuid' => '11111111-1111-4111-8111-111111111111', + 'uuid' => (string) $instance->uuid, 'deleted' => true, 'managed_artifacts_absent' => true, 'forced' => true, @@ -1823,5 +2148,727 @@ namespace { && CloudJob::where('order_id', $providerOrder->id)->count() === 1, 'A repeated paid callback duplicated or retried its durable create task.'); + // A definitively not-applied lifecycle failure starts a new audited + // generation after backoff. The failed job and its operation ID remain + // immutable; unknown, applied, or sticky failures remain fail-closed. + $lifecycle = new CloudLifecycleService(); + $reconcile = (new ReflectionClass(CloudLifecycleService::class)) + ->getMethod('reconcile'); + $oldPurgeOperation = (string) $purgeStopFailedJob->operation_id; + $purgeCount = CloudJob::where('instance_id', $purgeStopFailed->id) + ->where('kind', 'service_suspend')->count(); + $assert($reconcile->invoke($lifecycle, (int) $purgeStopFailed->id) === false + && CloudJob::where('instance_id', $purgeStopFailed->id) + ->where('kind', 'service_suspend')->count() === $purgeCount, + 'Lifecycle policy failure ignored the mandatory retry backoff.'); + Capsule::table('cloud_jobs')->where('id', $purgeStopFailedJob->id) + ->update(['terminal_at' => time() - 310, 'updated_at' => time() - 310]); + $assert($reconcile->invoke($lifecycle, (int) $purgeStopFailed->id) === true, + 'A definitively not-applied purge stop did not create a new generation: ' + . json_encode($purgeStopFailedJob->fresh()->toArray(), + JSON_THROW_ON_ERROR)); + $purgeRetry = CloudJob::where('instance_id', $purgeStopFailed->id) + ->where('kind', 'service_suspend')->orderByDesc('id')->first(); + $assert($purgeRetry !== null + && (int) $purgeRetry->id !== (int) $purgeStopFailedJob->id + && (string) $purgeRetry->operation_id !== $oldPurgeOperation + && (string) $purgeStopFailedJob->fresh()->operation_id + === $oldPurgeOperation + && (string) $purgeStopFailedJob->fresh()->phase === 'terminal' + && (string) $purgeStopFailed->fresh()->service_status + === 'purge_stopping', + 'Purge retry replayed or rewrote the failed generation.'); + + $oldDeleteOperation = (string) $expiryDeleteFailedJob->operation_id; + Capsule::table('cloud_jobs')->where('id', $expiryDeleteFailedJob->id) + ->update(['terminal_at' => time() - 310, 'updated_at' => time() - 310]); + $assert($reconcile->invoke($lifecycle, (int) $expiryDeleteFailed->id) === true, + 'A definitively not-applied expiry delete did not create a new generation.'); + $deleteRetry = CloudJob::where('instance_id', $expiryDeleteFailed->id) + ->where('kind', 'expiry_delete')->orderByDesc('id')->first(); + $assert($deleteRetry !== null + && (int) $deleteRetry->id !== (int) $expiryDeleteFailedJob->id + && (string) $deleteRetry->operation_id !== $oldDeleteOperation + && (string) $expiryDeleteFailedJob->fresh()->operation_id + === $oldDeleteOperation + && (string) $expiryDeleteFailedJob->fresh()->phase === 'terminal' + && (string) $expiryDeleteFailed->fresh()->status === 'deleting' + && (string) $expiryDeleteFailed->fresh()->service_status + === 'purge_deleting', + 'Expiry-delete retry replayed or rewrote the failed generation.'); + + $finalizeUndispatchedFailure = static function ( + CloudJob $job + ): CloudJob { + $past = time() - 310; + $job->attempts = 0; + $job->dispatch_attempts = 0; + $job->dispatch_started_at = null; + $job->agent_accepted_at = null; + $job->dispatched_at = null; + $job->receipt_deadline_at = null; + $job->completion_event_id = null; + $job->phase = 'terminal'; + $job->outcome = 'failed'; + $job->status = 'failed'; + $job->terminal_at = $past; + $job->effect_may_have_applied = 0; + $job->safe_to_resubmit = 1; + $job->effect_resolution = 'not_applied'; + $job->error_code = 'dispatch_not_sent'; + $job->finalization_incident = 0; + $job->finalization_error_code = null; + $job->updated_at = $past; + $job->save(); + return $job; + }; + $undispatchedDelete = $makeLifecycleInstance( + '90909090-9090-4090-8090-909090909090', + 'undispatched-delete-vm', + 'purge_deleting', + 'blocked_expired' + ); + $undispatchedDelete->status = 'deleting'; + $undispatchedDelete->save(); + $oldUndispatchedDelete = $finalizeUndispatchedFailure( + CloudJobService::enqueueExpiryDelete($undispatchedDelete) + ); + $undispatchedDelete->status = 'delete_failed'; + $undispatchedDelete->service_status = 'purge_failed'; + $undispatchedDelete->save(); + $assert($reconcile->invoke( + $lifecycle, + (int) $undispatchedDelete->id + ) === true, 'A generation-zero expiry failure did not create a safe new generation.'); + $undispatchedDeleteRetry = CloudJob::where( + 'instance_id', + $undispatchedDelete->id + )->where('kind', 'expiry_delete')->orderByDesc('id')->first(); + $assert($undispatchedDeleteRetry !== null + && (int) $undispatchedDeleteRetry->id + !== (int) $oldUndispatchedDelete->id + && (string) $undispatchedDeleteRetry->operation_id + !== (string) $oldUndispatchedDelete->operation_id + && (int) $oldUndispatchedDelete->fresh()->dispatch_attempts === 0, + 'Generation-zero expiry retry replayed or rewrote the prior operation.'); + + $undispatchedPurgeStop = $makeLifecycleInstance( + '97979797-9797-4797-8797-979797979797', + 'undispatched-purge-stop-vm', + 'purge_stopping', + 'blocked_expired' + ); + $undispatchedPurgeStop->status = 'deleting'; + $undispatchedPurgeStop->save(); + $oldUndispatchedPurgeStop = $finalizeUndispatchedFailure($queuePolicy( + $undispatchedPurgeStop, + 'service_suspend', + 'service/suspend', + 'purge' + )); + $undispatchedPurgeStop->service_status = 'purge_stop_failed'; + $undispatchedPurgeStop->save(); + $assert($reconcile->invoke( + $lifecycle, + (int) $undispatchedPurgeStop->id + ) === true, 'A generation-zero purge stop did not create a safe new generation.'); + $undispatchedPurgeStopRetry = CloudJob::where( + 'instance_id', + $undispatchedPurgeStop->id + )->where('kind', 'service_suspend')->orderByDesc('id')->first(); + $assert($undispatchedPurgeStopRetry !== null + && (int) $undispatchedPurgeStopRetry->id + !== (int) $oldUndispatchedPurgeStop->id + && (string) $undispatchedPurgeStopRetry->operation_id + !== (string) $oldUndispatchedPurgeStop->operation_id + && (int) $oldUndispatchedPurgeStop->fresh()->dispatch_attempts === 0 + && (string) $undispatchedPurgeStop->fresh()->service_status + === 'purge_stopping', + 'Generation-zero purge-stop retry replayed or rewrote the prior operation.'); + + $preparePolicyFailure = static function ( + CloudInstance $target, + string $kind, + string $suffix, + ?string $reason + ) use ($queuePolicy): CloudJob { + $job = $queuePolicy($target, $kind, $suffix, $reason); + $identity = CloudOperationRecoveryIdentity::expected($job); + $past = time() - 310; + $job->request_fingerprint = $identity['request_fingerprint']; + $job->attempts = 1; + $job->dispatch_attempts = 1; + $job->dispatch_started_at = $past - 30; + $job->agent_accepted_at = $past - 20; + $job->dispatched_at = $past - 20; + $job->receipt_deadline_at = $past - 10; + $job->phase = 'terminal'; + $job->outcome = 'failed'; + $job->status = 'failed'; + $job->terminal_at = $past; + $job->effect_may_have_applied = 0; + $job->safe_to_resubmit = 1; + $job->effect_resolution = 'not_applied'; + $job->error_code = 'operation_failed'; + $job->finalization_incident = 0; + $job->finalization_error_code = null; + $job->updated_at = $past; + $job->save(); + return $job; + }; + $setPolicyResolution = static function ( + CloudJob $job, + string $resolution, + bool $incident = false + ): CloudJob { + if ($resolution === 'applied') { + $job->outcome = 'succeeded'; + $job->status = 'succeeded'; + $job->effect_may_have_applied = 0; + $job->safe_to_resubmit = 0; + $job->error_code = null; + } elseif ($resolution === 'unknown') { + $job->outcome = 'failed'; + $job->status = 'failed'; + $job->effect_may_have_applied = 1; + $job->safe_to_resubmit = 0; + $job->error_code = 'operation_failed_effect_unknown'; + } + $job->effect_resolution = $resolution; + $job->finalization_incident = $incident ? 1 : 0; + $job->finalization_error_code = $incident + ? 'recovery_ledger_conflict' : null; + $job->save(); + return $job; + }; + $insertScheduledPeriod = static function ( + CloudInstance $target + ): int { + $now = time(); + return (int) Capsule::table('cloud_service_periods')->insertGetId([ + 'instance_id' => $target->id, + 'user_id' => $target->user_id, + 'plan_id' => $target->plan_id, + 'starts_at' => $now - 10, + 'ends_at' => $now + 3600, + 'traffic_quota_bytes' => 1000, + 'download_base_bytes' => null, + 'upload_base_bytes' => null, + 'download_used_bytes' => 0, + 'upload_used_bytes' => 0, + 'status' => 'scheduled', + 'created_at' => $now - 100, + 'updated_at' => $now - 100, + ]); + }; + + // Activating a scheduled paid period may update the billing ledger, but + // it must not overwrite a policy projection whose Agent conclusion is + // still unknown, contradictory, or sticky. + $scheduledSuspend = $makeLifecycleInstance( + '80808080-8080-4080-8080-808080808080', + 'scheduled-suspend-conflict-vm', + 'suspend_failed', + 'active' + ); + $scheduledSuspend->expires_at = time() + 3600; + $scheduledSuspend->current_period_id = null; + $scheduledSuspend->save(); + $scheduledSuspendJob = $setPolicyResolution($preparePolicyFailure( + $scheduledSuspend, + 'service_suspend', + 'service/suspend', + 'purge' + ), 'unknown'); + $scheduledSuspendPeriod = $insertScheduledPeriod($scheduledSuspend); + $reconcile->invoke($lifecycle, (int) $scheduledSuspend->id); + $assert((int) $scheduledSuspend->fresh()->current_period_id + === $scheduledSuspendPeriod + && (string) CloudServicePeriod::find($scheduledSuspendPeriod)->status + === 'active' + && (string) $scheduledSuspend->fresh()->service_status + === 'suspend_failed' + && (string) $scheduledSuspendJob->fresh()->effect_resolution + === 'unknown', + 'Scheduled activation falsely cleared an unknown service suspension.'); + + $scheduledBlock = $makeLifecycleInstance( + '81818181-8181-4181-8181-818181818181', + 'scheduled-block-conflict-vm', + 'expired_grace', + 'block_failed' + ); + $scheduledBlock->expires_at = time() + 3600; + $scheduledBlock->current_period_id = null; + $scheduledBlock->save(); + $scheduledBlockJob = $setPolicyResolution($preparePolicyFailure( + $scheduledBlock, + 'network_suspend', + 'network/suspend', + 'expired' + ), 'applied'); + $scheduledBlockPeriod = $insertScheduledPeriod($scheduledBlock); + $reconcile->invoke($lifecycle, (int) $scheduledBlock->id); + $assert((int) $scheduledBlock->fresh()->current_period_id + === $scheduledBlockPeriod + && (string) $scheduledBlock->fresh()->network_status + === 'block_failed' + && (bool) $scheduledBlockJob->fresh()->finalization_incident + && (string) $scheduledBlockJob->fresh()->finalization_error_code + === 'recovery_instance_state_conflict', + 'Scheduled activation hid an applied suspension/local-state conflict.'); + + $scheduledRestore = $makeLifecycleInstance( + '82828282-8282-4282-8282-828282828282', + 'scheduled-restore-conflict-vm', + 'expired_grace', + 'restore_failed' + ); + $scheduledRestore->expires_at = time() + 3600; + $scheduledRestore->current_period_id = null; + $scheduledRestore->save(); + $scheduledRestoreJob = $setPolicyResolution($preparePolicyFailure( + $scheduledRestore, + 'network_resume', + 'network/resume', + null + ), 'not_applied', true); + $scheduledRestorePeriod = $insertScheduledPeriod($scheduledRestore); + $reconcile->invoke($lifecycle, (int) $scheduledRestore->id); + $assert((int) $scheduledRestore->fresh()->current_period_id + === $scheduledRestorePeriod + && (string) $scheduledRestore->fresh()->network_status + === 'restore_failed' + && (bool) $scheduledRestoreJob->fresh()->finalization_incident, + 'Scheduled activation falsely cleared a sticky network restore failure.'); + + $makeImmediatelyRenewable = static function ( + CloudInstance $target + ): void { + $past = time() - 60; + $target->current_period_id = null; + $target->expires_at = $past; + $target->renewal_days = 30; + $target->renewal_price = '1.00'; + $target->renewal_traffic_bytes = 1000; + $target->traffic_synced_at = time() + 10; + $target->save(); + Capsule::table('cloud_service_periods')->insert([ + 'instance_id' => $target->id, + 'user_id' => $target->user_id, + 'plan_id' => $target->plan_id, + 'starts_at' => $past - 86400, + 'ends_at' => $past, + 'traffic_quota_bytes' => 1000, + 'download_base_bytes' => 0, + 'upload_base_bytes' => 0, + 'download_used_bytes' => 0, + 'upload_used_bytes' => 0, + 'status' => 'finished', + 'created_at' => $past - 86400, + 'updated_at' => $past, + ]); + }; + $user->money = '1000.00'; + $user->save(); + + $renewUnknownSuspend = $makeLifecycleInstance( + '83838383-8383-4383-8383-838383838383', + 'renew-unknown-suspend-vm', + 'suspend_failed', + 'active' + ); + $makeImmediatelyRenewable($renewUnknownSuspend); + $setPolicyResolution($preparePolicyFailure( + $renewUnknownSuspend, + 'service_suspend', + 'service/suspend', + 'purge' + ), 'unknown'); + $unknownRenewal = CloudRenewalService::renew( + $renewUnknownSuspend, + ['idempotency_key' => 'renew-unknown-suspend-0001'], + $actor + ); + $assert((string) CloudServicePeriod::find( + $unknownRenewal->period_id + )->status === 'active' + && (string) $renewUnknownSuspend->fresh()->service_status + === 'suspend_failed', + 'Immediate renewal falsely cleared an unknown service suspension.'); + + $renewAppliedBlock = $makeLifecycleInstance( + '84848484-8484-4484-8484-848484848484', + 'renew-applied-block-vm', + 'expired_grace', + 'block_failed' + ); + $makeImmediatelyRenewable($renewAppliedBlock); + $setPolicyResolution($preparePolicyFailure( + $renewAppliedBlock, + 'network_suspend', + 'network/suspend', + 'expired' + ), 'applied'); + CloudRenewalService::renew( + $renewAppliedBlock, + ['idempotency_key' => 'renew-applied-block-0001'], + $actor + ); + $assert((string) $renewAppliedBlock->fresh()->network_status + === 'block_failed', + 'Immediate renewal hid an applied network suspension conflict.'); + + $renewStickyRestore = $makeLifecycleInstance( + '85858585-8585-4585-8585-858585858585', + 'renew-sticky-restore-vm', + 'expired_grace', + 'restore_failed' + ); + $makeImmediatelyRenewable($renewStickyRestore); + $setPolicyResolution($preparePolicyFailure( + $renewStickyRestore, + 'network_resume', + 'network/resume', + null + ), 'not_applied', true); + CloudRenewalService::renew( + $renewStickyRestore, + ['idempotency_key' => 'renew-sticky-restore-0001'], + $actor + ); + $assert((string) $renewStickyRestore->fresh()->network_status + === 'restore_failed', + 'Immediate renewal cleared a sticky network restore failure.'); + + $renewSafeSuspend = $makeLifecycleInstance( + '86868686-8686-4686-8686-868686868686', + 'renew-safe-suspend-vm', + 'suspend_failed', + 'active' + ); + $makeImmediatelyRenewable($renewSafeSuspend); + $safeSuspendJob = $preparePolicyFailure( + $renewSafeSuspend, + 'service_suspend', + 'service/suspend', + 'purge' + ); + CloudRenewalService::renew( + $renewSafeSuspend, + ['idempotency_key' => 'renew-safe-suspend-0001'], + $actor + ); + $assert((string) $renewSafeSuspend->fresh()->service_status + === 'suspend_failed', + 'Immediate renewal bypassed lifecycle verification of a safe failure.'); + $reconcile->invoke($lifecycle, (int) $renewSafeSuspend->id); + $assert((string) $renewSafeSuspend->fresh()->service_status === 'active' + && (string) $safeSuspendJob->fresh()->phase === 'terminal', + 'Lifecycle did not clear a canonical not-applied failure after renewal.'); + + $trafficRetryInstance = $makeLifecycleInstance( + '91919191-9191-4191-8191-919191919191', + 'traffic-retry-vm', + 'active', + 'block_failed' + ); + $trafficRetryInstance->expires_at = time() + 86400; + $trafficRetryInstance->lifetime_download_bytes = 200; + $trafficRetryInstance->lifetime_upload_bytes = 0; + $trafficRetryInstance->traffic_synced_at = time(); + $trafficRetryInstance->save(); + $trafficPeriodId = Capsule::table('cloud_service_periods')->insertGetId([ + 'instance_id' => $trafficRetryInstance->id, + 'user_id' => $trafficRetryInstance->user_id, + 'starts_at' => time() - 3600, + 'ends_at' => time() + 3600, + 'traffic_quota_bytes' => 100, + 'download_base_bytes' => 0, + 'upload_base_bytes' => 0, + 'download_used_bytes' => 200, + 'upload_used_bytes' => 0, + 'status' => 'exhausted', + 'created_at' => time() - 3600, + 'updated_at' => time() - 310, + ]); + $trafficRetryInstance->current_period_id = $trafficPeriodId; + $trafficRetryInstance->save(); + $oldTrafficJob = $preparePolicyFailure( + $trafficRetryInstance, + 'network_suspend', + 'network/suspend', + 'traffic' + ); + $assert($reconcile->invoke( + $lifecycle, + (int) $trafficRetryInstance->id + ) === true, 'A still-required traffic block did not create a new generation.'); + $trafficRetry = CloudJob::where('instance_id', $trafficRetryInstance->id) + ->where('kind', 'network_suspend')->orderByDesc('id')->first(); + $assert($trafficRetry !== null + && (int) $trafficRetry->id !== (int) $oldTrafficJob->id + && (string) $trafficRetry->operation_id + !== (string) $oldTrafficJob->operation_id + && (string) $oldTrafficJob->fresh()->phase === 'terminal' + && (string) $trafficRetryInstance->fresh()->network_status + === 'blocking', + 'Traffic-block retry mutated or replayed its prior generation.'); + + $undispatchedTraffic = $makeLifecycleInstance( + '96969696-9696-4696-8696-969696969696', + 'undispatched-traffic-vm', + 'active', + 'block_failed' + ); + $undispatchedTraffic->expires_at = time() + 86400; + $undispatchedTraffic->lifetime_download_bytes = 200; + $undispatchedTraffic->lifetime_upload_bytes = 0; + $undispatchedTraffic->traffic_synced_at = time(); + $undispatchedTraffic->save(); + $undispatchedTrafficPeriod = Capsule::table( + 'cloud_service_periods' + )->insertGetId([ + 'instance_id' => $undispatchedTraffic->id, + 'user_id' => $undispatchedTraffic->user_id, + 'starts_at' => time() - 3600, + 'ends_at' => time() + 3600, + 'traffic_quota_bytes' => 100, + 'download_base_bytes' => 0, + 'upload_base_bytes' => 0, + 'download_used_bytes' => 200, + 'upload_used_bytes' => 0, + 'status' => 'exhausted', + 'created_at' => time() - 3600, + 'updated_at' => time() - 310, + ]); + $undispatchedTraffic->current_period_id = $undispatchedTrafficPeriod; + $undispatchedTraffic->save(); + $oldUndispatchedTraffic = $finalizeUndispatchedFailure($queuePolicy( + $undispatchedTraffic, + 'network_suspend', + 'network/suspend', + 'traffic' + )); + $assert($reconcile->invoke( + $lifecycle, + (int) $undispatchedTraffic->id + ) === true, 'A generation-zero traffic failure did not create a safe new generation.'); + $undispatchedTrafficRetry = CloudJob::where( + 'instance_id', + $undispatchedTraffic->id + )->where('kind', 'network_suspend')->orderByDesc('id')->first(); + $assert($undispatchedTrafficRetry !== null + && (int) $undispatchedTrafficRetry->id + !== (int) $oldUndispatchedTraffic->id + && (string) $undispatchedTrafficRetry->operation_id + !== (string) $oldUndispatchedTraffic->operation_id + && (int) $oldUndispatchedTraffic->fresh()->dispatch_attempts === 0, + 'Generation-zero traffic retry replayed or rewrote the prior operation.'); + + $resumeRetryInstance = $makeLifecycleInstance( + '92929292-9292-4292-8292-929292929292', + 'resume-retry-vm', + 'active', + 'restore_failed' + ); + $resumeRetryInstance->expires_at = time() + 86400; + $resumeRetryInstance->lifetime_download_bytes = 50; + $resumeRetryInstance->lifetime_upload_bytes = 0; + $resumeRetryInstance->traffic_synced_at = time(); + $resumeRetryInstance->save(); + $resumePeriodId = Capsule::table('cloud_service_periods')->insertGetId([ + 'instance_id' => $resumeRetryInstance->id, + 'user_id' => $resumeRetryInstance->user_id, + 'starts_at' => time() - 3600, + 'ends_at' => time() + 3600, + 'traffic_quota_bytes' => 1000, + 'download_base_bytes' => 0, + 'upload_base_bytes' => 0, + 'download_used_bytes' => 50, + 'upload_used_bytes' => 0, + 'status' => 'active', + 'created_at' => time() - 3600, + 'updated_at' => time() - 310, + ]); + $resumeRetryInstance->current_period_id = $resumePeriodId; + $resumeRetryInstance->save(); + $oldResumeJob = $preparePolicyFailure( + $resumeRetryInstance, + 'network_resume', + 'network/resume', + null + ); + $assert($reconcile->invoke( + $lifecycle, + (int) $resumeRetryInstance->id + ) === true, 'A still-required network restore did not create a new generation.'); + $resumeRetry = CloudJob::where('instance_id', $resumeRetryInstance->id) + ->where('kind', 'network_resume')->orderByDesc('id')->first(); + $assert($resumeRetry !== null + && (int) $resumeRetry->id !== (int) $oldResumeJob->id + && (string) $resumeRetry->operation_id + !== (string) $oldResumeJob->operation_id + && (string) $oldResumeJob->fresh()->phase === 'terminal' + && (string) $resumeRetryInstance->fresh()->network_status + === 'restoring', + 'Network-restore retry mutated or replayed its prior generation.'); + + $attachActivePeriod = static function (CloudInstance $target): void { + $target->expires_at = time() + 86400; + $target->lifetime_download_bytes = 50; + $target->lifetime_upload_bytes = 0; + $target->traffic_synced_at = time(); + $target->save(); + $periodId = Capsule::table('cloud_service_periods')->insertGetId([ + 'instance_id' => $target->id, + 'user_id' => $target->user_id, + 'starts_at' => time() - 3600, + 'ends_at' => time() + 3600, + 'traffic_quota_bytes' => 1000, + 'download_base_bytes' => 0, + 'upload_base_bytes' => 0, + 'download_used_bytes' => 50, + 'upload_used_bytes' => 0, + 'status' => 'active', + 'created_at' => time() - 3600, + 'updated_at' => time() - 310, + ]); + $target->current_period_id = $periodId; + $target->save(); + }; + $undispatchedResume = $makeLifecycleInstance( + '98989898-9898-4898-8898-989898989898', + 'undispatched-resume-vm', + 'active', + 'restore_failed' + ); + $attachActivePeriod($undispatchedResume); + $oldUndispatchedResume = $finalizeUndispatchedFailure($queuePolicy( + $undispatchedResume, + 'network_resume', + 'network/resume' + )); + $assert($reconcile->invoke( + $lifecycle, + (int) $undispatchedResume->id + ) === true, 'A generation-zero network restore did not create a safe new generation.'); + $undispatchedResumeRetry = CloudJob::where( + 'instance_id', + $undispatchedResume->id + )->where('kind', 'network_resume')->orderByDesc('id')->first(); + $assert($undispatchedResumeRetry !== null + && (int) $undispatchedResumeRetry->id + !== (int) $oldUndispatchedResume->id + && (string) $undispatchedResumeRetry->operation_id + !== (string) $oldUndispatchedResume->operation_id + && (int) $oldUndispatchedResume->fresh()->dispatch_attempts === 0 + && (string) $undispatchedResume->fresh()->network_status + === 'restoring', + 'Generation-zero network-restore retry replayed or rewrote the prior operation.'); + + $obsoleteSuspend = $makeLifecycleInstance( + '94949494-9494-4494-8494-949494949494', + 'obsolete-suspend-vm', + 'suspend_failed', + 'active' + ); + $attachActivePeriod($obsoleteSuspend); + $oldObsoleteSuspend = $preparePolicyFailure( + $obsoleteSuspend, + 'service_suspend', + 'service/suspend', + 'purge' + ); + $obsoleteCount = CloudJob::where( + 'instance_id', + $obsoleteSuspend->id + )->count(); + $assert($reconcile->invoke( + $lifecycle, + (int) $obsoleteSuspend->id + ) === false + && (string) $obsoleteSuspend->fresh()->service_status === 'active' + && CloudJob::where('instance_id', $obsoleteSuspend->id)->count() + === $obsoleteCount + && (string) $oldObsoleteSuspend->fresh()->phase === 'terminal', + 'A no-longer-required, definitively not-applied suspend was not safely cleared.'); + + $uncertainSuspend = $makeLifecycleInstance( + '95959595-9595-4595-8595-959595959595', + 'uncertain-suspend-vm', + 'suspend_failed', + 'active' + ); + $attachActivePeriod($uncertainSuspend); + $oldUncertainSuspend = $preparePolicyFailure( + $uncertainSuspend, + 'service_suspend', + 'service/suspend', + 'purge' + ); + $oldUncertainSuspend->effect_resolution = 'unknown'; + $oldUncertainSuspend->effect_may_have_applied = 1; + $oldUncertainSuspend->safe_to_resubmit = 0; + $oldUncertainSuspend->save(); + $assert($reconcile->invoke( + $lifecycle, + (int) $uncertainSuspend->id + ) === false + && (string) $uncertainSuspend->fresh()->service_status + === 'suspend_failed' + && (string) $oldUncertainSuspend->fresh()->effect_resolution + === 'unknown', + 'An unknown-effect suspend failure was falsely unlocked by a paid period.'); + + foreach ([ + ['unknown', 1, 0, false], + ['applied', 0, 0, false], + ['not_applied', 0, 1, true], + ] as $index => [$resolution, $effect, $safe, $incident]) { + $guarded = $makeLifecycleInstance( + sprintf('93939393-9393-4393-8393-%012d', $index + 1), + 'guarded-lifecycle-' . $index, + 'purge_deleting', + 'blocked_expired' + ); + $guarded->status = 'deleting'; + $guarded->save(); + $guardedJob = CloudJobService::enqueueExpiryDelete($guarded); + $identity = CloudOperationRecoveryIdentity::expected($guardedJob); + $past = time() - 310; + $guardedJob->request_fingerprint = $identity['request_fingerprint']; + $guardedJob->attempts = 1; + $guardedJob->dispatch_attempts = 1; + $guardedJob->dispatch_started_at = $past - 30; + $guardedJob->agent_accepted_at = $past - 20; + $guardedJob->dispatched_at = $past - 20; + $guardedJob->receipt_deadline_at = $past - 10; + $guardedJob->phase = 'terminal'; + $guardedJob->terminal_at = $past; + $guardedJob->error_code = 'operation_failed'; + $guardedJob->updated_at = $past; + $guardedJob->effect_resolution = $resolution; + $guardedJob->effect_may_have_applied = $effect; + $guardedJob->safe_to_resubmit = $safe; + $guardedJob->outcome = $resolution === 'applied' + ? 'succeeded' : 'failed'; + $guardedJob->status = $guardedJob->outcome; + $guardedJob->finalization_incident = $incident ? 1 : 0; + $guardedJob->finalization_error_code = $incident + ? 'recovery_ledger_conflict' : null; + $guardedJob->save(); + $guarded->status = 'delete_failed'; + $guarded->service_status = 'purge_failed'; + $guarded->save(); + $beforeGuarded = CloudJob::where('instance_id', $guarded->id)->count(); + $assert($reconcile->invoke($lifecycle, (int) $guarded->id) === false + && CloudJob::where('instance_id', $guarded->id)->count() + === $beforeGuarded + && (string) $guardedJob->fresh()->operation_id + === (string) $guardedJob->operation_id, + 'Unknown, applied, or sticky lifecycle evidence created a new mutation generation.'); + } + echo "Cloud SQLite purchase, provisioning, refund, ambiguity, quota and tenant checks passed (crypto double only).\n"; } diff --git a/web/tests/CloudFirewallWorkflowTest.php b/web/tests/CloudFirewallWorkflowTest.php index 2ae75b91..1e64ee69 100644 --- a/web/tests/CloudFirewallWorkflowTest.php +++ b/web/tests/CloudFirewallWorkflowTest.php @@ -265,6 +265,23 @@ namespace { $table->integer('created_at'); $table->integer('updated_at'); }); + $schema->create('cloud_agent_completion_events', static function ( + Blueprint $table + ): void { + $table->string('event_id')->primary(); + $table->integer('host_id'); + $table->string('operation_id'); + $table->string('payload_sha256'); + $table->string('outcome'); + $table->boolean('effect_may_have_applied'); + $table->boolean('safe_to_resubmit'); + $table->string('error_code')->default(''); + $table->text('result_json')->nullable(); + $table->string('disposition')->default('received'); + $table->integer('received_at'); + $table->integer('applied_at')->nullable(); + $table->unique(['host_id', 'operation_id']); + }); foreach ([10, 20, 30, 40] as $userId) { $user = new User(); $user->id = $userId; diff --git a/web/tests/CloudInstanceReadPerformanceTest.php b/web/tests/CloudInstanceReadPerformanceTest.php index 589e034b..9c05b35d 100644 --- a/web/tests/CloudInstanceReadPerformanceTest.php +++ b/web/tests/CloudInstanceReadPerformanceTest.php @@ -127,7 +127,10 @@ $assert(str_contains($detail, $assert(str_contains($powerAction, 'state.powerMutation = mutation') && str_contains($powerAction, 'renderVmDetail(vm)') && str_contains($powerAction, 'observeAcceptedTask(result') - && str_contains($powerAction, "task.status === 'failed'") + && str_contains( + $powerAction, + '!taskSucceededWithoutRecovery(task)' + ) && str_contains($powerAction, '任务已接收,可在任务中心查看结果。') && !str_contains($powerAction, 'waitForShutdownState') && !str_contains($powerAction, 'state.mutationBusy = true') diff --git a/web/tests/CloudInvoiceDetailContractTest.php b/web/tests/CloudInvoiceDetailContractTest.php index ad8b4bbf..7eb92075 100644 --- a/web/tests/CloudInvoiceDetailContractTest.php +++ b/web/tests/CloudInvoiceDetailContractTest.php @@ -116,7 +116,9 @@ $summaryMethod = $section($invoiceService, 'public static function listSummaries $assert(substr_count($summaryMethod, '::whereIn(') === 3 && str_contains($summaryMethod, "->get(['id', 'user_id', 'status'])") && str_contains($summaryMethod, - "->get(['id', 'order_id', 'user_id', 'phase', 'outcome'])") + "->get(['id', 'order_id', 'user_id', 'instance_id', 'kind',") + && str_contains($summaryMethod, + "'phase', 'outcome', 'effect_resolution'])") && str_contains($summaryMethod, 'self::publicStatus($invoice, $purpose, $instance, $now)'), 'Invoice list associations are not loaded with fixed-size batch queries.'); @@ -383,7 +385,7 @@ $paymentRequest = strpos($createPayment, 'api(`/api/v1/invoices/${encodeURIComponent(invoice.id)}/payments`'); $paymentObserve = strpos($createPayment, 'observeTask(result, {'); $paymentTerminal = strpos($createPayment, - "if (task.status === 'succeeded' && task?.result?.payment)"); + 'if (taskSucceededWithoutRecovery(task) && task?.result?.payment)'); $paymentRender = strpos($createPayment, 'renderOnlinePayment(paymentResult, task.result.payment)'); $assert($paymentRequest !== false && $paymentObserve !== false diff --git a/web/tests/CloudInvoiceLifecycleTest.php b/web/tests/CloudInvoiceLifecycleTest.php index a46a71ac..85e73959 100644 --- a/web/tests/CloudInvoiceLifecycleTest.php +++ b/web/tests/CloudInvoiceLifecycleTest.php @@ -94,11 +94,47 @@ namespace { $table->unique(['user_id', 'idempotency_key']); }); $schema->create('cloud_jobs', static function (Blueprint $table): void { - $table->increments('id'); $table->integer('instance_id')->nullable(); $table->string('kind'); + $table->increments('id'); + $table->string('operation_id')->nullable()->unique(); + $table->string('request_idempotency_key')->nullable(); + $table->string('request_fingerprint')->nullable(); + $table->integer('parent_job_id')->nullable(); + $table->integer('order_id')->nullable(); + $table->integer('invoice_id')->nullable(); + $table->integer('instance_id')->nullable(); + $table->integer('snapshot_id')->nullable(); + $table->integer('user_id')->nullable(); + $table->integer('host_id')->nullable(); + $table->string('kind'); $table->string('execution_mode')->default('agent'); + $table->string('phase')->default('accepted'); + $table->string('outcome')->nullable(); $table->string('status'); + $table->text('sealed_payload')->nullable(); + $table->integer('attempts')->default(0); + $table->integer('dispatch_attempts')->default(0); + $table->integer('dispatch_deadline_at')->default(0); + $table->integer('dispatch_started_at')->nullable(); + $table->integer('agent_accepted_at')->nullable(); + $table->integer('receipt_deadline_at')->nullable(); + $table->integer('terminal_at')->nullable(); + $table->boolean('effect_may_have_applied')->nullable(); + $table->boolean('safe_to_resubmit')->nullable(); + $table->string('effect_resolution')->default('not_applicable'); + $table->integer('effect_resolved_at')->nullable(); + $table->integer('effect_resolved_by')->nullable(); + $table->text('effect_resolution_reason')->nullable(); + $table->string('completion_event_id')->nullable(); + $table->integer('read_at')->nullable(); + $table->integer('dispatched_at')->nullable(); + $table->string('lease_token')->nullable(); + $table->integer('lease_until')->default(0); + $table->integer('available_at')->default(0); + $table->string('error_code')->nullable(); $table->boolean('finalization_incident')->default(0); $table->string('finalization_error_code')->nullable(); + $table->text('result_json')->nullable(); + $table->integer('created_at')->default(0); $table->integer('updated_at')->default(0); }); $schema->create('cloud_invoices', static function (Blueprint $table): void { diff --git a/web/tests/CloudOperationCompletionContractTest.php b/web/tests/CloudOperationCompletionContractTest.php index d8b8f323..1b9f52ba 100644 --- a/web/tests/CloudOperationCompletionContractTest.php +++ b/web/tests/CloudOperationCompletionContractTest.php @@ -21,6 +21,9 @@ $base = [ 'id' => str_repeat('e', 32), 'agent_id' => '7', 'operation_id' => str_repeat('a', 32), + 'action' => 'test-mutation', + 'resource_id' => 'test-resource', + 'request_fingerprint' => str_repeat('d', 64), 'status' => 'succeeded', 'effect_may_have_applied' => false, 'safe_to_resubmit' => false, @@ -133,7 +136,16 @@ Capsule::table('cloud_agent_completion_events')->insert([ 'payload_sha256' => $payloadHash, 'outcome' => 'succeeded', 'effect_may_have_applied' => 0, 'safe_to_resubmit' => 0, 'error_code' => '', - 'result_json' => json_encode(['uuid' => 'test'], JSON_THROW_ON_ERROR), + 'result_json' => json_encode([ + 'schema' => 'virt_cloud_completion_event', + 'version' => 1, + 'identity' => [ + 'action' => $base['action'], + 'resource_id' => $base['resource_id'], + 'request_fingerprint' => $base['request_fingerprint'], + ], + 'result' => ['uuid' => 'test'], + ], JSON_THROW_ON_ERROR), 'disposition' => 'received', 'received_at' => time(), 'applied_at' => null, ]); @@ -165,7 +177,16 @@ Capsule::table('cloud_agent_completion_events')->insert([ 'payload_sha256' => $lateHash, 'outcome' => 'succeeded', 'effect_may_have_applied' => 0, 'safe_to_resubmit' => 0, 'error_code' => '', - 'result_json' => json_encode(['uuid' => 'test'], JSON_THROW_ON_ERROR), + 'result_json' => json_encode([ + 'schema' => 'virt_cloud_completion_event', + 'version' => 1, + 'identity' => [ + 'action' => $late['action'], + 'resource_id' => $late['resource_id'], + 'request_fingerprint' => $late['request_fingerprint'], + ], + 'result' => ['uuid' => 'test'], + ], JSON_THROW_ON_ERROR), 'disposition' => 'received', 'received_at' => time(), 'applied_at' => null, ]); @@ -198,15 +219,18 @@ $assert($successEvent !== null ), 'A reserved completion_event_id concealed a failed receipt finalizer.'); -// Kinds without an audited receipt-recovery finalizer still consume the exact -// on-time event when their business finalizer intentionally degrades success -// to a terminal fenced failure (for example reinstall cleanup_pending). -$failedFinalizerJob->kind = 'reinstall'; -$assert(CloudOperationCompletionService::settledTaskWithEvent( - $failedFinalizerJob, - $successEvent - ), - 'An exact non-settings receipt was not acknowledged after fenced failure.'); +// Every registered Agent leaf keeps the exact receipt available when its PHP +// finalizer degraded success into a terminal unknown effect. The recovery +// worker, rather than completion ingestion, must converge its business ledger. +foreach (\App\Services\Cloud\CloudOperationRecoveryPolicy::kinds() as $kind) { + $failedFinalizerJob->kind = $kind; + $assert(!CloudOperationCompletionService::settledTaskWithEvent( + $failedFinalizerJob, + $successEvent + ), + 'A recoverable ' . $kind + . ' receipt was acknowledged before its ledger converged.'); +} $failedFinalizerJob->finalization_incident = 1; $assert(!CloudOperationCompletionService::settledTaskWithEvent( $failedFinalizerJob, diff --git a/web/tests/CloudOperationRecoveryPolicyTest.php b/web/tests/CloudOperationRecoveryPolicyTest.php new file mode 100644 index 00000000..a964ce73 --- /dev/null +++ b/web/tests/CloudOperationRecoveryPolicyTest.php @@ -0,0 +1,223 @@ +invoke( + null, + 'automatic_recovery:v1:1700000000:13:pending' + ); + $assert(is_array($state) && ($state['attempts'] ?? null) === 13, + 'A recovery marker was still capped at twelve attempts.'); + $saturated = $attemptState->invoke( + null, + 'automatic_recovery:v1:1700000000:' . str_repeat('9', 80) + . ':pending' + ); + $assert(is_array($saturated) + && ($saturated['attempts'] ?? null) === PHP_INT_MAX, + 'A durable saturated recovery attempt counter was rejected.'); + + $errorCode = new ReflectionMethod( + CloudAutomaticOperationRecoveryService::class, + 'recoveryErrorCode' + ); + $assert($errorCode->invoke(null, new CloudAgentError( + 'invalid inspection', 502, 'agent_invalid_inspection', false, 200 + )) === 'recovery_evidence_invalid' + && $errorCode->invoke( + null, + new CloudRecoveryInstanceStateConflict('state conflict', 409) + ) === 'recovery_instance_state_conflict', + 'Concrete evidence/state anomalies collapsed into a generic retry code.'); + + $operationId = str_repeat('a', 32); + $identity = [ + 'action' => 'change-network', + 'resource_id' => '11111111-1111-4111-8111-111111111111', + 'request_fingerprint' => str_repeat('f', 64), + ]; + $job = new CloudJob(); + $job->operation_id = $operationId; + $job->kind = 'network_change'; + $job->phase = 'terminal'; + $job->effect_resolution = 'not_applied'; + $job->sealed_payload = CloudSecrets::encrypt([ + '_operation_identity' => ['version' => 1] + $identity, + ], 'job-payload'); + $notApplied = new ReflectionMethod( + CloudOperationRecoveryService::class, + 'assertNotAppliedOperationIdentity' + ); + $notApplied->invoke(null, $job, [ + 'operation_id' => $operationId, + 'status' => 'failed', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => true, + 'error_code' => 'network_not_committed', + 'result' => null, + ] + $identity); + + $event = new CloudAgentCompletionEvent(); + $event->operation_id = $operationId; + $event->outcome = 'failed'; + $event->effect_may_have_applied = 0; + $event->safe_to_resubmit = 1; + $event->error_code = 'network_not_committed'; + $event->result_json = json_encode([ + 'schema' => 'virt_cloud_completion_event', + 'version' => 1, + 'identity' => $identity, + 'result' => ['public_ip_cidr' => '203.0.113.10/24'], + ], JSON_THROW_ON_ERROR); + $lateOperation = new ReflectionMethod( + CloudOperationRecoveryService::class, + 'lateReceiptOperation' + ); + $rebuilt = $lateOperation->invoke(null, $job, $event, 'not_applied'); + $assert($rebuilt === CloudOperationCompletionService::operation($event) + && ($rebuilt['safe_to_resubmit'] ?? null) === true + && ($rebuilt['error_code'] ?? null) === 'network_not_committed', + 'Late receipt recovery replaced the exact kind-specific Agent result.'); + + $preparedMarker = new ReflectionMethod( + CloudOperationRecoveryService::class, + 'preparedMarker' + ); + $baseOperation = [ + 'operation_id' => $operationId, + 'status' => 'succeeded', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'error_code' => '', + 'result' => ['snapshot_key' => str_repeat('b', 32), 'deleted' => true], + ]; + $otherOperation = $baseOperation; + $otherOperation['result']['snapshot_key'] = str_repeat('c', 32); + $source = 'automatic_applied_succeeded_nofence:' . str_repeat('d', 64); + $assert($preparedMarker->invoke(null, $baseOperation, $source) + !== $preparedMarker->invoke(null, $otherOperation, $source), + 'Prepared evidence ignored a non-settings ledger result field.'); + + $payloadJob = new CloudJob(); + $payloadJob->kind = 'network_change'; + $payloadJob->phase = 'terminal'; + $payloadJob->effect_resolution = 'applied'; + $payloadJob->sealed_payload = CloudSecrets::encrypt([ + 'body' => ['hostname' => 'vm.example'], + 'credential' => ['password' => 'never-persist'], + '_operation_identity' => ['version' => 1] + $identity, + '_operation_recovery' => [ + 'operation' => $baseOperation, + 'resolution' => 'applied', + ], + ], 'job-payload'); + $finalizedPayload = new ReflectionMethod( + CloudOperationRecoveryService::class, + 'finalizedRecoveryPayload' + ); + $clean = CloudSecrets::decrypt( + $finalizedPayload->invoke(null, $payloadJob), + 'job-payload' + ); + $assert(!array_key_exists('_operation_recovery', $clean) + && !array_key_exists('credential', $clean) + && ($clean['body']['hostname'] ?? null) === 'vm.example', + 'Recovery commit retained prepared evidence or a credential.'); + + echo "Cloud operation recovery policy contract passed.\n"; +} diff --git a/web/tests/CloudRescueTemplateRetryBoundaryTest.php b/web/tests/CloudRescueTemplateRetryBoundaryTest.php new file mode 100644 index 00000000..5bb7d173 --- /dev/null +++ b/web/tests/CloudRescueTemplateRetryBoundaryTest.php @@ -0,0 +1,550 @@ +addConnection([ + 'driver' => 'sqlite', + 'database' => ':memory:', + ], 'default'); + $capsule->setAsGlobal(); + $capsule->bootEloquent(); + + $capsule->schema('default')->create( + 'cloud_jobs', + static function (Blueprint $table): void { + $table->increments('id'); + $table->string('operation_id'); + $table->string('request_idempotency_key'); + $table->string('request_fingerprint', 64); + $table->integer('parent_job_id')->nullable(); + $table->integer('instance_id')->nullable(); + $table->integer('order_id')->nullable(); + $table->integer('invoice_id')->nullable(); + $table->integer('snapshot_id')->nullable(); + $table->integer('user_id'); + $table->integer('host_id')->nullable(); + $table->string('kind'); + $table->string('execution_mode'); + $table->string('phase'); + $table->string('outcome')->nullable(); + $table->string('status'); + $table->integer('attempts')->default(0); + $table->integer('dispatch_attempts')->default(0); + $table->integer('dispatch_deadline_at')->nullable(); + $table->integer('dispatch_started_at')->nullable(); + $table->integer('dispatched_at')->nullable(); + $table->integer('agent_accepted_at')->nullable(); + $table->integer('receipt_deadline_at')->nullable(); + $table->text('sealed_payload'); + $table->text('result_json')->nullable(); + $table->string('error_code')->nullable(); + $table->text('error_message')->nullable(); + $table->string('lease_token')->nullable(); + $table->integer('lease_until')->default(0); + $table->integer('available_at')->default(0); + $table->integer('created_at'); + $table->integer('updated_at'); + $table->integer('terminal_at')->nullable(); + $table->boolean('effect_may_have_applied')->nullable(); + $table->boolean('safe_to_resubmit')->nullable(); + $table->string('effect_resolution'); + $table->integer('effect_resolved_at')->nullable(); + $table->integer('effect_resolved_by')->nullable(); + $table->string('effect_resolution_reason')->default(''); + $table->boolean('finalization_incident')->default(0); + $table->string('finalization_error_code')->nullable(); + $table->string('completion_event_id')->nullable(); + $table->integer('read_at')->nullable(); + } + ); + $capsule->schema('default')->create( + 'cloud_rescue_template_imports', + static function (Blueprint $table): void { + $table->string('operation_id')->primary(); + $table->integer('host_id'); + $table->string('template_id', 32); + $table->integer('job_id'); + $table->string('import_type'); + $table->string('name'); + $table->integer('size_bytes')->default(0); + $table->string('sha256', 64)->default(''); + $table->string('state'); + $table->string('error_code')->default(''); + $table->integer('created_at'); + $table->integer('updated_at'); + } + ); + $capsule->schema('default')->create( + 'cloud_rescue_template_deletions', + static function (Blueprint $table): void { + $table->integer('host_id'); + $table->string('template_id', 32); + $table->string('operation_id'); + $table->integer('job_id'); + $table->string('state'); + $table->string('error_code')->default(''); + $table->integer('created_at'); + $table->integer('updated_at'); + $table->primary(['host_id', 'template_id']); + } + ); + + $now = time(); + $actor = [ + 'user_id' => 1, + 'is_admin' => true, + 'is_super_admin' => true, + 'can_manage' => true, + ]; + + $insertJob = static function (array $overrides) use ($now): int { + $operationId = (string) ($overrides['operation_id'] + ?? bin2hex(random_bytes(16))); + $values = [ + 'operation_id' => $operationId, + 'request_idempotency_key' => $operationId, + 'request_fingerprint' => hash('sha256', $operationId), + 'parent_job_id' => null, + 'instance_id' => null, + 'order_id' => null, + 'invoice_id' => null, + 'snapshot_id' => null, + 'user_id' => 1, + 'host_id' => 1, + 'kind' => 'rescue_template_import', + 'execution_mode' => 'agent', + 'phase' => 'terminal', + 'outcome' => 'failed', + 'status' => 'failed', + 'attempts' => 1, + 'dispatch_attempts' => 1, + 'dispatch_deadline_at' => $now - 10, + 'dispatch_started_at' => $now - 9, + 'dispatched_at' => $now - 8, + 'agent_accepted_at' => $now - 7, + 'receipt_deadline_at' => $now - 1, + 'sealed_payload' => '', + 'result_json' => null, + 'error_code' => 'operation_failed', + 'error_message' => '', + 'lease_token' => null, + 'lease_until' => 0, + 'available_at' => 0, + 'created_at' => $now - 20, + 'updated_at' => $now - 1, + 'terminal_at' => $now - 1, + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 1, + 'effect_resolution' => 'not_applied', + 'effect_resolved_at' => $now - 1, + 'effect_resolved_by' => null, + 'effect_resolution_reason' => 'test', + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'completion_event_id' => null, + 'read_at' => null, + ]; + $values = array_replace($values, $overrides); + return (int) Capsule::table('cloud_jobs')->insertGetId($values); + }; + + $insertImport = static function ( + string $name, + string $templateId, + string $state, + string $resolution, + bool $incident = false + ) use ($insertJob, $now): array { + $operationId = bin2hex(random_bytes(16)); + $payload = [ + 'can_manage' => true, + 'rescue_template_id' => $templateId, + 'method' => 'POST', + 'request_target' => '/v1/rescue-templates', + 'body' => [ + 'id' => $templateId, + 'name' => $name, + 'source_url' => 'https://example.invalid/rescue.qcow2', + 'sha256' => '', + 'operation_id' => $operationId, + ], + 'owner_id' => 1, + ]; + $jobId = $insertJob([ + 'operation_id' => $operationId, + 'kind' => 'rescue_template_import', + 'outcome' => $resolution === 'applied' ? 'succeeded' : 'failed', + 'status' => $resolution === 'applied' ? 'succeeded' : 'failed', + 'effect_resolution' => $resolution, + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => $resolution === 'applied' ? 0 : 1, + 'error_code' => $resolution === 'applied' + ? null : 'operation_failed', + 'sealed_payload' => CloudSecrets::encrypt( + $payload, + 'job-payload' + ), + 'finalization_incident' => $incident ? 1 : 0, + 'finalization_error_code' => $incident + ? 'recovery_instance_state_conflict' : null, + ]); + Capsule::table('cloud_rescue_template_imports')->insert([ + 'operation_id' => $operationId, + 'host_id' => 1, + 'template_id' => $templateId, + 'job_id' => $jobId, + 'import_type' => 'remote', + 'name' => $name, + 'size_bytes' => $resolution === 'applied' ? 1024 : 0, + 'sha256' => '', + 'state' => $state, + 'error_code' => $state === 'failed' ? 'import_failed' : '', + 'created_at' => $now - 20, + 'updated_at' => $now - 1, + ]); + return [$jobId, $operationId]; + }; + + $activeTemplateId = str_repeat('a', 32); + [$activeImportJobId] = $insertImport( + 'active-rescue', + $activeTemplateId, + 'active', + 'applied' + ); + + $firstDelete = CloudRescueTemplateDeletionService::delete( + 1, + $activeTemplateId, + $actor + ); + $firstDeleteJobId = (int) $firstDelete['task_id']; + $firstDeleteJob = CloudJob::findOrFail($firstDeleteJobId); + $firstDeleteOperation = (string) $firstDeleteJob->operation_id; + Capsule::table('cloud_jobs')->where('id', $firstDeleteJobId)->update([ + 'phase' => 'terminal', + 'outcome' => 'failed', + 'status' => 'failed', + 'attempts' => 1, + 'dispatch_attempts' => 1, + 'dispatch_started_at' => $now, + 'dispatched_at' => $now, + 'agent_accepted_at' => $now, + 'receipt_deadline_at' => $now + 60, + 'terminal_at' => $now, + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 1, + 'effect_resolution' => 'not_applied', + 'effect_resolved_at' => $now, + 'effect_resolution_reason' => 'test_not_applied', + 'error_code' => 'delete_failed', + 'finalization_incident' => 0, + 'finalization_error_code' => null, + ]); + Capsule::table('cloud_rescue_template_deletions') + ->where('host_id', 1) + ->where('template_id', $activeTemplateId) + ->update([ + 'state' => 'failed', + 'error_code' => 'delete_failed', + 'updated_at' => $now, + ]); + + $secondDelete = CloudRescueTemplateDeletionService::delete( + 1, + $activeTemplateId, + $actor + ); + $secondDeleteJobId = (int) $secondDelete['task_id']; + $secondDeleteRow = CloudRescueTemplateDeletion::query() + ->where('host_id', 1) + ->where('template_id', $activeTemplateId) + ->firstOrFail(); + $assert($secondDeleteJobId !== $firstDeleteJobId + && (int) $secondDeleteRow->job_id === $secondDeleteJobId + && !hash_equals( + $firstDeleteOperation, + (string) $secondDeleteRow->operation_id + ) + && (string) $secondDeleteRow->state === 'deleting' + && (string) CloudJob::findOrFail($firstDeleteJobId)->effect_resolution + === 'not_applied', + 'A proven not-applied rescue deletion did not admit one new generation.' + ); + + Capsule::table('cloud_jobs')->where('id', $secondDeleteJobId)->update([ + 'phase' => 'terminal', + 'outcome' => 'failed', + 'status' => 'failed', + 'dispatch_attempts' => 1, + 'effect_may_have_applied' => 1, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'finalization_incident' => 0, + 'finalization_error_code' => null, + ]); + Capsule::table('cloud_rescue_template_deletions') + ->where('host_id', 1) + ->where('template_id', $activeTemplateId) + ->update(['state' => 'failed', 'error_code' => 'delete_failed']); + $beforeBlockedDelete = CloudJob::count(); + try { + CloudRescueTemplateDeletionService::delete( + 1, + $activeTemplateId, + $actor + ); + throw new RuntimeException( + 'An applied rescue deletion was admitted as a new generation.' + ); + } catch (CloudError $error) { + $assert($error->httpStatus === 409, + 'An unsafe rescue deletion returned the wrong status.'); + } + $assert(CloudJob::count() === $beforeBlockedDelete + && (int) CloudRescueTemplateDeletion::query() + ->where('host_id', 1) + ->where('template_id', $activeTemplateId) + ->value('job_id') === $secondDeleteJobId, + 'A blocked rescue deletion changed its job or durable slot.'); + + $retryTemplateId = str_repeat('b', 32); + $insertImport( + 'retry-rescue', + $retryTemplateId, + 'failed', + 'not_applied' + ); + $retryImport = CloudRescueTemplateImportService::start( + 1, + 'remote', + 'retry-rescue', + 'https://example.invalid/new-rescue.qcow2', + '', + '', + $actor + ); + $retryImportJob = CloudJob::findOrFail((int) $retryImport['task_id']); + $assert((string) $retryImportJob->kind === 'rescue_template_import' + && (string) $retryImportJob->phase === 'accepted' + && CloudRescueTemplateImport::query() + ->where('host_id', 1) + ->where('name', 'retry-rescue') + ->count() === 2, + 'A proven not-applied rescue import did not admit a new operation.'); + + foreach ([ + ['applied-rescue', str_repeat('c', 32), 'applied', false], + ['incident-rescue', str_repeat('d', 32), 'not_applied', true], + ] as [$name, $templateId, $resolution, $incident]) { + $insertImport($name, $templateId, 'failed', $resolution, $incident); + $before = CloudJob::count(); + try { + CloudRescueTemplateImportService::start( + 1, + 'remote', + $name, + 'https://example.invalid/blocked-rescue.qcow2', + '', + '', + $actor + ); + throw new RuntimeException( + 'An unsafe same-name rescue import was admitted: ' . $name + ); + } catch (CloudError $error) { + $assert($error->httpStatus === 409, + 'An unsafe rescue import returned the wrong status.'); + } + $assert(CloudJob::count() === $before, + 'A blocked rescue import persisted a new job: ' . $name); + } + + $tupleTemplateId = str_repeat('f', 32); + [$tupleJobId] = $insertImport( + 'tuple-rescue', + $tupleTemplateId, + 'failed', + 'not_applied' + ); + Capsule::table('cloud_jobs')->where('id', $tupleJobId)->update([ + 'effect_may_have_applied' => 1, + 'safe_to_resubmit' => 1, + ]); + $beforeTupleConflict = CloudJob::count(); + try { + CloudRescueTemplateImportService::start( + 1, + 'remote', + 'tuple-rescue', + 'https://example.invalid/tuple-rescue.qcow2', + '', + '', + $actor + ); + throw new RuntimeException( + 'A rescue import with a contradictory terminal tuple was admitted.' + ); + } catch (CloudError $error) { + $assert($error->httpStatus === 409, + 'A rescue import tuple conflict returned the wrong status.'); + } + $assert(CloudJob::count() === $beforeTupleConflict, + 'A rescue import tuple conflict persisted a new job.'); + + $corruptActiveTemplateId = str_repeat('1', 32); + [$corruptActiveJobId] = $insertImport( + 'corrupt-active-rescue', + $corruptActiveTemplateId, + 'active', + 'applied' + ); + Capsule::table('cloud_jobs')->where('id', $corruptActiveJobId)->update([ + 'effect_may_have_applied' => 1, + ]); + $beforeCorruptActiveDelete = CloudJob::count(); + try { + CloudRescueTemplateDeletionService::delete( + 1, + $corruptActiveTemplateId, + $actor + ); + throw new RuntimeException( + 'A deletion was admitted for a corrupt active import tuple.' + ); + } catch (CloudError $error) { + $assert($error->httpStatus === 409, + 'A corrupt active import tuple returned the wrong status.'); + } + $assert(CloudJob::count() === $beforeCorruptActiveDelete, + 'A corrupt active import tuple persisted a deletion job.'); + + $tupleDeleteTemplateId = str_repeat('2', 32); + $insertImport( + 'tuple-delete-rescue', + $tupleDeleteTemplateId, + 'active', + 'applied' + ); + $tupleDelete = CloudRescueTemplateDeletionService::delete( + 1, + $tupleDeleteTemplateId, + $actor + ); + $tupleDeleteJobId = (int) $tupleDelete['task_id']; + Capsule::table('cloud_jobs')->where('id', $tupleDeleteJobId)->update([ + 'phase' => 'terminal', + 'outcome' => 'failed', + 'status' => 'failed', + 'attempts' => 1, + 'dispatch_attempts' => 1, + 'dispatch_started_at' => $now, + 'dispatched_at' => $now, + 'agent_accepted_at' => $now, + 'terminal_at' => $now, + 'effect_may_have_applied' => 1, + 'safe_to_resubmit' => 1, + 'effect_resolution' => 'not_applied', + 'effect_resolved_at' => $now, + 'effect_resolution_reason' => 'invalid_test_tuple', + 'error_code' => 'delete_failed', + 'finalization_incident' => 0, + 'finalization_error_code' => null, + ]); + Capsule::table('cloud_rescue_template_deletions') + ->where('host_id', 1) + ->where('template_id', $tupleDeleteTemplateId) + ->update(['state' => 'failed', 'error_code' => 'delete_failed']); + $beforeTupleDeleteRetry = CloudJob::count(); + try { + CloudRescueTemplateDeletionService::delete( + 1, + $tupleDeleteTemplateId, + $actor + ); + throw new RuntimeException( + 'A rescue deletion with a contradictory terminal tuple was admitted.' + ); + } catch (CloudError $error) { + $assert($error->httpStatus === 409, + 'A rescue deletion tuple conflict returned the wrong status.'); + } + $assert(CloudJob::count() === $beforeTupleDeleteRetry, + 'A rescue deletion tuple conflict persisted a new job.'); + + $identityTemplateId = str_repeat('e', 32); + [, $identityOperation] = $insertImport( + 'identity-rescue', + $identityTemplateId, + 'failed', + 'not_applied' + ); + Capsule::table('cloud_rescue_template_imports') + ->where('operation_id', $identityOperation) + ->update(['operation_id' => bin2hex(random_bytes(16))]); + $beforeIdentityConflict = CloudJob::count(); + try { + CloudRescueTemplateImportService::start( + 1, + 'remote', + 'identity-rescue', + 'https://example.invalid/identity-rescue.qcow2', + '', + '', + $actor + ); + throw new RuntimeException( + 'A rescue import with a corrupt durable identity was admitted.' + ); + } catch (CloudError $error) { + $assert($error->httpStatus === 409, + 'A rescue import identity conflict returned the wrong status.'); + } + $assert(CloudJob::count() === $beforeIdentityConflict, + 'A rescue import identity conflict persisted a new job.'); + + echo "Cloud rescue-template retry boundary checks passed.\n"; +} diff --git a/web/tests/CloudResolvedTaskPresentationTest.php b/web/tests/CloudResolvedTaskPresentationTest.php index 62574c11..413f9e7c 100644 --- a/web/tests/CloudResolvedTaskPresentationTest.php +++ b/web/tests/CloudResolvedTaskPresentationTest.php @@ -17,15 +17,30 @@ $job = static function (array $overrides = []): CloudJob { $model->setRawAttributes(array_replace([ 'id' => 91, 'operation_id' => '11111111111111111111111111111111', + 'request_idempotency_key' => 'resolved-task-fixture-91', + 'request_fingerprint' => str_repeat('2', 64), 'kind' => 'action', + 'execution_mode' => 'agent', + 'parent_job_id' => null, + 'host_id' => 7, 'phase' => 'terminal', 'outcome' => 'failed', 'status' => 'failed', + 'dispatch_attempts' => 1, + 'attempts' => 1, + 'dispatch_deadline_at' => $now - 20, + 'dispatch_started_at' => $now - 18, + 'agent_accepted_at' => $now - 17, + 'dispatched_at' => $now - 18, + 'receipt_deadline_at' => $now + 900, 'error_code' => 'operation_failed_effect_unknown', 'result_json' => null, 'effect_may_have_applied' => 1, 'safe_to_resubmit' => 0, 'effect_resolution' => 'unknown', + 'finalization_incident' => 1, + 'finalization_error_code' => 'recovery_evidence_conflict', + 'available_at' => $now + 20, 'terminal_at' => $now - 5, 'read_at' => null, 'sealed_payload' => '', @@ -39,6 +54,8 @@ $job = static function (array $overrides = []): CloudJob { foreach (['applied', 'not_applied'] as $resolution) { $display = CloudJobService::display($job([ 'effect_resolution' => $resolution, + 'finalization_incident' => 0, + 'finalization_error_code' => null, ])); $assert(($display['effect_resolution'] ?? null) === $resolution, 'Resolved terminal failure did not expose its bounded effect resolution.'); @@ -47,6 +64,94 @@ foreach (['applied', 'not_applied'] as $resolution) { && ($display['effect_may_have_applied'] ?? null) === true && ($display['safe_to_resubmit'] ?? null) === false, 'Effect convergence rewrote the original public failure contract.'); + $assert(!array_key_exists('recovery', $display), + 'A converged failure was still presented as awaiting recovery.'); +} + +$stickyResolved = CloudJobService::display($job([ + 'effect_resolution' => 'applied', +])); +$assert(($stickyResolved['recovery']['pending'] ?? null) === true + && str_contains( + (string) ($stickyResolved['recovery']['message'] ?? ''), + 'Agent 回执与宿主机证据暂不一致' + ), + 'A resolved task with a sticky incident was removed from recovery.'); + +$recoveryMessages = [ + 'recovery_limit_reached' => '旧任务已重新进入持续自动核对', + 'recovery_receipt_limit_reached' => '旧任务回执已重新进入持续自动核对', + 'recovery_state_invalid' => '任务状态与恢复记录暂不一致', + 'recovery_evidence_conflict' => 'Agent 回执与宿主机证据暂不一致', + 'recovery_evidence_partial' => '只能确认部分操作结果', + 'recovery_evidence_inconclusive' => '证据暂不足以确认操作结果', + 'recovery_evidence_invalid' => '核对或栅栏证据格式不匹配', + 'recovery_receipt_invalid' => 'Agent 回执未通过完整性核验', + 'recovery_completion_outbox_invalid' => '完成回执队列状态损坏', + 'recovery_completion_receipt_missing' => '完成回执内容缺失', + 'recovery_completion_receipt_invalid' => '完成回执内容无效', + 'recovery_completion_operation_missing' => + '完成回执缺少对应原操作记录', + 'recovery_completion_operation_invalid' => + '完成回执对应原操作记录无效', + 'recovery_completion_identity_mismatch' => + '完成回执身份与原操作记录不匹配', + 'recovery_payload_unavailable' => '恢复数据暂时无法安全读取', + 'recovery_operation_missing' => '暂未找到原任务记录', + 'recovery_authentication_failed' => '认证暂未通过', + 'recovery_operation_conflict' => '任务编号与宿主机记录暂不一致', + 'recovery_operation_identity_conflict' => + '操作、资源或请求指纹与原任务不匹配', + 'recovery_waiting_connection' => 'Agent 或网络暂不可用', + 'recovery_instance_state_conflict' => '实例状态与任务证据暂不一致', + 'recovery_ledger_conflict' => '面板账本暂未安全收敛', + 'recovery_internal_error' => '自动核对暂时遇到内部异常', +]; +foreach ($recoveryMessages as $code => $message) { + $recovering = $job(['finalization_error_code' => $code]); + $display = CloudJobService::display($recovering); + $assert(($display['recovery']['pending'] ?? null) === true + && str_contains((string) ($display['recovery']['message'] ?? ''), + $message) + && str_contains((string) ($display['recovery']['message'] ?? ''), + '仍会继续自动核对') + && ($display['recovery']['last_checked_at'] ?? null) + === (int) $recovering->updated_at + && ($display['recovery']['next_check_at'] ?? null) + === (int) $recovering->available_at, + 'Recovering task did not expose a safe Chinese incident summary: ' + . $code); + $assert(!array_key_exists('code', $display['recovery']), + 'The ordinary task DTO exposed an internal recovery code.'); + + $adminDisplay = CloudJobService::display($recovering, true); + $assert(($adminDisplay['recovery']['code'] ?? null) === $code, + 'The administrator DTO lost its bounded recovery diagnosis code.'); +} + +$unknownIncident = CloudJobService::display($job([ + 'finalization_error_code' => 'recovery_future_' . str_repeat('x', 200), +]), true); +$assert(($unknownIncident['recovery']['code'] ?? null) === 'recovery_pending' + && !str_contains(json_encode($unknownIncident['recovery'], + JSON_UNESCAPED_UNICODE), str_repeat('x', 20)), + 'An unrecognized server recovery error leaked through the safe DTO.'); + +$aggregate = CloudJobService::display($job([ + 'kind' => 'template_import', + 'execution_mode' => 'aggregate', + 'finalization_incident' => 0, + 'finalization_error_code' => null, +])); +$assert(($aggregate['recovery']['pending'] ?? null) === true + && str_contains((string) $aggregate['recovery']['message'], '子任务'), + 'Aggregate task did not explain that child convergence remains active.'); + +foreach (['create', 'payment_create', 'host_storage_configure'] as $kind) { + $display = CloudJobService::display($job(['kind' => $kind])); + $assert(!array_key_exists('recovery', $display), + 'A task with a dedicated recovery policy was mislabeled as generic recovery: ' + . $kind); } foreach ([ diff --git a/web/tests/CloudRuntimeHeartbeatTest.php b/web/tests/CloudRuntimeHeartbeatTest.php index f72c0baa..ed53b61b 100644 --- a/web/tests/CloudRuntimeHeartbeatTest.php +++ b/web/tests/CloudRuntimeHeartbeatTest.php @@ -250,7 +250,8 @@ try { $table->string('execution_mode')->default('agent'); $table->string('phase')->default('accepted'); $table->string('outcome')->nullable(); - foreach (['available_at', 'lease_until', 'attempts', 'user_id', 'host_id', 'updated_at'] as $column) { + foreach (['available_at', 'lease_until', 'attempts', 'user_id', + 'host_id', 'created_at', 'updated_at'] as $column) { $table->integer($column)->default(0); } foreach (['dispatched_at', 'order_id', 'invoice_id', 'instance_id', @@ -288,6 +289,34 @@ try { $table->integer('applied_at')->nullable(); $table->unique(['host_id', 'operation_id']); }); + $schema->create('cloud_templates', static function ( + Blueprint $table + ): void { + $table->increments('id'); + $table->integer('active_job_id')->nullable(); + $table->string('state')->default('active'); + }); + $schema->create('cloud_template_replicas', static function ( + Blueprint $table + ): void { + $table->integer('template_id'); + $table->integer('job_id')->nullable(); + $table->string('state')->default('pending'); + }); + $schema->create('cloud_user_isos', static function ( + Blueprint $table + ): void { + $table->increments('id'); + $table->integer('active_job_id')->nullable(); + $table->string('state')->default('ready'); + }); + $schema->create('cloud_user_iso_replicas', static function ( + Blueprint $table + ): void { + $table->integer('user_iso_id'); + $table->integer('job_id')->nullable(); + $table->string('state')->default('pending'); + }); $schema->create('cloud_mail_outbox', static function (Blueprint $table): void { $table->increments('id'); $table->string('status'); diff --git a/web/tests/CloudSingleDispatchArchitectureTest.php b/web/tests/CloudSingleDispatchArchitectureTest.php index 0388d872..651337e6 100644 --- a/web/tests/CloudSingleDispatchArchitectureTest.php +++ b/web/tests/CloudSingleDispatchArchitectureTest.php @@ -30,6 +30,9 @@ $operationRecovery = $read( $automaticRecovery = $read( 'app/Services/Cloud/CloudAutomaticOperationRecoveryService.php' ); +$adminOperationRecovery = $read( + 'app/Services/Cloud/CloudAdminOperationRecoveryService.php' +); $adminOperations = $read('app/Services/Cloud/CloudAdminOperationsService.php'); $adminOperationsController = $read( 'app/Controllers/CloudAdminOperationsController.php' @@ -66,10 +69,10 @@ $recoverySeam = substr( 1200 ); $assert(str_contains($recoverySeam, - "(string) \$job->kind !== 'instance_settings'") + 'CloudOperationRecoveryPolicy::supports((string) $job->kind)') && str_contains($recoverySeam, "throw new CloudError('任务类型不支持自动效果恢复', 409)"), - 'The public recovered-effect seam is not restricted to instance settings.'); + 'The public recovered-effect seam does not use the explicit leaf policy.'); $assert(str_contains($worker, "->where('dispatch_attempts', 0)") && str_contains($worker, "'dispatch_attempts' => 1") && substr_count($worker, 'self::dispatchableBeforeDeadline(') >= 3 @@ -166,14 +169,43 @@ $fenceWrite = strpos( 'CloudAdminOperationRecoveryService::resolveFenceForRecovery(' ); $effectCommit = strpos($fenceCommit, 'self::commitPrepared('); -$assert(str_contains($fenceCommit, '->lockForUpdate()->first()') - && str_contains($fenceCommit, "'lease_until', '>', time()") +$lockedJob = strpos($fenceCommit, '->lockForUpdate()->first()'); +$leaseCheck = strpos($fenceCommit, '(int) $job->lease_until <= time()'); +$jobContext = substr( + $adminOperationRecovery, + strpos($adminOperationRecovery, 'private static function jobContext'), + 3500 +); +$envelopeCheck = strpos( + $jobContext, + 'CloudJobService::hasTerminalRecoveryStateConflict($job)' +); +$clientCreation = strpos( + $jobContext, + 'CloudAgentSettingsService::clientForConfiguration(' +); +$terminalStateConflict = substr( + $jobs, + strpos($jobs, 'public static function hasTerminalRecoveryStateConflict'), + 2200 +); +$assert($lockedJob !== false + && $leaseCheck !== false && $pendingReceiptCheck !== false && $fenceWrite !== false && $effectCommit !== false + && $envelopeCheck !== false + && $clientCreation !== false + && $lockedJob < $leaseCheck + && $leaseCheck < $pendingReceiptCheck && $pendingReceiptCheck < $fenceWrite - && $fenceWrite < $effectCommit, - 'Automatic fence write is not serialized with lease, receipt, and PHP commit checks.'); + && $fenceWrite < $effectCommit + && $envelopeCheck < $clientCreation + && str_contains( + $terminalStateConflict, + 'self::hasAgentRecoveryEnvelopeConflict($job)' + ), + 'Automatic fence write is not serialized after locked lease, immutable envelope, receipt, and PHP commit checks.'); $assert(!str_contains(substr($jobModel, strpos($jobModel, "\$job->request_fingerprint = hash")), 'sealed_payload') diff --git a/web/tests/CloudSnapshotWorkflowTest.php b/web/tests/CloudSnapshotWorkflowTest.php index 9e5125e0..3ac3347a 100644 --- a/web/tests/CloudSnapshotWorkflowTest.php +++ b/web/tests/CloudSnapshotWorkflowTest.php @@ -117,6 +117,22 @@ namespace { $table->string('generation_token'); $table->string('state'); }); + $schema->create('cloud_template_replicas', + static function (Blueprint $table): void { + $table->integer('host_id'); + $table->string('template_id'); + $table->integer('revision'); + $table->string('generation_token'); + $table->string('state'); + $table->integer('image_bytes'); + $table->string('sha256'); + $table->string('operation_id'); + $table->integer('job_id')->nullable(); + $table->string('error_code'); + $table->integer('created_at'); + $table->integer('updated_at'); + $table->primary(['host_id', 'template_id']); + }); $capsule->getConnection('default')->table('cloud_templates')->insert([ 'id' => 'debian-12', 'name' => 'Debian 12', @@ -128,6 +144,22 @@ namespace { 'generation_token' => str_repeat('a', 32), 'state' => 'active', ]); + $capsule->getConnection('default')->table( + 'cloud_template_replicas' + )->insert([ + 'host_id' => 7, + 'template_id' => 'debian-12', + 'revision' => 1, + 'generation_token' => str_repeat('a', 32), + 'state' => 'active', + 'image_bytes' => 4096, + 'sha256' => hash('sha256', 'snapshot-template'), + 'operation_id' => 'snapshot-fixture-template-import', + 'job_id' => null, + 'error_code' => '', + 'created_at' => time(), + 'updated_at' => time(), + ]); $schema->create('cloud_jobs', static function (Blueprint $table): void { $table->increments('id'); $table->string('operation_id')->unique(); diff --git a/web/tests/CloudSpecialTaskSingleDispatchTest.php b/web/tests/CloudSpecialTaskSingleDispatchTest.php index 216503b4..59369f87 100644 --- a/web/tests/CloudSpecialTaskSingleDispatchTest.php +++ b/web/tests/CloudSpecialTaskSingleDispatchTest.php @@ -57,7 +57,11 @@ $assert(str_contains($jobs, 'reserveAggregate(') && str_contains($adminController, "'Idempotency-Key'"), 'Public task identity, idempotency, or parent visibility is incomplete.'); -$assert(str_contains($worker, +$assert(str_contains($worker, 'quarantineInvalidExecutionModeJob()') + && str_contains($worker, "->where('execution_mode', 'agent')") + && str_contains($worker, "->where('execution_mode', 'local')") + && str_contains($worker, "->where('kind', 'payment_create')") + && !str_contains($worker, "->whereIn('execution_mode', ['agent', 'local'])") && str_contains($worker, "->where('dispatch_attempts', 0)") && str_contains($jobs, "\$job->execution_mode = 'aggregate'") diff --git a/web/tests/CloudTaskDeadlineFallbackTest.php b/web/tests/CloudTaskDeadlineFallbackTest.php index d49371ae..00441b4e 100644 --- a/web/tests/CloudTaskDeadlineFallbackTest.php +++ b/web/tests/CloudTaskDeadlineFallbackTest.php @@ -34,6 +34,8 @@ namespace { use App\Services\Cloud\CloudAutomaticOperationRecoveryService; use App\Services\Cloud\CloudJobService; use App\Services\Cloud\CloudOperationCompletionService; + use App\Services\Cloud\CloudOperationRecoveryIdentity; + use App\Services\Cloud\CloudOperationRecoveryPolicy; use App\Services\Cloud\CloudOperationRecoveryService; use App\Services\Cloud\CloudSecrets; use App\Services\Cloud\CloudWorkerService; @@ -81,7 +83,7 @@ namespace { $table->text('sealed_payload'); $table->integer('attempts')->default(0); $table->integer('dispatch_attempts')->default(0); - $table->integer('dispatch_deadline_at'); + $table->integer('dispatch_deadline_at')->nullable(); $table->integer('dispatch_started_at')->nullable(); $table->integer('agent_accepted_at')->nullable(); $table->integer('receipt_deadline_at')->nullable(); @@ -167,6 +169,49 @@ namespace { $table->integer('applied_at')->nullable(); $table->unique(['host_id', 'operation_id']); }); + $schema->create('cloud_templates', + static function (Blueprint $table): void { + $table->string('id')->primary(); + $table->integer('active_job_id')->nullable(); + $table->string('state')->default('active'); + }); + $schema->create('cloud_user_isos', + static function (Blueprint $table): void { + $table->string('id')->primary(); + $table->integer('active_job_id')->nullable(); + $table->string('state')->default('active'); + }); + $schema->create('cloud_template_replicas', + static function (Blueprint $table): void { + $table->integer('host_id'); + $table->string('template_id'); + $table->integer('revision')->default(0); + $table->string('generation_token')->default(''); + $table->string('state')->default('pending'); + $table->integer('image_bytes')->default(0); + $table->string('sha256')->default(''); + $table->string('operation_id')->default(''); + $table->integer('job_id')->nullable(); + $table->string('error_code')->default(''); + $table->integer('created_at')->default(0); + $table->integer('updated_at')->default(0); + $table->primary(['host_id', 'template_id']); + }); + $schema->create('cloud_user_iso_replicas', + static function (Blueprint $table): void { + $table->integer('host_id'); + $table->string('user_iso_id'); + $table->integer('user_id'); + $table->string('state')->default('pending'); + $table->integer('size_bytes')->default(0); + $table->string('sha256')->default(''); + $table->string('operation_id')->default(''); + $table->integer('job_id')->nullable(); + $table->string('error_code')->default(''); + $table->integer('created_at')->default(0); + $table->integer('updated_at')->default(0); + $table->primary(['host_id', 'user_iso_id']); + }); $schema->create('cloud_invoice_payments', static function (Blueprint $table): void { $table->increments('id'); @@ -288,19 +333,133 @@ namespace { 'updated_at' => $now - 3600, ]); }; + $storagePayload = static function (string $operationId): string { + return CloudSecrets::encrypt([ + 'method' => 'POST', + 'request_target' => '/v1/storage/configuration', + 'body' => [ + 'managed_directory' => '/home/libvirt/kvm', + 'template_directory' => '/home/libvirt/images', + 'seed_directory' => '/home/libvirt/seed', + 'user_iso_directory' => '/home/libvirt/iso', + 'rescue_directory' => '/home/libvirt/rescue-iso', + 'operation_id' => $operationId, + ], + 'owner_id' => 1, + 'can_manage' => true, + 'storage_revision' => 1, + ], 'job-payload'); + }; + $identityFor = static function ( + string $operationId, + bool $applied + ): array { + $job = CloudJob::where('operation_id', $operationId)->firstOrFail(); + if (CloudOperationRecoveryIdentity::supports((string) $job->kind)) { + return CloudOperationRecoveryIdentity::expected($job, $applied); + } + return [ + 'action' => 'test-mutation', + 'resource_id' => 'operation-' . substr($operationId, 0, 16), + 'request_fingerprint' => hash('sha256', $operationId), + ]; + }; + $withIdentity = static function (array $receipt) use ( + $identityFor + ): array { + return $receipt + $identityFor( + (string) $receipt['operation_id'], + ($receipt['status'] ?? null) === 'succeeded' + ); + }; + $storedEvent = static function ( + array $receipt, + int $receivedAt, + string $disposition = 'received' + ): array { + $canonical = [ + 'event_id' => $receipt['id'], + 'host_id' => (int) $receipt['agent_id'], + 'operation_id' => $receipt['operation_id'], + 'action' => $receipt['action'], + 'resource_id' => $receipt['resource_id'], + 'request_fingerprint' => $receipt['request_fingerprint'], + 'status' => $receipt['status'], + 'effect_may_have_applied' => + $receipt['effect_may_have_applied'], + 'safe_to_resubmit' => $receipt['safe_to_resubmit'], + 'error_code' => $receipt['error_code'], + 'result' => $receipt['result'], + ]; + return [ + 'event_id' => $canonical['event_id'], + 'host_id' => $canonical['host_id'], + 'operation_id' => $canonical['operation_id'], + 'payload_sha256' => hash('sha256', json_encode( + $canonical, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + | JSON_UNESCAPED_UNICODE + )), + 'outcome' => $canonical['status'], + 'effect_may_have_applied' => + $canonical['effect_may_have_applied'] ? 1 : 0, + 'safe_to_resubmit' => $canonical['safe_to_resubmit'] ? 1 : 0, + 'error_code' => $canonical['error_code'], + 'result_json' => json_encode([ + 'schema' => 'virt_cloud_completion_event', + 'version' => 1, + 'identity' => [ + 'action' => $canonical['action'], + 'resource_id' => $canonical['resource_id'], + 'request_fingerprint' => + $canonical['request_fingerprint'], + ], + 'result' => $canonical['result'], + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + | JSON_UNESCAPED_UNICODE), + 'disposition' => $disposition, + 'received_at' => $receivedAt, + 'applied_at' => null, + ]; + }; $receiptOperation = str_repeat('a', 32); $receiptJobId = $insertJob(1, $receiptOperation, 'dispatching', 1); - Capsule::table('cloud_agent_completion_events')->insert([ + $receiptIdentity = [ + 'action' => 'test-mutation', + 'resource_id' => 'test-resource', + 'request_fingerprint' => str_repeat('1', 64), + ]; + $receipt = [ 'event_id' => str_repeat('e', 32), 'host_id' => 7, 'operation_id' => $receiptOperation, - 'payload_sha256' => str_repeat('1', 64), + ] + $receiptIdentity + [ + 'status' => 'succeeded', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'error_code' => '', + 'result' => ['confirmed' => true], + ]; + Capsule::table('cloud_agent_completion_events')->insert([ + 'event_id' => $receipt['event_id'], + 'host_id' => 7, + 'operation_id' => $receiptOperation, + 'payload_sha256' => hash('sha256', json_encode( + $receipt, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + | JSON_UNESCAPED_UNICODE + )), 'outcome' => 'succeeded', 'effect_may_have_applied' => 0, 'safe_to_resubmit' => 0, 'error_code' => '', - 'result_json' => json_encode(['confirmed' => true], JSON_THROW_ON_ERROR), + 'result_json' => json_encode([ + 'schema' => 'virt_cloud_completion_event', + 'version' => 1, + 'identity' => $receiptIdentity, + 'result' => $receipt['result'], + ], JSON_THROW_ON_ERROR), 'disposition' => 'received', 'received_at' => $now - 15, 'applied_at' => null, @@ -343,6 +502,102 @@ namespace { && !array_key_exists('credential', $failedRecoveryPayload), 'An unsupported unknown-effect kind retained secret recovery escrow.'); + // dispatch_attempts is a durable 0/1 fence, not a retry counter. Values + // outside that state machine must fail closed: neither deadline handling + // nor its last-resort finalizer may reinterpret them as "not dispatched". + $invalidLedgerUuid = + '00000000-0000-4000-8000-000000000301'; + $insertInstance(301, $invalidLedgerUuid, 'invalid-ledger-settings'); + $invalidLedgerOperation = str_repeat('cd', 16); + $invalidLedgerJobId = $insertJob( + 1, + $invalidLedgerOperation, + 'dispatching', + -1 + ); + $invalidLedgerPayload = CloudSecrets::encrypt([ + 'method' => 'POST', + 'request_target' => '/v1/vms/' . $invalidLedgerUuid . '/settings', + 'body' => [ + 'hostname' => 'invalid-ledger.example', + 'confirm_restart' => true, + ], + 'owner_id' => 1, + 'can_manage' => false, + 'settings_fields' => ['hostname'], + ], 'job-payload'); + Capsule::table('cloud_jobs')->where('id', $invalidLedgerJobId)->update([ + 'kind' => 'instance_settings', + 'instance_id' => 301, + 'sealed_payload' => $invalidLedgerPayload, + 'dispatch_started_at' => $now - 30, + 'dispatched_at' => $now - 30, + 'receipt_deadline_at' => $now - 10, + ]); + $assert(CloudWorkerService::expireDueTasksForOwner( + 1, + $invalidLedgerJobId, + 1 + ) === 1, 'The invalid dispatch-ledger deadline was not claimed.'); + $invalidLedgerJob = CloudJob::findOrFail($invalidLedgerJobId); + $assert((string) $invalidLedgerJob->phase === 'terminal' + && (string) $invalidLedgerJob->outcome === 'failed' + && (int) $invalidLedgerJob->dispatch_attempts === -1 + && (bool) $invalidLedgerJob->effect_may_have_applied + && !(bool) $invalidLedgerJob->safe_to_resubmit + && (string) $invalidLedgerJob->effect_resolution === 'unknown' + && (bool) $invalidLedgerJob->finalization_incident + && (string) $invalidLedgerJob->finalization_error_code + === 'recovery_dispatch_ledger_conflict' + && (string) $invalidLedgerJob->sealed_payload + === $invalidLedgerPayload, + 'A negative dispatch ledger was treated as a safe undispatched failure.'); + + // Exercise the same invariant through forceTerminalFailure(): the linked + // instance is intentionally absent so the ordinary policy finalizer fails + // and the last-resort path owns the durable incident write. + $forcedLedgerOperation = str_repeat('ce', 16); + $forcedLedgerJobId = $insertJob( + 1, + $forcedLedgerOperation, + 'dispatching', + 2 + ); + $forcedLedgerPayload = CloudSecrets::encrypt([ + 'method' => 'POST', + 'request_target' => '/v1/vms/' + . '00000000-0000-4000-8000-000000009999/suspend', + 'body' => [], + 'owner_id' => 1, + 'can_manage' => false, + ], 'job-payload'); + Capsule::table('cloud_jobs')->where('id', $forcedLedgerJobId)->update([ + 'kind' => 'service_suspend', + 'instance_id' => 9999, + 'sealed_payload' => $forcedLedgerPayload, + 'dispatch_started_at' => $now - 30, + 'dispatched_at' => $now - 30, + 'receipt_deadline_at' => $now - 10, + ]); + $assert(CloudWorkerService::expireDueTasksForOwner( + 1, + $forcedLedgerJobId, + 1 + ) === 1, 'The forced invalid dispatch-ledger deadline was not claimed.'); + $forcedLedgerJob = CloudJob::findOrFail($forcedLedgerJobId); + $assert((string) $forcedLedgerJob->phase === 'terminal' + && (string) $forcedLedgerJob->outcome === 'failed' + && (int) $forcedLedgerJob->dispatch_attempts === 2 + && (bool) $forcedLedgerJob->effect_may_have_applied + && !(bool) $forcedLedgerJob->safe_to_resubmit + && (string) $forcedLedgerJob->effect_resolution === 'unknown' + && (bool) $forcedLedgerJob->finalization_incident + && (string) $forcedLedgerJob->finalization_error_code + === 'recovery_dispatch_ledger_conflict' + && (string) $forcedLedgerJob->sealed_payload + === $forcedLedgerPayload, + 'The forced finalizer concealed or unlocked an invalid dispatch ledger.'); + // Deploying the shorter storage window must also bound tasks which already // persisted the old 960-second receipt deadline. No data rewrite is needed: // the effective deadline is the earlier of the two absolute boundaries. @@ -352,6 +607,7 @@ namespace { ); Capsule::table('cloud_jobs')->where('id', $legacyStorageJobId)->update([ 'kind' => 'host_storage_configure', + 'sealed_payload' => $storagePayload($legacyStorageOperation), 'dispatched_at' => $now - 181, 'dispatch_started_at' => $now - 181, 'receipt_deadline_at' => $now + 779, @@ -392,6 +648,7 @@ namespace { ); Capsule::table('cloud_jobs')->where('id', $lateStorageJobId)->update([ 'kind' => 'host_storage_configure', + 'sealed_payload' => $storagePayload($lateStorageOperation), 'dispatched_at' => $now - 181, 'dispatch_started_at' => $now - 181, 'receipt_deadline_at' => $now + 779, @@ -402,17 +659,20 @@ namespace { 'job_id' => $lateStorageJobId, 'updated_at' => $now, ]); $lateStorageEventId = str_repeat('4', 32); - Capsule::table('cloud_agent_completion_events')->insert([ - 'event_id' => $lateStorageEventId, 'host_id' => 7, + $lateStorageReceipt = $withIdentity([ + 'type' => 'completion', + 'id' => $lateStorageEventId, + 'agent_id' => '7', 'operation_id' => $lateStorageOperation, - 'payload_sha256' => str_repeat('3', 64), - 'outcome' => 'succeeded', 'effect_may_have_applied' => 0, - 'safe_to_resubmit' => 0, 'error_code' => '', - 'result_json' => json_encode(['configured' => true], - JSON_THROW_ON_ERROR), - 'disposition' => 'received', 'received_at' => $now - 1, - 'applied_at' => null, + 'status' => 'succeeded', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'error_code' => '', + 'result' => ['configured' => true], ]); + Capsule::table('cloud_agent_completion_events')->insert( + $storedEvent($lateStorageReceipt, $now - 1) + ); $lateStorage = (new CloudWorkerService())->settleCompletionReceipt( $lateStorageJobId, $lateStorageEventId ); @@ -429,6 +689,7 @@ namespace { ); Capsule::table('cloud_jobs')->where('id', $acceptedStorageJobId)->update([ 'kind' => 'host_storage_configure', + 'sealed_payload' => $storagePayload($acceptedStorageOperation), 'created_at' => $now - 61, 'dispatch_deadline_at' => $now + 239, ]); @@ -461,6 +722,7 @@ namespace { ); Capsule::table('cloud_jobs')->where('id', $tickStorageJobId)->update([ 'kind' => 'host_storage_configure', + 'sealed_payload' => $storagePayload($tickStorageOperation), 'created_at' => time() - 61, 'dispatch_deadline_at' => time() + 239, ]); @@ -511,7 +773,7 @@ namespace { && (string) $incident->error_code === 'local_finalization_failed' && (bool) $incident->finalization_incident && (string) $incident->finalization_error_code - === 'completion_deadline_exceeded' + === 'recovery_payload_unavailable' && (string) $incident->sealed_payload === '', 'A local finalizer crash left the task active, leaked its payload, or concealed the incident.'); @@ -538,28 +800,64 @@ namespace { ); $assert((bool) $redactedIncident->finalization_incident && (string) $redactedIncident->effect_resolution === 'unknown' - && !array_key_exists('credential', $redactedIncidentPayload), - 'An unsupported finalization incident retained secret recovery escrow.'); + && array_key_exists('credential', $redactedIncidentPayload), + 'A recoverable finalization incident lost its encrypted recovery escrow.'); + Capsule::table('cloud_jobs')->where( + 'id', + $redactedIncidentJobId + )->update(['available_at' => time() + 3600]); + + $unreadableEnvelope = 'deadline-test:missing-policy-payload'; + $unreadableIncidentJobId = $insertJob( + 1, + '823456789abcdef0823456789abcdef0', + 'awaiting_receipt', + 1 + ); + Capsule::table('cloud_jobs')->where( + 'id', + $unreadableIncidentJobId + )->update([ + 'kind' => 'network_change', + 'sealed_payload' => $unreadableEnvelope, + ]); + $assert(CloudWorkerService::expireDueTasksForOwner( + 1, + $unreadableIncidentJobId, + 1 + ) === 1, 'The unreadable recovery escrow fixture was not claimed.'); + $unreadableIncident = CloudJob::findOrFail($unreadableIncidentJobId); + $assert((bool) $unreadableIncident->finalization_incident + && (string) $unreadableIncident->finalization_error_code + === 'recovery_payload_unavailable' + && (string) $unreadableIncident->sealed_payload + === $unreadableEnvelope + && (int) $unreadableIncident->available_at >= time() + 290, + 'An unreadable recovery escrow was erased or left the retry queue.'); + Capsule::table('cloud_jobs')->where( + 'id', + $unreadableIncidentJobId + )->update(['available_at' => time() + 3600]); $lateOperation = str_repeat('7', 32); $lateJobId = $insertJob(1, $lateOperation, 'awaiting_receipt', 1); $lateEventId = str_repeat('6', 32); - Capsule::table('cloud_agent_completion_events')->insert([ - 'event_id' => $lateEventId, - 'host_id' => 7, + $lateReceipt = $withIdentity([ + 'type' => 'completion', + 'id' => $lateEventId, + 'agent_id' => '7', 'operation_id' => $lateOperation, - 'payload_sha256' => str_repeat('2', 64), - 'outcome' => 'succeeded', - 'effect_may_have_applied' => 0, - 'safe_to_resubmit' => 0, + 'status' => 'succeeded', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, 'error_code' => '', - 'result_json' => json_encode(['confirmed' => true], - JSON_THROW_ON_ERROR), - 'disposition' => 'received', - // Equal to or later than the absolute boundary is audit-only. - 'received_at' => $now - 9, - 'applied_at' => null, + 'result' => ['confirmed' => true], ]); + Capsule::table('cloud_agent_completion_events')->insert($storedEvent( + $lateReceipt, + // Equal to or later than the absolute boundary is audit-only. + $now - 9 + )); $lateJob = (new CloudWorkerService())->settleCompletionReceipt( $lateJobId, $lateEventId ); @@ -578,7 +876,7 @@ namespace { // If that finalizer fails, the matching on-time receipt must stay received // so the settings recovery worker can finish PHP without Agent replay. $onTimeRecoveryInstanceId = 90; - $onTimeRecoveryUuid = '00000000-1111-2222-3333-444444444444'; + $onTimeRecoveryUuid = '00000000-1111-4222-8333-444444444444'; $insertInstance( $onTimeRecoveryInstanceId, $onTimeRecoveryUuid, @@ -615,7 +913,7 @@ namespace { 'credential' => null, ], 'job-payload'), ]); - $onTimeRecoveryReceipt = [ + $onTimeRecoveryReceipt = $withIdentity([ 'type' => 'completion', 'id' => 'settings-on-time-finalizer-0001', 'agent_id' => '7', @@ -628,7 +926,7 @@ namespace { 'settings_changed' => true, 'hostname' => 'on-time-recovered.example', ], - ]; + ]); $assert(CloudOperationCompletionService::accept( $onTimeRecoveryReceipt ) === ['accepted' => true, 'disposition' => 'received'], @@ -684,7 +982,7 @@ namespace { // failed its task. The immutable late receipt must converge the instance // ledger and release the blocker without rewriting the failed task. $settingsInstanceId = 91; - $settingsUuid = '11111111-2222-3333-4444-555555555555'; + $settingsUuid = '11111111-2222-4333-8444-555555555555'; $insertInstance($settingsInstanceId, $settingsUuid, 'late-settings-vm'); $settingsOperation = 'abcdef0123456789abcdef0123456789'; $settingsJobId = $insertJob( @@ -734,7 +1032,7 @@ namespace { 'completion_event_id' => $timedOutSettings->completion_event_id, 'read_at' => $timedOutSettings->read_at, ]; - $settingsReceipt = [ + $settingsReceipt = $withIdentity([ 'type' => 'completion', 'id' => 'settings-recovery-event-000001', 'agent_id' => '7', @@ -746,7 +1044,7 @@ namespace { 'result' => [ 'settings_changed' => true, ], - ]; + ]); $settingsAccepted = CloudOperationCompletionService::accept( $settingsReceipt ); @@ -840,7 +1138,7 @@ namespace { // vocabulary is normalized to the settings no-effect finalizer; it never // authorizes replay even when safe_to_resubmit=true. $notAppliedInstanceId = 93; - $notAppliedUuid = 'bbbbbbbb-cccc-dddd-eeee-ffffffffffff'; + $notAppliedUuid = 'bbbbbbbb-cccc-4ddd-8eee-ffffffffffff'; $insertInstance( $notAppliedInstanceId, $notAppliedUuid, @@ -891,7 +1189,7 @@ namespace { 'completion_event_id' => $notAppliedTerminal->completion_event_id, ]; - $notAppliedReceipt = [ + $notAppliedReceipt = $withIdentity([ 'type' => 'completion', 'id' => 'settings-no-effect-event-000001', 'agent_id' => '7', @@ -901,7 +1199,7 @@ namespace { 'safe_to_resubmit' => true, 'error_code' => 'guest_update_failed', 'result' => ['agent_detail' => 'bounded'], - ]; + ]); $assert(CloudOperationCompletionService::accept( $notAppliedReceipt ) === ['accepted' => true, 'disposition' => 'applied'], @@ -936,7 +1234,7 @@ namespace { // worker must discover the exact received event through the job's indexed // host+operation key, even when inspection retries were already exhausted. $persistedEventInstanceId = 96; - $persistedEventUuid = 'eeeeeeee-ffff-0000-1111-000000000003'; + $persistedEventUuid = 'eeeeeeee-ffff-4000-8111-000000000003'; $insertInstance( $persistedEventInstanceId, $persistedEventUuid, @@ -981,41 +1279,20 @@ namespace { ]); $persistedEventId = 'settings-persisted-event-00001'; $persistedEventResult = ['agent_detail' => 'persisted-before-prepare']; - $persistedEventReceipt = [ - 'event_id' => $persistedEventId, - 'host_id' => 7, + $persistedEventReceipt = $withIdentity([ + 'type' => 'completion', + 'id' => $persistedEventId, + 'agent_id' => '7', 'operation_id' => $persistedEventOperationId, 'status' => 'failed', 'effect_may_have_applied' => false, 'safe_to_resubmit' => true, 'error_code' => 'guest_update_failed', 'result' => $persistedEventResult, - ]; - Capsule::table('cloud_agent_completion_events')->insert([ - 'event_id' => $persistedEventId, - 'host_id' => 7, - 'operation_id' => $persistedEventOperationId, - 'payload_sha256' => hash( - 'sha256', - json_encode( - $persistedEventReceipt, - JSON_THROW_ON_ERROR - | JSON_UNESCAPED_SLASHES - | JSON_UNESCAPED_UNICODE - ) - ), - 'outcome' => 'failed', - 'effect_may_have_applied' => 0, - 'safe_to_resubmit' => 1, - 'error_code' => 'guest_update_failed', - 'result_json' => json_encode( - $persistedEventResult, - JSON_THROW_ON_ERROR - ), - 'disposition' => 'received', - 'received_at' => time(), - 'applied_at' => null, ]); + Capsule::table('cloud_agent_completion_events')->insert( + $storedEvent($persistedEventReceipt, time()) + ); $persistedEventAudit = CloudJob::find($persistedEventJobId); $persistedEventAudit = [ 'phase' => (string) $persistedEventAudit->phase, @@ -1051,11 +1328,11 @@ namespace { 'Persisted pre-prepare receipt did not converge locally and exactly.'); // A row with the right indexed host+operation but a conflicting immutable - // payload hash is not receipt authority. Reject only that event and retain - // the original effect blocker; do not fall through to an Agent request in - // the same tick. + // payload hash is not receipt authority. Reject only that event, surface + // the concrete receipt error, and leave the job queued for fresh + // inspection without contacting the Agent in the same tick. $conflictEventInstanceId = 97; - $conflictEventUuid = 'ffffffff-0000-1111-2222-000000000004'; + $conflictEventUuid = 'ffffffff-0000-4111-8222-000000000004'; $insertInstance( $conflictEventInstanceId, $conflictEventUuid, @@ -1126,17 +1403,20 @@ namespace { && (string) $conflictEventJob->effect_resolution === 'unknown' && (bool) $conflictEventJob->finalization_incident && (string) $conflictEventJob->finalization_error_code - === 'recovery_state_invalid' + === 'recovery_receipt_invalid' + && (int) $conflictEventJob->available_at >= time() + 290 && CloudJobService::blockingQueryForInstance( $conflictEventInstanceId )->exists(), 'A conflicting persisted event altered the job or released its lock.'); // A self-consistent late receipt may still contradict an already prepared - // conclusion. Such conflicts are deterministic: atomically park the event - // once, retain the original marker/escrow/blocker, and never poll Agent. + // conclusion. Such conflicts are deterministic: atomically isolate the + // event once, retain the original marker/escrow/blocker, and schedule a + // later fresh inspection without polling Agent in the same tick. $conflictEscrow = (string) $conflictEventJob->sealed_payload; - $noEffectOperation = [ + $conflictIdentity = $identityFor($conflictEventOperationId, false); + $noEffectOperation = $conflictIdentity + [ 'effect_may_have_applied' => false, 'error_code' => 'settings_not_committed', 'operation_id' => $conflictEventOperationId, @@ -1144,10 +1424,12 @@ namespace { 'safe_to_resubmit' => false, 'status' => 'failed', ]; + $canonicalNoEffectOperation = $noEffectOperation; + ksort($canonicalNoEffectOperation, SORT_STRING); $noEffectOperationHash = hash( 'sha256', json_encode( - $noEffectOperation, + $canonicalNoEffectOperation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE @@ -1162,18 +1444,21 @@ namespace { ) use ( $conflictEventId, $conflictEventJobId, - $conflictEventOperationId + $conflictEventOperationId, + $storedEvent, + $withIdentity ): void { - $receipt = [ - 'event_id' => $conflictEventId, - 'host_id' => 7, + $receipt = $withIdentity([ + 'type' => 'completion', + 'id' => $conflictEventId, + 'agent_id' => '7', 'operation_id' => $conflictEventOperationId, 'status' => $status, 'effect_may_have_applied' => false, 'safe_to_resubmit' => $safeToResubmit, 'error_code' => $errorCode, 'result' => $result, - ]; + ]); Capsule::table('cloud_jobs')->where( 'id', $conflictEventJobId @@ -1185,31 +1470,11 @@ namespace { 'lease_until' => 0, 'available_at' => 0, ]); + $eventRow = $storedEvent($receipt, time()); Capsule::table('cloud_agent_completion_events')->where( 'event_id', $conflictEventId - )->update([ - 'payload_sha256' => hash( - 'sha256', - json_encode( - $receipt, - JSON_THROW_ON_ERROR - | JSON_UNESCAPED_SLASHES - | JSON_UNESCAPED_UNICODE - ) - ), - 'outcome' => $status, - 'effect_may_have_applied' => 0, - 'safe_to_resubmit' => $safeToResubmit ? 1 : 0, - 'error_code' => $errorCode, - 'result_json' => json_encode( - $result, - JSON_THROW_ON_ERROR - ), - 'disposition' => 'received', - 'received_at' => time(), - 'applied_at' => null, - ]); + )->update($eventRow); }; $assertPreparedConflict = static function ( string $marker, @@ -1237,18 +1502,19 @@ namespace { && (string) $job->sealed_payload === $conflictEscrow && $job->lease_token === null && (int) $job->lease_until === 0 - && (int) $job->available_at === 0 + && (int) $job->available_at >= time() + 290 && CloudJobService::blockingQueryForInstance( $conflictEventInstanceId )->exists(), $message . ' did not retain the fail-closed evidence fence.'); - $secondTick = (new CloudAutomaticOperationRecoveryService())->tick(); + // Other newly recoverable kinds may be claimed here; the isolated job + // itself must remain untouched until its own retry time arrives. + (new CloudAutomaticOperationRecoveryService())->tick(); $afterSecondTick = CloudJob::find($conflictEventJobId); $afterSecondEvent = Capsule::table( 'cloud_agent_completion_events' )->where('event_id', $conflictEventId)->first(); - $assert($secondTick === false - && (int) $afterSecondTick->updated_at === $updatedAt + $assert((int) $afterSecondTick->updated_at === $updatedAt && (string) $afterSecondTick->effect_resolution === 'unknown' && (string) $afterSecondTick->effect_resolution_reason === $marker && (bool) $afterSecondTick->finalization_incident @@ -1260,7 +1526,7 @@ namespace { && CloudJobService::blockingQueryForInstance( $conflictEventInstanceId )->exists(), - $message . ' was claimed more than once.'); + $message . ' ignored its retry backoff.'); }; $directionConflictMarker = 'automatic_recovery:v1:' @@ -1323,31 +1589,9 @@ namespace { $noEffectFenceConflictMarker, 'No-effect active-fence late evidence' ); - $staleConflictCommitRejected = false; - try { - CloudOperationRecoveryService::commitNotApplied( - $conflictEventJobId, - $noEffectOperation, - 'automatic_not_applied_failed_fence:' . str_repeat('4', 64), - 0 - ); - } catch (\App\Services\Cloud\CloudRecoveryEvidenceConflict $error) { - $staleConflictCommitRejected = $error->httpStatus === 409; - } - $staleConflictJob = CloudJob::find($conflictEventJobId); - $assert($staleConflictCommitRejected - && (string) $staleConflictJob->effect_resolution === 'unknown' - && (string) $staleConflictJob->effect_resolution_reason - === $noEffectFenceConflictMarker - && (string) $staleConflictJob->finalization_error_code - === 'recovery_evidence_conflict' - && CloudJobService::blockingQueryForInstance( - $conflictEventInstanceId - )->exists(), - 'An in-flight automatic worker committed after conflict parking.'); $appliedReceiptResult = ['settings_changed' => true]; - $appliedOperation = [ + $appliedOperation = $conflictIdentity + [ 'effect_may_have_applied' => false, 'error_code' => '', 'operation_id' => $conflictEventOperationId, @@ -1355,10 +1599,12 @@ namespace { 'safe_to_resubmit' => false, 'status' => 'succeeded', ]; + $canonicalAppliedOperation = $appliedOperation; + ksort($canonicalAppliedOperation, SORT_STRING); $appliedOperationHash = hash( 'sha256', json_encode( - $appliedOperation, + $canonicalAppliedOperation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE @@ -1390,9 +1636,9 @@ namespace { . ':' . $noEffectOperationHash; $armConflictReceipt( 'failed', - true, - 'guest_update_failed', - ['agent_detail' => 'receipt-wins-commit-race'], + false, + 'settings_not_committed', + [], $pendingReceiptMarker ); $pendingReceiptCommitRejected = false; @@ -1438,7 +1684,7 @@ namespace { // the exact immutable event and finish PHP locally without an Agent // retransmission or host request. $lateCrashInstanceId = 95; - $lateCrashUuid = 'dddddddd-eeee-ffff-0000-000000000002'; + $lateCrashUuid = 'dddddddd-eeee-4fff-8000-000000000002'; $insertInstance( $lateCrashInstanceId, $lateCrashUuid, @@ -1472,18 +1718,20 @@ namespace { $lateCrashJobId, 1 ) === 1, 'The late-receipt crash fixture did not expire.'); - $lateCrashOperation = [ + $lateCrashOperation = $identityFor($lateCrashOperationId, false) + [ 'effect_may_have_applied' => false, - 'error_code' => 'settings_not_committed', + 'error_code' => 'guest_update_failed', 'operation_id' => $lateCrashOperationId, - 'result' => [], - 'safe_to_resubmit' => false, + 'result' => ['agent_detail' => 'bounded'], + 'safe_to_resubmit' => true, 'status' => 'failed', ]; + $canonicalLateCrashOperation = $lateCrashOperation; + ksort($canonicalLateCrashOperation, SORT_STRING); $lateCrashOperationHash = hash( 'sha256', json_encode( - $lateCrashOperation, + $canonicalLateCrashOperation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE @@ -1498,36 +1746,20 @@ namespace { 'finalization_error_code' => 'recovery_limit_reached', ]); $lateCrashEventId = 'settings-late-crash-event-0001'; - Capsule::table('cloud_agent_completion_events')->insert([ - 'event_id' => $lateCrashEventId, - 'host_id' => 7, + $lateCrashReceipt = $withIdentity([ + 'type' => 'completion', + 'id' => $lateCrashEventId, + 'agent_id' => '7', 'operation_id' => $lateCrashOperationId, - 'payload_sha256' => hash( - 'sha256', - json_encode([ - 'event_id' => $lateCrashEventId, - 'host_id' => 7, - 'operation_id' => $lateCrashOperationId, - 'status' => 'failed', - 'effect_may_have_applied' => false, - 'safe_to_resubmit' => true, - 'error_code' => 'guest_update_failed', - 'result' => ['agent_detail' => 'bounded'], - ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES - | JSON_UNESCAPED_UNICODE) - ), - 'outcome' => 'failed', - 'effect_may_have_applied' => 0, - 'safe_to_resubmit' => 1, + 'status' => 'failed', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => true, 'error_code' => 'guest_update_failed', - 'result_json' => json_encode( - ['agent_detail' => 'bounded'], - JSON_THROW_ON_ERROR - ), - 'disposition' => 'received', - 'received_at' => time(), - 'applied_at' => null, + 'result' => ['agent_detail' => 'bounded'], ]); + Capsule::table('cloud_agent_completion_events')->insert( + $storedEvent($lateCrashReceipt, time()) + ); CloudOperationRecoveryService::prepareNotApplied( $lateCrashJobId, $lateCrashOperation, @@ -1580,7 +1812,7 @@ namespace { // contract. This deterministic local error must become one incident, not // an unbounded received-event loop every five minutes. $invalidReceiptInstanceId = 98; - $invalidReceiptUuid = '99999999-aaaa-bbbb-cccc-dddddddddddd'; + $invalidReceiptUuid = '99999999-aaaa-4bbb-8ccc-dddddddddddd'; $insertInstance( $invalidReceiptInstanceId, $invalidReceiptUuid, @@ -1617,7 +1849,7 @@ namespace { $invalidReceiptJobId, 1 ) === 1, 'The invalid-receipt fixture did not expire.'); - $invalidReceipt = [ + $invalidReceipt = $withIdentity([ 'type' => 'completion', 'id' => 'settings-invalid-result-event-01', 'agent_id' => '7', @@ -1629,7 +1861,7 @@ namespace { // The generic receipt is valid, but instance_settings requires the // explicit settings_changed proof before touching its PHP ledger. 'result' => ['hostname' => 'invalid-receipt.example'], - ]; + ]); $assert(CloudOperationCompletionService::accept( $invalidReceipt ) === ['accepted' => true, 'disposition' => 'late'], @@ -1638,85 +1870,70 @@ namespace { $invalidReceiptEvent = Capsule::table( 'cloud_agent_completion_events' )->where('event_id', $invalidReceipt['id'])->first(); - $invalidReceiptUpdatedAt = (int) $invalidReceiptJob->updated_at; $assert((string) $invalidReceiptJob->effect_resolution === 'unknown' && (bool) $invalidReceiptJob->finalization_incident && (string) $invalidReceiptJob->finalization_error_code === 'recovery_receipt_invalid' && (string) $invalidReceiptEvent->disposition === 'late' + && (int) $invalidReceiptJob->available_at >= time() + 290 && CloudJobService::blockingQueryForInstance( $invalidReceiptInstanceId )->exists(), 'An invalid receipt altered the ledger or released its blocker.'); - $assert(!(new CloudAutomaticOperationRecoveryService())->tick() - && (int) CloudJob::find($invalidReceiptJobId)->updated_at - === $invalidReceiptUpdatedAt - && CloudJobService::blockingQueryForInstance( - $invalidReceiptInstanceId - )->exists(), - 'An invalid receipt was re-claimed after terminal parking.'); - $invalidReceiptBefore = CloudJob::find($invalidReceiptJobId); - $invalidReceiptSpecBefore = (string) Capsule::table('cloud_instances') - ->where('id', $invalidReceiptInstanceId)->value('spec_json'); - $stalePrepareRejected = 0; - foreach ([ - [ - 'method' => 'prepareApplied', - 'operation' => [ - 'operation_id' => $invalidReceiptOperationId, - 'status' => 'succeeded', - 'effect_may_have_applied' => false, - 'safe_to_resubmit' => false, - 'error_code' => '', - 'result' => [ - 'settings_changed' => true, - 'hostname' => 'invalid-receipt.example', - ], - ], - ], - [ - 'method' => 'prepareNotApplied', - 'operation' => [ - 'operation_id' => $invalidReceiptOperationId, - 'status' => 'failed', - 'effect_may_have_applied' => false, - 'safe_to_resubmit' => false, - 'error_code' => 'settings_not_committed', - 'result' => [], - ], + // The incident is diagnostic, not a permanent queue state. A later fresh + // operation-bound inspection may prepare and publish a valid conclusion. + $freshInspectionOperation = $identityFor( + $invalidReceiptOperationId, + true + ) + [ + 'operation_id' => $invalidReceiptOperationId, + 'status' => 'succeeded', + 'effect_may_have_applied' => false, + 'safe_to_resubmit' => false, + 'error_code' => '', + 'result' => [ + 'settings_changed' => true, + 'hostname' => 'invalid-receipt.example', ], - ] as $stalePrepare) { - try { - $prepare = [ - CloudOperationRecoveryService::class, - $stalePrepare['method'], - ]; - $prepare( - $invalidReceiptJobId, - $stalePrepare['operation'], - 'agent_inspection:stale-after-receipt-incident' - ); - } catch (\App\Services\Cloud\CloudError $error) { - $stalePrepareRejected++; - } - } + ]; + $freshInspectionSource = + 'agent_inspection:fresh-after-receipt-incident'; + CloudOperationRecoveryService::prepareApplied( + $invalidReceiptJobId, + $freshInspectionOperation, + $freshInspectionSource + ); + CloudOperationRecoveryService::commitApplied( + $invalidReceiptJobId, + $freshInspectionOperation, + $freshInspectionSource, + 0 + ); $invalidReceiptAfter = CloudJob::find($invalidReceiptJobId); - $assert($stalePrepareRejected === 2 + $invalidReceiptSpec = json_decode( + (string) Capsule::table('cloud_instances') + ->where('id', $invalidReceiptInstanceId)->value('spec_json'), + true, + flags: JSON_THROW_ON_ERROR + ); + $assert((string) $invalidReceiptAfter->effect_resolution === 'applied' && (string) $invalidReceiptAfter->effect_resolution_reason - === (string) $invalidReceiptBefore->effect_resolution_reason - && (string) $invalidReceiptAfter->sealed_payload - === (string) $invalidReceiptBefore->sealed_payload - && (string) Capsule::table('cloud_instances') - ->where('id', $invalidReceiptInstanceId)->value('spec_json') - === $invalidReceiptSpecBefore, - 'A stale recovery prepared ledger state after a terminal incident.'); + === $freshInspectionSource + && !(bool) $invalidReceiptAfter->finalization_incident + && $invalidReceiptAfter->finalization_error_code === null + && $invalidReceiptAfter->read_at === null + && ($invalidReceiptSpec['guest_hostname'] ?? null) + === 'invalid-receipt.example' + && !CloudJobService::blockingQueryForInstance( + $invalidReceiptInstanceId + )->exists(), + 'A fresh inspection could not converge after an invalid receipt.'); // A valid immutable receipt may be temporarily unable to update a damaged - // local projection. Keep it retryable so an operator can repair PHP state, - // but park it after the absolute recovery window instead of looping - // forever. + // local projection. Age is audit metadata only: keep it retryable until an + // operator repairs PHP state, even beyond the former six-hour window. $receiptLimitInstanceId = 99; - $receiptLimitUuid = 'aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb'; + $receiptLimitUuid = 'aaaaaaaa-1111-4222-8333-bbbbbbbbbbbb'; $insertInstance( $receiptLimitInstanceId, $receiptLimitUuid, @@ -1757,7 +1974,7 @@ namespace { $receiptLimitJobId, 1 ) === 1, 'The receipt-limit fixture did not expire.'); - $receiptLimitReceipt = [ + $receiptLimitReceipt = $withIdentity([ 'type' => 'completion', 'id' => 'settings-receipt-limit-event-01', 'agent_id' => '7', @@ -1770,7 +1987,7 @@ namespace { 'settings_changed' => true, 'hostname' => 'receipt-limit.example', ], - ]; + ]); $assert(CloudOperationCompletionService::accept( $receiptLimitReceipt ) === ['accepted' => true, 'disposition' => 'received'], @@ -1782,16 +1999,11 @@ namespace { $assert((new CloudAutomaticOperationRecoveryService())->tick(), 'The recovery worker did not claim the near-limit receipt.'); $nearLimitJob = CloudJob::find($receiptLimitJobId); - $nearLimitReceivedAt = (int) Capsule::table( - 'cloud_agent_completion_events' - )->where('event_id', $receiptLimitReceipt['id']) - ->value('received_at'); $assert((string) Capsule::table('cloud_agent_completion_events') ->where('event_id', $receiptLimitReceipt['id']) ->value('disposition') === 'received' - && (int) $nearLimitJob->available_at - <= $nearLimitReceivedAt + 21600, - 'Receipt retry backoff crossed its absolute recovery deadline.'); + && (int) $nearLimitJob->available_at >= time() + 290, + 'A repairable receipt did not retain its retry backoff.'); Capsule::table('cloud_agent_completion_events')->where( 'event_id', $receiptLimitReceipt['id'] @@ -1805,34 +2017,59 @@ namespace { 'lease_token' => null, ]); $assert((new CloudAutomaticOperationRecoveryService())->tick(), - 'The recovery worker did not claim the expired receipt.'); + 'The recovery worker did not claim the six-hour-old receipt.'); $receiptLimitJob = CloudJob::find($receiptLimitJobId); $receiptLimitEvent = CloudAgentCompletionEvent::find( $receiptLimitReceipt['id'] ); - $receiptLimitUpdatedAt = (int) $receiptLimitJob->updated_at; $assert((string) $receiptLimitJob->effect_resolution === 'unknown' - && (bool) $receiptLimitJob->finalization_incident - && (string) $receiptLimitJob->finalization_error_code - === 'recovery_receipt_limit_reached' - && (string) $receiptLimitEvent->disposition === 'late' + && (string) $receiptLimitEvent->disposition === 'received' + && (int) $receiptLimitJob->available_at >= time() + 290 && CloudJobService::blockingQueryForInstance( $receiptLimitInstanceId )->exists(), - 'The expired receipt was not parked with its blocker intact.'); - $assert(CloudOperationRecoveryService::settleLateReceipt( - $receiptLimitJob, - $receiptLimitEvent - ) === 'late' - && (int) CloudJob::find($receiptLimitJobId)->updated_at - === $receiptLimitUpdatedAt, - 'A receipt was retried after its recovery limit incident.'); + 'A six-hour-old receipt left the recovery queue.'); + Capsule::table('cloud_instances')->where( + 'id', + $receiptLimitInstanceId + )->update(['spec_json' => json_encode( + ['managed' => true], + JSON_THROW_ON_ERROR + )]); + Capsule::table('cloud_jobs')->where( + 'id', + $receiptLimitJobId + )->update([ + 'available_at' => 0, + 'lease_until' => 0, + 'lease_token' => null, + ]); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'The repaired six-hour-old receipt was not claimed.'); + $receiptLimitJob = CloudJob::find($receiptLimitJobId); + $receiptLimitEvent = CloudAgentCompletionEvent::find( + $receiptLimitReceipt['id'] + ); + $receiptLimitSpec = json_decode( + (string) Capsule::table('cloud_instances') + ->where('id', $receiptLimitInstanceId)->value('spec_json'), + true, + flags: JSON_THROW_ON_ERROR + ); + $assert((string) $receiptLimitJob->effect_resolution === 'applied' + && (string) $receiptLimitEvent->disposition === 'applied' + && ($receiptLimitSpec['guest_hostname'] ?? null) + === 'receipt-limit.example' + && !CloudJobService::blockingQueryForInstance( + $receiptLimitInstanceId + )->exists(), + 'A repaired six-hour-old receipt did not converge.'); // Decryptable escrow is not enough: a password operation whose retained // credential DTO is missing must never be treated as a complete ledger // finalization merely because the Agent receipt says settings_changed. $damagedEscrowInstanceId = 100; - $damagedEscrowUuid = 'aaaaaaaa-2222-3333-4444-cccccccccccc'; + $damagedEscrowUuid = 'aaaaaaaa-2222-4333-8444-cccccccccccc'; $insertInstance( $damagedEscrowInstanceId, $damagedEscrowUuid, @@ -1872,7 +2109,7 @@ namespace { $damagedEscrowPayload = (string) CloudJob::find( $damagedEscrowJobId )->sealed_payload; - $damagedEscrowReceipt = [ + $damagedEscrowReceipt = $withIdentity([ 'type' => 'completion', 'id' => 'settings-damaged-escrow-event-01', 'agent_id' => '7', @@ -1882,7 +2119,7 @@ namespace { 'safe_to_resubmit' => false, 'error_code' => '', 'result' => ['settings_changed' => true], - ]; + ]); $assert(CloudOperationCompletionService::accept( $damagedEscrowReceipt ) === ['accepted' => true, 'disposition' => 'received'], @@ -1899,11 +2136,19 @@ namespace { 'event_id', $damagedEscrowReceipt['id'] )->update(['received_at' => time() - 21601]); - $assert((new CloudAutomaticOperationRecoveryService())->tick() - && (string) CloudJob::find( - $damagedEscrowJobId - )->finalization_error_code === 'recovery_receipt_limit_reached', - 'Damaged escrow did not stop at the bounded local recovery incident.'); + $assert((new CloudAutomaticOperationRecoveryService())->tick(), + 'Damaged escrow was not retried beyond six hours.'); + $damagedEscrowJob = CloudJob::find($damagedEscrowJobId); + $damagedEscrowEvent = CloudAgentCompletionEvent::find( + $damagedEscrowReceipt['id'] + ); + $assert((string) $damagedEscrowJob->effect_resolution === 'unknown' + && (string) $damagedEscrowEvent->disposition === 'received' + && (int) $damagedEscrowJob->available_at >= time() + 290 + && CloudJobService::blockingQueryForInstance( + $damagedEscrowInstanceId + )->exists(), + 'Damaged escrow left the recovery queue or released its blocker.'); // A structurally valid credential DTO must still match the setting being // recovered. Otherwise a late receipt could overwrite credential metadata @@ -1916,7 +2161,7 @@ namespace { [ 'label' => 'hostname-only credential', 'instance_id' => 103, - 'uuid' => 'aaaaaaaa-4444-5555-6666-eeeeeeeeeeee', + 'uuid' => 'aaaaaaaa-4444-4555-8666-eeeeeeeeeeee', 'operation_id' => 'd234567890abcdef1234567890abcdef', 'event_id' => 'settings-hostname-credential-damaged-01', 'body' => [ @@ -1937,7 +2182,7 @@ namespace { [ 'label' => 'SSH-key credential mode', 'instance_id' => 104, - 'uuid' => 'aaaaaaaa-5555-6666-7777-ffffffffffff', + 'uuid' => 'aaaaaaaa-5555-4666-8777-ffffffffffff', 'operation_id' => 'e234567890abcdef1234567890abcdef', 'event_id' => 'settings-ssh-credential-damaged-0001', 'body' => [ @@ -1986,7 +2231,7 @@ namespace { $credentialPayload = (string) CloudJob::find( $credentialJobId )->sealed_payload; - $credentialReceipt = [ + $credentialReceipt = $withIdentity([ 'type' => 'completion', 'id' => $credentialCase['event_id'], 'agent_id' => '7', @@ -1996,7 +2241,7 @@ namespace { 'safe_to_resubmit' => false, 'error_code' => '', 'result' => $credentialCase['result'], - ]; + ]); $assert(CloudOperationCompletionService::accept( $credentialReceipt ) === ['accepted' => true, 'disposition' => 'received'], @@ -2023,25 +2268,26 @@ namespace { $credentialCase['event_id'] )->update(['received_at' => time() - 21601]); $assert((new CloudAutomaticOperationRecoveryService())->tick(), - $credentialCase['label'] . ' receipt was not claimed at its limit.'); + $credentialCase['label'] + . ' receipt was not retried beyond six hours.'); $credentialJob = CloudJob::find($credentialJobId); $credentialEvent = CloudAgentCompletionEvent::find( $credentialCase['event_id'] ); - $assert((string) $credentialJob->finalization_error_code - === 'recovery_receipt_limit_reached' - && (string) $credentialEvent->disposition === 'late' + $assert((string) $credentialJob->effect_resolution === 'unknown' + && (string) $credentialEvent->disposition === 'received' + && (int) $credentialJob->available_at >= time() + 290 && CloudJobService::blockingQueryForInstance( $credentialCase['instance_id'] )->exists(), $credentialCase['label'] - . ' corruption did not stop at the bounded incident.'); + . ' corruption left the recovery queue or released its blocker.'); } // A stored event whose immutable fields no longer match its accepted hash // must be rejected before any settings projection or prepare marker moves. $corruptEventInstanceId = 101; - $corruptEventUuid = 'aaaaaaaa-3333-4444-5555-dddddddddddd'; + $corruptEventUuid = 'aaaaaaaa-3333-4444-8555-dddddddddddd'; $insertInstance( $corruptEventInstanceId, $corruptEventUuid, @@ -2135,10 +2381,11 @@ namespace { 'A hash-inconsistent event changed PHP settings state.'); // Agent VM metadata may include a hostname even when the original setting - // changed only a password. That unrelated observation must be removed - // before comparing a late receipt with an automatic no-fence prepare. + // changed only a password. Preserve that exact bounded observation in both + // recovery sources; the settings finalizer ignores it for password-only + // requests instead of rewriting the receipt into a synthetic result. $extraHostnameInstanceId = 102; - $extraHostnameUuid = 'aaaaaaaa-4444-5555-6666-eeeeeeeeeeee'; + $extraHostnameUuid = 'aaaaaaaa-4444-4555-8666-eeeeeeeeeeee'; $insertInstance( $extraHostnameInstanceId, $extraHostnameUuid, @@ -2186,7 +2433,10 @@ namespace { 'effect_resolution_reason' => 'automatic_recovery:v1:' . (time() - 60) . ':1:pending', ]); - $extraHostnameOperation = [ + $extraHostnameOperation = $identityFor( + $extraHostnameOperationId, + true + ) + [ 'operation_id' => $extraHostnameOperationId, 'status' => 'succeeded', 'effect_may_have_applied' => false, @@ -2195,6 +2445,7 @@ namespace { 'result' => [ 'uuid' => $extraHostnameUuid, 'settings_changed' => true, + 'hostname' => 'metadata-only.example', ], ]; CloudOperationRecoveryService::prepareApplied( @@ -2202,7 +2453,7 @@ namespace { $extraHostnameOperation, 'automatic_applied_succeeded_nofence:' . str_repeat('7', 64) ); - $extraHostnameReceipt = [ + $extraHostnameReceipt = $withIdentity([ 'type' => 'completion', 'id' => 'settings-extra-hostname-event-01', 'agent_id' => '7', @@ -2216,7 +2467,7 @@ namespace { 'settings_changed' => true, 'hostname' => 'metadata-only.example', ], - ]; + ]); $assert(CloudOperationCompletionService::accept( $extraHostnameReceipt ) === ['accepted' => true, 'disposition' => 'applied'], @@ -2234,7 +2485,7 @@ namespace { // A failed receipt which still reports possible effect is not no-effect // evidence. It remains late and the original unknown-effect fence stays. $ambiguousInstanceId = 94; - $ambiguousUuid = 'cccccccc-dddd-eeee-ffff-000000000001'; + $ambiguousUuid = 'cccccccc-dddd-4eee-8fff-000000000001'; $insertInstance( $ambiguousInstanceId, $ambiguousUuid, @@ -2250,13 +2501,24 @@ namespace { Capsule::table('cloud_jobs')->where('id', $ambiguousJobId)->update([ 'instance_id' => $ambiguousInstanceId, 'kind' => 'instance_settings', + 'sealed_payload' => CloudSecrets::encrypt([ + 'method' => 'POST', + 'request_target' => '/v1/vms/' . $ambiguousUuid . '/settings', + 'body' => [ + 'hostname' => 'ambiguous.example', + 'confirm_restart' => true, + ], + 'owner_id' => 1, + 'settings_fields' => ['hostname'], + 'credential' => null, + ], 'job-payload'), ]); $assert(CloudWorkerService::expireDueTasksForOwner( 1, $ambiguousJobId, 1 ) === 1, 'The ambiguous late receipt fixture did not expire.'); - $ambiguousReceipt = [ + $ambiguousReceipt = $withIdentity([ 'type' => 'completion', 'id' => 'settings-ambiguous-event-0001', 'agent_id' => '7', @@ -2266,7 +2528,7 @@ namespace { 'safe_to_resubmit' => false, 'error_code' => 'operation_failed', 'result' => null, - ]; + ]); $assert(CloudOperationCompletionService::accept( $ambiguousReceipt ) === ['accepted' => true, 'disposition' => 'late'] @@ -2281,7 +2543,7 @@ namespace { // first converge the ledger while preserving the blocker, then publish // the resolution only after the caller releases the Agent fence. $preparedInstanceId = 92; - $preparedUuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'; + $preparedUuid = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'; $insertInstance( $preparedInstanceId, $preparedUuid, @@ -2325,7 +2587,7 @@ namespace { $preparedResult = $preparedTerminal->result_json; $preparedCompletionEvent = $preparedTerminal->completion_event_id; $preparedReadAt = $preparedTerminal->read_at; - $preparedOperation = [ + $preparedOperation = $identityFor($preparedOperationId, true) + [ 'operation_id' => $preparedOperationId, 'status' => 'succeeded', 'effect_may_have_applied' => false, @@ -2542,6 +2804,50 @@ namespace { && Capsule::table('cloud_invoice_payments')->count() === 2, 'Payment deadline fallback retried a provider POST or misclassified its durable attempt.'); + $nullDispatchOperation = md5('null-dispatch-deadline-fixture'); + $nullDispatchJobId = $insertJob( + 1, + $nullDispatchOperation, + 'accepted', + 0 + ); + Capsule::table('cloud_jobs')->where('id', $nullDispatchJobId)->update([ + 'dispatch_deadline_at' => null, + ]); + $invalidReceiptOperation = md5('invalid-receipt-deadline-fixture'); + $invalidReceiptJobId = $insertJob( + 1, + $invalidReceiptOperation, + 'dispatching', + 1 + ); + Capsule::table('cloud_jobs')->where('id', $invalidReceiptJobId)->update([ + 'receipt_deadline_at' => 0, + ]); + $assert(CloudWorkerService::expireDueTasksForOwner( + 1, + $nullDispatchJobId, + 1 + ) === 1, 'An accepted task with a NULL dispatch deadline stayed active.'); + $assert(CloudWorkerService::expireDueTasksForOwner( + 1, + $invalidReceiptJobId, + 1 + ) === 1, 'A dispatched task with an invalid receipt deadline stayed active.'); + $nullDispatchJob = CloudJob::find($nullDispatchJobId); + $invalidReceiptJob = CloudJob::find($invalidReceiptJobId); + $assert($nullDispatchJob !== null + && (string) $nullDispatchJob->phase === 'terminal' + && (string) $nullDispatchJob->outcome === 'failed' + && !(bool) $nullDispatchJob->effect_may_have_applied + && (bool) $nullDispatchJob->safe_to_resubmit + && $invalidReceiptJob !== null + && (string) $invalidReceiptJob->phase === 'terminal' + && (string) $invalidReceiptJob->outcome === 'failed' + && (bool) $invalidReceiptJob->effect_may_have_applied + && !(bool) $invalidReceiptJob->safe_to_resubmit, + 'Malformed active deadlines did not fail closed by dispatch evidence.'); + $assert(CloudJobService::dispatchDeadlineSeconds('action') === 300 && CloudJobService::dispatchDeadlineSeconds( 'host_storage_configure') === 60 diff --git a/web/tests/CloudTaskObserverBehaviorTest.mjs b/web/tests/CloudTaskObserverBehaviorTest.mjs index fdaf0616..52e08607 100644 --- a/web/tests/CloudTaskObserverBehaviorTest.mjs +++ b/web/tests/CloudTaskObserverBehaviorTest.mjs @@ -12,9 +12,11 @@ const detailUrl = new URL('../public/cloud/detail.js', import.meta.url); const adminInstancesUrl = new URL('../public/cloud/admin-instances.js', import.meta.url); const runtimeUrl = new URL('../public/cloud/runtime.js', import.meta.url); const isoImagesUrl = new URL('../public/cloud/iso-images.js', import.meta.url); +const invoiceDetailRuntimeUrl = new URL('../public/cloud/invoice-detail-runtime.js', import.meta.url); const reinstallViewUrl = new URL('../resources/views/venix/cloud/pages/reinstall.tpl', import.meta.url); const { - normalizeTask, observeTask, readTask, resolvedTaskFailureNotice, taskUrl, + normalizeTask, observeTask, readTask, recoveryTaskFailureNotice, + resolvedTaskFailureNotice, taskSucceededWithoutRecovery, taskUrl, } = await import(`${observerUrl.href}?test=${Date.now()}`); const { dateText, taskTitle } = await import(`${centerUrl.href}?test=${Date.now()}`); @@ -38,6 +40,7 @@ const protocolFailure = task => { const task = normalizeTask({ id: '41', completed: true, status }); assert.equal(task.status, status); assert.equal(task.terminal, true); + assert.equal(taskSucceededWithoutRecovery(task), status === 'succeeded'); } for (const malformed of [ @@ -74,8 +77,8 @@ const protocolFailure = task => { assert.equal(nestedOnly.safe_to_resubmit, false); for (const [effectResolution, expected] of [ - ['applied', '原任务失败,但系统已确认操作已生效,资源锁已解除。'], - ['not_applied', '原任务失败,但系统已确认操作未生效,资源锁已解除。'], + ['applied', '原任务失败,但系统已确认操作已应用,资源锁已解除。'], + ['not_applied', '原任务失败,但系统已确认操作未应用,资源锁已解除。'], ]) { const resolved = normalizeTask({ id: '44', completed: true, status: 'failed', @@ -115,6 +118,82 @@ const protocolFailure = task => { id: '50', completed: true, status: 'failed', effect_may_have_applied: true, }); assert.equal(normalizeTask(inheritedResolution).effect_resolution, null); + + const recovering = normalizeTask({ + id: '51', completed: true, status: 'failed', + effect_may_have_applied: true, safe_to_resubmit: false, + recovery: { + pending: true, + message: 'Agent 回执与宿主机证据暂不一致;系统仍会继续自动核对。', + last_checked_at: 1_600_000_000, + next_check_at: 1_600_000_030, + }, + }); + assert.deepEqual(recovering.recovery, { + pending: true, + message: 'Agent 回执与宿主机证据暂不一致;系统仍会继续自动核对。', + last_checked_at: 1_600_000_000, + next_check_at: 1_600_000_030, + }); + assert.equal(recoveryTaskFailureNotice(recovering), recovering.recovery.message); + + const succeededWithInvalidLedger = normalizeTask({ + id: '53', completed: true, status: 'succeeded', + effect_may_have_applied: false, safe_to_resubmit: false, + recovery: { + pending: true, + message: '任务派发账本异常;资源保持安全锁定。', + last_checked_at: 1_600_000_000, + next_check_at: 1_600_000_300, + }, + }); + assert.equal(succeededWithInvalidLedger.status, 'succeeded'); + assert.equal(succeededWithInvalidLedger.recovery?.pending, true); + assert.equal(taskSucceededWithoutRecovery(succeededWithInvalidLedger), false); + assert.equal( + recoveryTaskFailureNotice(succeededWithInvalidLedger), + succeededWithInvalidLedger.recovery.message, + ); + + // A previously resolved failed task can become fenced again when its + // dispatch ledger is found corrupt or a repaired counter still has a sticky + // incident. Every consumer (task center, instance pages and administrator + // pages) shares this normalization, so recovery must win over "已解除". + for (const message of [ + '任务单次派发计数账本异常;资源保持安全锁定。', + '派发计数已修复,但原任务回执未通过完整性校验;不会解锁。', + ]) { + const failedResolvedButFenced = normalizeTask({ + id: '54', completed: true, status: 'failed', + effect_may_have_applied: true, safe_to_resubmit: false, + effect_resolution: 'applied', + recovery: { + pending: true, + message, + last_checked_at: 1_600_000_000, + next_check_at: 1_600_000_300, + }, + }); + assert.equal(failedResolvedButFenced.effect_resolution, null); + assert.equal(failedResolvedButFenced.recovery?.pending, true); + assert.equal(resolvedTaskFailureNotice(failedResolvedButFenced), ''); + assert.equal(recoveryTaskFailureNotice(failedResolvedButFenced), message); + } + + for (const recovery of [ + null, + { pending: false, message: '伪造恢复状态' }, + { pending: true, message: '' }, + { pending: true, message: '服务端原始异常', last_checked_at: 'not-a-time' }, + { pending: true, message: '服务端原始异常', next_check_at: -1 }, + ]) { + const task = normalizeTask({ + id: '52', completed: true, status: 'failed', + effect_may_have_applied: true, safe_to_resubmit: false, recovery, + }); + assert.equal(task.recovery, null); + assert.equal(recoveryTaskFailureNotice(task), ''); + } } // Receipts accept only the two top-level fields from the fresh API. @@ -310,12 +389,22 @@ const protocolFailure = task => { assert.match(source, /raw\?\.kind === 'host_storage_configure'/); assert.match(source, /旧存储任务已终止且不会重放/); assert.match(source, /resolvedTaskFailureNotice\(task\)/); + assert.match(source, /recoveryTaskFailureNotice\(task\)/); assert.match(source, /'panel-task-warning', resolvedNotice/); + assert.match(source, /recoveringCount/); + assert.match(source, /recovering_count/); + assert.match(source, /state\.activeCount \+ state\.recoveringCount/); + assert.match(source, + /state\.recoveringCount < 1 && Date\.now\(\) >= state\.deadline/); + assert.match(source, /最近异常/); + assert.match(source, /下次核对/); + assert.match(source, /账本异常 · 待修复/); assert.doesNotMatch(source, /重试任务|重新提交任务|data-task-retry/); const observerSource = await readFile(observerUrl, 'utf8'); - assert.match(observerSource, /原任务失败,但系统已确认操作已生效,资源锁已解除/); - assert.match(observerSource, /原任务失败,但系统已确认操作未生效,资源锁已解除/); + assert.match(observerSource, /原任务失败,但系统已确认操作已应用,资源锁已解除/); + assert.match(observerSource, /原任务失败,但系统已确认操作未应用,资源锁已解除/); + assert.doesNotMatch(observerSource, /finalization_error_code/); const appSource = await readFile(appUrl, 'utf8'); const layoutAssets = await readFile(layoutAssetsUrl, 'utf8'); @@ -343,6 +432,8 @@ const protocolFailure = task => { const detailSource = await readFile(detailUrl, 'utf8'); assert.match(detailSource, /resolvedTaskFailureNotice\(task\)/); assert.match(detailSource, /resolvedTaskFailureNotice\(normalizeTask\(entry\)\)/); + assert.match(detailSource, /recoveryTaskFailureNotice\(task\)/); + assert.match(detailSource, /recoveryTaskFailureNotice\(normalizeTask\(entry\)\)/); assert.match(detailSource, /task\.effect_resolution === 'applied'/); assert.match(detailSource, /task\.effect_resolution === 'not_applied'/); const firewallReceipt = detailSource.indexOf('expectedStatus: 202', detailSource.indexOf('async function saveVmFirewall')); @@ -352,27 +443,66 @@ const protocolFailure = task => { assert.match(detailSource, /requireTaskReceipt: true/); assert.match(detailSource, /syncInstanceSettingForm\(form\)/); assert.match(detailSource, /snapshotMutation = null;[\s\S]*loadVmSnapshots\(vmId, true, false\)/); + assert.match(detailSource, /taskSucceededWithoutRecovery\(task\)/); + assert.doesNotMatch(detailSource, /task\.status === 'succeeded'/); const adminInstancesSource = await readFile(adminInstancesUrl, 'utf8'); assert.doesNotMatch(adminInstancesSource, /state\.networkRequest \|\| activeJob/); assert.match(adminInstancesSource, /response\.status !== 202 \|\| !taskUrl\(payload\)/); assert.match(adminInstancesSource, /await refreshDetail\(vm\.id\)/); + assert.match(adminInstancesSource, /recoveryTaskFailureNotice\(task\)/); + assert.match(adminInstancesSource, /PHP 本地账本收尾尚未完成/); + assert.match(adminInstancesSource, /taskSucceededWithoutRecovery\(task\)/); + assert.doesNotMatch(adminInstancesSource, /task\.status === 'succeeded'/); const runtimeSource = await readFile(runtimeUrl, 'utf8'); assert.match(runtimeSource, /resolvedTaskFailureNotice\(task\)/); + assert.match(runtimeSource, /recoveryTaskFailureNotice\(task\)/); assert.match(runtimeSource, /task\.effect_resolution === 'applied'/); assert.match(runtimeSource, /task\.effect_resolution === 'not_applied'/); assert.match(runtimeSource, /expectedStatus: 202, requireTaskReceipt: true/); assert.match(runtimeSource, /syncReinstallControls\(refreshed \|\| selectedVm\(\)\)/); + assert.match(runtimeSource, /taskSucceededWithoutRecovery\(task\)/); + assert.doesNotMatch(runtimeSource, /task\.status === 'succeeded'/); const isoImagesSource = await readFile(isoImagesUrl, 'utf8'); + assert.match(isoImagesSource, /recoveryTaskFailureNotice\(task\)/); assert.match(isoImagesSource, /method: 'DELETE', expectedStatus: 202, requireTaskReceipt: true/); assert.match(isoImagesSource, /const refreshed = await loadIsos\(\{ observeActive: false \}\)/); - assert.match(isoImagesSource, /const canDelete = String\(record\.state \|\| ''\) === 'active'/); + assert.match(isoImagesSource, /const canDelete = record\.can_delete === true/); + assert.doesNotMatch(isoImagesSource, /const canDelete = String\(record\.state/); + assert.match(isoImagesSource, /record\.cleanup_reason === 'quota_exceeded_after_import'/); + assert.match(isoImagesSource, /该 ISO 已下载到宿主机,但导入后超出个人库配额;可删除以释放空间/); + assert.match(isoImagesSource, /清理已下载 ISO/); + assert.match(isoImagesSource, /确定删除其宿主机副本并释放空间/); + assert.match(isoImagesSource, /taskSucceededWithoutRecovery\(task\)/); + assert.doesNotMatch(isoImagesSource, /task\.status === 'succeeded'/); + + const adminOperationsSource = await readFile(new URL('../public/cloud/admin-operations.js', import.meta.url), 'utf8'); + assert.match(adminOperationsSource, /recoveryTaskFailureNotice\(task\)/); + assert.match(adminOperationsSource, /job\.recovery\?\.pending/); + assert.match(adminOperationsSource, /最近异常/); + assert.match(adminOperationsSource, /下次核对/); + assert.match(adminOperationsSource, /派发账本修复/); + assert.match(adminOperationsSource, /PHP 本地账本收尾/); + assert.match(adminOperationsSource, /taskSucceededWithoutRecovery\(task\)/); + assert.doesNotMatch(adminOperationsSource, /task\.status === 'succeeded'/); + + assert.match(sourceForSuccessGuard(await readFile(adminUrl, 'utf8')), + /taskSucceededWithoutRecovery\(task\)/); + const invoiceDetailRuntimeSource = await readFile(invoiceDetailRuntimeUrl, 'utf8'); + assert.match(invoiceDetailRuntimeSource, /taskSucceededWithoutRecovery\(task\)/); + assert.match(invoiceDetailRuntimeSource, /recoveryTaskFailureNotice\(task\)/); + assert.doesNotMatch(invoiceDetailRuntimeSource, /task\.status === 'succeeded'/); const reinstallView = await readFile(reinstallViewUrl, 'utf8'); assert.doesNotMatch(reinstallView, /reinstall-(?:retry|forget)/); assert.doesNotMatch(reinstallView, />\s*重新查询任务\s*addConnection([ + 'driver' => 'sqlite', 'database' => ':memory:', +], 'default'); +$capsule->setAsGlobal(); +$capsule->bootEloquent(); +$schema = $capsule->schema('default'); +$schema->create('cloud_jobs', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('operation_id'); + $table->string('request_idempotency_key'); + $table->string('request_fingerprint'); + $table->integer('parent_job_id')->nullable(); + $table->integer('order_id')->nullable(); + $table->integer('invoice_id')->nullable(); + $table->integer('instance_id')->nullable(); + $table->integer('snapshot_id')->nullable(); + $table->integer('user_id'); + $table->integer('host_id')->nullable(); + $table->string('kind'); + $table->string('execution_mode'); + $table->string('phase'); + $table->string('outcome')->nullable(); + $table->string('status'); + $table->integer('attempts')->default(0); + $table->integer('dispatch_attempts')->nullable()->default(0); + $table->integer('dispatch_deadline_at'); + $table->integer('dispatch_started_at')->nullable(); + $table->integer('agent_accepted_at')->nullable(); + $table->integer('dispatched_at')->nullable(); + $table->integer('receipt_deadline_at')->nullable(); + $table->integer('terminal_at')->nullable(); + $table->string('completion_event_id')->nullable(); + $table->boolean('effect_may_have_applied')->nullable(); + $table->boolean('safe_to_resubmit')->nullable(); + $table->string('effect_resolution'); + $table->boolean('finalization_incident')->default(0); + $table->string('finalization_error_code')->nullable(); + $table->string('lease_token')->nullable(); + $table->integer('lease_until')->default(0); + $table->integer('available_at')->default(0); + $table->string('error_code')->nullable(); + $table->text('result_json')->nullable(); + $table->text('sealed_payload')->default(''); + $table->integer('read_at')->nullable(); + $table->integer('created_at'); + $table->integer('updated_at'); +}); +$schema->create('cloud_templates', static function (Blueprint $table): void { + $table->string('id')->primary(); + $table->integer('active_job_id')->nullable(); + $table->string('state')->default('active'); +}); +$schema->create('cloud_user_isos', static function (Blueprint $table): void { + $table->string('id')->primary(); + $table->integer('active_job_id')->nullable(); + $table->string('state')->default('active'); +}); +$schema->create('cloud_template_replicas', + static function (Blueprint $table): void { + $table->integer('host_id'); + $table->string('template_id'); + $table->integer('revision')->default(0); + $table->string('generation_token')->default(''); + $table->string('state')->default('pending'); + $table->integer('image_bytes')->default(0); + $table->string('sha256')->default(''); + $table->string('operation_id')->default(''); + $table->integer('job_id')->nullable(); + $table->string('error_code')->default(''); + $table->integer('created_at')->default(0); + $table->integer('updated_at')->default(0); + $table->primary(['host_id', 'template_id']); + }); +$schema->create('cloud_user_iso_replicas', + static function (Blueprint $table): void { + $table->integer('host_id'); + $table->string('user_iso_id'); + $table->integer('user_id'); + $table->string('state')->default('pending'); + $table->integer('size_bytes')->default(0); + $table->string('sha256')->default(''); + $table->string('operation_id')->default(''); + $table->integer('job_id')->nullable(); + $table->string('error_code')->default(''); + $table->integer('created_at')->default(0); + $table->integer('updated_at')->default(0); + $table->primary(['host_id', 'user_iso_id']); + }); + +$now = time(); +$insert = static function (int $id, array $overrides = []) use ($now): void { + $values = array_replace([ + 'id' => $id, + 'operation_id' => sprintf('%032x', $id), + 'request_idempotency_key' => sprintf('%032x', $id), + 'request_fingerprint' => hash('sha256', (string) $id), + 'parent_job_id' => null, + 'order_id' => null, + 'invoice_id' => null, + 'instance_id' => 10, + 'snapshot_id' => null, + 'user_id' => 7, + 'host_id' => 3, + 'kind' => 'instance_settings', + 'execution_mode' => 'agent', + 'phase' => 'terminal', + 'outcome' => 'failed', + 'status' => 'failed', + 'attempts' => 1, + 'dispatch_attempts' => 1, + 'dispatch_deadline_at' => $now - 100, + 'dispatch_started_at' => $now - 95, + 'agent_accepted_at' => $now - 92, + 'dispatched_at' => $now - 90, + 'receipt_deadline_at' => $now - 60, + 'terminal_at' => $now - 30, + 'completion_event_id' => null, + 'effect_may_have_applied' => 1, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'unknown', + 'finalization_incident' => 1, + 'finalization_error_code' => 'recovery_evidence_conflict', + 'lease_until' => 0, + 'available_at' => $now + 30, + 'error_code' => 'operation_failed_effect_unknown', + 'created_at' => $now - 120, + 'updated_at' => $now, + ], $overrides); + if (($values['execution_mode'] ?? '') === 'aggregate') { + foreach ([ + 'attempts' => 0, + 'dispatch_started_at' => null, + 'agent_accepted_at' => null, + 'dispatched_at' => null, + 'completion_event_id' => null, + ] as $field => $value) { + if (!array_key_exists($field, $overrides)) { + $values[$field] = $value; + } + } + } + if (($values['execution_mode'] ?? '') === 'agent' + && (int) ($values['dispatch_attempts'] ?? -1) === 0) { + foreach (['attempts' => 0, 'dispatch_started_at' => null, + 'agent_accepted_at' => null, 'dispatched_at' => null, + 'receipt_deadline_at' => null, 'completion_event_id' => null] + as $field => $value) { + if (!array_key_exists($field, $overrides)) { + $values[$field] = $value; + } + } + } + if (($values['outcome'] ?? null) === 'succeeded' + && !array_key_exists('error_code', $overrides)) { + $values['error_code'] = null; + } + Capsule::table('cloud_jobs')->insert($values); +}; + +$insert(1); +$insert(2, [ + 'effect_resolution' => 'applied', + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'available_at' => 0, +]); +$insert(3, ['kind' => 'create']); +$insert(4, [ + 'phase' => 'accepted', + 'outcome' => null, + 'status' => 'queued', + 'dispatch_attempts' => 0, + 'dispatched_at' => null, + 'receipt_deadline_at' => null, + 'terminal_at' => null, + 'effect_may_have_applied' => null, + 'safe_to_resubmit' => null, + 'effect_resolution' => 'not_applicable', + 'finalization_incident' => 0, + 'finalization_error_code' => null, + 'dispatch_deadline_at' => $now + 300, + 'available_at' => $now, +]); +$insert(5, [ + 'kind' => 'template_import', + 'execution_mode' => 'aggregate', + 'host_id' => null, + 'instance_id' => null, + 'dispatch_attempts' => 0, + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +$insert(6, [ + 'parent_job_id' => 5, + 'kind' => 'template_import_replica', + 'finalization_error_code' => 'recovery_operation_identity_conflict', + 'error_code' => 'raw-agent-secret-must-not-appear', + 'result_json' => json_encode([ + 'message' => 'raw-agent-text-must-not-appear', + ], JSON_THROW_ON_ERROR), +]); +$insert(7, [ + 'parent_job_id' => 5, + 'kind' => 'template_import_replica', + 'finalization_error_code' => 'recovery_receipt_invalid', +]); + +$tasks = CloudJobService::tasks(['user_id' => 7, 'is_admin' => false], + 'completed'); +$assert(($tasks['active_count'] ?? null) === 1, + 'Task center active count changed while adding recovery polling.'); +$assert(($tasks['recovering_count'] ?? null) === 2, + 'Task center did not count visible terminal tasks that still converge.'); +$assert(array_map(static fn (array $item): string => $item['id'], + $tasks['items']) === ['5', '3', '2', '1'], + 'Task center exposed hidden child work or changed terminal ordering.'); +$assert(($tasks['items'][0]['recovery']['pending'] ?? null) === true + && ($tasks['items'][3]['recovery']['pending'] ?? null) === true + && !isset($tasks['items'][1]['recovery']) + && !isset($tasks['items'][2]['recovery']), + 'Task recovery status did not match the visible recovery count.'); +$aggregateRecovery = $tasks['items'][0]['recovery'] ?? []; +$adminAggregate = CloudJobService::display( + \App\Models\CloudJob::findOrFail(5), + true +); +$assert(str_contains( + (string) ($aggregateRecovery['message'] ?? ''), + '操作、资源或请求指纹' + ) + && str_contains( + (string) ($aggregateRecovery['message'] ?? ''), + '另有 1 类子任务异常' + ) + && !array_key_exists('code', $aggregateRecovery) + && !str_contains( + (string) ($aggregateRecovery['message'] ?? ''), + 'raw-agent' + ) + && ($adminAggregate['recovery']['code'] ?? null) + === 'recovery_operation_identity_conflict' + && ($adminAggregate['recovery']['affected_child_count'] ?? null) === 2 + && ($adminAggregate['recovery']['additional_error_count'] ?? null) === 1, + 'Aggregate recovery did not safely expose the deterministic child anomaly.'); + +// A dispatch counter outside the durable 0/1 state machine is corruption, +// not proof that the mutation stayed on the PHP side of the dispatch fence. +// Keep both the leaf and its public aggregate parent visibly recovering with +// one reviewed Chinese anomaly instead of hiding the child as undispatched. +$insert(8, [ + 'kind' => 'template_import', + 'execution_mode' => 'aggregate', + 'host_id' => null, + 'instance_id' => null, + 'dispatch_attempts' => 0, + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +$insert(9, [ + 'parent_job_id' => 8, + 'kind' => 'template_import_replica', + 'dispatch_attempts' => 2, + 'finalization_error_code' => 'recovery_dispatch_ledger_conflict', +]); +$invalidDispatchLeaf = CloudJobService::recoveryPresentation( + \App\Models\CloudJob::findOrFail(9), + true +); +$invalidDispatchParent = CloudJobService::recoveryPresentation( + \App\Models\CloudJob::findOrFail(8), + true +); +$assert(($invalidDispatchLeaf['code'] ?? null) + === 'recovery_dispatch_ledger_conflict' + && str_contains( + (string) ($invalidDispatchLeaf['message'] ?? ''), + '派发' + ) + && ($invalidDispatchParent['code'] ?? null) + === 'recovery_dispatch_ledger_conflict' + && ($invalidDispatchParent['affected_child_count'] ?? null) === 1 + && str_contains( + (string) ($invalidDispatchParent['message'] ?? ''), + '派发' + ), + 'An invalid dispatch ledger was hidden from the task center or aggregate parent.'); + +// A historical row may still carry an immutable succeeded receipt while its +// dispatch generation is corrupt. The public DTO must expose the concrete +// recovery incident without rewriting that terminal receipt. +$insert(10, [ + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'dispatch_attempts' => 2, + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +$invalidSucceeded = CloudJobService::display( + \App\Models\CloudJob::findOrFail(10), + false +); +$assert(($invalidSucceeded['status'] ?? null) === 'succeeded' + && ($invalidSucceeded['recovery']['pending'] ?? null) === true + && str_contains( + (string) ($invalidSucceeded['recovery']['message'] ?? ''), + '派发' + ), + 'A succeeded task with an invalid dispatch ledger hid its recovery incident.'); + +// Repairing the counter to a legal value must not create a brief unlock +// window. The sticky repair incident remains visible until the coordinator +// validates the immutable terminal receipt and explicitly clears it. +$insert(11, [ + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'dispatch_attempts' => 1, + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'finalization_incident' => 1, + 'finalization_error_code' => 'recovery_dispatch_repair_receipt_invalid', +]); +$stickySucceeded = CloudJobService::display( + \App\Models\CloudJob::findOrFail(11), + true +); +$assert(($stickySucceeded['status'] ?? null) === 'succeeded' + && ($stickySucceeded['recovery']['code'] ?? null) + === 'recovery_dispatch_repair_receipt_invalid' + && str_contains( + (string) ($stickySucceeded['recovery']['message'] ?? ''), + '完整性校验' + ) + && CloudJobService::blockingQueryForInstance(10) + ->where('id', 11)->exists(), + 'A repaired succeeded task unlocked before its sticky incident was validated.'); + +// A zero counter proves the Agent was never contacted, but a failed PHP +// business-ledger finalizer still owns the resource lock until local recovery +// completes. +$insert(12, [ + 'dispatch_attempts' => 0, + 'dispatched_at' => null, + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'not_applied', + 'finalization_incident' => 1, + 'finalization_error_code' => 'recovery_ledger_conflict', +]); +$localFinalizer = CloudJobService::display( + \App\Models\CloudJob::findOrFail(12), + true +); +$assert(($localFinalizer['recovery']['code'] ?? null) + === 'recovery_ledger_conflict' + && str_contains( + (string) ($localFinalizer['recovery']['message'] ?? ''), + '面板账本' + ) + && CloudJobService::blockingQueryForInstance(10) + ->where('id', 12)->exists(), + 'An undispatched local finalizer failure was hidden or unlocked.'); + +$insert(13, [ + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'dispatch_attempts' => null, + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +$nullDispatch = CloudJobService::display( + \App\Models\CloudJob::findOrFail(13), + true +); +$assert(($nullDispatch['status'] ?? null) === 'succeeded' + && ($nullDispatch['recovery']['code'] ?? null) + === 'recovery_dispatch_ledger_conflict' + && CloudJobService::blockingQueryForInstance(10) + ->where('id', 13)->exists(), + 'A NULL dispatch ledger was treated as undispatched and unlocked.'); + +// Aggregate parents must inherit a zero-dispatch child's unresolved local +// finalizer instead of appearing complete while the child remains fenced. +$insert(14, [ + 'kind' => 'template_import', + 'execution_mode' => 'aggregate', + 'host_id' => null, + 'instance_id' => null, + 'dispatch_attempts' => 0, + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 1, + 'effect_resolution' => 'not_applied', + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +$insert(15, [ + 'parent_job_id' => 14, + 'kind' => 'template_import_replica', + 'dispatch_attempts' => 0, + 'dispatched_at' => null, + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'not_applied', + 'finalization_incident' => 1, + 'finalization_error_code' => 'recovery_ledger_conflict', +]); +$localAggregate = CloudJobService::display( + \App\Models\CloudJob::findOrFail(14), + true +); +$afterRepairCases = CloudJobService::tasks( + ['user_id' => 7, 'is_admin' => false], + 'completed' +); +$assert(($localAggregate['recovery']['code'] ?? null) + === 'recovery_ledger_conflict' + && ($localAggregate['recovery']['affected_child_count'] ?? null) === 1 + && ($afterRepairCases['recovering_count'] ?? null) === 8, + 'Aggregate/recovering queries omitted sticky, local-finalizer, or NULL-ledger work.'); + +// A resource-projection validator records its bounded diagnosis on the parent +// after every child is already resolved. The user must see that concrete +// Chinese reason, and administrators must receive the reviewed code instead +// of a misleading generic child-convergence status. +$insert(16, [ + 'kind' => 'template_import', + 'execution_mode' => 'aggregate', + 'host_id' => null, + 'instance_id' => null, + 'dispatch_attempts' => 0, + 'finalization_incident' => 1, + 'finalization_error_code' => 'recovery_instance_state_conflict', +]); +$insert(17, [ + 'parent_job_id' => 16, + 'kind' => 'template_import_replica', + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +$projectionUser = CloudJobService::display( + \App\Models\CloudJob::findOrFail(16), + false +); +$projectionAdmin = CloudJobService::display( + \App\Models\CloudJob::findOrFail(16), + true +); +$assert(str_contains( + (string) ($projectionUser['recovery']['message'] ?? ''), + '实例状态与任务证据暂不一致' + ) + && !array_key_exists('code', $projectionUser['recovery'] ?? []) + && ($projectionAdmin['recovery']['code'] ?? null) + === 'recovery_instance_state_conflict' + && ($projectionAdmin['recovery']['affected_child_count'] ?? null) === 0 + && ($projectionAdmin['recovery']['additional_error_count'] ?? null) === 0, + 'Aggregate parent projection anomaly was hidden as child convergence.'); + +// Damaged terminal safety tuples are neither resolved jobs nor trustworthy +// Agent recovery candidates. They remain visibly fenced with one concrete +// reviewed code, including when the valid dispatch generation is zero. +$insert(18, [ + 'safe_to_resubmit' => 1, + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +$insert(19, [ + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +$insert(20, [ + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +$insert(21, [ + 'dispatch_attempts' => 0, + 'dispatched_at' => null, + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +$insert(26, [ + 'dispatch_attempts' => 0, + 'dispatched_at' => null, + 'effect_may_have_applied' => 1, + 'safe_to_resubmit' => 0, + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +foreach ([18, 19, 20, 21, 26] as $stateConflictId) { + $stateConflict = CloudJobService::display( + \App\Models\CloudJob::findOrFail($stateConflictId), + true + ); + $assert(($stateConflict['recovery']['code'] ?? null) + === 'recovery_instance_state_conflict' + && CloudJobService::blockingQueryForInstance(10) + ->where('id', $stateConflictId)->exists(), + 'A damaged leaf safety tuple left recovery or unlocked its instance.'); +} + +$insert(22, [ + 'kind' => 'template_import', + 'execution_mode' => 'aggregate', + 'host_id' => null, + 'instance_id' => null, + 'dispatch_attempts' => 0, + 'safe_to_resubmit' => 1, + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +$insert(23, [ + 'parent_job_id' => 22, + 'kind' => 'template_import_replica', + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'effect_resolution' => 'applied', + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +$aggregateStateConflict = CloudJobService::display( + \App\Models\CloudJob::findOrFail(22), + true +); +$assert(($aggregateStateConflict['recovery']['code'] ?? null) + === 'recovery_aggregate_state_conflict', + 'A damaged aggregate-parent safety tuple was hidden from administrators.'); + +$insert(24, [ + 'kind' => 'template_import', + 'execution_mode' => 'aggregate', + 'host_id' => null, + 'instance_id' => null, + 'dispatch_attempts' => 0, + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +$insert(25, [ + 'parent_job_id' => 24, + 'kind' => 'template_import_replica', + 'safe_to_resubmit' => 1, + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +$childStateConflict = CloudJobService::display( + \App\Models\CloudJob::findOrFail(24), + true +); +$assert(($childStateConflict['recovery']['code'] ?? null) + === 'recovery_instance_state_conflict' + && ($childStateConflict['recovery']['affected_child_count'] ?? null) === 1, + 'An anomalous aggregate child did not keep its parent visibly pending.'); + +// Every code that a published aggregate projection validator can persist must +// remain selectable and visible. Missing codes here would leave the catalog +// locked by finalization_incident while both task center and administrators +// incorrectly report an ordinary completed task. +$beforePublishedIncidents = CloudJobService::tasks( + ['user_id' => 7, 'is_admin' => false], + 'completed' +)['recovering_count']; +foreach ([ + 27 => 'recovery_dispatch_ledger_conflict', + 29 => 'recovery_payload_unavailable', +] as $parentId => $incidentCode) { + $insert($parentId, [ + 'kind' => 'template_import', + 'execution_mode' => 'aggregate', + 'host_id' => null, + 'instance_id' => null, + 'dispatch_attempts' => 0, + 'effect_resolution' => 'applied', + 'finalization_incident' => 1, + 'finalization_error_code' => $incidentCode, + ]); + $insert($parentId + 1, [ + 'parent_job_id' => $parentId, + 'kind' => 'template_import_replica', + 'outcome' => 'succeeded', + 'status' => 'succeeded', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'finalization_incident' => 0, + 'finalization_error_code' => null, + ]); + $publishedIncident = CloudJobService::display( + \App\Models\CloudJob::findOrFail($parentId), + true + ); + $assert(($publishedIncident['recovery']['code'] ?? null) === $incidentCode, + 'A published aggregate projection incident disappeared: ' + . $incidentCode); +} +$afterPublishedIncidents = CloudJobService::tasks( + ['user_id' => 7, 'is_admin' => false], + 'completed' +)['recovering_count']; +$assert($afterPublishedIncidents === $beforePublishedIncidents + 2, + 'Published aggregate projection incidents left the recovering filter.'); + +// A child cannot have a final effect while its task is still nonterminal. The +// contradiction belongs to the PHP aggregate ledger and must be visible before +// a worker has had a chance to persist the parent incident. +$insert(31, [ + 'kind' => 'template_import', + 'execution_mode' => 'aggregate', + 'host_id' => null, + 'instance_id' => null, + 'dispatch_attempts' => 0, + 'effect_resolution' => 'applied', + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +$insert(32, [ + 'parent_job_id' => 31, + 'kind' => 'template_import_replica', + 'phase' => 'awaiting_receipt', + 'outcome' => null, + 'status' => 'running', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'applied', + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +$nonterminalResolved = CloudJobService::display( + \App\Models\CloudJob::findOrFail(31), + true +); +$assert(($nonterminalResolved['recovery']['code'] ?? null) + === 'recovery_aggregate_state_conflict' + && ($nonterminalResolved['recovery']['affected_child_count'] ?? null) === 1, + 'A nonterminal child with a published effect concealed its aggregate conflict.'); + +// Immutable request-identity damage is more specific than the generic terminal +// state conflict it also implies. Administrators need that concrete cause for +// both a direct leaf and a leaf summarized through its aggregate parent. +$insert(33, [ + 'request_idempotency_key' => 'bad-key', + 'finalization_incident' => 1, + 'finalization_error_code' => 'recovery_operation_identity_conflict', +]); +$identityLeaf = CloudJobService::recoveryPresentation( + \App\Models\CloudJob::findOrFail(33), + true +); +$assert(($identityLeaf['code'] ?? null) + === 'recovery_operation_identity_conflict' + && str_contains( + (string) ($identityLeaf['message'] ?? ''), + '请求指纹' + ), + 'A damaged leaf request identity was generalized in the admin DTO.'); + +$insert(34, [ + 'kind' => 'template_import', + 'execution_mode' => 'aggregate', + 'host_id' => null, + 'instance_id' => null, + 'dispatch_attempts' => 0, + 'finalization_incident' => 0, + 'finalization_error_code' => null, +]); +$insert(35, [ + 'parent_job_id' => 34, + 'kind' => 'template_import_replica', + 'request_fingerprint' => 'bad-fingerprint', + 'finalization_incident' => 1, + 'finalization_error_code' => 'recovery_operation_identity_conflict', +]); +$identityAggregate = CloudJobService::recoveryPresentation( + \App\Models\CloudJob::findOrFail(34), + true +); +$assert(($identityAggregate['code'] ?? null) + === 'recovery_operation_identity_conflict' + && ($identityAggregate['affected_child_count'] ?? null) === 1, + 'An aggregate child request-identity conflict was generalized.'); + +// Sticky repair and data-integrity incidents retain their origin even if a +// second malformed envelope field also satisfies the generic state predicate. +$insert(36, [ + 'receipt_deadline_at' => 0, + 'finalization_incident' => 1, + 'finalization_error_code' => + 'recovery_dispatch_repair_instance_state_conflict', +]); +$repairSpecific = CloudJobService::recoveryPresentation( + \App\Models\CloudJob::findOrFail(36), + true +); +$assert(($repairSpecific['code'] ?? null) + === 'recovery_dispatch_repair_instance_state_conflict', + 'A sticky dispatch-repair cause was generalized in the admin DTO.'); + +$insert(37, [ + 'receipt_deadline_at' => 0, + 'finalization_incident' => 1, + 'finalization_error_code' => 'recovery_payload_unavailable', +]); +$payloadSpecific = CloudJobService::recoveryPresentation( + \App\Models\CloudJob::findOrFail(37), + true +); +$assert(($payloadSpecific['code'] ?? null) + === 'recovery_payload_unavailable', + 'A concrete recovery-data incident was generalized in the admin DTO.'); + +echo "Cloud task recovery presentation checks passed.\n"; diff --git a/web/tests/CloudTemplateCatalogTest.php b/web/tests/CloudTemplateCatalogTest.php index ce891927..10402934 100644 --- a/web/tests/CloudTemplateCatalogTest.php +++ b/web/tests/CloudTemplateCatalogTest.php @@ -57,6 +57,7 @@ $capsule->schema('default')->create('cloud_template_replicas', $table->integer('image_bytes')->default(0); $table->string('sha256')->default(''); $table->string('operation_id')->default(''); + $table->integer('job_id')->nullable(); $table->string('error_code')->default(''); $table->integer('created_at'); $table->integer('updated_at'); diff --git a/web/tests/CloudTemplateWorkerConvergenceTest.php b/web/tests/CloudTemplateWorkerConvergenceTest.php index 4fa08562..42e304fb 100644 --- a/web/tests/CloudTemplateWorkerConvergenceTest.php +++ b/web/tests/CloudTemplateWorkerConvergenceTest.php @@ -15,6 +15,17 @@ $jobs = file_get_contents($root . '/app/Services/Cloud/CloudJobService.php'); if (!is_string($catalog) || !is_string($worker) || !is_string($jobs)) { throw new RuntimeException('Cannot read template task sources.'); } +$finishStart = strpos($catalog, 'public static function finishJobLocked('); +$finishEnd = $finishStart === false ? false : strpos( + $catalog, + 'public static function settleRecoveredParentLocked(', + $finishStart +); +$finishMethod = $finishStart === false || $finishEnd === false ? '' : substr( + $catalog, + $finishStart, + $finishEnd - $finishStart +); $assert = static function (bool $condition, string $message): void { if (!$condition) { @@ -38,13 +49,20 @@ $assert(str_contains($catalog, "if ((string) \$job->kind === 'template_import_replica')") && str_contains($catalog, 'self::finishImportReplica($template, $replica, $status, $result,') + && !str_contains($finishMethod, 'settleImportParent(') + && !str_contains($finishMethod, 'settleMetadataParent(') + && !str_contains($finishMethod, 'settleDeleteParent(') && str_contains($catalog, - 'self::settleImportParent($template, (int) $job->parent_job_id,') + 'public static function settleRecoveredParentLocked(') + && str_contains($catalog, + 'self::settleImportParent(') + && str_contains($worker, + 'CloudJobService::reconcileAggregateParentEffectLocked(') && str_contains($catalog, "CloudJobService::completeAggregateLocked(\$parent, 'succeeded',") && str_contains($catalog, "CloudJobService::completeAggregateLocked(\$parent, 'failed', \$effect,"), - 'Template completion receipts do not deterministically settle replica and aggregate ledgers.'); + 'Template completion does not defer aggregate publication until the child terminal effect is durable.'); $assert(str_contains($catalog, "'error_code' => 'aggregate_deadline_exceeded'") diff --git a/web/tests/CloudUndispatchedFinalizerRecoveryTest.php b/web/tests/CloudUndispatchedFinalizerRecoveryTest.php new file mode 100644 index 00000000..06cdf43f --- /dev/null +++ b/web/tests/CloudUndispatchedFinalizerRecoveryTest.php @@ -0,0 +1,365 @@ +addConnection([ + 'driver' => 'sqlite', 'database' => ':memory:', + ], 'default'); + $capsule->setAsGlobal(); + $capsule->bootEloquent(); + $schema = $capsule->schema('default'); + $schema->create('user', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('enable')->default(1); + $table->integer('is_admin')->default(0); + }); + $schema->create('cloud_jobs', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('operation_id')->unique(); + $table->string('request_idempotency_key')->unique(); + $table->string('request_fingerprint'); + $table->integer('parent_job_id')->nullable(); + $table->integer('order_id')->nullable(); + $table->integer('invoice_id')->nullable(); + $table->integer('instance_id')->nullable(); + $table->integer('snapshot_id')->nullable(); + $table->integer('user_id'); + $table->integer('host_id')->nullable(); + $table->string('kind'); + $table->string('execution_mode'); + $table->string('phase'); + $table->string('outcome')->nullable(); + $table->string('status'); + $table->text('sealed_payload'); + $table->integer('attempts')->default(0); + $table->integer('dispatch_attempts')->default(0); + $table->integer('dispatch_deadline_at')->default(0); + $table->integer('dispatch_started_at')->nullable(); + $table->integer('agent_accepted_at')->nullable(); + $table->integer('receipt_deadline_at')->nullable(); + $table->integer('terminal_at')->nullable(); + $table->boolean('effect_may_have_applied')->nullable(); + $table->boolean('safe_to_resubmit')->nullable(); + $table->string('effect_resolution'); + $table->integer('effect_resolved_at')->nullable(); + $table->integer('effect_resolved_by')->nullable(); + $table->string('effect_resolution_reason')->default(''); + $table->string('completion_event_id')->nullable(); + $table->integer('read_at')->nullable(); + $table->integer('dispatched_at')->nullable(); + $table->string('lease_token')->nullable(); + $table->integer('lease_until')->default(0); + $table->integer('available_at')->default(0); + $table->string('error_code')->nullable(); + $table->boolean('finalization_incident')->default(0); + $table->string('finalization_error_code')->nullable(); + $table->text('result_json')->nullable(); + $table->integer('created_at'); + $table->integer('updated_at'); + }); + $schema->create('cloud_instances', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('uuid'); + $table->integer('host_id'); + $table->integer('user_id'); + $table->string('name'); + $table->string('status'); + $table->string('service_status'); + $table->string('network_status'); + $table->text('spec_json'); + $table->text('sealed_credential')->nullable(); + $table->integer('created_at'); + $table->integer('updated_at'); + }); + $schema->create('cloud_agent_completion_events', + static function (Blueprint $table): void { + $table->string('event_id')->primary(); + $table->integer('host_id'); + $table->string('operation_id'); + $table->string('payload_sha256'); + $table->string('outcome'); + $table->boolean('effect_may_have_applied'); + $table->boolean('safe_to_resubmit'); + $table->string('error_code')->default(''); + $table->text('result_json')->nullable(); + $table->string('disposition')->default('received'); + $table->integer('received_at'); + $table->integer('applied_at')->nullable(); + $table->unique(['host_id', 'operation_id']); + }); + $schema->create('cloud_templates', + static function (Blueprint $table): void { + $table->string('id')->primary(); + $table->integer('active_job_id')->nullable(); + $table->string('state')->default('active'); + }); + $schema->create('cloud_user_isos', + static function (Blueprint $table): void { + $table->string('id')->primary(); + $table->integer('active_job_id')->nullable(); + $table->string('state')->default('active'); + }); + $schema->create('cloud_template_replicas', + static function (Blueprint $table): void { + $table->integer('host_id'); + $table->string('template_id'); + $table->integer('revision')->default(0); + $table->string('generation_token')->default(''); + $table->string('state')->default('pending'); + $table->integer('image_bytes')->default(0); + $table->string('sha256')->default(''); + $table->string('operation_id')->default(''); + $table->integer('job_id')->nullable(); + $table->string('error_code')->default(''); + $table->integer('created_at')->default(0); + $table->integer('updated_at')->default(0); + $table->primary(['host_id', 'template_id']); + }); + $schema->create('cloud_user_iso_replicas', + static function (Blueprint $table): void { + $table->integer('host_id'); + $table->string('user_iso_id'); + $table->integer('user_id'); + $table->string('state')->default('pending'); + $table->integer('size_bytes')->default(0); + $table->string('sha256')->default(''); + $table->string('operation_id')->default(''); + $table->integer('job_id')->nullable(); + $table->string('error_code')->default(''); + $table->integer('created_at')->default(0); + $table->integer('updated_at')->default(0); + $table->primary(['host_id', 'user_iso_id']); + }); + + $now = time(); + $operationId = str_repeat('ad', 16); + $uuid = '00000000-0000-4000-8000-000000000501'; + $payload = [ + 'method' => 'POST', + 'request_target' => '/v1/vms/' . $uuid . '/settings', + 'body' => [ + 'hostname' => 'local-finalizer.example', + 'root_password' => 'Secret9!Password', + 'confirm_restart' => true, + ], + 'owner_id' => 1, + 'can_manage' => false, + 'credential' => [ + 'password' => 'Secret9!Password', + 'login_name' => 'root', + 'auth_mode' => 'password', + ], + 'settings_fields' => ['hostname', 'password'], + ]; + Capsule::table('user')->insert([ + 'id' => 1, 'enable' => 1, 'is_admin' => 0, + ]); + Capsule::table('cloud_instances')->insert([ + 'id' => 501, + 'uuid' => $uuid, + 'host_id' => 7, + 'user_id' => 1, + 'name' => 'local-finalizer', + 'status' => 'active', + 'service_status' => 'exempt', + 'network_status' => 'active', + 'spec_json' => json_encode( + ['managed' => true], + JSON_THROW_ON_ERROR + ), + 'sealed_credential' => null, + 'created_at' => $now - 3600, + 'updated_at' => $now - 3600, + ]); + $originalEnvelope = CloudSecrets::encrypt($payload, 'job-payload'); + $originalResult = json_encode( + ['cause_code' => 'local_finalization_failed'], + JSON_THROW_ON_ERROR + ); + Capsule::table('cloud_jobs')->insert([ + 'id' => 501, + 'operation_id' => $operationId, + 'request_idempotency_key' => $operationId, + 'request_fingerprint' => hash('sha256', $operationId), + 'parent_job_id' => null, + 'order_id' => null, + 'invoice_id' => null, + 'instance_id' => 501, + 'snapshot_id' => null, + 'user_id' => 1, + 'host_id' => 7, + 'kind' => 'instance_settings', + 'execution_mode' => 'agent', + 'phase' => 'terminal', + 'outcome' => 'failed', + 'status' => 'failed', + 'sealed_payload' => $originalEnvelope, + 'attempts' => 0, + 'dispatch_attempts' => 0, + 'dispatch_deadline_at' => $now - 30, + 'terminal_at' => $now - 20, + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'not_applied', + 'effect_resolution_reason' => '', + 'lease_until' => 0, + 'available_at' => 0, + 'error_code' => 'local_finalization_failed', + 'finalization_incident' => 1, + 'finalization_error_code' => 'recovery_ledger_conflict', + 'result_json' => $originalResult, + 'created_at' => $now - 30, + 'updated_at' => $now - 20, + ]); + + $before = CloudJob::findOrFail(501); + $assert(CloudJobService::blockingQueryForInstance(501)->exists(), + 'An undispatched local finalizer incident did not block mutations.'); + $service = new CloudAutomaticOperationRecoveryService(); + $assert($service->tick(), + 'The undispatched PHP-only finalizer was not claimed.'); + $after = CloudJob::findOrFail(501); + $scrubbed = CloudSecrets::decrypt( + (string) $after->sealed_payload, + 'job-payload' + ); + $assert((string) $after->phase === (string) $before->phase + && (string) $after->outcome === (string) $before->outcome + && (string) $after->status === (string) $before->status + && (int) $after->terminal_at === (int) $before->terminal_at + && (string) $after->error_code === (string) $before->error_code + && (string) $after->result_json === (string) $before->result_json + && $after->completion_event_id === $before->completion_event_id + && !(bool) $after->effect_may_have_applied + && (bool) $after->safe_to_resubmit + && (string) $after->effect_resolution === 'not_applied' + && (string) $after->effect_resolution_reason + === 'automatic_local_not_dispatched' + && (int) $after->effect_resolved_at > 0 + && !(bool) $after->finalization_incident + && $after->finalization_error_code === null + && $after->lease_token === null + && (int) $after->lease_until === 0 + && (int) $after->available_at === 0 + && (string) $after->sealed_payload !== $originalEnvelope + && !isset($scrubbed['credential']) + && !isset($scrubbed['body']['root_password']) + && !CloudJobService::blockingQueryForInstance(501)->exists(), + 'The PHP-only finalizer changed terminal audit data or failed to converge safely.'); + $updatedAt = (int) $after->updated_at; + $assert(!$service->tick(), + 'A converged PHP-only finalizer was claimed a second time.'); + $afterSecondTick = CloudJob::findOrFail(501); + $assert((int) $afterSecondTick->updated_at === $updatedAt, + 'A converged PHP-only finalizer repeated its side effects.'); + + // A missing/corrupt encrypted escrow remains a concrete payload incident; + // it must not degrade into a generic ledger-conflict message. + Capsule::table('cloud_instances')->insert([ + 'id' => 502, + 'uuid' => '00000000-0000-4000-8000-000000000502', + 'host_id' => 7, + 'user_id' => 1, + 'name' => 'local-finalizer-corrupt-payload', + 'status' => 'active', + 'service_status' => 'exempt', + 'network_status' => 'active', + 'spec_json' => json_encode(['managed' => true], JSON_THROW_ON_ERROR), + 'sealed_credential' => null, + 'created_at' => $now - 3600, + 'updated_at' => $now - 3600, + ]); + $corruptOperationId = str_repeat('ae', 16); + Capsule::table('cloud_jobs')->insert([ + 'id' => 502, + 'operation_id' => $corruptOperationId, + 'request_idempotency_key' => $corruptOperationId, + 'request_fingerprint' => hash('sha256', $corruptOperationId), + 'parent_job_id' => null, + 'order_id' => null, + 'invoice_id' => null, + 'instance_id' => 502, + 'snapshot_id' => null, + 'user_id' => 1, + 'host_id' => 7, + 'kind' => 'instance_settings', + 'execution_mode' => 'agent', + 'phase' => 'terminal', + 'outcome' => 'failed', + 'status' => 'failed', + 'sealed_payload' => 'undispatched-finalizer-test:missing', + 'attempts' => 0, + 'dispatch_attempts' => 0, + 'dispatch_deadline_at' => $now - 30, + 'terminal_at' => $now - 20, + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 0, + 'effect_resolution' => 'not_applied', + 'effect_resolution_reason' => '', + 'lease_until' => 0, + 'available_at' => 0, + 'error_code' => 'local_finalization_failed', + 'finalization_incident' => 1, + 'finalization_error_code' => 'recovery_payload_unavailable', + 'result_json' => $originalResult, + 'created_at' => $now - 30, + 'updated_at' => $now - 20, + ]); + $assert($service->tick(), + 'The corrupt undispatched recovery payload was not checked.'); + $corruptPayloadJob = CloudJob::findOrFail(502); + $assert((bool) $corruptPayloadJob->finalization_incident + && (string) $corruptPayloadJob->finalization_error_code + === 'recovery_payload_unavailable' + && (string) $corruptPayloadJob->sealed_payload + === 'undispatched-finalizer-test:missing' + && (int) $corruptPayloadJob->lease_until >= time() + 290 + && (int) $corruptPayloadJob->available_at >= time() + 290 + && CloudJobService::blockingQueryForInstance(502)->exists(), + 'A corrupt PHP-only recovery payload lost its concrete incident or resource fence.'); + + echo "Cloud undispatched finalizer recovery tests passed.\n"; +} diff --git a/web/tests/CloudWorkerExecutionModeTest.php b/web/tests/CloudWorkerExecutionModeTest.php index 4748cc30..319cb1c3 100644 --- a/web/tests/CloudWorkerExecutionModeTest.php +++ b/web/tests/CloudWorkerExecutionModeTest.php @@ -1,8 +1,36 @@ addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default'); $capsule->setAsGlobal(); $capsule->bootEloquent(); +$capsule->schema('default')->create('user', + static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('enable')->default(1); + $table->integer('is_admin')->default(0); + }); $capsule->schema('default')->create('cloud_jobs', static function (Blueprint $table): void { $table->increments('id'); @@ -62,6 +96,22 @@ $capsule->schema('default')->create('cloud_jobs', $table->integer('created_at'); $table->integer('updated_at'); }); +$capsule->schema('default')->create('cloud_agent_completion_events', + static function (Blueprint $table): void { + $table->string('event_id')->primary(); + $table->integer('host_id'); + $table->string('operation_id'); + $table->string('payload_sha256'); + $table->string('outcome'); + $table->boolean('effect_may_have_applied'); + $table->boolean('safe_to_resubmit'); + $table->string('error_code')->default(''); + $table->text('result_json')->nullable(); + $table->string('disposition')->default('received'); + $table->integer('received_at'); + $table->integer('applied_at')->nullable(); + $table->unique(['host_id', 'operation_id']); + }); $now = time(); $base = [ @@ -103,8 +153,49 @@ Capsule::table('cloud_jobs')->insert(array_merge($base, [ 'phase' => 'accepted', 'status' => 'queued', ])); +Capsule::table('user')->insert(['id' => 1, 'enable' => 1, 'is_admin' => 0]); +Capsule::table('cloud_jobs')->insert(array_merge($base, [ + 'id' => 3, + 'operation_id' => str_repeat('c', 32), + 'request_idempotency_key' => str_repeat('c', 32), + 'host_id' => 7, + 'kind' => 'instance_settings', + 'execution_mode' => 'local', + 'phase' => 'accepted', + 'status' => 'queued', + 'sealed_payload' => CloudSecrets::encrypt([ + 'method' => 'POST', + 'request_target' => '/v1/vms/11111111-2222-4333-8444-555555555555/settings', + 'body' => ['hostname' => 'mode-conflict.example'], + 'owner_id' => 1, + ], 'job-payload'), +])); -$worker = new CloudWorkerService(); +$agentCalls = 0; +$transport = new Client(['handler' => static function () use ( + &$agentCalls +) { + $agentCalls++; + throw new RuntimeException('Mode-conflict task reached Agent'); +}]); +$tripwireAgent = new CloudAgentClient( + '7', str_repeat('a', 32), $transport, 120.0, + 'http://127.0.0.1:8001/internal/agent/request', + str_repeat('b', 32) +); +$worker = new CloudWorkerService($tripwireAgent); +$assert($worker->tick() === true, + 'The mode-conflict task was not consumed by the local quarantine path.'); +$corruptLeaf = Capsule::table('cloud_jobs')->where('id', 3)->first(); +$assert($agentCalls === 0 + && $corruptLeaf !== null + && $corruptLeaf->phase === 'terminal' + && $corruptLeaf->outcome === 'failed' + && $corruptLeaf->effect_resolution === 'unknown' + && (int) $corruptLeaf->finalization_incident === 1 + && $corruptLeaf->finalization_error_code + === 'recovery_instance_state_conflict', + 'A supported Agent task with a corrupt local mode was dispatched or not quarantined.'); $assert($worker->tick() === true, 'The host-null local payment task was not claimed.'); $local = Capsule::table('cloud_jobs')->where('id', 2)->first(); @@ -121,3 +212,4 @@ $assert($worker->tick() === false, 'The terminal local failure or aggregate parent remained worker-claimable.'); echo "Explicit execution-mode worker claim tests passed.\n"; +} diff --git a/web/tests/VirtualizationAssetsTest.php b/web/tests/VirtualizationAssetsTest.php index ee441a11..3795d41e 100644 --- a/web/tests/VirtualizationAssetsTest.php +++ b/web/tests/VirtualizationAssetsTest.php @@ -782,7 +782,8 @@ $assert(str_contains($detailTemplate, 'id="vm-snapshot-create-form"') && str_contains($clientScript, 'const activeJobPresent = Boolean(payload?.active_job)') && str_contains($clientScript, 'payload?.can_mutate === false') && str_contains($clientScript, 'snapshotHasUnsafeFailure(items)') - && str_contains($clientScript, 'snapshotEffectLocked = task.effect_may_have_applied || task.safe_to_resubmit === false') + && str_contains($clientScript, 'const succeeded = taskSucceededWithoutRecovery(task)') + && str_contains($clientScript, 'snapshotEffectLocked = task.recovery?.pending === true') && str_contains($clientScript, '操作效果可能已经发生。相关操作已停用') && str_contains($clientScript, '宿主机未能安全完成自动降级') && str_contains($clientScript, '实际模式为${snapshotConsistency(actualConsistency)}')