fix(cloud): keep operation recovery identity-bound

go
codex 1 month ago
parent cf2cd70b6f
commit 0659a75b45

@ -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
}

@ -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()

@ -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)

@ -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)
}
}

@ -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)

@ -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)
}
}

@ -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) {

@ -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"`
}

@ -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": {

@ -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

File diff suppressed because it is too large Load Diff

@ -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")

@ -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 栅栏审计元数据;原任务仍作为不可变审计记录保留。
## 运行状态

@ -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`。
## 关键资源语义

@ -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 提交后才解除栅栏。

@ -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,只有确认效果并完成账本收敛后才释放,期间不得退款、释放或再次删除。
## 控制台

@ -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 的成功判定来自明确证据而非仅观察“仍在运行”。
## 设计依据

@ -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 进程的文件锁。

@ -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
<per-host-secret>`, and the exact `virt-agent-control.v2` subprotocol. The
<per-host-secret>`, 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:

@ -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,
})

@ -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()

@ -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")

@ -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())
}
}

@ -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<string> $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,

@ -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(

@ -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<string> $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 '无任务级安全栅栏';
}
}

@ -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'];
}

@ -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();
}

@ -0,0 +1,105 @@
<?php
namespace App\Services\Cloud;
/**
* Fail-closed interpretation of the immutable single-dispatch counter.
*
* Zero is the only proof that no Agent mutation crossed the dispatch boundary.
* One is the only valid dispatched generation. Any other value is corruption:
* callers must retain the resource fence and must not consume recovery proof
* until an operator repairs the ledger.
*/
final class CloudDispatchLedger
{
public const CONFLICT_CODE = 'recovery_dispatch_ledger_conflict';
private const REPAIR_INCIDENT_CODES = [
self::CONFLICT_CODE,
'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',
];
public static function attempts(object $job): int
{
$value = $job->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<string> */
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
);
}
}

@ -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.

File diff suppressed because it is too large Load Diff

@ -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) {

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -0,0 +1,49 @@
<?php
namespace App\Services\Cloud;
/**
* Allow-list of single-dispatch Agent leaf operations whose PHP ledgers may be
* converged from immutable completion or operation-bound inspection evidence.
*
* Aggregate parents are deliberately absent: they never cross the Agent
* dispatch boundary and must be recomputed from their recovered child jobs.
*/
final class CloudOperationRecoveryPolicy
{
private const AGENT_LEAF_KINDS = [
'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',
'template_import_replica',
'template_metadata_replica',
'template_delete_replica',
'rescue_template_import',
'rescue_template_delete',
'user_iso_import_replica',
'user_iso_delete_replica',
];
/** @return list<string> */
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);
}
}

@ -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();
}
}

@ -0,0 +1,8 @@
<?php
namespace App\Services\Cloud;
/** The aggregate parent/child ledger cannot safely publish a leaf verdict. */
final class CloudRecoveryAggregateStateConflict extends CloudError
{
}

@ -0,0 +1,8 @@
<?php
namespace App\Services\Cloud;
/** The single-dispatch ledger contains a value outside its 0/1 contract. */
final class CloudRecoveryDispatchLedgerConflict extends CloudError
{
}

@ -0,0 +1,8 @@
<?php
namespace App\Services\Cloud;
/** The current PHP-owned instance/resource ledger contradicts recovery input. */
final class CloudRecoveryInstanceStateConflict extends CloudError
{
}

@ -0,0 +1,8 @@
<?php
namespace App\Services\Cloud;
/** The Agent Journal identity does not name the exact PHP operation request. */
final class CloudRecoveryOperationIdentityConflict extends CloudError
{
}

@ -0,0 +1,8 @@
<?php
namespace App\Services\Cloud;
/** The encrypted recovery escrow is missing, unreadable, or incomplete. */
final class CloudRecoveryPayloadUnavailable extends CloudError
{
}

@ -158,11 +158,29 @@ final class CloudRenewalService
$locked->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;
}

@ -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) {

@ -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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -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} 执行失败。`);

@ -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} 失败。`);

@ -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);

@ -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',

@ -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);

@ -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) {

@ -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 {

@ -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; }
}

@ -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('任务记录暂时不可用,请稍后刷新。');

@ -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();

@ -40,7 +40,7 @@
<td data-label="所在位置"><span class="admin-checkout-user"><strong>{$vm.host_name|escape}</strong><span>{$vm.region|default:'地区未记录'|escape}</span></span></td>
<td data-label="公网 IP"><span class="admin-instance-ip"><span class="admin-mono">{$vm.public_ip|default:'未记录'|escape}</span>{if $vm.public_ip}<button class="btn btn-light btn-sm" type="button" data-copy="{$vm.public_ip|escape}" aria-label="复制公网 IP {$vm.public_ip|escape}"><i class="mdi mdi-content-copy" aria-hidden="true"></i></button>{/if}</span></td>
<td data-label="配置"><span class="admin-checkout-user"><strong>{$vm.display.configuration|escape}</strong><span>{$vm.plan_name|default:'无关联套餐'|escape}</span></span></td>
<td data-label="状态"><div class="admin-instance-status"><span class="badge bg-light text-dark" data-power-status>电源:待获取</span><span class="fs-12">服务:{$vm.display.service|escape}</span><span class="fs-12">网络:{$vm.display.network|escape}</span>{if $vm.active_job}<span class="text-warning fs-12">任务 #{$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}</span>{/if}</div></td>
<td data-label="状态"><div class="admin-instance-status"><span class="badge bg-light text-dark" data-power-status>电源:待获取</span><span class="fs-12">服务:{$vm.display.service|escape}</span><span class="fs-12">网络:{$vm.display.network|escape}</span>{if $vm.active_job}<span class="text-warning fs-12">任务 #{$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}</span>{/if}</div></td>
<td data-label="用量与期限"><span class="admin-checkout-user"><strong>{$vm.display.traffic|escape}</strong><span>{$vm.display.expiry|escape}</span>{if $vm.service_expires_at && $vm.service_status != 'exempt'}<span>到期 {$vm.service_expires_at|date_format:'%Y-%m-%d'|escape}</span>{/if}</span></td>
<td data-label="操作"><button class="btn btn-primary btn-sm" type="button" data-instance-detail="{$vm.id|escape}" aria-label="查看 {$vm.name|escape} 的详情">查看详情</button></td>
</tr>

@ -5,7 +5,7 @@
{assign var=operations_statuses value=['all'=>'全部状态','active'=>'执行中','succeeded'=>'已成功','failed'=>'已失败']}
<main data-admin-operations data-can-manage="{if $admin_can_manage|default:false}1{else}0{/if}">
<div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column gap-3">
<div class="flex-grow-1"><h1 class="fs-20 fw-semibold mb-1">系统运行与任务记录</h1><p class="text-muted mb-0">任务只展示执行中、成功或失败。失败且效果可能已发生时,资源保持安全锁定并由管理员人工处理;固定存储池配置失败不保留跨任务栅栏。</p></div>
<div class="flex-grow-1"><h1 class="fs-20 fw-semibold mb-1">系统运行与任务记录</h1><p class="text-muted mb-0">任务只展示执行中、成功或失败。失败且效果尚未确认时,资源保持安全锁定;支持恢复的 Agent 任务会持续自动核对,且绝不会重放原操作。</p></div>
<div class="admin-checkout-actions"><span class="admin-config-status {if $operations_error|default:''}is-error{else}is-success{/if}" id="operations-notice" role="status" aria-live="polite">{if $operations_error|default:''}{$operations_error|escape}{else}已读取 {$operations_page.pagination.total|default:0|escape} 条任务{/if}</span><button class="btn btn-light" id="operations-refresh" type="button"><i class="mdi mdi-refresh me-1" aria-hidden="true"></i>刷新任务</button></div>
</div>
<section class="card mb-3" aria-labelledby="operations-health-title">
@ -18,7 +18,7 @@
{/foreach}
</section>
<section class="card mb-3 admin-billing-filter" aria-labelledby="operations-filter-title">
<div class="card-header"><h2 class="h5 card-title mb-1" id="operations-filter-title">查找任务</h2><p class="text-muted fs-13 mb-0">摘要和列表均按筛选条件统计。任务失败不会在此页自动重新提交。</p></div>
<div class="card-header"><h2 class="h5 card-title mb-1" id="operations-filter-title">查找任务</h2><p class="text-muted fs-13 mb-0">摘要和列表均按筛选条件统计。自动核对只读取原任务证据,不会重新提交原操作。</p></div>
<div class="card-body"><form class="row g-2 align-items-end" id="operations-filter" method="get" action="/admin/operations">
<label class="col-xl-4 col-lg-6" for="operations-query"><span class="form-label d-block">关键词</span><input class="form-control" type="search" id="operations-query" name="q" maxlength="80" value="{$operations_filters.q|default:''|escape}" placeholder="任务 ID / 操作标识 / 实例名称或 UUID"></label>
<label class="col-xl-2 col-lg-3 col-6" for="operations-status"><span class="form-label d-block">任务状态</span><select class="form-select" id="operations-status" name="status">{foreach $operations_statuses as $value=>$label}<option value="{$value|escape}" {if $operations_filters.status|default:'all' == $value}selected{/if}>{$label|escape}</option>{/foreach}</select></label>
@ -39,7 +39,7 @@
<dialog data-admin-instance-drawer data-admin-operations-drawer id="operation-detail" aria-labelledby="operation-detail-title">
<header class="admin-instance-drawer-header"><div><p class="text-muted fs-13 mb-1">任务详情</p><h2 class="h4 fw-semibold mb-0" id="operation-detail-title">任务</h2></div><button class="admin-modal-close position-static flex-shrink-0" id="operation-detail-close" type="button" aria-label="关闭任务详情" autofocus><i class="mdi mdi-close" aria-hidden="true"></i></button></header>
<div class="admin-instance-drawer-body"><p class="alert alert-info" id="operation-detail-state" role="status" aria-live="polite">正在读取任务详情…</p><div id="operation-detail-body"></div><section class="alert alert-warning mt-4" id="operation-effect-resolution" hidden><h3 class="h6">人工收敛任务级资源安全栅栏</h3><p class="fs-13">仅在已取得可审计的真实效果证据后使用。原任务仍保持失败,不会重放 Agent 或支付请求;服务端只会执行该任务类型已实现的原子账本收尾。</p><label class="form-label" for="operation-effect-value">人工核实结果</label><select class="form-select" id="operation-effect-value"><option value="">请选择</option><option value="applied">操作效果已经发生</option><option value="not_applied">操作效果未发生</option></select><label class="form-label mt-3" for="operation-effect-reason">审计证据与说明(20–500 字符)</label><textarea class="form-control" id="operation-effect-reason" minlength="20" maxlength="500" rows="4"></textarea><button class="btn btn-danger btn-sm mt-3" id="operation-effect-submit" type="button">人工确认并收敛安全栅栏</button></section></div>
<footer class="admin-instance-drawer-footer"><span class="text-muted fs-12">失败任务不会自动重提。资源已锁定时,请按失败详情进行人工处理。</span><div class="d-flex flex-wrap gap-2"><button class="btn btn-primary btn-sm" id="operation-detail-inspect" type="button" hidden>只读检查宿主机</button><button class="btn btn-danger btn-sm" id="operation-detail-force-delete" type="button" hidden>确认强制删除</button><div class="d-flex flex-wrap gap-2" id="operation-detail-links"></div></div></footer>
<footer class="admin-instance-drawer-footer"><span class="text-muted fs-12">失败任务不会自动重提。详情标为持续自动核对时,只需修复所示通信或数据异常;系统会继续收敛。</span><div class="d-flex flex-wrap gap-2"><button class="btn btn-primary btn-sm" id="operation-detail-inspect" type="button" hidden>只读检查宿主机</button><button class="btn btn-danger btn-sm" id="operation-detail-force-delete" type="button" hidden>确认强制删除</button><div class="d-flex flex-wrap gap-2" id="operation-detail-links"></div></div></footer>
</dialog>
<script id="admin-operations-bootstrap" type="application/json">{$operations_bootstrap_json|default:'null' nofilter}</script>
<script type="module" src="/cloud/admin-operations.js?v={$venix_asset_version}"></script>

@ -4,7 +4,7 @@
<td data-label="关联实例"><span class="admin-checkout-user"><strong>{$job.instance_name|default:'无关联实例'|escape}</strong>{if $job.instance_id}<span>实例 #{$job.instance_id|escape}</span>{/if}{if $job.order_id}<span>订单 #{$job.order_id|escape}</span>{/if}</span></td>
<td data-label="用户"><span class="admin-checkout-user"><strong>操作人:{$job.actor_name|default:'未记录'|escape}{if $job.actor_id} #{$job.actor_id|escape}{/if}</strong>{if $job.owner_id}<span>所属:{$job.owner_name|default:'未记录'|escape} #{$job.owner_id|escape}</span>{/if}</span></td>
<td data-label="宿主机"><span class="admin-checkout-user"><strong>{$job.host_name|default:'未记录'|escape}</strong><span>{$job.region|default:'地区未记录'|escape}</span></span></td>
<td data-label="状态"><span class="admin-checkout-user">{if isset($job.completed) && !$job.completed && $job.status == 'active'}<strong class="text-primary">执行中</strong>{elseif isset($job.completed) && $job.completed && in_array($job.status,['succeeded','failed'])}<strong class="{if $job.status == 'succeeded'}text-success{else}text-danger{/if}">{if $job.status == 'succeeded'}已成功{else}已失败{/if}</strong>{if $job.status == 'failed' && $job.kind == 'host_storage_configure'}<span class="text-danger">旧存储任务已终止且不会重放;后续任务须沿用已定义固定池的路径。</span>{elseif $job.status == 'failed' && $job.effect_may_have_applied|default:false && $job.effect_resolution == 'unknown'}<span class="text-danger">操作效果可能已发生;资源已安全锁定,需管理员人工处理。</span>{elseif $job.status == 'failed' && $job.effect_may_have_applied|default:false && in_array($job.effect_resolution,['applied','not_applied'])}<span>任务仍为失败;人工审计已解除任务级安全栅栏。</span>{/if}{else}<strong class="text-danger">协议错误</strong><span class="text-danger">资源按可能已生效处理并保持锁定。</span>{/if}</span></td>
<td data-label="状态"><span class="admin-checkout-user">{if $job.recovery.pending|default:false}<strong class="text-warning">安全恢复中</strong><span class="text-warning">{$job.recovery.message|default:'资源保持安全锁定,系统仍会继续自动核对。'|escape}</span>{elseif isset($job.completed) && !$job.completed && $job.status == 'active'}<strong class="text-primary">执行中</strong>{elseif isset($job.completed) && $job.completed && in_array($job.status,['succeeded','failed'])}<strong class="{if $job.status == 'succeeded'}text-success{else}text-danger{/if}">{if $job.status == 'succeeded'}已成功{else}已失败{/if}</strong>{if $job.status == 'failed' && $job.kind == 'host_storage_configure'}<span class="text-danger">旧存储任务已终止且不会重放;后续任务须沿用已定义固定池的路径。</span>{elseif $job.status == 'failed' && $job.effect_may_have_applied|default:false && $job.effect_resolution == 'unknown'}<span class="text-danger">操作效果可能已发生;资源已安全锁定,需管理员人工处理。</span>{elseif $job.status == 'failed' && $job.effect_may_have_applied|default:false && in_array($job.effect_resolution,['applied','not_applied'])}<span>任务仍为失败;系统已确认操作{if $job.effect_resolution == 'applied'}已应用{else}未应用{/if},安全栅栏已解除。</span>{/if}{else}<strong class="text-danger">协议错误</strong><span class="text-danger">资源按可能已生效处理并保持锁定。</span>{/if}</span></td>
<td data-label="执行信息"><span class="admin-checkout-user"><strong>{$job.operation_id|default:'无操作标识'|escape}</strong><span>{$job.phase|default:'未记录阶段'|escape}</span></span></td>
<td data-label="更新与异常"><span class="admin-checkout-user"><strong>{if $job.updated_at}{$job.updated_at|date_format:'%Y-%m-%d %H:%M:%S'|escape}{else}更新时间未记录{/if}</strong>{if $job.error}<span class="text-danger">{$job.error|escape}</span>{else}<span>未记录错误</span>{/if}</span></td>
<td data-label="操作"><div class="d-flex flex-wrap gap-1"><button class="btn btn-primary btn-sm" type="button" data-operation-detail="{$job.id|escape}" aria-label="查看任务 #{$job.id|escape} 的详情">查看详情</button></div></td>

@ -142,7 +142,7 @@
<span class="badge fs-12 bg-info-subtle text-info-emphasis">{$overview.jobs.active}</span>
</a>
<a href="/admin/operations?status=failed">
<span><strong class="d-block">资源安全锁定</strong><small class="text-muted">失败且效果可能已发生,需管理员人工处理</small></span>
<span><strong class="d-block">资源安全锁定</strong><small class="text-muted">支持恢复的 Agent 任务会持续自动核对,不会重放原操作</small></span>
<span class="badge fs-12 bg-danger-subtle text-danger-emphasis">{$overview.jobs.unresolved_effect|default:0}</span>
</a>
<a href="/admin/operations?status=failed">

@ -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'}

@ -2,7 +2,7 @@
<header class="panel-task-header">
<div>
<h2 id="panel-task-title">任务中心</h2>
<p id="panel-task-description">查看后台任务的执行结果。离开页面不会取消已经接收的任务。</p>
<p id="panel-task-description">查看后台任务的执行结果。离开页面不会取消任务;效果待确认的失败任务会持续自动核对,且不会重复执行原操作。</p>
</div>
<button class="button button-ghost panel-task-close" id="panel-task-close" type="button" aria-label="关闭任务中心"><i class="mdi mdi-close" aria-hidden="true"></i></button>
</header>

@ -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/);

@ -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'")

@ -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/);

@ -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('<?xml encoding="UTF-8">' . $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.');

@ -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')

@ -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,

@ -1,6 +1,27 @@
<?php
namespace App\Services\Cloud {
final class CloudSecrets
{
private static array $values = [];
public static function encrypt(array $value, string $purpose): string
{
$key = bin2hex(random_bytes(16));
self::$values[$key] = $value;
return 'admin-recovery-test:' . $key;
}
public static function decrypt(string $value, string $purpose): array
{
$key = substr($value, strlen('admin-recovery-test:'));
if (!array_key_exists($key, self::$values)) {
throw new \RuntimeException('Missing admin recovery payload.');
}
return self::$values[$key];
}
}
final class RecoveryTestAgentClient
{
public array $requests = [];
@ -79,7 +100,10 @@ namespace {
use App\Services\Cloud\CloudAgentError;
use App\Services\Cloud\CloudAgentSettingsService;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudOperationRecoveryIdentity;
use App\Services\Cloud\CloudSecrets;
use App\Services\Cloud\RecoveryTestAgentClient;
use App\Models\CloudJob;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
@ -115,6 +139,8 @@ namespace {
static function (Blueprint $table): void {
$table->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.');

@ -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 = [

@ -0,0 +1,650 @@
<?php
declare(strict_types=1);
namespace App\Services\Cloud {
/** Isolated encrypted envelope for Agent mutation identity tests. */
final class CloudSecrets
{
private static array $values = [];
public static function encrypt(array $value, string $purpose): string
{
$key = bin2hex(random_bytes(16));
self::$values[$key] = $value;
return 'agent-mutation-identity-test:' . $key;
}
public static function decrypt(string $value, string $purpose): array
{
$key = substr(
$value,
strlen('agent-mutation-identity-test:')
);
if (!array_key_exists($key, self::$values)) {
throw new \RuntimeException('Missing identity test payload.');
}
return self::$values[$key];
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudJob;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudOperationCompletionService;
use App\Services\Cloud\CloudOperationRecoveryIdentity;
use App\Services\Cloud\CloudOperationRecoveryPolicy;
use App\Services\Cloud\CloudRecoveryOperationIdentityConflict;
use App\Services\Cloud\CloudSecrets;
use App\Services\Cloud\CloudWorkerService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$expectCloudError = static function (
callable $callback,
int $status
) use ($assert): void {
try {
$callback();
} catch (CloudError $error) {
$assert($error->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";
}

@ -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']),

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -0,0 +1,585 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudTemplate;
use App\Models\CloudUserIso;
use App\Models\CloudJob;
use App\Services\Cloud\CloudDispatchLedger;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudJobService;
use App\Services\Cloud\CloudTemplateCatalogService;
use App\Services\Cloud\CloudUserIsoService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
foreach ([
0 => 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";

@ -0,0 +1,191 @@
<?php
declare(strict_types=1);
$root = dirname(__DIR__);
$worker = file_get_contents(
$root . '/app/Services/Cloud/CloudWorkerService.php'
);
$recovery = file_get_contents(
$root . '/app/Services/Cloud/CloudOperationRecoveryService.php'
);
$automatic = file_get_contents(
$root . '/app/Services/Cloud/CloudAutomaticOperationRecoveryService.php'
);
$jobs = file_get_contents(
$root . '/app/Services/Cloud/CloudJobService.php'
);
$templates = file_get_contents(
$root . '/app/Services/Cloud/CloudTemplateCatalogService.php'
);
$isos = file_get_contents(
$root . '/app/Services/Cloud/CloudUserIsoService.php'
);
if (!is_string($worker) || !is_string($recovery) || !is_string($automatic)
|| !is_string($jobs)
|| !is_string($templates) || !is_string($isos)) {
throw new RuntimeException('Cannot read catalog lock-order sources.');
}
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$method = static function (
string $source,
string $start,
string $end
): string {
$from = strpos($source, $start);
$to = $from === false ? false : strpos($source, $end, $from + 1);
return $from === false || $to === false
? '' : substr($source, $from, $to - $from);
};
$ordered = static function (
string $source,
array $needles
): bool {
$offset = -1;
foreach ($needles as $needle) {
$next = strpos($source, $needle, $offset + 1);
if ($next === false || $next <= $offset) {
return false;
}
$offset = $next;
}
return true;
};
$finish = $method(
$worker,
'$aggregateParentId = (int) ($claimed->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";

File diff suppressed because it is too large Load Diff

@ -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;

@ -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')

@ -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

@ -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 {

@ -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,

@ -0,0 +1,223 @@
<?php
declare(strict_types=1);
namespace App\Services\Cloud {
/** Isolated encrypted envelope used only by this focused contract test. */
final class CloudSecrets
{
private static array $values = [];
public static function encrypt(array $value, string $purpose): string
{
$key = bin2hex(random_bytes(16));
self::$values[$key] = $value;
return 'operation-recovery-policy-test:' . $key;
}
public static function decrypt(string $value, string $purpose): array
{
$key = substr(
$value,
strlen('operation-recovery-policy-test:')
);
if (!array_key_exists($key, self::$values)) {
throw new \RuntimeException('Missing recovery policy payload.');
}
return self::$values[$key];
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudAgentCompletionEvent;
use App\Models\CloudJob;
use App\Services\Cloud\CloudAgentError;
use App\Services\Cloud\CloudAutomaticOperationRecoveryService;
use App\Services\Cloud\CloudOperationCompletionService;
use App\Services\Cloud\CloudOperationRecoveryPolicy;
use App\Services\Cloud\CloudOperationRecoveryService;
use App\Services\Cloud\CloudRecoveryInstanceStateConflict;
use App\Services\Cloud\CloudSecrets;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$expectedKinds = [
'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',
'template_import_replica',
'template_metadata_replica',
'template_delete_replica',
'rescue_template_import',
'rescue_template_delete',
'user_iso_import_replica',
'user_iso_delete_replica',
];
$assert(CloudOperationRecoveryPolicy::kinds() === $expectedKinds,
'The Agent leaf recovery policy changed without updating its contract.');
$assert(count(CloudOperationRecoveryPolicy::kinds()) === 22,
'The recovery policy contract must contain exactly 22 Agent leaf kinds.');
foreach ($expectedKinds as $kind) {
$assert(CloudOperationRecoveryPolicy::supports($kind),
'The recovery policy omitted ' . $kind . '.');
}
foreach ([
// Provisioning is finalized through its paid-order cleanup contract.
'create',
// Aggregate parents never cross the Agent dispatch boundary.
'template_import', 'template_metadata_sync', 'template_delete',
'user_iso_import', 'user_iso_delete',
// Payments and host storage have independent reconciliation rules.
'payment_create', 'host_storage_configure',
] as $kind) {
$assert(!CloudOperationRecoveryPolicy::supports($kind),
'An aggregate or separately finalized kind entered leaf recovery: '
. $kind);
}
$attemptState = new ReflectionMethod(
CloudOperationRecoveryService::class,
'automaticRecoveryState'
);
$state = $attemptState->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";
}

@ -0,0 +1,550 @@
<?php
declare(strict_types=1);
namespace App\Services\Cloud {
/** Isolated encrypted payload store for this SQLite contract test. */
final class CloudSecrets
{
private static array $values = [];
public static function encrypt(array $value, string $purpose): string
{
$key = bin2hex(random_bytes(16));
self::$values[$key] = $value;
return 'rescue-template-retry-test:' . $key;
}
public static function decrypt(string $value, string $purpose): array
{
$key = substr($value, strlen('rescue-template-retry-test:'));
if (!array_key_exists($key, self::$values)) {
throw new \RuntimeException('Missing test payload.');
}
return self::$values[$key];
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudJob;
use App\Models\CloudRescueTemplateDeletion;
use App\Models\CloudRescueTemplateImport;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudRescueTemplateDeletionService;
use App\Services\Cloud\CloudRescueTemplateImportService;
use App\Services\Cloud\CloudSecrets;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$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');
$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";
}

@ -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 ([

@ -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');

@ -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')

@ -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();

@ -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'")

File diff suppressed because it is too large Load Diff

@ -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*</);
}
function sourceForSuccessGuard(source) {
assert.doesNotMatch(source, /task\.status === 'succeeded'/);
return source;
}
console.log('Cloud task observer behavior tests passed.');

@ -0,0 +1,746 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudJobService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$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->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";

@ -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');

@ -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'")

@ -0,0 +1,365 @@
<?php
declare(strict_types=1);
namespace App\Services\Cloud {
/** Isolated encrypted envelope for PHP-only finalizer recovery tests. */
final class CloudSecrets
{
private static array $values = [];
public static function encrypt(array $value, string $purpose): string
{
$key = bin2hex(random_bytes(16));
self::$values[$key] = $value;
return 'undispatched-finalizer-test:' . $key;
}
public static function decrypt(string $value, string $purpose): array
{
$key = substr(
$value,
strlen('undispatched-finalizer-test:')
);
if (!array_key_exists($key, self::$values)) {
throw new \RuntimeException('Missing finalizer test payload.');
}
return self::$values[$key];
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudJob;
use App\Services\Cloud\CloudAutomaticOperationRecoveryService;
use App\Services\Cloud\CloudJobService;
use App\Services\Cloud\CloudSecrets;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$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')->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";
}

@ -1,8 +1,36 @@
<?php
namespace App\Services\Cloud {
/** In-memory payload escrow for execution-mode boundary tests. */
final class CloudSecrets
{
private static array $values = [];
public static function encrypt(array $value, string $purpose): string
{
$key = bin2hex(random_bytes(16));
self::$values[$key] = $value;
return 'execution-mode-test:' . $key;
}
public static function decrypt(string $value, string $purpose): array
{
$key = substr($value, strlen('execution-mode-test:'));
if (!array_key_exists($key, self::$values)) {
throw new \RuntimeException('Missing test payload');
}
return self::$values[$key];
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudAgentClient;
use App\Services\Cloud\CloudSecrets;
use App\Services\Cloud\CloudWorkerService;
use GuzzleHttp\Client;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
@ -17,6 +45,12 @@ $capsule->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";
}

@ -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)}')

Loading…
Cancel
Save