diff --git a/seaweed-block/AGENTS.md b/seaweed-block/AGENTS.md new file mode 100644 index 0000000000..030b04dd7b --- /dev/null +++ b/seaweed-block/AGENTS.md @@ -0,0 +1,73 @@ +# Agent Guidelines + +Behavioral guidelines to reduce common LLM coding mistakes. Merge with +project-specific instructions as needed. + +Tradeoff: these guidelines bias toward caution over speed. For trivial tasks, +use judgment. + +## 1. Think Before Coding + +Do not assume. Do not hide confusion. Surface tradeoffs. + +Before implementing: + +- State assumptions explicitly. If uncertain, ask. +- If multiple interpretations exist, present them; do not pick silently. +- If a simpler approach exists, say so. Push back when warranted. +- If something is unclear, stop, name what is confusing, and ask. + +## 2. Simplicity First + +Minimum code that solves the problem. Nothing speculative. + +- No features beyond what was asked. +- No abstractions for single-use code. +- No flexibility or configurability that was not requested. +- No error handling for impossible scenarios. +- If 200 lines could be 50, rewrite it. + +Ask: would a senior engineer say this is overcomplicated? If yes, simplify. + +## 3. Surgical Changes + +Touch only what you must. Clean up only your own mess. + +When editing existing code: + +- Do not improve adjacent code, comments, or formatting. +- Do not refactor things that are not broken. +- Match existing style, even if you would do it differently. +- If you notice unrelated dead code, mention it; do not delete it. + +When your changes create orphans: + +- Remove imports, variables, and functions that your changes made unused. +- Do not remove pre-existing dead code unless asked. + +Every changed line should trace directly to the user's request. + +## 4. Goal-Driven Execution + +Define success criteria. Loop until verified. + +Transform tasks into verifiable goals: + +- "Add validation" -> "Write tests for invalid inputs, then make them pass." +- "Fix the bug" -> "Write a test that reproduces it, then make it pass." +- "Refactor X" -> "Ensure tests pass before and after." + +For multi-step tasks, state a brief plan: + +```text +1. [Step] -> verify: [check] +2. [Step] -> verify: [check] +3. [Step] -> verify: [check] +``` + +Strong success criteria let agents loop independently. Weak criteria such as +"make it work" require clarification. + +These guidelines are working if there are fewer unnecessary changes in diffs, +fewer rewrites due to overcomplication, and clarifying questions come before +implementation rather than after mistakes. diff --git a/seaweed-block/README.md b/seaweed-block/README.md index 95ff490998..fbad62db9d 100644 --- a/seaweed-block/README.md +++ b/seaweed-block/README.md @@ -33,7 +33,7 @@ This is an **alpha** product path for supported lab clusters, not production. | Support-bundle replay | Available | Negative-first status reasons | Available | | Multi-volume RF=3 lab path | Gated | CSI reattach recovery | Gated | | iSCSI ALUA/dm-multipath mounted failover | Gated | Restart persistence with hostPath | Gated | -| Read-only operator snapshot | Partial | Production operator lifecycle | Planned | +| Actionable read-only CRD status + Events | Available | Bounded SwBlockVolume finalizer lifecycle | Beta candidate | | Backup/snapshot/restore | Planned | Returned-replica rebuild/failback | Planned | | NVMe ANA parity | Planned | Production SLO/performance claims | Not claimed | @@ -50,6 +50,15 @@ This is an **alpha** product path for supported lab clusters, not production. - interleaved multi-volume failover isolation. - Inspect cluster, volume, replica, primary, frontend, timeline, and reason evidence through read-only CLI/report/dashboard surfaces. +- Publish the same read-only status into Kubernetes-native `SwBlockCluster` / + `SwBlockVolume` `.status` and Events on the gated operator-status path. +- Inspect node readiness, support evidence refs, cleanup-required status, and + safe read-only/scripted next-step hints through that same status model. +- Use the beta-candidate lifecycle-owner path to protect `SwBlockVolume` CRs + with a Seaweed Block finalizer and release it only after clean externally + supplied cleanup evidence. +- Inspect install drift status for current versus desired chart/app/image + identity. This is visibility only, not upgrade execution. - Replay support bundles offline. These are narrow alpha claims tied to documented gates. See @@ -58,13 +67,18 @@ These are narrow alpha claims tied to documented gates. See ## What You Should Not Expect Yet - Production readiness or production SLOs. -- A production-grade operator or mutating admin workflow. +- A production-grade operator or broad mutating admin workflow. The current + lifecycle-owner owns only the Seaweed Block `SwBlockVolume` protection + finalizer. +- Automatic cleanup execution, host repair, or PVC/PV/workload deletion. + Delete-safety uses externally supplied cleanup evidence. - Backup, snapshot, or restore. - Returned-replica rebuild, reintegration, or failback. - Transparent Kubernetes node-loss failover without pod recreate. - NVMe ANA parity for the transparent failover path. - Broad distro/kernel/initiator compatibility. -- Broad upgrade/rollback safety beyond gated smoke paths. +- Upgrade or rollback execution. The status layer can report install drift, but + it does not run Helm or kubectl mutations. ## Five-Minute Quick Start @@ -76,8 +90,8 @@ export PATH="$PWD:$PATH" sw-block ops generate-helm-values \ --out values.day1.yaml \ - --image ghcr.io/seaweedfs/seaweed-block:sha-6260e46fd3be \ - --csi-image ghcr.io/seaweedfs/seaweed-block-csi:sha-6260e46fd3be + --image ghcr.io/seaweedfs/seaweed-block:sha-dc2972d0059b \ + --csi-image ghcr.io/seaweedfs/seaweed-block-csi:sha-dc2972d0059b helm install sw-block charts/seaweed-block \ --namespace kube-system \ @@ -104,7 +118,11 @@ status_report=status/report/index.html cleanup_status=ok ``` -Current validated alpha image tag: `sha-6260e46fd3be`. +Current validated published quickstart image tag: `sha-dc2972d0059b`. +This tag covers the v0.4 read-only/status foundation path. The v0.5 +bounded lifecycle-owner path requires matching `sw-block` and `sw-block-csi` +images published from the Phase 44 release commit; do not use the older +quickstart tag to validate lifecycle-owner behavior. Mutable `:alpha` is a smoke/demo tag only; it can drift from the source tree. @@ -130,7 +148,9 @@ Common read-only commands: | `sw-block ops inventory --namespace default --master 127.0.0.1:9333 --out ` | Collect replica-level inventory. | Reports and dashboard expose `operator-snapshot.json`, a read-only status -projection for future operator work. There are no mutating admin actions. +projection. The gated operator-status controller can publish that model into +Kubernetes CRD `.status` and Events, including node readiness, cleanup/delete +safety, and install-drift visibility. It has no mutating admin actions. Support-bundle replay: diff --git a/seaweed-block/charts/seaweed-block/README.md b/seaweed-block/charts/seaweed-block/README.md index abc9bd13dc..ff2e30f606 100644 --- a/seaweed-block/charts/seaweed-block/README.md +++ b/seaweed-block/charts/seaweed-block/README.md @@ -13,14 +13,10 @@ mutating dashboard, operator reconciliation, backup/restore, or upgrade safety. ## Quick Install -Single-node or local-dev loopback mode: - -```bash -helm install sw-block charts/seaweed-block \ - --namespace kube-system -``` - -Multi-node Day-1 mode should use non-loopback node IPs and CHAP: +Use generated values for the supported alpha install path. The generator reads +the live Kubernetes nodes and writes the node names/IPs that the launcher uses +for placement. On a single-node lab it keeps loopback/local-consumer mode; on a +multi-node lab it switches to non-loopback iSCSI with CHAP. ```bash SW_BLOCK_HELM_VALUES_OUT=values.day1.yaml \ @@ -31,6 +27,11 @@ helm install sw-block charts/seaweed-block \ -f values.day1.yaml ``` +The raw chart defaults are render/development defaults only. Do not treat a +plain `helm install sw-block charts/seaweed-block` as a release-gated install: +it does not run preflight, does not discover the live Kubernetes node set, and +can leave placement/launcher evidence incomplete on real labs. + Example `values.day1.yaml`: ```yaml @@ -45,6 +46,7 @@ network: rejectLoopbackPublishTargets: true compat: + launcherDurableImplFlag: false launcherReplicationAckFlag: false launcherRejectLoopbackFlag: false @@ -74,8 +76,11 @@ blockNodes: `network.rejectLoopbackPublishTargets` records the intended safety boundary. Some blockmaster launcher flags are gated by `compat.*` settings because older published alpha images do not accept every v0.3 flag. Keep -`compat.launcherReplicationAckFlag` and `compat.launcherRejectLoopbackFlag` -false unless the selected image is known to support the corresponding flag. +`compat.launcherDurableImplFlag`, `compat.launcherReplicationAckFlag`, and +`compat.launcherRejectLoopbackFlag` false unless the selected image is known to +support the corresponding flag. The default durable implementation is still +`walstore` because that is the blockmaster binary default when the +`--launcher-durable-impl` flag is omitted. ## RF=3 Sync-Quorum Profile diff --git a/seaweed-block/charts/seaweed-block/crds/swblockclusters.block.seaweedfs.com.yaml b/seaweed-block/charts/seaweed-block/crds/swblockclusters.block.seaweedfs.com.yaml new file mode 100644 index 0000000000..21c7357bb6 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/crds/swblockclusters.block.seaweedfs.com.yaml @@ -0,0 +1,310 @@ +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: swblockclusters.block.seaweedfs.com +spec: + group: block.seaweedfs.com + scope: Namespaced + names: + plural: swblockclusters + singular: swblockcluster + kind: SwBlockCluster + shortNames: + - swbc + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Ready + type: integer + jsonPath: .status.readyVolumeCount + - name: Blocked + type: integer + jsonPath: .status.blockedVolumeCount + - name: Stale + type: integer + jsonPath: .status.staleVolumeCount + - name: Age + type: date + jsonPath: .metadata.creationTimestamp + schema: + openAPIV3Schema: + type: object + description: Read-only Seaweed Block cluster status projection. + properties: + spec: + type: object + description: Declarative install metadata. Phase 35 does not reconcile spec into storage mutation. + properties: + image: + type: string + csiImage: + type: string + storageClass: + type: string + ackProfile: + type: string + protocol: + type: string + blockNodes: + type: array + items: + type: object + properties: + name: + type: string + internalIP: + type: string + status: + type: object + properties: + observedAt: + type: string + format: date-time + observedGeneration: + type: integer + format: int64 + nodeCount: + type: integer + minimum: 0 + nodes: + type: array + items: + type: object + required: + - name + - schedulable + - ready + properties: + name: + type: string + kubernetesNode: + type: string + internalIP: + type: string + schedulable: + type: boolean + ready: + type: boolean + status: + type: string + reasonCode: + type: string + lastHeartbeatAt: + type: string + format: date-time + replicaCount: + type: integer + minimum: 0 + requiredImages: + type: array + items: + type: string + missingImages: + type: array + items: + type: string + conditions: + type: array + items: + x-kubernetes-preserve-unknown-fields: true + type: object + required: + - type + - status + properties: + type: + type: string + enum: + - Ready + - Recovered + - Recovering + - Blocked + - Invalid + - CleanupRequired + - EvidenceStale + status: + type: string + enum: + - "True" + - "False" + - Unknown + reason: + type: string + severity: + type: string + enum: + - info + - warning + - error + message: + type: string + lastTransitionTime: + type: string + format: date-time + evidenceRefs: + type: array + items: + type: string + evidenceRefs: + type: array + items: + type: string + volumeCount: + type: integer + minimum: 0 + readyVolumeCount: + type: integer + minimum: 0 + blockedVolumeCount: + type: integer + minimum: 0 + staleVolumeCount: + type: integer + minimum: 0 + conditions: + type: array + items: + x-kubernetes-preserve-unknown-fields: true + type: object + required: + - type + - status + properties: + type: + type: string + enum: + - Ready + - Recovered + - Recovering + - Blocked + - Invalid + - CleanupRequired + - EvidenceStale + status: + type: string + enum: + - "True" + - "False" + - Unknown + reason: + type: string + severity: + type: string + enum: + - info + - warning + - error + message: + type: string + lastTransitionTime: + type: string + format: date-time + evidenceRefs: + type: array + items: + type: string + evidenceRefs: + type: array + items: + type: string + supportBundleRefs: + type: array + items: + type: string + cleanup: + type: object + properties: + status: + type: string + k8sResidueCount: + type: integer + minimum: 0 + iscsiResidueCount: + type: integer + minimum: 0 + multipathResidueCount: + type: integer + minimum: 0 + processResidueCount: + type: integer + minimum: 0 + hostPathResidueCount: + type: integer + minimum: 0 + failureCount: + type: integer + minimum: 0 + failedPhase: + type: string + reasonCodes: + type: array + items: + type: string + evidenceRef: + type: string + installDrift: + type: object + properties: + status: + type: string + enum: + - ok + - mismatch + - unknown + reasonCode: + type: string + chartName: + type: string + currentChartVersion: + type: string + desiredChartVersion: + type: string + currentAppVersion: + type: string + desiredAppVersion: + type: string + currentImage: + type: string + desiredImage: + type: string + currentCsiImage: + type: string + desiredCsiImage: + type: string + currentOperatorImage: + type: string + desiredOperatorImage: + type: string + evidenceRef: + type: string + safeNextSteps: + type: array + items: + type: object + required: + - type + - mode + - mutationAllowed + properties: + type: + type: string + mode: + type: string + enum: + - read_only + - dry_run + - scripted + command: + type: string + reasonCode: + type: string + mutationAllowed: + type: boolean + evidenceRefs: + type: array + items: + type: string diff --git a/seaweed-block/charts/seaweed-block/crds/swblockvolumes.block.seaweedfs.com.yaml b/seaweed-block/charts/seaweed-block/crds/swblockvolumes.block.seaweedfs.com.yaml new file mode 100644 index 0000000000..a4d3bbab9b --- /dev/null +++ b/seaweed-block/charts/seaweed-block/crds/swblockvolumes.block.seaweedfs.com.yaml @@ -0,0 +1,200 @@ +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: swblockvolumes.block.seaweedfs.com +spec: + group: block.seaweedfs.com + scope: Namespaced + names: + plural: swblockvolumes + singular: swblockvolume + kind: SwBlockVolume + shortNames: + - swbv + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Status + type: string + jsonPath: .status.status + - name: Reason + type: string + jsonPath: .status.reasonCode + - name: PVC + type: string + jsonPath: .status.pvcName + - name: Age + type: date + jsonPath: .metadata.creationTimestamp + schema: + openAPIV3Schema: + type: object + description: Read-only Seaweed Block volume status projection. + properties: + spec: + type: object + description: PVC binding metadata. Phase 35 does not reconcile spec into storage mutation. + properties: + pvcName: + type: string + storageClass: + type: string + status: + type: object + properties: + volumeID: + type: string + pvcName: + type: string + status: + type: string + enum: + - ready + - recovered + - recovering + - degraded + - blocked + - invalid + - unsafe + - unknown + reasonCode: + type: string + observedAt: + type: string + format: date-time + conditions: + type: array + items: + x-kubernetes-preserve-unknown-fields: true + type: object + required: + - type + - status + properties: + type: + type: string + enum: + - Ready + - Recovered + - Recovering + - Blocked + - Invalid + - CleanupRequired + - EvidenceStale + status: + type: string + enum: + - "True" + - "False" + - Unknown + reason: + type: string + severity: + type: string + enum: + - info + - warning + - error + message: + type: string + lastTransitionTime: + type: string + format: date-time + evidenceRefs: + type: array + items: + type: string + deleteSafety: + type: object + properties: + actionType: + type: string + decision: + type: string + enum: + - allowed + - rejected + - unknown + state: + type: string + enum: + - not_requested + - requested + - blocked + - releasable + - released + reason: + type: string + finalizerReleaseAllowed: + type: boolean + missingFacts: + type: array + items: + type: string + evidenceRefs: + type: array + items: + type: string + safeNextAction: + type: string + nonClaims: + type: array + items: + type: string + evidenceRefs: + type: array + items: + type: string + allowedActions: + type: array + items: + type: object + required: + - type + - mode + - mutationAllowed + properties: + type: + type: string + mode: + type: string + enum: + - read_only + - dry_run + - scripted + sideEffectClass: + type: string + ownerExecutor: + type: string + decision: + type: string + enum: + - allowed + - rejected + - unknown + decisionReason: + type: string + missingFacts: + type: array + items: + type: string + mutationAllowed: + type: boolean + preconditions: + type: array + items: + type: string + invariantRefs: + type: array + items: + type: string + evidenceRequired: + type: string + evidenceRefs: + type: array + items: + type: string diff --git a/seaweed-block/charts/seaweed-block/templates/blockmaster.yaml b/seaweed-block/charts/seaweed-block/templates/blockmaster.yaml index d4af748213..8842b5d5ec 100644 --- a/seaweed-block/charts/seaweed-block/templates/blockmaster.yaml +++ b/seaweed-block/charts/seaweed-block/templates/blockmaster.yaml @@ -4,6 +4,9 @@ {{- if and .Values.network.externalStatus (not .Values.network.externalISCSI) -}} {{- fail "network.externalStatus=true requires network.externalISCSI=true because external status is only supported with external block frontend publishing" -}} {{- end -}} +{{- if and (ne .Values.blockmaster.durableImpl "walstore") (not .Values.compat.launcherDurableImplFlag) -}} +{{- fail "blockmaster.durableImpl requires compat.launcherDurableImplFlag=true because older published images do not accept --launcher-durable-impl" -}} +{{- end -}} apiVersion: apps/v1 kind: Deployment metadata: @@ -26,6 +29,10 @@ spec: hostNetwork: true dnsPolicy: ClusterFirstWithHostNet serviceAccountName: {{ include "seaweed-block.fullname" . }}-master + {{- with .Values.blockmaster.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} {{- if .Values.blockmaster.stateHostPath }} initContainers: - name: state-permissions @@ -56,6 +63,9 @@ spec: - "--launcher-image={{ include "seaweed-block.image" . }}" - "--launcher-namespace={{ .Release.Namespace }}" - "--launcher-durable-root={{ .Values.blockmaster.durableRoot }}" + {{- if .Values.compat.launcherDurableImplFlag }} + - "--launcher-durable-impl={{ .Values.blockmaster.durableImpl }}" + {{- end }} {{- if .Values.blockmaster.launcherStatus }} - "--launcher-status" {{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/csi-controller.yaml b/seaweed-block/charts/seaweed-block/templates/csi-controller.yaml index 9342938401..5aa0ae0104 100644 --- a/seaweed-block/charts/seaweed-block/templates/csi-controller.yaml +++ b/seaweed-block/charts/seaweed-block/templates/csi-controller.yaml @@ -29,6 +29,9 @@ spec: {{- if .Values.blockmaster.launcherPVCOwnerRef }} - "--kubernetes-pvc-uid-lookup" {{- end }} + {{- if or .Values.operatorStatus.create .Values.lifecycleOwner.create }} + - "--swblockvolume-cr-namespace={{ .Release.Namespace }}" + {{- end }} {{- if .Values.stage2Multipath.enabled }} - "--stage2-multipath" {{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/lifecycle-owner-admission.yaml b/seaweed-block/charts/seaweed-block/templates/lifecycle-owner-admission.yaml new file mode 100644 index 0000000000..822b485d98 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/lifecycle-owner-admission.yaml @@ -0,0 +1,47 @@ +{{- if and .Values.lifecycleOwner.create .Values.lifecycleOwner.admission.create }} +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: + name: {{ include "seaweed-block.fullname" . }}-lifecycle-owner-finalizer-boundary + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +spec: + failurePolicy: Fail + matchConstraints: + resourceRules: + - apiGroups: ["block.seaweedfs.com"] + apiVersions: ["v1alpha1"] + operations: ["UPDATE"] + resources: ["swblockvolumes"] + validations: + - expression: >- + request.userInfo.username != "system:serviceaccount:{{ .Release.Namespace }}:{{ include "seaweed-block.fullname" . }}-lifecycle-owner" || + ( + (has(object.spec) == has(oldObject.spec)) && + (!has(object.spec) || object.spec == oldObject.spec) && + (has(object.status) == has(oldObject.status)) && + (!has(object.status) || object.status == oldObject.status) && + (has(object.metadata.labels) == has(oldObject.metadata.labels)) && + (!has(object.metadata.labels) || object.metadata.labels == oldObject.metadata.labels) && + (has(object.metadata.annotations) == has(oldObject.metadata.annotations)) && + (!has(object.metadata.annotations) || object.metadata.annotations == oldObject.metadata.annotations) && + (has(object.metadata.ownerReferences) == has(oldObject.metadata.ownerReferences)) && + (!has(object.metadata.ownerReferences) || object.metadata.ownerReferences == oldObject.metadata.ownerReferences) && + (has(object.metadata.deletionTimestamp) == has(oldObject.metadata.deletionTimestamp)) && + (!has(object.metadata.deletionTimestamp) || object.metadata.deletionTimestamp == oldObject.metadata.deletionTimestamp) && + ((has(object.metadata.finalizers) ? object.metadata.finalizers : []).filter(f, f != "{{ .Values.lifecycleOwner.finalizerName | default "block.seaweedfs.com/swblockvolume-protection" }}") == + (has(oldObject.metadata.finalizers) ? oldObject.metadata.finalizers : []).filter(f, f != "{{ .Values.lifecycleOwner.finalizerName | default "block.seaweedfs.com/swblockvolume-protection" }}")) && + ((has(object.metadata.finalizers) ? object.metadata.finalizers : []).filter(f, f == "{{ .Values.lifecycleOwner.finalizerName | default "block.seaweedfs.com/swblockvolume-protection" }}").size() <= 1) + ) + message: lifecycle-owner may only add or remove the Seaweed Block protection finalizer +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: + name: {{ include "seaweed-block.fullname" . }}-lifecycle-owner-finalizer-boundary + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +spec: + policyName: {{ include "seaweed-block.fullname" . }}-lifecycle-owner-finalizer-boundary + validationActions: ["Deny"] +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/lifecycle-owner-rbac.yaml b/seaweed-block/charts/seaweed-block/templates/lifecycle-owner-rbac.yaml new file mode 100644 index 0000000000..d8939534ea --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/lifecycle-owner-rbac.yaml @@ -0,0 +1,38 @@ +{{- if and .Values.lifecycleOwner.create .Values.lifecycleOwner.rbac.create }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "seaweed-block.fullname" . }}-lifecycle-owner + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: {{ include "seaweed-block.fullname" . }}-lifecycle-owner + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +rules: + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockvolumes"] + verbs: ["get", "list", "watch", "patch"] + - apiGroups: [""] + resources: ["events"] + verbs: ["create"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ include "seaweed-block.fullname" . }}-lifecycle-owner + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +subjects: + - kind: ServiceAccount + name: {{ include "seaweed-block.fullname" . }}-lifecycle-owner + namespace: {{ .Release.Namespace }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ include "seaweed-block.fullname" . }}-lifecycle-owner +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/lifecycle-owner.yaml b/seaweed-block/charts/seaweed-block/templates/lifecycle-owner.yaml new file mode 100644 index 0000000000..13b8ddf75b --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/lifecycle-owner.yaml @@ -0,0 +1,39 @@ +{{- if .Values.lifecycleOwner.create }} +apiVersion: apps/v1 +kind: Deployment +metadata: + name: sw-block-lifecycle-owner + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} + app: sw-block-lifecycle-owner +spec: + replicas: 1 + selector: + matchLabels: + app: sw-block-lifecycle-owner + template: + metadata: + labels: + app: sw-block-lifecycle-owner + {{- include "seaweed-block.labels" . | nindent 8 }} + spec: + serviceAccountName: {{ include "seaweed-block.fullname" . }}-lifecycle-owner + {{- with .Values.lifecycleOwner.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + containers: + - name: lifecycle-owner + image: {{ include "seaweed-block.image" . | quote }} + imagePullPolicy: {{ .Values.image.pullPolicy }} + command: ["/usr/local/bin/sw-block"] + args: + - "ops" + - "lifecycle-owner" + {{- if .Values.lifecycleOwner.dryRun }} + - "--dry-run" + {{- end }} + - "--namespace={{ .Release.Namespace }}" + - "--interval={{ .Values.lifecycleOwner.interval }}" +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/operator-status-rbac.yaml b/seaweed-block/charts/seaweed-block/templates/operator-status-rbac.yaml new file mode 100644 index 0000000000..e8f8568c0c --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/operator-status-rbac.yaml @@ -0,0 +1,47 @@ +{{- if and .Values.operatorStatus.create .Values.operatorStatus.rbac.create }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "seaweed-block.fullname" . }}-operator-status + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: {{ include "seaweed-block.fullname" . }}-operator-status + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +rules: + - apiGroups: [""] + resources: ["nodes", "pods"] + verbs: ["get", "list", "watch"] + - apiGroups: ["storage.k8s.io"] + resources: ["csidrivers", "csinodes"] + verbs: ["get", "list", "watch"] + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockclusters", "swblockvolumes"] + verbs: ["get", "list", "watch"] + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockclusters/status", "swblockvolumes/status"] + verbs: ["get", "update", "patch"] + - apiGroups: [""] + resources: ["events"] + verbs: ["create"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ include "seaweed-block.fullname" . }}-operator-status + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +subjects: + - kind: ServiceAccount + name: {{ include "seaweed-block.fullname" . }}-operator-status + namespace: {{ .Release.Namespace }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ include "seaweed-block.fullname" . }}-operator-status +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/operator-status.yaml b/seaweed-block/charts/seaweed-block/templates/operator-status.yaml new file mode 100644 index 0000000000..7d44ce7253 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/operator-status.yaml @@ -0,0 +1,41 @@ +{{- if .Values.operatorStatus.create }} +apiVersion: apps/v1 +kind: Deployment +metadata: + name: sw-block-operator-status + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} + app: sw-block-operator-status +spec: + replicas: 1 + selector: + matchLabels: + app: sw-block-operator-status + template: + metadata: + labels: + app: sw-block-operator-status + {{- include "seaweed-block.labels" . | nindent 8 }} + spec: + serviceAccountName: {{ include "seaweed-block.fullname" . }}-operator-status + {{- with .Values.operatorStatus.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + containers: + - name: operator-status + image: {{ include "seaweed-block.image" . | quote }} + imagePullPolicy: {{ .Values.image.pullPolicy }} + command: ["/usr/local/bin/sw-block"] + args: + - "ops" + - "operator-status" + {{- if .Values.operatorStatus.dryRun }} + - "--dry-run" + {{- end }} + - "--master-api={{ include "seaweed-block.blockmasterAddress" . }}" + - "--namespace={{ .Release.Namespace }}" + - "--cluster-name={{ .Values.operatorStatus.clusterName }}" + - "--interval={{ .Values.operatorStatus.interval }}" +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/rbac.yaml b/seaweed-block/charts/seaweed-block/templates/rbac.yaml index 84e8d8d6d4..6e0a6cceb4 100644 --- a/seaweed-block/charts/seaweed-block/templates/rbac.yaml +++ b/seaweed-block/charts/seaweed-block/templates/rbac.yaml @@ -60,6 +60,11 @@ rules: - apiGroups: ["coordination.k8s.io"] resources: ["leases"] verbs: ["get", "list", "watch", "create", "update", "patch"] + {{- if or .Values.operatorStatus.create .Values.lifecycleOwner.create }} + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockvolumes"] + verbs: ["get", "list", "watch", "create", "update", "patch"] + {{- end }} --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding diff --git a/seaweed-block/charts/seaweed-block/values.schema.json b/seaweed-block/charts/seaweed-block/values.schema.json index 7f3d20d22b..364fe3fba3 100644 --- a/seaweed-block/charts/seaweed-block/values.schema.json +++ b/seaweed-block/charts/seaweed-block/values.schema.json @@ -30,6 +30,11 @@ "blockmaster": { "type": "object", "properties": { + "nodeSelector": { + "type": "object", + "additionalProperties": { "type": "string" } + }, + "durableImpl": { "type": "string", "enum": ["walstore", "smartwal"] }, "stateHostPath": { "type": "string" }, "stateHostPathType": { "type": "string" }, "statePermissionsImage": { @@ -61,6 +66,7 @@ "compat": { "type": "object", "properties": { + "launcherDurableImplFlag": { "type": "boolean" }, "launcherReplicationAckFlag": { "type": "boolean" }, "launcherRejectLoopbackFlag": { "type": "boolean" } } @@ -80,6 +86,25 @@ "poolID": { "type": "string" } } } + }, + "operatorStatus": { + "type": "object", + "properties": { + "create": { "type": "boolean" }, + "dryRun": { "type": "boolean" }, + "interval": { "type": "string" }, + "clusterName": { "type": "string" }, + "rbac": { + "type": "object", + "properties": { + "create": { "type": "boolean" } + } + }, + "nodeSelector": { + "type": "object", + "additionalProperties": { "type": "string" } + } + } } } } diff --git a/seaweed-block/charts/seaweed-block/values.yaml b/seaweed-block/charts/seaweed-block/values.yaml index 7e27232b28..d91a179dde 100644 --- a/seaweed-block/charts/seaweed-block/values.yaml +++ b/seaweed-block/charts/seaweed-block/values.yaml @@ -28,6 +28,7 @@ appNamespace: default blockmaster: replicas: 1 + nodeSelector: {} serviceName: blockmaster listenPort: 9333 authorityStore: /var/lib/sw-block/authority @@ -39,6 +40,7 @@ blockmaster: launcherNamespace: kube-system launcherStatus: true launcherPVCOwnerRef: true + durableImpl: walstore stateHostPath: "" stateHostPathType: DirectoryOrCreate statePermissionsImage: @@ -76,6 +78,7 @@ network: compat: # Some published alpha images predate these blockmaster launcher flags. Keep # these false unless the selected image is known to support the flag. + launcherDurableImplFlag: false launcherReplicationAckFlag: false launcherRejectLoopbackFlag: false @@ -111,6 +114,34 @@ blockNodes: rbac: create: true +operatorStatus: + # Phase 35 read-only operator foundation. When enabled, this installs the + # status service account/RBAC plus a status projection Deployment. dryRun + # logs the projection only. dryRun=false patches existing SwBlockCluster / + # SwBlockVolume .status subresources and does not create CR objects. + create: false + dryRun: true + interval: 30s + clusterName: sw-block + rbac: + create: true + nodeSelector: {} + +lifecycleOwner: + # Phase 43 bounded lifecycle owner. Disabled by default. When enabled with + # dryRun=false it may patch only SwBlockVolume metadata.finalizers, and the + # admission policy confines the patch to the Seaweed Block protection + # finalizer. + create: false + dryRun: true + interval: 30s + finalizerName: block.seaweedfs.com/swblockvolume-protection + rbac: + create: true + admission: + create: true + nodeSelector: {} + csiController: replicas: 1 diff --git a/seaweed-block/cmd/blockcsi/g15b_manifest_test.go b/seaweed-block/cmd/blockcsi/g15b_manifest_test.go index 2b1dba6f5a..c48cd42904 100644 --- a/seaweed-block/cmd/blockcsi/g15b_manifest_test.go +++ b/seaweed-block/cmd/blockcsi/g15b_manifest_test.go @@ -207,7 +207,14 @@ func TestG15b_Manifest_NoAuthorityShapedFields(t *testing.T) { func TestG15b_ImageBuildInputs_ContainExpectedBinariesAndNodeTools(t *testing.T) { swBlock := g15bReadDeployFile(t, "Dockerfile.sw-block") - for _, want := range []string{"./cmd/blockmaster", "./cmd/blockvolume", "/usr/local/bin/blockmaster", "/usr/local/bin/blockvolume"} { + for _, want := range []string{ + "./cmd/blockmaster", + "./cmd/blockvolume", + "./cmd/sw-block", + "/usr/local/bin/blockmaster", + "/usr/local/bin/blockvolume", + "/usr/local/bin/sw-block", + } { if !strings.Contains(swBlock, want) { t.Fatalf("Dockerfile.sw-block missing %q", want) } diff --git a/seaweed-block/cmd/blockcsi/g15d_manifest_test.go b/seaweed-block/cmd/blockcsi/g15d_manifest_test.go index d68cff3583..65a83ff3ab 100644 --- a/seaweed-block/cmd/blockcsi/g15d_manifest_test.go +++ b/seaweed-block/cmd/blockcsi/g15d_manifest_test.go @@ -46,6 +46,31 @@ func TestAlphaK8sCSIController_IncludesCreateMetadata(t *testing.T) { } } +func TestPhase44HelmCSIController_RegistersSwBlockVolumeWhenOperatorSurfacesEnabled(t *testing.T) { + controller := g15dReadFile(t, "charts", "seaweed-block", "templates", "csi-controller.yaml") + for _, want := range []string{ + "or .Values.operatorStatus.create .Values.lifecycleOwner.create", + `"--swblockvolume-cr-namespace={{ .Release.Namespace }}"`, + } { + if !strings.Contains(controller, want) { + t.Fatalf("csi-controller template missing %q:\n%s", want, controller) + } + } + rbac := g15dReadFile(t, "charts", "seaweed-block", "templates", "rbac.yaml") + for _, want := range []string{ + `apiGroups: ["block.seaweedfs.com"]`, + `resources: ["swblockvolumes"]`, + `verbs: ["get", "list", "watch", "create", "update", "patch"]`, + } { + if !strings.Contains(rbac, want) { + t.Fatalf("csi RBAC template missing %q:\n%s", want, rbac) + } + } + if strings.Contains(rbac, `resources: ["swblockvolumes/status"]`) || strings.Contains(rbac, `resources: ["swblockvolumes/finalizers"]`) { + t.Fatalf("CSI controller must not receive SwBlockVolume status/finalizer ownership:\n%s", rbac) + } +} + func TestG15d_K8sDynamicPVC_UsesStorageClassNoPrecreatedPV(t *testing.T) { body := g15dReadFile(t, "deploy", "k8s", "g15d", "dynamic-pvc-pod.yaml") for _, want := range []string{ diff --git a/seaweed-block/cmd/blockcsi/main.go b/seaweed-block/cmd/blockcsi/main.go index 31c3a9030e..eeabda79fe 100644 --- a/seaweed-block/cmd/blockcsi/main.go +++ b/seaweed-block/cmd/blockcsi/main.go @@ -30,6 +30,7 @@ type flags struct { nodeID string iqnPrefix string pvcUIDLookup bool + swBlockVolumeCRNamespace string stage2Multipath bool rejectLoopbackPublishTargets bool version bool @@ -44,6 +45,7 @@ func parseFlags(args []string) (flags, error) { fs.StringVar(&f.nodeID, "node-id", "", "CSI node ID; defaults to hostname") fs.StringVar(&f.iqnPrefix, "iqn-prefix", "iqn.2026-05.io.seaweedfs", "fallback IQN prefix for unstage after plugin restart") fs.BoolVar(&f.pvcUIDLookup, "kubernetes-pvc-uid-lookup", false, "opt-in: resolve PVC UID through the in-cluster Kubernetes API before CreateVolume is sent to blockmaster") + fs.StringVar(&f.swBlockVolumeCRNamespace, "swblockvolume-cr-namespace", "", "opt-in: create or update SwBlockVolume CR identity objects in this namespace after successful CreateVolume") fs.BoolVar(&f.stage2Multipath, "stage2-multipath", false, "opt-in: consume multiple iSCSI frontend targets as one host multipath device") fs.BoolVar(&f.rejectLoopbackPublishTargets, "reject-loopback-publish-targets", false, "opt-in: reject loopback publish targets for node-loss recovery gates") fs.BoolVar(&f.version, "version", false, "print build provenance and exit") @@ -58,8 +60,8 @@ func parseFlags(args []string) (flags, error) { if f.endpoint == "" { return flags{}, fmt.Errorf("--endpoint is required") } - if f.masterAddr == "" && (f.stage2Multipath || f.rejectLoopbackPublishTargets || f.pvcUIDLookup) { - return flags{}, fmt.Errorf("--stage2-multipath, --reject-loopback-publish-targets, and --kubernetes-pvc-uid-lookup require --master") + if f.masterAddr == "" && (f.stage2Multipath || f.rejectLoopbackPublishTargets || f.pvcUIDLookup || f.swBlockVolumeCRNamespace != "") { + return flags{}, fmt.Errorf("--stage2-multipath, --reject-loopback-publish-targets, --kubernetes-pvc-uid-lookup, and --swblockvolume-cr-namespace require --master") } if f.nodeID == "" { host, err := os.Hostname() @@ -118,6 +120,7 @@ func run(f flags) int { reporter blockcsi.EventReporter provisioner blockcsi.VolumeProvisioner resolver blockcsi.KubernetesMetadataResolver + registrar blockcsi.VolumeObjectRegistrar ) if f.masterAddr != "" { masterConn, err = grpc.NewClient(f.masterAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) @@ -145,10 +148,17 @@ func run(f flags) int { return 1 } } + if f.swBlockVolumeCRNamespace != "" && provisioner != nil { + registrar, err = blockcsi.NewInClusterSwBlockVolumeRegistrar(f.swBlockVolumeCRNamespace) + if err != nil { + fmt.Fprintln(os.Stderr, "blockcsi: swblockvolume registrar:", err) + return 1 + } + } srv := grpc.NewServer() csipb.RegisterIdentityServer(srv, blockcsi.NewIdentityServer()) - csipb.RegisterControllerServer(srv, blockcsi.NewControllerServerWithProvisionerAndMetadataResolver(lookup, provisioner, resolver)) + csipb.RegisterControllerServer(srv, blockcsi.NewControllerServerWithProvisionerMetadataAndRegistrar(lookup, provisioner, resolver, registrar)) csipb.RegisterNodeServer(srv, blockcsi.NewDefaultNodeServerWithLookupAndEventReporter(f.nodeID, f.iqnPrefix, lookup, reporter)) if f.printReadyLine { diff --git a/seaweed-block/cmd/blockcsi/main_test.go b/seaweed-block/cmd/blockcsi/main_test.go index b47e7459eb..9f7fb4c15c 100644 --- a/seaweed-block/cmd/blockcsi/main_test.go +++ b/seaweed-block/cmd/blockcsi/main_test.go @@ -113,6 +113,19 @@ func TestParseFlags_RejectLoopbackPublishTargetsIsExplicitOptIn(t *testing.T) { } } +func TestParseFlags_SwBlockVolumeCRNamespaceRequiresMaster(t *testing.T) { + f, err := parseFlags([]string{"--endpoint", "unix:///tmp/csi.sock", "--node-id", "node-a", "--master", "blockmaster:9333", "--swblockvolume-cr-namespace", "kube-system"}) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if f.swBlockVolumeCRNamespace != "kube-system" { + t.Fatalf("swblockvolume namespace=%q", f.swBlockVolumeCRNamespace) + } + if _, err := parseFlags([]string{"--endpoint", "unix:///tmp/csi.sock", "--node-id", "node-a", "--swblockvolume-cr-namespace", "kube-system"}); err == nil { + t.Fatal("expected --swblockvolume-cr-namespace without --master to fail") + } +} + func TestParseFlags_MasterDependentFlagsRequireMaster(t *testing.T) { if _, err := parseFlags([]string{"--endpoint", "unix:///tmp/csi.sock", "--node-id", "node-a", "--stage2-multipath"}); err == nil { t.Fatal("expected --stage2-multipath without --master to fail") diff --git a/seaweed-block/cmd/blockmaster/main.go b/seaweed-block/cmd/blockmaster/main.go index efa7043010..55ab0aef85 100644 --- a/seaweed-block/cmd/blockmaster/main.go +++ b/seaweed-block/cmd/blockmaster/main.go @@ -36,6 +36,7 @@ type flags struct { launcherImage string launcherMasterAddr string launcherDurableRoot string + launcherDurableImpl string launcherStateHostPath string launcherReplicationAck string launcherISCSIPortBase int @@ -75,6 +76,7 @@ func parseFlags(args []string) (flags, error) { fs.StringVar(&f.launcherImage, "launcher-image", "sw-block:local", "G15d rendered blockvolume container image") fs.StringVar(&f.launcherMasterAddr, "launcher-master-addr", "", "G15d master address used in rendered blockvolume args; defaults to listener address after bind") fs.StringVar(&f.launcherDurableRoot, "launcher-durable-root", "/var/lib/sw-block", "G15d rendered blockvolume durable root base") + fs.StringVar(&f.launcherDurableImpl, "launcher-durable-impl", "walstore", "G15d rendered blockvolume durable implementation: walstore (default) or smartwal") fs.StringVar(&f.launcherStateHostPath, "launcher-state-hostpath", "", "optional hostPath base mounted at the blockvolume durable root; empty keeps generated blockvolume state on throwaway emptyDir") fs.StringVar(&f.launcherReplicationAck, "launcher-replication-ack", "best-effort", "G15d rendered blockvolume replication ACK profile: best-effort, sync-quorum, or sync-all") fs.IntVar(&f.launcherISCSIPortBase, "launcher-iscsi-port-base", 3260, "G15d iSCSI port base for generated blockvolume workloads") @@ -328,6 +330,7 @@ func runLifecycleLauncherTick(h *master.Host, f flags) error { Image: f.launcherImage, MasterAddr: masterAddr, DurableRootBase: f.launcherDurableRoot, + DurableImpl: f.launcherDurableImpl, StateHostPathBase: f.launcherStateHostPath, ReplicationAck: f.launcherReplicationAck, OwnerReferenceToPVC: f.launcherPVCOwnerRef, diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 315dfa2817..442173de02 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -412,6 +412,9 @@ func run(f flags) int { fmt.Fprintln(os.Stderr, "blockvolume:", err) return 1 } + if f.durableRoot != "" { + h.BlockLocalReadiness("awaiting durable recovery") + } h.Start() var status *volume.StatusServer @@ -495,8 +498,11 @@ func run(f flags) int { recCancel() if recErr != nil { fmt.Fprintln(os.Stderr, "blockvolume: durable recovery failed:", report.Evidence) + h.BlockLocalReadiness(report.Evidence) + return waitFaultedDurableRecovery(h, status, durableProv, report.Evidence) } else { fmt.Fprintln(os.Stderr, "blockvolume: durable recovered:", report.Evidence) + h.ClearLocalReadinessBlock() } } else { // memback fallback — wraps the volume's AdapterProjectionView @@ -925,6 +931,28 @@ func run(f flags) int { return 0 } +func waitFaultedDurableRecovery(h *volume.Host, status *volume.StatusServer, durableProv *durable.DurableProvider, evidence string) int { + fmt.Fprintln(os.Stderr, "blockvolume: durable recovery faulted; status endpoint remains available and local readiness remains blocked:", evidence) + sig := make(chan os.Signal, 1) + signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) + <-sig + signal.Stop(sig) + + if durableProv != nil { + _ = durableProv.Close() + } + if status != nil { + shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = status.Close(shutCtx) + shutCancel() + } + if err := h.Close(); err != nil { + fmt.Fprintln(os.Stderr, "blockvolume: close:", err) + return 1 + } + return 0 +} + // deriveDualLaneAddr maps "host:port" → "host:port+1". Per // docs/recovery-wiring-plan.md §4 Option A: dual-lane traffic uses a // separate port from the legacy data port via this fixed convention. diff --git a/seaweed-block/cmd/sw-block-testutil/main.go b/seaweed-block/cmd/sw-block-testutil/main.go new file mode 100644 index 0000000000..171b1f36fd --- /dev/null +++ b/seaweed-block/cmd/sw-block-testutil/main.go @@ -0,0 +1,129 @@ +package main + +import ( + "encoding/hex" + "flag" + "fmt" + "io" + "os" + "path/filepath" + + "github.com/seaweedfs/seaweed-block/core/storage/smartwal" +) + +func main() { + os.Exit(run(os.Args[1:], os.Stdout, os.Stderr)) +} + +func run(args []string, stdout, stderr io.Writer) int { + if len(args) == 0 { + usage(stderr) + return 2 + } + switch args[0] { + case "smartwal-corrupt-latest-record": + return runSmartWALCorruptLatest(args[1:], stdout, stderr) + default: + fmt.Fprintf(stderr, "sw-block-testutil: unknown command %q\n", args[0]) + usage(stderr) + return 2 + } +} + +func usage(w io.Writer) { + fmt.Fprintln(w, "usage: sw-block-testutil smartwal-corrupt-latest-record --path --out ") +} + +func runSmartWALCorruptLatest(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("smartwal-corrupt-latest-record", flag.ContinueOnError) + fs.SetOutput(stderr) + var path, outDir string + fs.StringVar(&path, "path", "", "SmartWAL store file to mutate") + fs.StringVar(&outDir, "out", "", "directory for smartwal-corruption-evidence.txt") + if err := fs.Parse(args); err != nil { + return 2 + } + if path == "" || outDir == "" { + fmt.Fprintln(stderr, "smartwal-corrupt-latest-record: --path and --out are required") + return 2 + } + + layout, rec, err := smartwal.LatestRecord(path) + if err != nil { + fmt.Fprintf(stderr, "smartwal-corrupt-latest-record: %v\n", err) + return 1 + } + mutateOffset := rec.Offset + layout.RecordSize - 1 + if !layout.ContainsWALOffset(mutateOffset) || layout.ContainsExtentOffset(mutateOffset) { + fmt.Fprintf(stderr, "smartwal-corrupt-latest-record: mutate offset %d is not safely inside WAL\n", mutateOffset) + return 1 + } + + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + fmt.Fprintf(stderr, "smartwal-corrupt-latest-record: open %s: %v\n", path, err) + return 1 + } + defer f.Close() + + before := make([]byte, layout.RecordSize) + if _, err := f.ReadAt(before, rec.Offset); err != nil { + fmt.Fprintf(stderr, "smartwal-corrupt-latest-record: read before: %v\n", err) + return 1 + } + after := make([]byte, len(before)) + copy(after, before) + after[len(after)-1] ^= 0xff + if _, err := f.WriteAt(after[len(after)-1:], mutateOffset); err != nil { + fmt.Fprintf(stderr, "smartwal-corrupt-latest-record: write corruption: %v\n", err) + return 1 + } + if err := f.Sync(); err != nil { + fmt.Fprintf(stderr, "smartwal-corrupt-latest-record: fsync: %v\n", err) + return 1 + } + + if err := os.MkdirAll(outDir, 0o755); err != nil { + fmt.Fprintf(stderr, "smartwal-corrupt-latest-record: mkdir %s: %v\n", outDir, err) + return 1 + } + evidencePath := filepath.Join(outDir, "smartwal-corruption-evidence.txt") + evidence := fmt.Sprintf(`smartwal_corruption_status=ok +smartwal_path=%s +wal_offset=%d +wal_length=%d +wal_end=%d +extent_start=%d +target_lsn=%d +target_lba=%d +target_slot=%d +target_record_offset=%d +mutated_offset=%d +target_offset_inside_wal=%t +target_offset_inside_extent=%t +before_bytes=%s +after_bytes=%s +mutation=flip_last_record_crc_byte +`, + path, + layout.WALOffset, + layout.WALLength, + layout.WALEnd, + layout.ExtentStart, + rec.LSN, + rec.LBA, + rec.Slot, + rec.Offset, + mutateOffset, + layout.ContainsWALOffset(mutateOffset), + layout.ContainsExtentOffset(mutateOffset), + hex.EncodeToString(before), + hex.EncodeToString(after), + ) + if err := os.WriteFile(evidencePath, []byte(evidence), 0o644); err != nil { + fmt.Fprintf(stderr, "smartwal-corrupt-latest-record: write evidence: %v\n", err) + return 1 + } + fmt.Fprint(stdout, evidence) + return 0 +} diff --git a/seaweed-block/cmd/sw-block-testutil/main_test.go b/seaweed-block/cmd/sw-block-testutil/main_test.go new file mode 100644 index 0000000000..7fbda44904 --- /dev/null +++ b/seaweed-block/cmd/sw-block-testutil/main_test.go @@ -0,0 +1,65 @@ +package main + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage/smartwal" +) + +func TestSmartWALCorruptLatestRecordWritesEvidence(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "store.sw") + store, err := smartwal.CreateStoreWithSlots(path, 8, 4096, 8) + if err != nil { + t.Fatalf("CreateStoreWithSlots: %v", err) + } + data := make([]byte, 4096) + data[0] = 0xab + if _, err := store.Write(2, data); err != nil { + t.Fatalf("Write: %v", err) + } + if _, err := store.Sync(); err != nil { + t.Fatalf("Sync: %v", err) + } + if err := store.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + + outDir := filepath.Join(dir, "out") + var stdout, stderr bytes.Buffer + code := run([]string{"smartwal-corrupt-latest-record", "--path", path, "--out", outDir}, &stdout, &stderr) + if code != 0 { + t.Fatalf("run code=%d stderr=%s", code, stderr.String()) + } + evidencePath := filepath.Join(outDir, "smartwal-corruption-evidence.txt") + raw, err := os.ReadFile(evidencePath) + if err != nil { + t.Fatalf("ReadFile evidence: %v", err) + } + evidence := string(raw) + for _, want := range []string{ + "smartwal_corruption_status=ok", + "target_offset_inside_wal=true", + "target_offset_inside_extent=false", + "mutation=flip_last_record_crc_byte", + } { + if !strings.Contains(evidence, want) { + t.Fatalf("evidence missing %q:\n%s", want, evidence) + } + } + if stdout.String() != evidence { + t.Fatalf("stdout should mirror evidence file") + } + + _, records, err := smartwal.InspectRecords(path) + if err != nil { + t.Fatalf("InspectRecords after corruption: %v", err) + } + if len(records) != 0 { + t.Fatalf("corrupted latest record should no longer decode, got %d valid records", len(records)) + } +} diff --git a/seaweed-block/cmd/sw-block/main.go b/seaweed-block/cmd/sw-block/main.go index 3ba3a03ab2..b04bdb4cc3 100644 --- a/seaweed-block/cmd/sw-block/main.go +++ b/seaweed-block/cmd/sw-block/main.go @@ -31,6 +31,23 @@ var ( opsStatusRunCommand = ops.DefaultRunCommand opsInventoryRunCommand = ops.DefaultRunCommand opsGenerateHelmValuesRunCommand = ops.DefaultRunCommand + opsNodeEvidenceEnricherFactory = func() (ops.OperatorNodeEvidenceEnricher, error) { + return ops.NewInClusterKubernetesStatusClient() + } + opsOperatorStatusWriterFactory = func() (ops.OperatorStatusWriter, error) { + return ops.NewInClusterKubernetesStatusClient() + } + opsSwBlockVolumeSourceFactory = func() (ops.OperatorSwBlockVolumeSource, error) { + return ops.NewInClusterKubernetesStatusClient() + } + opsLifecycleOwnerClientFactory = func() (ops.LifecycleOwnerClient, ops.OperatorEventSink, error) { + client, err := ops.NewInClusterKubernetesStatusClient() + if err != nil { + return nil, nil, err + } + client.EventComponent = "sw-block-lifecycle-owner" + return client, client, nil + } ) func run(args []string, stdout, stderr io.Writer) int { @@ -48,7 +65,7 @@ func run(args []string, stdout, stderr io.Writer) int { return ops.VolumeStatusExitInvalid } if len(args) < 2 { - fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report|dashboard|generate-helm-values") + fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report|dashboard|generate-helm-values|operator-status|lifecycle-owner") usage(stderr) return ops.VolumeStatusExitInvalid } @@ -73,6 +90,10 @@ func run(args []string, stdout, stderr io.Writer) int { return runOpsDashboard(args[2:], stdout, stderr) case "generate-helm-values": return runOpsGenerateHelmValues(args[2:], stdout, stderr) + case "operator-status": + return runOpsOperatorStatus(args[2:], stdout, stderr) + case "lifecycle-owner": + return runOpsLifecycleOwner(args[2:], stdout, stderr) default: fmt.Fprintf(stderr, "sw-block: unknown ops subcommand %q\n", args[1]) usage(stderr) @@ -80,6 +101,203 @@ func run(args []string, stdout, stderr io.Writer) int { } } +func runOpsLifecycleOwner(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block ops lifecycle-owner", flag.ContinueOnError) + fs.SetOutput(stderr) + var ( + dryRun bool + namespace string + interval time.Duration + ) + fs.BoolVar(&dryRun, "dry-run", false, "evaluate lifecycle-owner reconciliation without patching finalizers or emitting Events") + fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace containing SwBlockVolume objects") + fs.DurationVar(&interval, "interval", 0, "repeat lifecycle-owner reconciliation at this interval; 0 runs once") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if fs.NArg() != 0 { + fmt.Fprintf(stderr, "sw-block ops lifecycle-owner: unexpected args %s\n", strings.Join(fs.Args(), " ")) + return ops.VolumeStatusExitInvalid + } + runOnce := func() int { + client, events, err := opsLifecycleOwnerClientFactory() + if err != nil { + fmt.Fprintf(stderr, "sw-block ops lifecycle-owner: %v\n", err) + return ops.VolumeStatusExitInvalid + } + mode := "finalizer_mutation" + if dryRun { + mode = "dry_run" + events = nil + } + result, err := (ops.LifecycleOwnerReconciler{ + Namespace: namespace, + Client: client, + EventSink: events, + DryRun: dryRun, + }).Reconcile(context.Background()) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops lifecycle-owner: %v\n", err) + return ops.VolumeStatusExitInvalid + } + fmt.Fprintf(stdout, "lifecycle_owner=%s namespace=%s volumes=%d finalizer_patches=%d finalizer_added=%d finalizer_held=%d finalizer_released=%d events=%d mutation_allowed=%t\n", + mode, + namespace, + result.VolumeCount, + result.FinalizerPatchCount, + result.FinalizerAddedCount, + result.FinalizerHeldCount, + result.FinalizerReleasedCount, + result.EventCount, + !dryRun) + return ops.VolumeStatusExitOK + } + if interval <= 0 { + return runOnce() + } + for { + code := runOnce() + if code != ops.VolumeStatusExitOK { + fmt.Fprintf(stderr, "sw-block ops lifecycle-owner: iteration failed exit=%d; retrying in %s\n", code, interval) + } + time.Sleep(interval) + } +} + +func runOpsOperatorStatus(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block ops operator-status", flag.ContinueOnError) + fs.SetOutput(stderr) + var ( + dryRun bool + fromBundle string + cleanupSummary string + namespace string + masterAddr string + masterAPIAddr string + outDir string + productRevision string + claimProfile string + clusterName string + timeout time.Duration + interval time.Duration + ) + fs.BoolVar(&dryRun, "dry-run", false, "render the status projection without writing Kubernetes CRD status") + fs.StringVar(&fromBundle, "from-bundle", "", "existing inventory/support bundle directory to project") + fs.StringVar(&cleanupSummary, "cleanup-summary", "", "cleanup-summary.txt evidence to project into delete-safety status") + fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace for live read-only inventory") + fs.StringVar(&masterAddr, "master", "", "optional blockmaster gRPC address for live per-replica status evidence") + fs.StringVar(&masterAPIAddr, "master-api", "", "optional blockmaster gRPC address for ClusterEvidenceService read-only snapshot") + fs.StringVar(&outDir, "out", "", "optional directory for nested live status evidence") + fs.StringVar(&productRevision, "product-revision", "", "product revision label for live evidence") + fs.StringVar(&claimProfile, "claim-profile", "", "promotion-readiness claim profile for live evidence") + fs.StringVar(&clusterName, "cluster-name", ops.DefaultSwBlockClusterName, "SwBlockCluster object name") + fs.DurationVar(&timeout, "timeout", 5*time.Second, "live collection timeout") + fs.DurationVar(&interval, "interval", 0, "repeat dry-run projection at this interval; 0 runs once") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if fs.NArg() != 0 { + fmt.Fprintf(stderr, "sw-block ops operator-status: unexpected args %s\n", strings.Join(fs.Args(), " ")) + return ops.VolumeStatusExitInvalid + } + runOnce := func() int { + clusterArgs := []string{"--namespace", namespace, "--timeout", timeout.String()} + if fromBundle != "" { + clusterArgs = append(clusterArgs, "--from-bundle", fromBundle) + } + if masterAddr != "" { + clusterArgs = append(clusterArgs, "--master", masterAddr) + } + if masterAPIAddr != "" { + clusterArgs = append(clusterArgs, "--master-api", masterAPIAddr) + } + if outDir != "" { + clusterArgs = append(clusterArgs, "--out", outDir) + } + if productRevision != "" { + clusterArgs = append(clusterArgs, "--product-revision", productRevision) + } + if claimProfile != "" { + clusterArgs = append(clusterArgs, "--claim-profile", claimProfile) + } + cluster, _, code := loadObservationCluster("sw-block ops operator-status", clusterArgs, stderr) + if code != ops.VolumeStatusExitOK { + return code + } + if cleanupSummary != "" { + cleanup, err := ops.LoadCleanupEvidenceSummary(cleanupSummary) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops operator-status: %v\n", err) + return ops.VolumeStatusExitInvalid + } + cluster.Cleanup = cleanup + } + mode := "write_status" + var writer ops.OperatorStatusWriter + var events ops.OperatorEventSink + var volumes ops.OperatorSwBlockVolumeSource + if dryRun { + mode = "dry_run" + writer = &operatorStatusDryRunWriter{} + events = &operatorStatusDryRunEventSink{} + } else { + var err error + writer, err = opsOperatorStatusWriterFactory() + if err != nil { + fmt.Fprintf(stderr, "sw-block ops operator-status: %v\n", err) + return ops.VolumeStatusExitInvalid + } + events, _ = writer.(ops.OperatorEventSink) + volumes, _ = writer.(ops.OperatorSwBlockVolumeSource) + } + result, err := (ops.OperatorStatusReconciler{ + Namespace: namespace, + ClusterName: clusterName, + Source: operatorStatusClusterSource{cluster: cluster}, + Writer: writer, + Volumes: volumes, + EventSink: events, + }).Reconcile(context.Background()) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops operator-status: %v\n", err) + return ops.VolumeStatusExitInvalid + } + fmt.Fprintf(stdout, "operator_status=%s cluster=%s/%s volumes=%d events=%d finalizer_patches=%d mutation_allowed=false\n", + mode, + result.ClusterRef.Namespace, + result.ClusterRef.Name, + len(result.VolumeRefs), + result.EventCount, + result.FinalizerPatchCount) + if dryWriter, ok := writer.(*operatorStatusDryRunWriter); ok { + fmt.Fprintf(stdout, "cluster_status volumes=%d ready=%d blocked=%d stale=%d\n", + dryWriter.cluster.VolumeCount, + dryWriter.cluster.ReadyVolumeCount, + dryWriter.cluster.BlockedVolumeCount, + dryWriter.cluster.StaleVolumeCount) + for _, volume := range dryWriter.volumes { + fmt.Fprintf(stdout, "volume_status name=%s volume_id=%s pvc=%s status=%s reason=%s\n", + volume.ref.Name, + emptyCLI(volume.status.VolumeID), + emptyCLI(volume.status.PVCName), + emptyCLI(volume.status.Status), + emptyCLI(volume.status.ReasonCode)) + } + } + return ops.VolumeStatusExitOK + } + if interval <= 0 { + return runOnce() + } + for { + code := runOnce() + if code != ops.VolumeStatusExitOK { + fmt.Fprintf(stderr, "sw-block ops operator-status: iteration failed exit=%d; retrying in %s\n", code, interval) + } + time.Sleep(interval) + } +} + func runOpsStatus(args []string, stdout, stderr io.Writer) int { fs := flag.NewFlagSet("sw-block ops status", flag.ContinueOnError) fs.SetOutput(stderr) @@ -265,6 +483,7 @@ func loadObservationCluster(command string, args []string, stderr io.Writer) (op fs.SetOutput(stderr) var ( fromBundle string + cleanupSummary string namespace string masterAddr string masterAPIAddr string @@ -276,6 +495,7 @@ func loadObservationCluster(command string, args []string, stderr io.Writer) (op timeout time.Duration ) fs.StringVar(&fromBundle, "from-bundle", "", "existing inventory/support bundle directory to explain") + fs.StringVar(&cleanupSummary, "cleanup-summary", "", "cleanup-summary.txt evidence to project into delete-safety status") fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace for live read-only inventory") fs.StringVar(&masterAddr, "master", "", "optional blockmaster gRPC address for live per-replica status evidence") fs.StringVar(&masterAPIAddr, "master-api", "", "optional blockmaster gRPC address for ClusterEvidenceService read-only snapshot") @@ -331,9 +551,75 @@ func loadObservationCluster(command string, args []string, stderr io.Writer) (op fmt.Fprintf(stderr, "%s: %v\n", command, err) return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid } + cluster, err = applyCleanupSummaryProjection(namespace, cleanupSummary, cluster) + if err != nil { + fmt.Fprintf(stderr, "%s: %v\n", command, err) + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + cluster, err = enrichLiveObservationCluster(namespace, timeout, fromBundle == "", cluster) + if err != nil { + fmt.Fprintf(stderr, "%s: %v\n", command, err) + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } return ops.NormalizeObservationCluster(cluster), out, ops.VolumeStatusExitOK } +func enrichLiveObservationCluster(namespace string, timeout time.Duration, live bool, cluster ops.ClusterEvidence) (ops.ClusterEvidence, error) { + if !live || os.Getenv("KUBERNETES_SERVICE_HOST") == "" { + return cluster, nil + } + enricher, err := opsNodeEvidenceEnricherFactory() + if err != nil { + return cluster, err + } + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + cluster, err = enricher.EnrichNodeEvidence(ctx, liveNodeEvidenceNamespace(namespace), cluster) + if err != nil { + return cluster, fmt.Errorf("enrich node evidence: %w", err) + } + return cluster, nil +} + +func applyCleanupSummaryProjection(namespace, cleanupSummary string, cluster ops.ClusterEvidence) (ops.ClusterEvidence, error) { + if cleanupSummary == "" { + return cluster, nil + } + cleanup, err := ops.LoadCleanupEvidenceSummary(cleanupSummary) + if err != nil { + return ops.ClusterEvidence{}, err + } + cluster.Cleanup = cleanup + if os.Getenv("KUBERNETES_SERVICE_HOST") == "" { + return cluster, nil + } + client, err := opsSwBlockVolumeSourceFactory() + if err != nil { + return ops.ClusterEvidence{}, err + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + listNamespace := strings.TrimSpace(namespace) + if listNamespace == "" { + listNamespace = "default" + } + volumes, err := client.ListSwBlockVolumes(ctx, listNamespace) + if err != nil { + return ops.ClusterEvidence{}, err + } + return ops.ProjectSwBlockVolumeDeleteSafety(cluster, volumes), nil +} + +func liveNodeEvidenceNamespace(namespace string) string { + if namespace := strings.TrimSpace(os.Getenv("SW_BLOCK_HELM_NAMESPACE")); namespace != "" { + return namespace + } + if namespace = strings.TrimSpace(namespace); namespace != "" && namespace != "default" { + return namespace + } + return "kube-system" +} + func readMasterClusterEvidence(ctx context.Context, masterAddr string) (ops.ClusterEvidence, error) { conn, err := grpc.NewClient(masterAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { @@ -543,6 +829,7 @@ func runOpsReport(args []string, stdout, stderr io.Writer) int { fs.SetOutput(stderr) var ( fromBundle string + cleanupSummary string namespace string masterAddr string masterAPIAddr string @@ -554,6 +841,7 @@ func runOpsReport(args []string, stdout, stderr io.Writer) int { timeout time.Duration ) fs.StringVar(&fromBundle, "from-bundle", "", "existing inventory/support bundle directory to render") + fs.StringVar(&cleanupSummary, "cleanup-summary", "", "cleanup-summary.txt evidence to project into delete-safety status") fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace for live read-only inventory") fs.StringVar(&masterAddr, "master", "", "optional blockmaster gRPC address for live per-replica status evidence") fs.StringVar(&masterAPIAddr, "master-api", "", "optional blockmaster gRPC address for ClusterEvidenceService read-only snapshot") @@ -615,6 +903,16 @@ func runOpsReport(args []string, stdout, stderr io.Writer) int { fmt.Fprintf(stderr, "sw-block ops report: %v\n", err) return ops.VolumeStatusExitInvalid } + cluster, err = applyCleanupSummaryProjection(namespace, cleanupSummary, cluster) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops report: %v\n", err) + return ops.VolumeStatusExitInvalid + } + cluster, err = enrichLiveObservationCluster(namespace, timeout, fromBundle == "", cluster) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops report: %v\n", err) + return ops.VolumeStatusExitInvalid + } if err := ops.WriteObservationReportArtifacts(outDir, cluster); err != nil { fmt.Fprintf(stderr, "sw-block ops report: %v\n", err) return ops.VolumeStatusExitInvalid @@ -635,6 +933,7 @@ func runOpsDashboard(args []string, stdout, stderr io.Writer) int { fs.SetOutput(stderr) var ( fromBundle string + cleanupSummary string namespace string masterAddr string masterAPIAddr string @@ -647,6 +946,7 @@ func runOpsDashboard(args []string, stdout, stderr io.Writer) int { serveDuration time.Duration ) fs.StringVar(&fromBundle, "from-bundle", "", "existing inventory/support bundle directory to serve") + fs.StringVar(&cleanupSummary, "cleanup-summary", "", "cleanup-summary.txt evidence to project into delete-safety status") fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace for live read-only inventory") fs.StringVar(&masterAddr, "master", "", "optional blockmaster gRPC address for live per-replica status evidence") fs.StringVar(&masterAPIAddr, "master-api", "", "optional blockmaster gRPC address for ClusterEvidenceService read-only snapshot") @@ -667,6 +967,7 @@ func runOpsDashboard(args []string, stdout, stderr io.Writer) int { cluster, err := loadDashboardCluster(dashboardClusterOptions{ FromBundle: fromBundle, + CleanupSummary: cleanupSummary, Namespace: namespace, MasterAddr: masterAddr, MasterAPIAddr: masterAPIAddr, @@ -738,6 +1039,7 @@ func runOpsDashboard(args []string, stdout, stderr io.Writer) int { type dashboardClusterOptions struct { FromBundle string + CleanupSummary string Namespace string MasterAddr string MasterAPIAddr string @@ -749,13 +1051,19 @@ type dashboardClusterOptions struct { } func loadDashboardCluster(options dashboardClusterOptions) (ops.ClusterEvidence, error) { + var ( + cluster ops.ClusterEvidence + err error + live bool + ) switch { case options.FromBundle != "": - return ops.BuildObservationFromBundle(ops.ObservationBundleOptions{Dir: options.FromBundle}) + cluster, err = ops.BuildObservationFromBundle(ops.ObservationBundleOptions{Dir: options.FromBundle}) case options.MasterAPIAddr != "": ctx, cancel := context.WithTimeout(context.Background(), options.Timeout) defer cancel() - return readMasterClusterEvidence(ctx, options.MasterAPIAddr) + cluster, err = readMasterClusterEvidence(ctx, options.MasterAPIAddr) + live = true default: productRevision := options.ProductRevision if productRevision == "" { @@ -779,8 +1087,17 @@ func loadDashboardCluster(options dashboardClusterOptions) (ops.ClusterEvidence, if collectErr != nil { inventory.CollectionErrors = append(inventory.CollectionErrors, strings.Split(collectErr.Error(), "\n")...) } - return ops.BuildObservationFromInventory(inventory, "", options.EvidenceOutDir) + cluster, err = ops.BuildObservationFromInventory(inventory, "", options.EvidenceOutDir) + live = true } + if err != nil { + return ops.ClusterEvidence{}, err + } + cluster, err = applyCleanupSummaryProjection(options.Namespace, options.CleanupSummary, cluster) + if err != nil { + return ops.ClusterEvidence{}, err + } + return enrichLiveObservationCluster(options.Namespace, options.Timeout, live, cluster) } type helmValuesFile struct { @@ -832,6 +1149,7 @@ type helmValuesNetwork struct { } type helmValuesCompat struct { + LauncherDurableImplFlag bool `yaml:"launcherDurableImplFlag"` LauncherReplicationAckFlag bool `yaml:"launcherReplicationAckFlag"` LauncherRejectLoopbackFlag bool `yaml:"launcherRejectLoopbackFlag"` } @@ -1158,6 +1476,7 @@ func loadObservationVolume(command string, args []string, stderr io.Writer) (ops fs.SetOutput(stderr) var ( fromBundle string + cleanupSummary string namespace string masterAddr string out string @@ -1168,6 +1487,7 @@ func loadObservationVolume(command string, args []string, stderr io.Writer) (ops timeout time.Duration ) fs.StringVar(&fromBundle, "from-bundle", "", "existing inventory/support bundle directory to explain") + fs.StringVar(&cleanupSummary, "cleanup-summary", "", "cleanup-summary.txt evidence to project into delete-safety status") fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace for live read-only inventory") fs.StringVar(&masterAddr, "master", "", "optional blockmaster gRPC address for live per-replica status evidence") fs.StringVar(&out, "o", "text", "output format: text, json, or jsonl where supported") @@ -1218,17 +1538,31 @@ func loadObservationVolume(command string, args []string, stderr io.Writer) (ops inventory.CollectionErrors = append(inventory.CollectionErrors, strings.Split(collectErr.Error(), "\n")...) } cluster, err = ops.BuildObservationFromInventory(inventory, volumeID, outDir) + if err != nil && cleanupSummary != "" && strings.Contains(err.Error(), "not found in inventory") { + cluster, err = ops.BuildObservationFromInventory(inventory, "", outDir) + } } if err != nil { fmt.Fprintf(stderr, "%s: %v\n", command, err) return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid } + cluster, err = applyCleanupSummaryProjection(namespace, cleanupSummary, cluster) + if err != nil { + fmt.Fprintf(stderr, "%s: %v\n", command, err) + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + cluster, err = enrichLiveObservationCluster(namespace, timeout, fromBundle == "", cluster) + if err != nil { + fmt.Fprintf(stderr, "%s: %v\n", command, err) + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } return cluster, out, ops.VolumeStatusExitOK } func normalizeObservationVolumeArgs(args []string) []string { valueFlags := map[string]bool{ "--from-bundle": true, + "--cleanup-summary": true, "--namespace": true, "--master": true, "--out": true, @@ -1284,6 +1618,8 @@ func usage(w io.Writer) { fmt.Fprintln(w, " sw-block ops dashboard --master-api [--listen 127.0.0.1:9334]") fmt.Fprintln(w, " sw-block ops generate-helm-values --out values.yaml [--target-node ] [--replication-factor ]") fmt.Fprintln(w, " [--restart-persistence ephemeral|hostpath] [--state-hostpath /var/lib/sw-block] [--timeout 10s]") + fmt.Fprintln(w, " sw-block ops operator-status --dry-run [--master-api |--from-bundle ] [--cleanup-summary ] [--interval 30s]") + fmt.Fprintln(w, " sw-block ops lifecycle-owner [--dry-run] [--namespace ] [--interval 30s]") } func emptyCLI(value string) string { @@ -1293,6 +1629,43 @@ func emptyCLI(value string) string { return value } +type operatorStatusClusterSource struct { + cluster ops.ClusterEvidence +} + +func (s operatorStatusClusterSource) ClusterEvidence(context.Context) (ops.ClusterEvidence, error) { + return s.cluster, nil +} + +type operatorStatusDryRunWriter struct { + cluster ops.SwBlockClusterCRDStatus + volumes []operatorStatusDryRunVolumeWrite +} + +type operatorStatusDryRunVolumeWrite struct { + ref ops.OperatorObjectRef + status ops.SwBlockVolumeCRDStatus +} + +func (w *operatorStatusDryRunWriter) WriteClusterStatus(_ context.Context, _ ops.OperatorObjectRef, status ops.SwBlockClusterCRDStatus) error { + w.cluster = status + return nil +} + +func (w *operatorStatusDryRunWriter) WriteVolumeStatus(_ context.Context, ref ops.OperatorObjectRef, status ops.SwBlockVolumeCRDStatus) error { + w.volumes = append(w.volumes, operatorStatusDryRunVolumeWrite{ref: ref, status: status}) + return nil +} + +type operatorStatusDryRunEventSink struct { + events []ops.OperatorKubernetesEvent +} + +func (s *operatorStatusDryRunEventSink) EmitEvent(_ context.Context, event ops.OperatorKubernetesEvent) error { + s.events = append(s.events, event) + return nil +} + type requiredFrontierFlags struct { values map[string]uint64 } diff --git a/seaweed-block/cmd/sw-block/main_test.go b/seaweed-block/cmd/sw-block/main_test.go index 1ff2ca5ca9..07fb9f48e3 100644 --- a/seaweed-block/cmd/sw-block/main_test.go +++ b/seaweed-block/cmd/sw-block/main_test.go @@ -237,6 +237,578 @@ func TestOpsInventoryMissingOutReturnsInvalid(t *testing.T) { } } +func TestOpsOperatorStatusDryRunFromBundle(t *testing.T) { + dir := t.TempDir() + cluster := ops.NewClusterEvidence(time.Date(2026, 6, 2, 23, 30, 0, 0, time.UTC)) + cluster.ManagedVolumes = []ops.ManagedVolumeProjection{ops.ProjectManagedVolume(ops.ManagedVolumeFacts{ + VolumeID: "pvc-operator", + PVCName: "demo-pvc", + PVC: &ops.PVCFact{Phase: "Bound"}, + Authority: &ops.AuthorityFact{ + PrimaryReplica: "r1", + PublishTarget: "192.168.1.184:3260", + }, + Replicas: []ops.ReplicaFact{{ + ReplicaID: "r1", + KubernetesNode: "m02", + Role: "primary", + Observed: true, + }}, + CSIStages: []ops.CSIStageFact{{NodeName: "m02", Target: "192.168.1.184:3260"}}, + Workload: &ops.WorkloadCheckFact{WriterVerified: true, ReaderVerified: true}, + })} + raw, err := ops.MarshalObservationJSON(cluster) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, ops.ClusterEvidenceArtifact), raw, 0o644); err != nil { + t.Fatal(err) + } + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "operator-status", "--dry-run", "--from-bundle", dir, "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + out := stdout.String() + for _, want := range []string{ + "operator_status=dry_run cluster=kube-system/sw-block volumes=1", + "mutation_allowed=false", + "cluster_status volumes=1 ready=1 blocked=0 stale=0", + "volume_status name=demo-pvc volume_id=pvc-operator pvc=demo-pvc status=ready reason=first_volume_verified", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsOperatorStatusWritesCRDStatusWhenDryRunDisabled(t *testing.T) { + dir := t.TempDir() + cluster := ops.NewClusterEvidence(time.Date(2026, 6, 3, 10, 30, 0, 0, time.UTC)) + cluster.ManagedVolumes = []ops.ManagedVolumeProjection{ops.ProjectManagedVolume(ops.ManagedVolumeFacts{ + VolumeID: "pvc-write", + PVCName: "write-pvc", + PVC: &ops.PVCFact{Phase: "Bound"}, + Authority: &ops.AuthorityFact{ + PrimaryReplica: "r1", + PublishTarget: "192.168.1.184:3260", + }, + Replicas: []ops.ReplicaFact{{ + ReplicaID: "r1", + KubernetesNode: "m02", + Role: "primary", + Observed: true, + }}, + CSIStages: []ops.CSIStageFact{{NodeName: "m02", Target: "192.168.1.184:3260"}}, + Workload: &ops.WorkloadCheckFact{WriterVerified: true, ReaderVerified: true}, + })} + raw, err := ops.MarshalObservationJSON(cluster) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, ops.ClusterEvidenceArtifact), raw, 0o644); err != nil { + t.Fatal(err) + } + + writer := &operatorStatusTestWriter{} + oldFactory := opsOperatorStatusWriterFactory + opsOperatorStatusWriterFactory = func() (ops.OperatorStatusWriter, error) { + return writer, nil + } + t.Cleanup(func() { opsOperatorStatusWriterFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "operator-status", "--from-bundle", t.TempDir()}, &stdout, &stderr) + if code == ops.VolumeStatusExitOK { + t.Fatalf("empty bundle unexpectedly succeeded stdout=%s stderr=%s", stdout.String(), stderr.String()) + } + + stdout.Reset() + stderr.Reset() + code = run([]string{"ops", "operator-status", "--from-bundle", dir, "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if writer.cluster.VolumeCount != 1 || len(writer.volumes) != 1 { + t.Fatalf("writer cluster=%+v volumes=%+v", writer.cluster, writer.volumes) + } + if writer.volumes[0].ref.Name != "write-pvc" || writer.volumes[0].status.Status != ops.ManagedVolumeStatusReady { + t.Fatalf("volume write=%+v", writer.volumes[0]) + } + out := stdout.String() + for _, want := range []string{ + "operator_status=write_status cluster=kube-system/sw-block volumes=1", + "mutation_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsLifecycleOwnerDryRunDoesNotPatch(t *testing.T) { + client := &lifecycleOwnerTestClient{ + volumes: []ops.SwBlockVolumeObject{{ + Ref: ops.OperatorObjectRef{ + APIVersion: ops.SwBlockVolumeAPIVersion, + Kind: ops.SwBlockVolumeKind, + Namespace: "kube-system", + Name: "demo-volume", + }, + }}, + } + oldFactory := opsLifecycleOwnerClientFactory + opsLifecycleOwnerClientFactory = func() (ops.LifecycleOwnerClient, ops.OperatorEventSink, error) { + return client, client, nil + } + t.Cleanup(func() { opsLifecycleOwnerClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "lifecycle-owner", "--dry-run", "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if len(client.patches) != 0 || len(client.events) != 0 { + t.Fatalf("dry-run patched/events: patches=%+v events=%+v", client.patches, client.events) + } + out := stdout.String() + for _, want := range []string{ + "lifecycle_owner=dry_run namespace=kube-system volumes=1", + "finalizer_patches=0", + "finalizer_added=1", + "events=0", + "mutation_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsLifecycleOwnerWritesProtectionFinalizer(t *testing.T) { + client := &lifecycleOwnerTestClient{ + volumes: []ops.SwBlockVolumeObject{{ + Ref: ops.OperatorObjectRef{ + APIVersion: ops.SwBlockVolumeAPIVersion, + Kind: ops.SwBlockVolumeKind, + Namespace: "kube-system", + Name: "demo-volume", + }, + Finalizers: []string{"example.com/foreign"}, + }}, + } + oldFactory := opsLifecycleOwnerClientFactory + opsLifecycleOwnerClientFactory = func() (ops.LifecycleOwnerClient, ops.OperatorEventSink, error) { + return client, client, nil + } + t.Cleanup(func() { opsLifecycleOwnerClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "lifecycle-owner", "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if len(client.patches) != 1 { + t.Fatalf("patches=%+v", client.patches) + } + wantFinalizers := []string{"example.com/foreign", ops.SwBlockVolumeFinalizerName} + if fmt.Sprint(client.patches[0].finalizers) != fmt.Sprint(wantFinalizers) { + t.Fatalf("finalizers=%+v want %+v", client.patches[0].finalizers, wantFinalizers) + } + if len(client.events) != 1 || client.events[0].Reason != ops.ReasonDeleteFinalizerAdded { + t.Fatalf("events=%+v", client.events) + } + out := stdout.String() + for _, want := range []string{ + "lifecycle_owner=finalizer_mutation namespace=kube-system volumes=1", + "finalizer_patches=1", + "finalizer_added=1", + "events=1", + "mutation_allowed=true", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsLifecycleOwnerReleasesProtectionFinalizerWhenDeleteSafetyAllows(t *testing.T) { + deletingAt := time.Date(2026, 6, 15, 2, 0, 0, 0, time.UTC) + client := &lifecycleOwnerTestClient{ + volumes: []ops.SwBlockVolumeObject{{ + Ref: ops.OperatorObjectRef{ + APIVersion: ops.SwBlockVolumeAPIVersion, + Kind: ops.SwBlockVolumeKind, + Namespace: "kube-system", + Name: "demo-volume", + }, + Finalizers: []string{"example.com/foreign", ops.SwBlockVolumeFinalizerName}, + DeletionTimestamp: &deletingAt, + Status: ops.SwBlockVolumeCRDStatus{DeleteSafety: &ops.SwBlockVolumeCRDDeleteSafety{ + Decision: ops.ManagedVolumeActionDecisionAllowed, + State: ops.DeleteSafetyStateReleasable, + Reason: ops.ReasonDeleteFinalizerReleasable, + FinalizerReleaseAllowed: true, + }}, + }}, + } + oldFactory := opsLifecycleOwnerClientFactory + opsLifecycleOwnerClientFactory = func() (ops.LifecycleOwnerClient, ops.OperatorEventSink, error) { + return client, client, nil + } + t.Cleanup(func() { opsLifecycleOwnerClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "lifecycle-owner", "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if len(client.patches) != 1 { + t.Fatalf("patches=%+v", client.patches) + } + if got, want := fmt.Sprint(client.patches[0].finalizers), fmt.Sprint([]string{"example.com/foreign"}); got != want { + t.Fatalf("finalizers=%s want %s", got, want) + } + out := stdout.String() + for _, want := range []string{ + "finalizer_patches=1", + "finalizer_released=1", + "events=1", + "mutation_allowed=true", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsClusterMasterAPIUsesSharedInClusterNodeEvidenceEnrichment(t *testing.T) { + masterAddr, closeMaster := startCmdFakeMaster(t) + defer closeMaster() + oldFactory := opsNodeEvidenceEnricherFactory + opsNodeEvidenceEnricherFactory = func() (ops.OperatorNodeEvidenceEnricher, error) { + return fakeNodeEvidenceEnricher{}, nil + } + t.Cleanup(func() { opsNodeEvidenceEnricherFactory = oldFactory }) + t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1") + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "cluster", "--master-api", masterAddr, "-o", "json"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + out := stdout.String() + for _, want := range []string{ + `"kubernetes_node": "m02"`, + `"ready": false`, + `"reason": "node_not_ready"`, + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsReportMasterAPIUsesSharedInClusterNodeEvidenceEnrichment(t *testing.T) { + masterAddr, closeMaster := startCmdFakeMaster(t) + defer closeMaster() + oldFactory := opsNodeEvidenceEnricherFactory + opsNodeEvidenceEnricherFactory = func() (ops.OperatorNodeEvidenceEnricher, error) { + return fakeNodeEvidenceEnricher{}, nil + } + t.Cleanup(func() { opsNodeEvidenceEnricherFactory = oldFactory }) + t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1") + + outDir := t.TempDir() + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "report", "--master-api", masterAddr, "--out", outDir}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + raw, err := os.ReadFile(filepath.Join(outDir, ops.ObservationReportJSONArtifact)) + if err != nil { + t.Fatal(err) + } + out := string(raw) + for _, want := range []string{ + `"kubernetes_node": "m02"`, + `"ready": false`, + `"reason": "node_not_ready"`, + } { + if !strings.Contains(out, want) { + t.Fatalf("report missing %q:\n%s", want, out) + } + } +} + +func TestLoadObservationVolumeUsesSharedInClusterNodeEvidenceEnrichment(t *testing.T) { + oldFactory := opsNodeEvidenceEnricherFactory + opsNodeEvidenceEnricherFactory = func() (ops.OperatorNodeEvidenceEnricher, error) { + return fakeNodeEvidenceEnricher{}, nil + } + t.Cleanup(func() { opsNodeEvidenceEnricherFactory = oldFactory }) + t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1") + oldRunCommand := opsInventoryRunCommand + opsInventoryRunCommand = fixtureCmdKubectl(map[string]string{ + "kubectl -n default get pvc -o json": cmdSinglePVCListJSON, + "kubectl get pv -o json": cmdSinglePVListJSON, + "kubectl -n default get deploy -l app=sw-blockvolume -o json": cmdSingleDeploymentListJSON, + }) + t.Cleanup(func() { opsInventoryRunCommand = oldRunCommand }) + + var stderr bytes.Buffer + cluster, _, code := loadObservationVolume("sw-block ops explain", []string{"volume", "--namespace", "default", "--product-revision", "product-rev", "pvc-live"}, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s cluster=%+v", code, stderr.String(), cluster) + } + if len(cluster.Nodes) != 1 || cluster.Nodes[0].KubernetesNode != "m02" { + t.Fatalf("cluster nodes=%+v", cluster.Nodes) + } + if !cmdConditionReason(cluster.Nodes[0].Conditions, ops.ReasonNodeNotReady) { + t.Fatalf("volume loader did not enrich node evidence: %+v", cluster.Nodes[0]) + } +} + +func TestOpsExplainProjectsDeletingCRFromCleanupSummary(t *testing.T) { + oldInventoryRun := opsInventoryRunCommand + opsInventoryRunCommand = fixtureCmdKubectl(map[string]string{ + "kubectl -n default get pvc -o json": `{"items":[]}`, + "kubectl get pv -o json": `{"items":[]}`, + "kubectl -n default get deploy -l app=sw-blockvolume -o json": `{"items":[]}`, + }) + t.Cleanup(func() { opsInventoryRunCommand = oldInventoryRun }) + + oldNodeFactory := opsNodeEvidenceEnricherFactory + opsNodeEvidenceEnricherFactory = func() (ops.OperatorNodeEvidenceEnricher, error) { + return fakeNodeEvidenceEnricher{}, nil + } + t.Cleanup(func() { opsNodeEvidenceEnricherFactory = oldNodeFactory }) + + deletingAt := time.Date(2026, 6, 17, 8, 0, 0, 0, time.UTC) + oldVolumeSourceFactory := opsSwBlockVolumeSourceFactory + opsSwBlockVolumeSourceFactory = func() (ops.OperatorSwBlockVolumeSource, error) { + return &lifecycleOwnerTestClient{volumes: []ops.SwBlockVolumeObject{{ + Ref: ops.OperatorObjectRef{ + Namespace: "default", + Name: "delete-pvc", + }, + Finalizers: []string{ops.SwBlockVolumeFinalizerName}, + DeletionTimestamp: &deletingAt, + Spec: ops.SwBlockVolumeSpec{PVCName: "delete-pvc"}, + Status: ops.SwBlockVolumeCRDStatus{ + VolumeID: "pvc-delete", + PVCName: "delete-pvc", + }, + }}}, nil + } + t.Cleanup(func() { opsSwBlockVolumeSourceFactory = oldVolumeSourceFactory }) + t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1") + + cleanupSummary := filepath.Join(t.TempDir(), "cleanup-summary.txt") + if err := os.WriteFile(cleanupSummary, []byte(strings.Join([]string{ + "cleanup_status=failed", + "iscsi_residue_count=1", + "failure_count=1", + "reason_codes=iscsi_node_records_present", + "cleanup_observed_at=2026-06-17T08:00:00Z", + }, "\n")), 0o600); err != nil { + t.Fatal(err) + } + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "explain", "volume", "--namespace", "default", "--cleanup-summary", cleanupSummary, "delete-pvc"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + out := stdout.String() + for _, want := range []string{ + "managed_volume pvc-delete status=blocked reason=iscsi_node_records_present", + "managed_volume_delete_safety state=blocked decision=rejected reason=iscsi_node_records_present", + "managed_volume_action safe_k8s.release_swblockvolume_finalizer mode=dry_run", + } { + if !strings.Contains(out, want) { + t.Fatalf("explain missing %q:\n%s", want, out) + } + } +} + +func TestOpsDashboardMasterAPIUsesSharedInClusterNodeEvidenceEnrichment(t *testing.T) { + masterAddr, closeMaster := startCmdFakeMaster(t) + defer closeMaster() + oldFactory := opsNodeEvidenceEnricherFactory + opsNodeEvidenceEnricherFactory = func() (ops.OperatorNodeEvidenceEnricher, error) { + return fakeNodeEvidenceEnricher{}, nil + } + t.Cleanup(func() { opsNodeEvidenceEnricherFactory = oldFactory }) + t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1") + + addr := freeTCPAddr(t) + var stdout, stderr bytes.Buffer + done := make(chan int, 1) + go func() { + done <- run([]string{ + "ops", "dashboard", + "--master-api", masterAddr, + "--listen", addr, + "--serve-duration", "1500ms", + }, &stdout, &stderr) + }() + + body := waitForHTTPContains(t, "http://"+addr+"/cluster-evidence.json", `"reason": "node_not_ready"`) + if !strings.Contains(body, `"kubernetes_node": "m02"`) || !strings.Contains(body, `"ready": false`) { + t.Fatalf("dashboard cluster evidence missing enriched node:\n%s", body) + } + select { + case code := <-done: + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + case <-time.After(2 * time.Second): + t.Fatalf("dashboard command did not stop; stdout=%s stderr=%s", stdout.String(), stderr.String()) + } +} + +func TestLiveNodeEvidenceUsesHelmNamespaceWhenAppNamespaceDefaults(t *testing.T) { + recorder := &recordingNodeEvidenceEnricher{} + oldFactory := opsNodeEvidenceEnricherFactory + opsNodeEvidenceEnricherFactory = func() (ops.OperatorNodeEvidenceEnricher, error) { + return recorder, nil + } + t.Cleanup(func() { opsNodeEvidenceEnricherFactory = oldFactory }) + t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1") + + _, err := enrichLiveObservationCluster("default", time.Second, true, ops.ClusterEvidence{}) + if err != nil { + t.Fatalf("enrich: %v", err) + } + if recorder.namespace != "kube-system" { + t.Fatalf("node evidence namespace=%q want kube-system", recorder.namespace) + } +} + +func TestLiveNodeEvidenceNamespaceHonorsHelmNamespaceOverride(t *testing.T) { + recorder := &recordingNodeEvidenceEnricher{} + oldFactory := opsNodeEvidenceEnricherFactory + opsNodeEvidenceEnricherFactory = func() (ops.OperatorNodeEvidenceEnricher, error) { + return recorder, nil + } + t.Cleanup(func() { opsNodeEvidenceEnricherFactory = oldFactory }) + t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1") + t.Setenv("SW_BLOCK_HELM_NAMESPACE", "sw-system") + + _, err := enrichLiveObservationCluster("default", time.Second, true, ops.ClusterEvidence{}) + if err != nil { + t.Fatalf("enrich: %v", err) + } + if recorder.namespace != "sw-system" { + t.Fatalf("node evidence namespace=%q want sw-system", recorder.namespace) + } +} + +func TestLiveNodeEvidenceUsesExplicitNonDefaultNamespace(t *testing.T) { + recorder := &recordingNodeEvidenceEnricher{} + oldFactory := opsNodeEvidenceEnricherFactory + opsNodeEvidenceEnricherFactory = func() (ops.OperatorNodeEvidenceEnricher, error) { + return recorder, nil + } + t.Cleanup(func() { opsNodeEvidenceEnricherFactory = oldFactory }) + t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1") + + _, err := enrichLiveObservationCluster("sw-system", time.Second, true, ops.ClusterEvidence{}) + if err != nil { + t.Fatalf("enrich: %v", err) + } + if recorder.namespace != "sw-system" { + t.Fatalf("node evidence namespace=%q want sw-system", recorder.namespace) + } +} + +type fakeNodeEvidenceEnricher struct{} + +func (fakeNodeEvidenceEnricher) EnrichNodeEvidence(_ context.Context, _ string, cluster ops.ClusterEvidence) (ops.ClusterEvidence, error) { + cluster.Nodes = []ops.NodeEvidence{{ + NodeName: "m02", + KubernetesNode: "m02", + Ready: false, + Schedulable: true, + Conditions: []ops.ObservationCondition{{ + Type: ops.ConditionReady, + Status: "Unknown", + Reason: ops.ReasonNodeNotReady, + Severity: "warning", + Message: "Kubernetes node Ready condition is not True", + }}, + }} + return cluster, nil +} + +type recordingNodeEvidenceEnricher struct { + namespace string +} + +func (r *recordingNodeEvidenceEnricher) EnrichNodeEvidence(_ context.Context, namespace string, cluster ops.ClusterEvidence) (ops.ClusterEvidence, error) { + r.namespace = namespace + return cluster, nil +} + +func cmdConditionReason(conditions []ops.ObservationCondition, reason string) bool { + for _, condition := range conditions { + if condition.Reason == reason { + return true + } + } + return false +} + +type operatorStatusTestWriter struct { + cluster ops.SwBlockClusterCRDStatus + volumes []operatorStatusTestVolumeWrite +} + +type operatorStatusTestVolumeWrite struct { + ref ops.OperatorObjectRef + status ops.SwBlockVolumeCRDStatus +} + +func (w *operatorStatusTestWriter) WriteClusterStatus(_ context.Context, _ ops.OperatorObjectRef, status ops.SwBlockClusterCRDStatus) error { + w.cluster = status + return nil +} + +func (w *operatorStatusTestWriter) WriteVolumeStatus(_ context.Context, ref ops.OperatorObjectRef, status ops.SwBlockVolumeCRDStatus) error { + w.volumes = append(w.volumes, operatorStatusTestVolumeWrite{ref: ref, status: status}) + return nil +} + +type lifecycleOwnerTestClient struct { + volumes []ops.SwBlockVolumeObject + patches []lifecycleOwnerTestPatch + events []ops.OperatorKubernetesEvent +} + +type lifecycleOwnerTestPatch struct { + ref ops.OperatorObjectRef + finalizers []string +} + +func (c *lifecycleOwnerTestClient) ListSwBlockVolumes(_ context.Context, _ string) ([]ops.SwBlockVolumeObject, error) { + return append([]ops.SwBlockVolumeObject(nil), c.volumes...), nil +} + +func (c *lifecycleOwnerTestClient) PatchSwBlockVolumeFinalizers(_ context.Context, ref ops.OperatorObjectRef, finalizers []string) error { + c.patches = append(c.patches, lifecycleOwnerTestPatch{ + ref: ref, + finalizers: append([]string(nil), finalizers...), + }) + return nil +} + +func (c *lifecycleOwnerTestClient) EmitEvent(_ context.Context, event ops.OperatorKubernetesEvent) error { + c.events = append(c.events, event) + return nil +} + func TestOpsInventoryRejectsBadRequiredFrontierFlag(t *testing.T) { var stdout, stderr bytes.Buffer code := run([]string{"ops", "inventory", "--out", t.TempDir(), "--required-frontier", "pvc-a=not-a-number"}, &stdout, &stderr) @@ -332,6 +904,7 @@ func TestOpsGenerateHelmValuesSingleNodeFromKubernetes(t *testing.T) { "internalIP: 127.0.0.1", "dataPort: 19101", "controlPort: 19102", + "launcherDurableImplFlag: false", "launcherReplicationAckFlag: false", } { if !strings.Contains(string(values), want) { @@ -399,6 +972,7 @@ func TestOpsGenerateHelmValuesMultiNodeExternalISCSI(t *testing.T) { "internalIP: 192.168.1.188", "dataPort: 19105", "controlPort: 19106", + "launcherDurableImplFlag: false", "launcherReplicationAckFlag: false", } { if !strings.Contains(string(values), want) { @@ -606,6 +1180,59 @@ func TestOpsReportFromBundleAllowsEmptyClusterEvidence(t *testing.T) { } } +func TestOpsReportFromBundleSkipsCorruptClusterEvidenceCandidate(t *testing.T) { + dir := t.TempDir() + if err := os.MkdirAll(filepath.Join(dir, "a-stale", "status"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "a-stale", "status", ops.ClusterEvidenceArtifact), []byte("{not-json"), 0o644); err != nil { + t.Fatal(err) + } + validDir := filepath.Join(dir, "z-restart") + if err := os.MkdirAll(validDir, 0o755); err != nil { + t.Fatal(err) + } + cluster := ops.NewClusterEvidence(time.Date(2026, 5, 27, 12, 0, 0, 0, time.UTC)) + cluster.Volumes = []ops.VolumeEvidence{{ + VolumeID: "pvc-valid", + Namespace: "default", + PVCName: "demo-pvc", + ReplicationFactor: 1, + Status: ops.ObservationStatusOK, + PrimaryReplica: "r1", + PrimaryNode: "m02", + PublishTarget: "192.168.1.184:3260", + }} + raw, err := ops.MarshalObservationJSON(cluster) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(validDir, ops.RestartClusterEvidenceArtifact), raw, 0o644); err != nil { + t.Fatal(err) + } + + outDir := t.TempDir() + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "report", "--from-bundle", dir, "--out", outDir}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + summary, err := os.ReadFile(filepath.Join(outDir, ops.ObservationReportTextArtifact)) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(summary), "volume=pvc-valid") || strings.Contains(string(summary), "not-json") { + t.Fatalf("summary did not use valid evidence:\n%s", summary) + } + snapshot, err := os.ReadFile(filepath.Join(outDir, ops.ObservationOperatorSnapshotArtifact)) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(snapshot), `"volume_id": "pvc-valid"`) || !strings.Contains(string(snapshot), `"read_only": true`) { + t.Fatalf("operator snapshot missing valid read-only evidence:\n%s", snapshot) + } +} + func TestOpsDashboardFromBundleServesReadOnlyHTTP(t *testing.T) { dir := writeCmdProductClusterBundle(t) addr := freeTCPAddr(t) diff --git a/seaweed-block/core/csi/backend.go b/seaweed-block/core/csi/backend.go index 1f635c9025..e3f810bb7d 100644 --- a/seaweed-block/core/csi/backend.go +++ b/seaweed-block/core/csi/backend.go @@ -79,6 +79,14 @@ type VolumeProvisioner interface { DeleteVolume(ctx context.Context, volumeID string) error } +// VolumeObjectRegistrar creates the Kubernetes-facing SwBlockVolume identity +// object after CSI provisioning succeeds. It owns metadata/spec identity only; +// status remains operator-status owned and finalizers remain lifecycle-owner +// owned. +type VolumeObjectRegistrar interface { + EnsureVolumeObject(ctx context.Context, spec VolumeSpec) error +} + type KubernetesMetadataResolver interface { ResolvePVCUID(ctx context.Context, name, namespace string) (string, error) } @@ -92,6 +100,7 @@ type VolumeSpec struct { PVCNamespace string PVCUID string PVName string + StorageClass string } func publishContext(t PublishTarget) map[string]string { diff --git a/seaweed-block/core/csi/controller.go b/seaweed-block/core/csi/controller.go index cad48ce3b9..123a642248 100644 --- a/seaweed-block/core/csi/controller.go +++ b/seaweed-block/core/csi/controller.go @@ -18,6 +18,7 @@ type ControllerServer struct { lookup PublishTargetLookup provisioner VolumeProvisioner metadataResolver KubernetesMetadataResolver + registrar VolumeObjectRegistrar } func NewControllerServer(lookup PublishTargetLookup) *ControllerServer { @@ -32,6 +33,10 @@ func NewControllerServerWithProvisionerAndMetadataResolver(lookup PublishTargetL return &ControllerServer{lookup: lookup, provisioner: provisioner, metadataResolver: resolver} } +func NewControllerServerWithProvisionerMetadataAndRegistrar(lookup PublishTargetLookup, provisioner VolumeProvisioner, resolver KubernetesMetadataResolver, registrar VolumeObjectRegistrar) *ControllerServer { + return &ControllerServer{lookup: lookup, provisioner: provisioner, metadataResolver: resolver, registrar: registrar} +} + func (s *ControllerServer) CreateVolume(ctx context.Context, req *csipb.CreateVolumeRequest) (*csipb.CreateVolumeResponse, error) { if s.provisioner == nil { return nil, status.Error(codes.Unimplemented, "dynamic provisioning is not configured") @@ -51,6 +56,11 @@ func (s *ControllerServer) CreateVolume(ctx context.Context, req *csipb.CreateVo } return nil, status.Errorf(codes.Internal, "create volume intent: %v", err) } + if s.registrar != nil { + if err := s.registrar.EnsureVolumeObject(ctx, created); err != nil { + return nil, status.Errorf(codes.Internal, "ensure SwBlockVolume object: %v", err) + } + } protocol := normalizeProtocol(created.Protocol) return &csipb.CreateVolumeResponse{ Volume: &csipb.Volume{ @@ -199,6 +209,7 @@ func volumeSpecFromCreateRequest(req *csipb.CreateVolumeRequest) (VolumeSpec, er PVCNamespace: req.GetParameters()["csi.storage.k8s.io/pvc/namespace"], PVCUID: req.GetParameters()["csi.storage.k8s.io/pvc/uid"], PVName: req.GetParameters()["csi.storage.k8s.io/pv/name"], + StorageClass: req.GetParameters()["csi.storage.k8s.io/storageclass/name"], }, nil } diff --git a/seaweed-block/core/csi/controller_test.go b/seaweed-block/core/csi/controller_test.go index 5024da9627..10daa308be 100644 --- a/seaweed-block/core/csi/controller_test.go +++ b/seaweed-block/core/csi/controller_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "strings" "testing" csipb "github.com/container-storage-interface/spec/lib/go/csi" @@ -59,6 +60,16 @@ func (s *stubMetadataResolver) ResolvePVCUID(_ context.Context, name, namespace return s.uid, s.err } +type stubVolumeRegistrar struct { + err error + calls []VolumeSpec +} + +func (s *stubVolumeRegistrar) EnsureVolumeObject(_ context.Context, spec VolumeSpec) error { + s.calls = append(s.calls, spec) + return s.err +} + func TestControllerPublish_ReturnsISCSIPublishContextFromTargetFact(t *testing.T) { lookup := &stubLookup{target: PublishTarget{ VolumeID: "v1", @@ -279,6 +290,76 @@ func TestG15c_ControllerCreateVolume_RecordsDesiredIntentOnly(t *testing.T) { } } +func TestPhase44_ControllerCreateVolume_RegistersSwBlockVolumeObjectAfterProvisioning(t *testing.T) { + prov := &stubProvisioner{} + registrar := &stubVolumeRegistrar{} + s := NewControllerServerWithProvisionerMetadataAndRegistrar(&stubLookup{}, prov, nil, registrar) + + _, err := s.CreateVolume(context.Background(), &csipb.CreateVolumeRequest{ + Name: "pvc-a", + CapacityRange: &csipb.CapacityRange{ + RequiredBytes: 1 << 30, + }, + Parameters: map[string]string{ + "replicationFactor": "1", + "csi.storage.k8s.io/pvc/name": "demo-pvc", + "csi.storage.k8s.io/pvc/namespace": "default", + "csi.storage.k8s.io/pvc/uid": "uid-123", + "csi.storage.k8s.io/pv/name": "pvc-a", + "csi.storage.k8s.io/storageclass/name": "sw-block-dynamic", + "csi.storage.k8s.io/serviceAccount.name": "ignored", + "csi.storage.k8s.io/serviceAccount.secrets": "ignored", + }, + VolumeCapabilities: []*csipb.VolumeCapability{ + testVolumeCapability(), + }, + }) + if err != nil { + t.Fatalf("CreateVolume: %v", err) + } + if len(prov.calls) != 1 { + t.Fatalf("provisioner calls=%d want 1", len(prov.calls)) + } + if len(registrar.calls) != 1 { + t.Fatalf("registrar calls=%d want 1", len(registrar.calls)) + } + got := registrar.calls[0] + if got.VolumeID != "pvc-a" || got.PVCName != "demo-pvc" || got.PVCNamespace != "default" || got.PVCUID != "uid-123" || got.StorageClass != "sw-block-dynamic" { + t.Fatalf("registered spec=%+v", got) + } +} + +func TestPhase44_ControllerCreateVolume_FailsWhenSwBlockVolumeRegistrationFails(t *testing.T) { + prov := &stubProvisioner{} + registrar := &stubVolumeRegistrar{err: errors.New("api rejected object")} + s := NewControllerServerWithProvisionerMetadataAndRegistrar(&stubLookup{}, prov, nil, registrar) + + _, err := s.CreateVolume(context.Background(), &csipb.CreateVolumeRequest{ + Name: "pvc-a", + CapacityRange: &csipb.CapacityRange{ + RequiredBytes: 1 << 30, + }, + Parameters: map[string]string{ + "replicationFactor": "1", + "csi.storage.k8s.io/pvc/name": "demo-pvc", + "csi.storage.k8s.io/pvc/namespace": "default", + }, + VolumeCapabilities: []*csipb.VolumeCapability{ + testVolumeCapability(), + }, + }) + if err == nil { + t.Fatal("expected registration failure") + } + st, _ := status.FromError(err) + if st.Code() != codes.Internal || !strings.Contains(st.Message(), "ensure SwBlockVolume object") { + t.Fatalf("error=%v", err) + } + if len(prov.calls) != 1 { + t.Fatalf("provisioner should be called before registration: %d", len(prov.calls)) + } +} + func TestG15c_ControllerCreateVolume_RecordsProtocolSelection(t *testing.T) { for _, tc := range []struct { name string diff --git a/seaweed-block/core/csi/kubernetes_metadata.go b/seaweed-block/core/csi/kubernetes_metadata.go index f9367f61d3..688f1c4b04 100644 --- a/seaweed-block/core/csi/kubernetes_metadata.go +++ b/seaweed-block/core/csi/kubernetes_metadata.go @@ -1,6 +1,7 @@ package csi import ( + "bytes" "context" "crypto/tls" "crypto/x509" @@ -13,6 +14,8 @@ import ( "os" "strings" "time" + + blockops "github.com/seaweedfs/seaweed-block/core/ops" ) const ( @@ -26,35 +29,59 @@ type InClusterPVCMetadataResolver struct { token string } +type InClusterSwBlockVolumeRegistrar struct { + client *http.Client + host string + token string + namespace string +} + func NewInClusterPVCMetadataResolver() (*InClusterPVCMetadataResolver, error) { + client, host, token, err := newInClusterKubernetesClient() + if err != nil { + return nil, err + } + return &InClusterPVCMetadataResolver{client: client, host: host, token: token}, nil +} + +func NewInClusterSwBlockVolumeRegistrar(namespace string) (*InClusterSwBlockVolumeRegistrar, error) { + namespace = strings.TrimSpace(namespace) + if namespace == "" { + return nil, fmt.Errorf("SwBlockVolume namespace is required") + } + client, host, token, err := newInClusterKubernetesClient() + if err != nil { + return nil, err + } + return &InClusterSwBlockVolumeRegistrar{client: client, host: host, token: token, namespace: namespace}, nil +} + +func newInClusterKubernetesClient() (*http.Client, string, string, error) { host := os.Getenv("KUBERNETES_SERVICE_HOST") port := os.Getenv("KUBERNETES_SERVICE_PORT") if host == "" || port == "" { - return nil, fmt.Errorf("KUBERNETES_SERVICE_HOST/PORT are not set") + return nil, "", "", fmt.Errorf("KUBERNETES_SERVICE_HOST/PORT are not set") } tokenBytes, err := os.ReadFile(serviceAccountTokenPath) if err != nil { - return nil, fmt.Errorf("read service account token: %w", err) + return nil, "", "", fmt.Errorf("read service account token: %w", err) } caBytes, err := os.ReadFile(serviceAccountCAPath) if err != nil { - return nil, fmt.Errorf("read service account ca: %w", err) + return nil, "", "", fmt.Errorf("read service account ca: %w", err) } roots := x509.NewCertPool() if !roots.AppendCertsFromPEM(caBytes) { - return nil, fmt.Errorf("parse service account ca") + return nil, "", "", fmt.Errorf("parse service account ca") } - return &InClusterPVCMetadataResolver{ - client: &http.Client{ - Timeout: 10 * time.Second, - Transport: &http.Transport{TLSClientConfig: &tls.Config{ - RootCAs: roots, - MinVersion: tls.VersionTLS12, - }}, - }, - host: "https://" + net.JoinHostPort(host, port), - token: strings.TrimSpace(string(tokenBytes)), - }, nil + client := &http.Client{ + Timeout: 10 * time.Second, + Transport: &http.Transport{TLSClientConfig: &tls.Config{ + RootCAs: roots, + MinVersion: tls.VersionTLS12, + }}, + } + return client, "https://" + net.JoinHostPort(host, port), strings.TrimSpace(string(tokenBytes)), nil } func (r *InClusterPVCMetadataResolver) ResolvePVCUID(ctx context.Context, name, namespace string) (string, error) { @@ -92,3 +119,99 @@ func (r *InClusterPVCMetadataResolver) ResolvePVCUID(ctx context.Context, name, } return out.Metadata.UID, nil } + +func (r *InClusterSwBlockVolumeRegistrar) EnsureVolumeObject(ctx context.Context, spec VolumeSpec) error { + if r == nil || r.client == nil { + return fmt.Errorf("registrar not configured") + } + name := blockops.SwBlockVolumeObjectName(blockops.ManagedVolumeOperatorStatus{ + VolumeID: spec.VolumeID, + PVCName: spec.PVCName, + }) + body := swBlockVolumeObject{ + APIVersion: blockops.SwBlockVolumeAPIVersion, + Kind: blockops.SwBlockVolumeKind, + Metadata: swBlockVolumeMetadata{ + Name: name, + Namespace: r.namespace, + }, + Spec: swBlockVolumeSpec{ + PVCName: spec.PVCName, + StorageClass: spec.StorageClass, + }, + } + raw, err := json.Marshal(body) + if err != nil { + return fmt.Errorf("marshal SwBlockVolume: %w", err) + } + endpoint := r.host + "/apis/block.seaweedfs.com/v1alpha1/namespaces/" + url.PathEscape(r.namespace) + "/swblockvolumes" + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(raw)) + if err != nil { + return err + } + r.setJSONHeaders(req) + resp, err := r.client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode >= 200 && resp.StatusCode < 300 { + return nil + } + if resp.StatusCode == http.StatusConflict { + return r.patchVolumeSpec(ctx, name, body.Spec) + } + respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + return fmt.Errorf("create SwBlockVolume %s/%s failed: http %d %s", r.namespace, name, resp.StatusCode, strings.TrimSpace(string(respBody))) +} + +func (r *InClusterSwBlockVolumeRegistrar) patchVolumeSpec(ctx context.Context, name string, spec swBlockVolumeSpec) error { + raw, err := json.Marshal(map[string]any{"spec": spec}) + if err != nil { + return fmt.Errorf("marshal SwBlockVolume spec patch: %w", err) + } + endpoint := r.host + "/apis/block.seaweedfs.com/v1alpha1/namespaces/" + url.PathEscape(r.namespace) + "/swblockvolumes/" + url.PathEscape(name) + req, err := http.NewRequestWithContext(ctx, http.MethodPatch, endpoint, bytes.NewReader(raw)) + if err != nil { + return err + } + r.setJSONHeaders(req) + req.Header.Set("Content-Type", "application/merge-patch+json") + resp, err := r.client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode >= 200 && resp.StatusCode < 300 { + return nil + } + respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + return fmt.Errorf("patch SwBlockVolume %s/%s spec failed: http %d %s", r.namespace, name, resp.StatusCode, strings.TrimSpace(string(respBody))) +} + +func (r *InClusterSwBlockVolumeRegistrar) setJSONHeaders(req *http.Request) { + req.Header.Set("Accept", "application/json") + if req.Header.Get("Content-Type") == "" { + req.Header.Set("Content-Type", "application/json") + } + if r.token != "" { + req.Header.Set("Authorization", "Bearer "+r.token) + } +} + +type swBlockVolumeObject struct { + APIVersion string `json:"apiVersion"` + Kind string `json:"kind"` + Metadata swBlockVolumeMetadata `json:"metadata"` + Spec swBlockVolumeSpec `json:"spec"` +} + +type swBlockVolumeMetadata struct { + Name string `json:"name"` + Namespace string `json:"namespace"` +} + +type swBlockVolumeSpec struct { + PVCName string `json:"pvcName,omitempty"` + StorageClass string `json:"storageClass,omitempty"` +} diff --git a/seaweed-block/core/csi/kubernetes_metadata_test.go b/seaweed-block/core/csi/kubernetes_metadata_test.go new file mode 100644 index 0000000000..ac7bac30af --- /dev/null +++ b/seaweed-block/core/csi/kubernetes_metadata_test.go @@ -0,0 +1,111 @@ +package csi + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" +) + +func TestPhase44SwBlockVolumeRegistrarCreatesIdentityObject(t *testing.T) { + var got map[string]any + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + t.Fatalf("method=%s want POST", r.Method) + } + if r.URL.Path != "/apis/block.seaweedfs.com/v1alpha1/namespaces/kube-system/swblockvolumes" { + t.Fatalf("path=%s", r.URL.Path) + } + if r.Header.Get("Authorization") != "Bearer token" { + t.Fatalf("authorization=%s", r.Header.Get("Authorization")) + } + if err := json.NewDecoder(r.Body).Decode(&got); err != nil { + t.Fatalf("decode body: %v", err) + } + w.WriteHeader(http.StatusCreated) + })) + defer server.Close() + + registrar := &InClusterSwBlockVolumeRegistrar{ + client: server.Client(), + host: server.URL, + token: "token", + namespace: "kube-system", + } + if err := registrar.EnsureVolumeObject(context.Background(), VolumeSpec{ + VolumeID: "pvc-1234", + PVCName: "Demo_PVC", + StorageClass: "sw-block-dynamic", + }); err != nil { + t.Fatalf("ensure object: %v", err) + } + if got["apiVersion"] != "block.seaweedfs.com/v1alpha1" || got["kind"] != "SwBlockVolume" { + t.Fatalf("type meta=%+v", got) + } + metadata := got["metadata"].(map[string]any) + if metadata["name"] != "demo-pvc" || metadata["namespace"] != "kube-system" { + t.Fatalf("metadata=%+v", metadata) + } + spec := got["spec"].(map[string]any) + if spec["pvcName"] != "Demo_PVC" || spec["storageClass"] != "sw-block-dynamic" { + t.Fatalf("spec=%+v", spec) + } + if _, ok := got["status"]; ok { + t.Fatalf("registrar must not write status: %+v", got) + } +} + +func TestPhase44SwBlockVolumeRegistrarPatchesSpecOnConflict(t *testing.T) { + var calls []string + var patch map[string]any + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls = append(calls, r.Method+" "+r.URL.Path) + switch len(calls) { + case 1: + if r.Method != http.MethodPost { + t.Fatalf("first method=%s want POST", r.Method) + } + w.WriteHeader(http.StatusConflict) + case 2: + if r.Method != http.MethodPatch { + t.Fatalf("second method=%s want PATCH", r.Method) + } + if r.URL.Path != "/apis/block.seaweedfs.com/v1alpha1/namespaces/kube-system/swblockvolumes/demo-pvc" { + t.Fatalf("patch path=%s", r.URL.Path) + } + if r.Header.Get("Content-Type") != "application/merge-patch+json" { + t.Fatalf("patch content-type=%s", r.Header.Get("Content-Type")) + } + if err := json.NewDecoder(r.Body).Decode(&patch); err != nil { + t.Fatalf("decode patch: %v", err) + } + w.WriteHeader(http.StatusOK) + default: + t.Fatalf("unexpected extra call %d", len(calls)) + } + })) + defer server.Close() + + registrar := &InClusterSwBlockVolumeRegistrar{ + client: server.Client(), + host: server.URL, + namespace: "kube-system", + } + if err := registrar.EnsureVolumeObject(context.Background(), VolumeSpec{ + VolumeID: "pvc-1234", + PVCName: "demo-pvc", + }); err != nil { + t.Fatalf("ensure object: %v", err) + } + if len(calls) != 2 { + t.Fatalf("calls=%v", calls) + } + if _, ok := patch["status"]; ok { + t.Fatalf("patch must not include status: %+v", patch) + } + spec := patch["spec"].(map[string]any) + if spec["pvcName"] != "demo-pvc" { + t.Fatalf("patch spec=%+v", spec) + } +} diff --git a/seaweed-block/core/host/master/observation_snapshot.go b/seaweed-block/core/host/master/observation_snapshot.go index bdc5528496..c89e0e6947 100644 --- a/seaweed-block/core/host/master/observation_snapshot.go +++ b/seaweed-block/core/host/master/observation_snapshot.go @@ -120,6 +120,39 @@ func (h *Host) observationVolume(volumeID string, rec lifecycle.VolumeRecord, pl volume.PublishTarget = publishTargetForReplica(replicas, volume.PrimaryReplica) } + if volume.PrimaryReplica != "" { + primary, ok := replicaEvidenceByID(replicas, volume.PrimaryReplica) + if !ok || !primary.Observed { + if volume.Status == ops.ObservationStatusOK { + volume.Status = ops.ObservationStatusDegraded + volume.Reason = ops.ReasonStatusEndpointUnreachable + } + volume.Conditions = append(volume.Conditions, ops.ObservationCondition{ + Type: "PrimaryReady", + Status: "false", + Reason: ops.ReasonStatusEndpointUnreachable, + Severity: "warning", + Message: "published primary has no fresh readiness observation", + }) + } else if !primary.CandidateReady { + reason := primary.CandidateReadyReason + if reason == "" { + reason = ops.ReasonNoPromotionReadyCandidate + } + if volume.Status == ops.ObservationStatusOK { + volume.Status = ops.ObservationStatusDegraded + volume.Reason = reason + } + volume.Conditions = append(volume.Conditions, ops.ObservationCondition{ + Type: "PrimaryReady", + Status: "false", + Reason: reason, + Severity: "warning", + Message: "published primary has not confirmed local readiness", + }) + } + } + if volume.DesiredReplicas > 0 && volume.ObservedReplicas < volume.DesiredReplicas { volume.Status = ops.ObservationStatusDegraded volume.Reason = ops.ReasonObservedReplicasBelowDesired @@ -286,6 +319,15 @@ func publishTargetForReplica(replicas []ops.ReplicaEvidence, replicaID string) s return "" } +func replicaEvidenceByID(replicas []ops.ReplicaEvidence, replicaID string) (ops.ReplicaEvidence, bool) { + for _, replica := range replicas { + if replica.ReplicaID == replicaID { + return replica, true + } + } + return ops.ReplicaEvidence{}, false +} + func candidateReason(ready bool) string { if ready { return ops.ReasonCandidateCoversRequiredFrontier diff --git a/seaweed-block/core/host/master/observation_snapshot_test.go b/seaweed-block/core/host/master/observation_snapshot_test.go index d5b1811a0b..63b58ca0ed 100644 --- a/seaweed-block/core/host/master/observation_snapshot_test.go +++ b/seaweed-block/core/host/master/observation_snapshot_test.go @@ -97,6 +97,43 @@ func TestMasterObservationSnapshot_MissingReplicaIsDegraded(t *testing.T) { } } +func TestMasterObservationSnapshot_PrimaryMustConfirmReadiness(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }) + defer closeTestMaster(t, h) + seedObservationSnapshotVolume(t, h) + seedRF3PlacementForServers(t, h, "pvc-a", "m01", "m02", "tp01") + ingestObservationSnapshotRF3(t, h, true, true, true) + + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) + } + line := waitAuthorityLine(t, h.Publisher(), "pvc-a") + ingestObservationSnapshotReplica(t, h, line.ReplicaID, false) + + snapshot := h.ObservationSnapshot(time.Now().UTC()) + if snapshot.Status != ops.ObservationStatusDegraded { + t.Fatalf("cluster status=%q want degraded", snapshot.Status) + } + if len(snapshot.Volumes) != 1 { + t.Fatalf("volumes=%d want 1", len(snapshot.Volumes)) + } + volume := snapshot.Volumes[0] + if volume.Status == ops.ObservationStatusOK { + t.Fatalf("volume incorrectly reported ok after primary readiness block: %+v", volume) + } + if volume.Reason != ops.ReasonNoPromotionReadyCandidate { + t.Fatalf("volume reason=%q want %q: %+v", volume.Reason, ops.ReasonNoPromotionReadyCandidate, volume) + } + if !hasVolumeCondition(volume, "PrimaryReady", ops.ReasonNoPromotionReadyCandidate) { + t.Fatalf("volume conditions=%+v missing primary readiness block", volume.Conditions) + } + if !hasReplicaNotReady(volume.Replicas, line.ReplicaID) { + t.Fatalf("replicas=%+v missing not-ready primary %s", volume.Replicas, line.ReplicaID) + } +} + func TestMasterObservationSnapshot_NoLifecycleStoreReturnsEmptyOK(t *testing.T) { h := newTestMaster(t, "") defer closeTestMaster(t, h) @@ -154,43 +191,57 @@ func seedObservationSnapshotVolume(t *testing.T, h *Host) { func ingestObservationSnapshotRF3(t *testing.T, h *Host, r1Ready, r2Ready, r3Ready bool) { t.Helper() - now := time.Now().UTC() - for i, item := range []struct { - serverID string - replica string - ip string - ready bool + for _, item := range []struct { + replica string + ready bool }{ - {serverID: "m01", replica: "r1", ip: "192.168.1.181", ready: r1Ready}, - {serverID: "m02", replica: "r2", ip: "192.168.1.184", ready: r2Ready}, - {serverID: "tp01", replica: "r3", ip: "192.168.1.188", ready: r3Ready}, + {replica: "r1", ready: r1Ready}, + {replica: "r2", ready: r2Ready}, + {replica: "r3", ready: r3Ready}, } { if !item.ready { continue } - if err := h.ObservationHost().Ingest(authority.Observation{ - ServerID: item.serverID, - ObservedAt: now, - Server: authority.ServerFact{Reachable: true, Eligible: true}, - Slots: []authority.SlotFact{{ - VolumeID: "pvc-a", - ReplicaID: item.replica, - DataAddr: item.ip + ":19101", - CtrlAddr: item.ip + ":19102", - Reachable: true, - ReadyForPrimary: true, - Eligible: true, - EvidenceScore: uint64(30 - i), - Frontends: []authority.FrontendTargetFact{{ - Protocol: "iscsi", - Addr: item.ip + ":3260", - IQN: "iqn.2026-05.io.seaweedfs:pvc-a", - LUN: 1, - }}, + ingestObservationSnapshotReplica(t, h, item.replica, true) + } +} + +func ingestObservationSnapshotReplica(t *testing.T, h *Host, replica string, ready bool) { + t.Helper() + item, ok := map[string]struct { + serverID string + ip string + score uint64 + }{ + "r1": {serverID: "m01", ip: "192.168.1.181", score: 30}, + "r2": {serverID: "m02", ip: "192.168.1.184", score: 29}, + "r3": {serverID: "tp01", ip: "192.168.1.188", score: 28}, + }[replica] + if !ok { + t.Fatalf("unknown replica %s", replica) + } + if err := h.ObservationHost().Ingest(authority.Observation{ + ServerID: item.serverID, + ObservedAt: time.Now().UTC(), + Server: authority.ServerFact{Reachable: true, Eligible: true}, + Slots: []authority.SlotFact{{ + VolumeID: "pvc-a", + ReplicaID: replica, + DataAddr: item.ip + ":19101", + CtrlAddr: item.ip + ":19102", + Reachable: true, + ReadyForPrimary: ready, + Eligible: true, + EvidenceScore: item.score, + Frontends: []authority.FrontendTargetFact{{ + Protocol: "iscsi", + Addr: item.ip + ":3260", + IQN: "iqn.2026-05.io.seaweedfs:pvc-a", + LUN: 1, }}, - }); err != nil { - t.Fatalf("ingest %s: %v", item.replica, err) - } + }}, + }); err != nil { + t.Fatalf("ingest %s: %v", replica, err) } } @@ -216,3 +267,21 @@ func hasReplicaCondition(replicas []ops.ReplicaEvidence, replicaID, reason strin } return false } + +func hasVolumeCondition(volume ops.VolumeEvidence, conditionType, reason string) bool { + for _, condition := range volume.Conditions { + if condition.Type == conditionType && condition.Reason == reason { + return true + } + } + return false +} + +func hasReplicaNotReady(replicas []ops.ReplicaEvidence, replicaID string) bool { + for _, replica := range replicas { + if replica.ReplicaID == replicaID && replica.Observed && replica.Role == "primary" && !replica.CandidateReady { + return true + } + } + return false +} diff --git a/seaweed-block/core/host/volume/apply_fact_test.go b/seaweed-block/core/host/volume/apply_fact_test.go index 0b26dcbe8e..3b7b1897ce 100644 --- a/seaweed-block/core/host/volume/apply_fact_test.go +++ b/seaweed-block/core/host/volume/apply_fact_test.go @@ -205,6 +205,74 @@ func TestHost_ApplyFact_Self_UpdateReplicaSetFailure_SkipsOnAssignment(t *testin } } +func TestHost_ApplyFact_Self_LocalReadinessBlocked_SkipsReplicationAndAdapter(t *testing.T) { + rec := &orderingRecorder{} + h, a, r := newStubbedHost(t, "vol1", "r1", rec) + readyCh := make(chan adapter.AssignmentInfo, 1) + h.cfg.ReadyMarker = readyCh + h.BlockLocalReadiness("durable recovery failed: wal_integrity_fault") + + fact := &control.AssignmentFact{ + VolumeId: "vol1", + ReplicaId: "r1", + Epoch: 2, + EndpointVersion: 1, + PeerSetGeneration: 7, + Peers: []*control.ReplicaDescriptor{ + {ReplicaId: "r1", DataAddr: "d1", CtrlAddr: "c1", Epoch: 2, EndpointVersion: 1}, + }, + } + + h.applyFact(fact) + + if got := r.callCount.Load(); got != 0 { + t.Fatalf("local readiness block must skip UpdateReplicaSet: got %d calls", got) + } + if got := a.callCount.Load(); got != 0 { + t.Fatalf("local readiness block must skip OnAssignment: got %d calls", got) + } + if seq := rec.snapshot(); len(seq) != 0 { + t.Fatalf("local readiness block sequence=%v want empty", seq) + } + select { + case got := <-readyCh: + t.Fatalf("local readiness block must not emit ready marker: %+v", got) + default: + } +} + +func TestHost_ApplyFact_SupportingReplica_LocalReadinessBlocked_SkipsAdapter(t *testing.T) { + rec := &orderingRecorder{} + h, a, _ := newStubbedHost(t, "vol1", "r2", rec) + readyCh := make(chan adapter.AssignmentInfo, 1) + h.cfg.ReadyMarker = readyCh + h.BlockLocalReadiness("awaiting durable recovery") + + fact := &control.AssignmentFact{ + VolumeId: "vol1", + ReplicaId: "r1", + Epoch: 5, + EndpointVersion: 2, + Peers: []*control.ReplicaDescriptor{ + {ReplicaId: "r2", DataAddr: "d2", CtrlAddr: "c2", Epoch: 5, EndpointVersion: 2}, + }, + } + + h.applyFact(fact) + + if got := a.callCount.Load(); got != 0 { + t.Fatalf("local readiness block must skip supporting OnAssignment: got %d calls", got) + } + if seq := rec.snapshot(); len(seq) != 0 { + t.Fatalf("local readiness block sequence=%v want empty", seq) + } + select { + case got := <-readyCh: + t.Fatalf("local readiness block must not emit supporting ready marker: %+v", got) + default: + } +} + // --- Test 3: supersede branch unaffected --- // TestHost_ApplyFact_Supersede_NeverCallsAdapterOrReplication — diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index a14229600a..4b235bfd72 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -123,6 +123,9 @@ type Host struct { readyMarkerMu sync.Mutex supportingReadyMarks map[string]struct{} + localReadinessBlocked atomic.Bool + localReadinessReason atomic.Value // string + // lastOtherLine captures the most recent AssignmentFact that // named a REPLICA OTHER than self for this host's VolumeID. // Populated when the master's volume-scoped subscription @@ -229,6 +232,35 @@ func New(cfg Config) (*Host, error) { return h, nil } +// BlockLocalReadiness prevents assignment facts from entering the local +// adapter while preserving heartbeat/status serving. Use this when local +// storage evidence says this replica must not publish Healthy. +func (h *Host) BlockLocalReadiness(reason string) { + if reason == "" { + reason = "local readiness blocked" + } + h.localReadinessReason.Store(reason) + h.localReadinessBlocked.Store(true) +} + +// ClearLocalReadinessBlock allows future assignment stream replays to enter +// the adapter after local startup/recovery evidence is clean. +func (h *Host) ClearLocalReadinessBlock() { + h.localReadinessReason.Store("") + h.localReadinessBlocked.Store(false) +} + +func (h *Host) localReadinessBlock() (bool, string) { + if !h.localReadinessBlocked.Load() { + return false, "" + } + reason, _ := h.localReadinessReason.Load().(string) + if reason == "" { + reason = "local readiness blocked" + } + return true, reason +} + // SetReplicationVolume installs (or replaces) the per-volume // replication fan-out coordinator AFTER Host.New. Used by the // production binary path: storage isn't available until the durable @@ -539,6 +571,11 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { // unhealthy even if its local engine is otherwise caught up. h.recordOtherLine(fact) if info, ok := decodeSelfPeerAssignment(fact, h.cfg.ReplicaID); ok { + if blocked, reason := h.localReadinessBlock(); blocked { + h.log.Printf("blockvolume: volume %s local readiness blocked (%s); NOT admitting supporting replica %s at epoch=%d EV=%d", + h.cfg.VolumeID, reason, info.ReplicaID, info.Epoch, info.EndpointVersion) + return + } h.adpt.OnAssignment(info) h.log.Printf("blockvolume: volume %s admitted as SUPPORTING replica %s at epoch=%d EV=%d behind primary %s; frontend remains gated", h.cfg.VolumeID, info.ReplicaID, info.Epoch, info.EndpointVersion, fact.ReplicaId) @@ -553,6 +590,12 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { return } + if blocked, reason := h.localReadinessBlock(); blocked { + h.log.Printf("blockvolume: volume %s local readiness blocked (%s); NOT applying primary assignment %s@%d to adapter", + h.cfg.VolumeID, reason, fact.ReplicaId, fact.Epoch) + return + } + // Step (2a): install replication peer set first. Decoded via // the separate host-only decodeReplicaTargets path (not through // AssignmentInfo), so the TestNoOtherAssignmentInfoConstruction diff --git a/seaweed-block/core/launcher/k8s_renderer.go b/seaweed-block/core/launcher/k8s_renderer.go index faef00e81e..0284798ec7 100644 --- a/seaweed-block/core/launcher/k8s_renderer.go +++ b/seaweed-block/core/launcher/k8s_renderer.go @@ -18,6 +18,7 @@ type K8sRenderConfig struct { Image string MasterAddr string DurableRootBase string + DurableImpl string StateHostPathBase string RecoveryMode string ReplicationAck string @@ -49,6 +50,14 @@ func RenderBlockVolumeDeployments(plan lifecycle.BlockVolumeWorkloadPlan, cfg K8 if cfg.DurableRootBase == "" { cfg.DurableRootBase = stateMountPath } + if cfg.DurableImpl == "" { + cfg.DurableImpl = "walstore" + } + switch cfg.DurableImpl { + case "walstore", "smartwal": + default: + return nil, fmt.Errorf("launcher: durable impl %q invalid; want walstore or smartwal", cfg.DurableImpl) + } if cfg.StateHostPathBase != "" && path.Clean(cfg.DurableRootBase) != stateMountPath { return nil, fmt.Errorf("launcher: state hostPath requires durable root base %q, got %q", stateMountPath, cfg.DurableRootBase) } @@ -173,7 +182,7 @@ func blockVolumeArgs(plan lifecycle.BlockVolumeWorkloadPlan, replica lifecycle.B "--data-addr=" + replica.DataAddr, "--ctrl-addr=" + replica.CtrlAddr, "--durable-root=" + durableRoot(plan, replica, cfg), - "--durable-impl=walstore", + "--durable-impl=" + cfg.DurableImpl, fmt.Sprintf("--durable-blocks=%d", plan.SizeBytes/4096), "--durable-blocksize=4096", "--recovery-mode=" + cfg.RecoveryMode, diff --git a/seaweed-block/core/launcher/k8s_renderer_test.go b/seaweed-block/core/launcher/k8s_renderer_test.go index a8aeb1ac6f..85787afb14 100644 --- a/seaweed-block/core/launcher/k8s_renderer_test.go +++ b/seaweed-block/core/launcher/k8s_renderer_test.go @@ -36,6 +36,7 @@ func TestG15d_K8sRenderer_RendersBlockVolumeDeploymentArgs(t *testing.T) { "--volume-id=pvc-a", "--replica-id=r1", "--durable-root=/var/lib/sw-block/pvc-a/r1", + "--durable-impl=walstore", "--recovery-mode=dual-lane", "--replication-ack=best-effort", "sw-block.seaweedfs.com/volume: pvc-a", @@ -60,6 +61,33 @@ func TestG15d_K8sRenderer_RendersBlockVolumeDeploymentArgs(t *testing.T) { } } +func TestPhase34_K8sRendererCanRenderSmartWALDurableImpl(t *testing.T) { + manifests, err := RenderBlockVolumeDeployments(sampleWorkloadPlan(), K8sRenderConfig{ + MasterAddr: "m:9333", + DurableImpl: "smartwal", + }) + if err != nil { + t.Fatalf("RenderBlockVolumeDeployments: %v", err) + } + raw := string(manifests[0].YAML) + if !strings.Contains(raw, "--durable-impl=smartwal") { + t.Fatalf("manifest missing smartwal durable impl:\n%s", raw) + } +} + +func TestPhase34_K8sRendererRejectsUnknownDurableImpl(t *testing.T) { + _, err := RenderBlockVolumeDeployments(sampleWorkloadPlan(), K8sRenderConfig{ + MasterAddr: "m:9333", + DurableImpl: "maybe", + }) + if err == nil { + t.Fatal("expected error") + } + if !strings.Contains(err.Error(), "durable impl") { + t.Fatalf("error=%v", err) + } +} + func TestG15d_K8sRenderer_RF2UsesDistinctNamesAndPorts(t *testing.T) { manifests, err := RenderBlockVolumeDeployments(sampleWorkloadPlan(), K8sRenderConfig{MasterAddr: "m:9333"}) if err != nil { diff --git a/seaweed-block/core/ops/cleanup_evidence.go b/seaweed-block/core/ops/cleanup_evidence.go index f82713c37b..3356104682 100644 --- a/seaweed-block/core/ops/cleanup_evidence.go +++ b/seaweed-block/core/ops/cleanup_evidence.go @@ -1,9 +1,12 @@ package ops import ( + "bufio" "fmt" + "os" "strconv" "strings" + "time" ) const ( @@ -17,6 +20,7 @@ const ( CleanupSummaryFailedPhaseKey = "failed_phase" CleanupSummaryReasonCodesKey = "reason_codes" CleanupSummaryEvidenceKey = "cleanup_evidence" + CleanupSummaryObservedAtKey = "cleanup_observed_at" ) type CleanupEvidenceReportRow struct { @@ -39,6 +43,7 @@ func CleanupEvidenceFromSummary(summary map[string]string, evidencePath string) Status: defaultString(summary[CleanupSummaryStatusKey], ObservationStatusUnavailable), EvidenceRef: evidencePath, } + cleanup.ObservedAt = cleanupTimeFromSummary(summary, CleanupSummaryObservedAtKey) cleanup.KubernetesResidueCount = cleanupIntFromSummary(summary, CleanupSummaryKubernetesResidueKey) cleanup.ISCSIResidueCount = cleanupIntFromSummary(summary, CleanupSummaryISCSIResidueKey) cleanup.MultipathResidueCount = cleanupIntFromSummary(summary, CleanupSummaryMultipathResidueKey) @@ -57,6 +62,27 @@ func CleanupEvidenceFromSummary(summary map[string]string, evidencePath string) return cleanup } +func LoadCleanupEvidenceSummary(path string) (*CleanupEvidence, error) { + raw, err := os.Open(path) + if err != nil { + return nil, fmt.Errorf("read cleanup summary: %w", err) + } + defer raw.Close() + summary := map[string]string{} + scanner := bufio.NewScanner(raw) + for scanner.Scan() { + line := strings.TrimSpace(scanner.Text()) + key, value, ok := strings.Cut(line, "=") + if ok { + summary[strings.TrimSpace(key)] = strings.TrimSpace(value) + } + } + if err := scanner.Err(); err != nil { + return nil, fmt.Errorf("read cleanup summary: %w", err) + } + return CleanupEvidenceFromSummary(summary, path), nil +} + func (cleanup CleanupEvidence) ReportSummaryLines() []string { lines := []string{ fmt.Sprintf("%s=%s", CleanupSummaryStatusKey, emptyAsDash(cleanup.Status)), @@ -73,6 +99,9 @@ func (cleanup CleanupEvidence) ReportSummaryLines() []string { if cleanup.EvidenceRef != "" { lines = append(lines, fmt.Sprintf("%s=%s", CleanupSummaryEvidenceKey, cleanup.EvidenceRef)) } + if !cleanup.ObservedAt.IsZero() { + lines = append(lines, fmt.Sprintf("%s=%s", CleanupSummaryObservedAtKey, cleanup.ObservedAt.UTC().Format(time.RFC3339))) + } return lines } @@ -105,3 +134,15 @@ func cleanupIntFromSummary(summary map[string]string, key string) int { } return parsed } + +func cleanupTimeFromSummary(summary map[string]string, key string) time.Time { + value := strings.TrimSpace(summary[key]) + if value == "" { + return time.Time{} + } + parsed, err := time.Parse(time.RFC3339, value) + if err != nil { + return time.Time{} + } + return parsed.UTC() +} diff --git a/seaweed-block/core/ops/cleanup_evidence_test.go b/seaweed-block/core/ops/cleanup_evidence_test.go index 1d7ba012d2..6a7e37ea80 100644 --- a/seaweed-block/core/ops/cleanup_evidence_test.go +++ b/seaweed-block/core/ops/cleanup_evidence_test.go @@ -1,8 +1,11 @@ package ops import ( + "os" + "path/filepath" "strings" "testing" + "time" ) func TestCleanupEvidenceProjectionOwnsSummaryAndReportShape(t *testing.T) { @@ -16,6 +19,7 @@ func TestCleanupEvidenceProjectionOwnsSummaryAndReportShape(t *testing.T) { CleanupSummaryFailureKey: "6", CleanupSummaryFailedPhaseKey: "collect_and_cleanup", CleanupSummaryReasonCodesKey: "k8s_residue,multipath_residue", + CleanupSummaryObservedAtKey: "2026-06-14T12:00:00Z", }, "cleanup-summary.txt") if cleanup == nil { @@ -29,6 +33,7 @@ func TestCleanupEvidenceProjectionOwnsSummaryAndReportShape(t *testing.T) { cleanup.HostPathResidueCount != 5 || cleanup.FailureCount != 6 || cleanup.FailedPhase != "collect_and_cleanup" || + !cleanup.ObservedAt.Equal(time.Date(2026, 6, 14, 12, 0, 0, 0, time.UTC)) || cleanup.EvidenceRef != "cleanup-summary.txt" { t.Fatalf("cleanup evidence=%+v", cleanup) } @@ -47,6 +52,7 @@ func TestCleanupEvidenceProjectionOwnsSummaryAndReportShape(t *testing.T) { "failure_count=6", "failed_phase=collect_and_cleanup", "cleanup_evidence=cleanup-summary.txt", + "cleanup_observed_at=2026-06-14T12:00:00Z", } { if !strings.Contains(lines, want) { t.Fatalf("summary lines missing %q:\n%s", want, lines) @@ -69,6 +75,20 @@ func TestCleanupEvidenceProjectionMarksCleanStatusOK(t *testing.T) { } } +func TestLoadCleanupEvidenceSummary(t *testing.T) { + path := filepath.Join(t.TempDir(), "cleanup-summary.txt") + if err := os.WriteFile(path, []byte("cleanup_status=ok\ncleanup_observed_at=2026-06-16T10:05:00Z\ncleanup_evidence=cleanup-summary.txt\n"), 0o600); err != nil { + t.Fatal(err) + } + cleanup, err := LoadCleanupEvidenceSummary(path) + if err != nil { + t.Fatalf("load: %v", err) + } + if cleanup == nil || cleanup.Status != ObservationStatusOK || cleanup.EvidenceRef != path || cleanup.ObservedAt.IsZero() { + t.Fatalf("cleanup=%+v", cleanup) + } +} + func TestCleanupEvidenceRejectsNegativeCounters(t *testing.T) { cleanup := CleanupEvidenceFromSummary(map[string]string{ CleanupSummaryStatusKey: "failed", diff --git a/seaweed-block/core/ops/cleanup_projection.go b/seaweed-block/core/ops/cleanup_projection.go new file mode 100644 index 0000000000..ae22d61eb2 --- /dev/null +++ b/seaweed-block/core/ops/cleanup_projection.go @@ -0,0 +1,70 @@ +package ops + +const ( + ReasonCleanupVerified = "cleanup_verified" + ReasonCleanupRequired = "cleanup_required" +) + +func cleanupRequired(cleanup *CleanupEvidence) bool { + if cleanup == nil { + return false + } + return cleanup.Status != ObservationStatusOK || + cleanup.KubernetesResidueCount > 0 || + cleanup.ISCSIResidueCount > 0 || + cleanup.MultipathResidueCount > 0 || + cleanup.ProcessResidueCount > 0 || + cleanup.HostPathResidueCount > 0 || + cleanup.FailureCount > 0 +} + +func cleanupReason(cleanup *CleanupEvidence) string { + if cleanup != nil && len(cleanup.ReasonCodes) > 0 && cleanup.ReasonCodes[0] != "" { + return cleanup.ReasonCodes[0] + } + if cleanupRequired(cleanup) { + return ReasonCleanupRequired + } + return ReasonCleanupVerified +} + +func cleanupCondition(cleanup *CleanupEvidence) *ObservationCondition { + if cleanup == nil { + return nil + } + condition := ObservationCondition{ + Type: ConditionCleanupRequired, + Status: "False", + Reason: ReasonCleanupVerified, + Severity: "info", + Message: "cleanup verifier found no Seaweed Block residue", + } + if cleanupRequired(cleanup) { + condition.Status = "True" + condition.Reason = cleanupReason(cleanup) + condition.Severity = "warning" + condition.Message = "cleanup verifier found Seaweed Block residue; run the scripted verifier/cleanup path" + } + return &condition +} + +func cleanupEvidenceRefs(cleanup *CleanupEvidence) []string { + if cleanup == nil || cleanup.EvidenceRef == "" { + return nil + } + return []string{cleanup.EvidenceRef} +} + +func cleanupSafeNextStep(cleanup *CleanupEvidence) *SwBlockSafeNextStep { + if !cleanupRequired(cleanup) { + return nil + } + return &SwBlockSafeNextStep{ + Type: ManagedVolumeActionVerifyCleanup, + Mode: ManagedVolumeActionModeScripted, + Command: `bash scripts/verify-helm-cleanup.sh "$PWD"`, + ReasonCode: cleanupReason(cleanup), + MutationAllowed: false, + EvidenceRefs: cleanupEvidenceRefs(cleanup), + } +} diff --git a/seaweed-block/core/ops/delete_safety_contract.go b/seaweed-block/core/ops/delete_safety_contract.go new file mode 100644 index 0000000000..83810012fe --- /dev/null +++ b/seaweed-block/core/ops/delete_safety_contract.go @@ -0,0 +1,166 @@ +package ops + +import "time" + +const ( + SwBlockVolumeFinalizerName = "block.seaweedfs.com/swblockvolume-protection" + + SwBlockVolumeDeleteActionReleaseFinalizer = "safe_k8s.release_swblockvolume_finalizer" + + DeleteSafetyStateNotRequested = "not_requested" + DeleteSafetyStateRequested = "requested" + DeleteSafetyStateBlocked = "blocked" + DeleteSafetyStateReleasable = "releasable" + DeleteSafetyStateReleased = "released" + + ReasonDeleteNotRequested = "delete_not_requested" + ReasonCleanupEvidenceMissing = "cleanup_evidence_missing" + ReasonCleanupEvidenceStale = "cleanup_evidence_stale" + ReasonDeleteFinalizerReleasable = "finalizer_releasable" + ReasonDeleteFinalizerAdded = "finalizer_added" + ReasonDeleteFinalizerReleased = "finalizer_released" +) + +type SwBlockVolumeDeleteSafetyContract struct { + FinalizerName string `json:"finalizer_name"` + OwnedKind string `json:"owned_kind"` + OwnedMutationScope []string `json:"owned_mutation_scope"` + RequiredFacts []string `json:"required_facts"` + DeleteStates []string `json:"delete_states"` + BlockingReasons []string `json:"blocking_reasons"` + ReleaseReason string `json:"release_reason"` + NonClaims []string `json:"non_claims"` + ReleaseActionType string `json:"release_action_type"` + ReleaseEvidence string `json:"release_evidence"` + BlockedSafeNextAction string `json:"blocked_safe_next_action"` +} + +type SwBlockVolumeDeleteSafetyFacts struct { + DeleteRequested bool `json:"delete_requested"` + FinalizerPresent bool `json:"finalizer_present"` + Cleanup *CleanupEvidence `json:"cleanup,omitempty"` + ObservedAt time.Time `json:"observed_at,omitempty"` + MaxEvidenceAge time.Duration `json:"max_evidence_age,omitempty"` +} + +type SwBlockVolumeDeleteSafetyDecision struct { + ActionType string `json:"action_type"` + Decision string `json:"decision"` + State string `json:"state"` + Reason string `json:"reason"` + FinalizerReleaseAllowed bool `json:"finalizer_release_allowed"` + MissingFacts []string `json:"missing_facts,omitempty"` + EvidenceRefs []string `json:"evidence_refs,omitempty"` + SafeNextAction string `json:"safe_next_action,omitempty"` +} + +func SwBlockVolumeDeleteSafetyContractDefinition() SwBlockVolumeDeleteSafetyContract { + return SwBlockVolumeDeleteSafetyContract{ + FinalizerName: SwBlockVolumeFinalizerName, + OwnedKind: SwBlockVolumeKind, + OwnedMutationScope: []string{ + "swblockvolumes.metadata.finalizers", + "swblockvolumes/status", + "events", + }, + RequiredFacts: []string{ + "identity.volume_id", + "identity.pvc_name", + "identity.pv_name", + "kubernetes.swblockvolume.deletion_timestamp", + "cleanup.status", + "cleanup.k8s_residue_count", + "cleanup.iscsi_residue_count", + "cleanup.multipath_residue_count", + "cleanup.process_residue_count", + "cleanup.hostpath_residue_count", + }, + DeleteStates: []string{ + DeleteSafetyStateNotRequested, + DeleteSafetyStateRequested, + DeleteSafetyStateBlocked, + DeleteSafetyStateReleasable, + DeleteSafetyStateReleased, + }, + BlockingReasons: []string{ + ReasonCleanupEvidenceMissing, + ReasonCleanupRequired, + "iscsi_node_records_present", + "iscsi_sessions_present", + "multipath_maps_present", + "dmsetup_devices_present", + "kubernetes_resources_present", + "hostpath_residue_present", + }, + ReleaseReason: ReasonDeleteFinalizerReleasable, + ReleaseActionType: SwBlockVolumeDeleteActionReleaseFinalizer, + ReleaseEvidence: "cleanup-summary.txt with cleanup_status=ok and all residue counts 0", + BlockedSafeNextAction: ManagedVolumeActionVerifyCleanup, + NonClaims: []string{ + "no_pvc_finalizer_ownership", + "no_automatic_cleanup_execution", + "no_pv_or_pvc_delete", + "no_pod_or_deployment_delete", + "no_iscsi_or_multipath_mutation", + "no_hostpath_delete", + }, + } +} + +func EvaluateSwBlockVolumeDeleteSafety(facts SwBlockVolumeDeleteSafetyFacts) SwBlockVolumeDeleteSafetyDecision { + if !facts.DeleteRequested { + return SwBlockVolumeDeleteSafetyDecision{ + ActionType: SwBlockVolumeDeleteActionReleaseFinalizer, + Decision: ManagedVolumeActionDecisionRejected, + State: DeleteSafetyStateNotRequested, + Reason: ReasonDeleteNotRequested, + } + } + if facts.Cleanup == nil { + return SwBlockVolumeDeleteSafetyDecision{ + ActionType: SwBlockVolumeDeleteActionReleaseFinalizer, + Decision: ManagedVolumeActionDecisionUnknown, + State: DeleteSafetyStateRequested, + Reason: ReasonCleanupEvidenceMissing, + MissingFacts: []string{"cleanup.status"}, + SafeNextAction: ManagedVolumeActionVerifyCleanup, + } + } + if cleanupEvidenceStale(facts) { + return SwBlockVolumeDeleteSafetyDecision{ + ActionType: SwBlockVolumeDeleteActionReleaseFinalizer, + Decision: ManagedVolumeActionDecisionUnknown, + State: DeleteSafetyStateRequested, + Reason: ReasonCleanupEvidenceStale, + MissingFacts: []string{"cleanup.freshness"}, + EvidenceRefs: cleanupEvidenceRefs(facts.Cleanup), + SafeNextAction: ManagedVolumeActionVerifyCleanup, + } + } + if cleanupRequired(facts.Cleanup) { + return SwBlockVolumeDeleteSafetyDecision{ + ActionType: SwBlockVolumeDeleteActionReleaseFinalizer, + Decision: ManagedVolumeActionDecisionRejected, + State: DeleteSafetyStateBlocked, + Reason: cleanupReason(facts.Cleanup), + EvidenceRefs: cleanupEvidenceRefs(facts.Cleanup), + SafeNextAction: ManagedVolumeActionVerifyCleanup, + } + } + return SwBlockVolumeDeleteSafetyDecision{ + ActionType: SwBlockVolumeDeleteActionReleaseFinalizer, + Decision: ManagedVolumeActionDecisionAllowed, + State: DeleteSafetyStateReleasable, + Reason: ReasonDeleteFinalizerReleasable, + FinalizerReleaseAllowed: true, + EvidenceRefs: cleanupEvidenceRefs(facts.Cleanup), + } +} + +func cleanupEvidenceStale(facts SwBlockVolumeDeleteSafetyFacts) bool { + if facts.Cleanup == nil || facts.Cleanup.ObservedAt.IsZero() || + facts.ObservedAt.IsZero() || facts.MaxEvidenceAge <= 0 { + return false + } + return facts.Cleanup.ObservedAt.Add(facts.MaxEvidenceAge).Before(facts.ObservedAt) +} diff --git a/seaweed-block/core/ops/delete_safety_contract_test.go b/seaweed-block/core/ops/delete_safety_contract_test.go new file mode 100644 index 0000000000..b8d07418ba --- /dev/null +++ b/seaweed-block/core/ops/delete_safety_contract_test.go @@ -0,0 +1,173 @@ +package ops + +import ( + "testing" + "time" +) + +func TestSwBlockVolumeDeleteSafetyContract_BoundsFinalizerOwnership(t *testing.T) { + contract := SwBlockVolumeDeleteSafetyContractDefinition() + if contract.FinalizerName != SwBlockVolumeFinalizerName { + t.Fatalf("finalizer=%s", contract.FinalizerName) + } + if contract.OwnedKind != SwBlockVolumeKind { + t.Fatalf("owned kind=%s", contract.OwnedKind) + } + if contract.ReleaseActionType != SwBlockVolumeDeleteActionReleaseFinalizer { + t.Fatalf("release action=%s", contract.ReleaseActionType) + } + for _, want := range []string{ + "swblockvolumes.metadata.finalizers", + "swblockvolumes/status", + "events", + } { + if !stringSliceContains(contract.OwnedMutationScope, want) { + t.Fatalf("mutation scope missing %s: %+v", want, contract.OwnedMutationScope) + } + } + for _, forbidden := range []string{ + "persistentvolumeclaims", + "persistentvolumes", + "pods", + "deployments", + "storageclasses", + "iscsi", + "multipath", + "hostpath", + } { + if stringSliceContains(contract.OwnedMutationScope, forbidden) { + t.Fatalf("mutation scope includes forbidden target %s: %+v", forbidden, contract.OwnedMutationScope) + } + } + for _, want := range []string{ + "identity.volume_id", + "identity.pvc_name", + "identity.pv_name", + "kubernetes.swblockvolume.deletion_timestamp", + "cleanup.status", + "cleanup.iscsi_residue_count", + "cleanup.multipath_residue_count", + "cleanup.hostpath_residue_count", + } { + if !stringSliceContains(contract.RequiredFacts, want) { + t.Fatalf("required facts missing %s: %+v", want, contract.RequiredFacts) + } + } + for _, want := range []string{ + DeleteSafetyStateNotRequested, + DeleteSafetyStateRequested, + DeleteSafetyStateBlocked, + DeleteSafetyStateReleasable, + DeleteSafetyStateReleased, + } { + if !stringSliceContains(contract.DeleteStates, want) { + t.Fatalf("delete states missing %s: %+v", want, contract.DeleteStates) + } + } + for _, want := range []string{ + "no_pvc_finalizer_ownership", + "no_automatic_cleanup_execution", + "no_iscsi_or_multipath_mutation", + "no_hostpath_delete", + } { + if !stringSliceContains(contract.NonClaims, want) { + t.Fatalf("non-claims missing %s: %+v", want, contract.NonClaims) + } + } +} + +func TestEvaluateSwBlockVolumeDeleteSafety_NotRequested(t *testing.T) { + decision := EvaluateSwBlockVolumeDeleteSafety(SwBlockVolumeDeleteSafetyFacts{}) + if decision.State != DeleteSafetyStateNotRequested || + decision.Decision != ManagedVolumeActionDecisionRejected || + decision.Reason != ReasonDeleteNotRequested || + decision.FinalizerReleaseAllowed { + t.Fatalf("decision=%+v", decision) + } +} + +func TestEvaluateSwBlockVolumeDeleteSafety_UnknownWithoutCleanupEvidence(t *testing.T) { + decision := EvaluateSwBlockVolumeDeleteSafety(SwBlockVolumeDeleteSafetyFacts{ + DeleteRequested: true, + FinalizerPresent: true, + }) + if decision.State != DeleteSafetyStateRequested || + decision.Decision != ManagedVolumeActionDecisionUnknown || + decision.Reason != ReasonCleanupEvidenceMissing || + decision.FinalizerReleaseAllowed || + decision.SafeNextAction != ManagedVolumeActionVerifyCleanup { + t.Fatalf("decision=%+v", decision) + } + if !stringSliceContains(decision.MissingFacts, "cleanup.status") { + t.Fatalf("missing facts=%+v", decision.MissingFacts) + } +} + +func TestEvaluateSwBlockVolumeDeleteSafety_BlocksWithResidue(t *testing.T) { + decision := EvaluateSwBlockVolumeDeleteSafety(SwBlockVolumeDeleteSafetyFacts{ + DeleteRequested: true, + FinalizerPresent: true, + Cleanup: &CleanupEvidence{ + Status: ObservationStatusBlocked, + ISCSIResidueCount: 1, + ReasonCodes: []string{"iscsi_node_records_present"}, + EvidenceRef: "cleanup-summary.txt", + }, + }) + if decision.State != DeleteSafetyStateBlocked || + decision.Decision != ManagedVolumeActionDecisionRejected || + decision.Reason != "iscsi_node_records_present" || + decision.FinalizerReleaseAllowed || + decision.SafeNextAction != ManagedVolumeActionVerifyCleanup { + t.Fatalf("decision=%+v", decision) + } + if !stringSliceContains(decision.EvidenceRefs, "cleanup-summary.txt") { + t.Fatalf("evidence refs=%+v", decision.EvidenceRefs) + } +} + +func TestEvaluateSwBlockVolumeDeleteSafety_UnknownWithStaleCleanupEvidence(t *testing.T) { + now := time.Date(2026, 6, 14, 12, 0, 0, 0, time.UTC) + decision := EvaluateSwBlockVolumeDeleteSafety(SwBlockVolumeDeleteSafetyFacts{ + DeleteRequested: true, + FinalizerPresent: true, + ObservedAt: now, + MaxEvidenceAge: 15 * time.Minute, + Cleanup: &CleanupEvidence{ + Status: ObservationStatusOK, + ObservedAt: now.Add(-16 * time.Minute), + EvidenceRef: "cleanup-summary.txt", + }, + }) + if decision.State != DeleteSafetyStateRequested || + decision.Decision != ManagedVolumeActionDecisionUnknown || + decision.Reason != ReasonCleanupEvidenceStale || + decision.FinalizerReleaseAllowed || + decision.SafeNextAction != ManagedVolumeActionVerifyCleanup { + t.Fatalf("decision=%+v", decision) + } + if !stringSliceContains(decision.MissingFacts, "cleanup.freshness") { + t.Fatalf("missing facts=%+v", decision.MissingFacts) + } +} + +func TestEvaluateSwBlockVolumeDeleteSafety_ReleasableWithCleanCleanupEvidence(t *testing.T) { + decision := EvaluateSwBlockVolumeDeleteSafety(SwBlockVolumeDeleteSafetyFacts{ + DeleteRequested: true, + FinalizerPresent: true, + Cleanup: &CleanupEvidence{ + Status: ObservationStatusOK, + EvidenceRef: "cleanup-summary.txt", + }, + }) + if decision.State != DeleteSafetyStateReleasable || + decision.Decision != ManagedVolumeActionDecisionAllowed || + decision.Reason != ReasonDeleteFinalizerReleasable || + !decision.FinalizerReleaseAllowed || + decision.SafeNextAction != "" { + t.Fatalf("decision=%+v", decision) + } + if !stringSliceContains(decision.EvidenceRefs, "cleanup-summary.txt") { + t.Fatalf("evidence refs=%+v", decision.EvidenceRefs) + } +} diff --git a/seaweed-block/core/ops/install_drift.go b/seaweed-block/core/ops/install_drift.go new file mode 100644 index 0000000000..c2ae663268 --- /dev/null +++ b/seaweed-block/core/ops/install_drift.go @@ -0,0 +1,117 @@ +package ops + +import "strings" + +const ( + InstallDriftStatusOK = "ok" + InstallDriftStatusMismatch = "mismatch" + InstallDriftStatusUnknown = "unknown" +) + +func InstallDriftEvidenceFromSummary(summary map[string]string, evidenceRef string) *InstallDriftEvidence { + if len(summary) == 0 { + return nil + } + drift := &InstallDriftEvidence{ + Status: strings.TrimSpace(summary["install_drift_status"]), + ReasonCode: strings.TrimSpace(summary["reason"]), + ChartName: strings.TrimSpace(summary["chart_name"]), + CurrentChartVersion: firstNonEmpty(summary["current_chart_version"], summary["chart_version"]), + DesiredChartVersion: strings.TrimSpace(summary["desired_chart_version"]), + CurrentAppVersion: firstNonEmpty(summary["current_app_version"], summary["chart_app_version"]), + DesiredAppVersion: strings.TrimSpace(summary["desired_app_version"]), + CurrentImage: strings.TrimSpace(summary["current_image"]), + DesiredImage: strings.TrimSpace(summary["desired_image"]), + CurrentCSIImage: strings.TrimSpace(summary["current_csi_image"]), + DesiredCSIImage: strings.TrimSpace(summary["desired_csi_image"]), + CurrentOperatorImage: strings.TrimSpace(summary["current_operator_image"]), + DesiredOperatorImage: strings.TrimSpace(summary["desired_operator_image"]), + EvidenceRef: evidenceRef, + } + if drift.Status == "" { + drift.Status = deriveInstallDriftStatus(drift) + } + if drift.ReasonCode == "" { + drift.ReasonCode = installDriftReason(drift.Status) + } + return drift +} + +func installDriftCondition(drift *InstallDriftEvidence) *ObservationCondition { + if drift == nil { + return nil + } + switch drift.Status { + case InstallDriftStatusOK: + return &ObservationCondition{ + Type: ConditionReady, + Status: "True", + Reason: installDriftReason(drift.Status), + Severity: "info", + Message: "install evidence is aligned", + EvidenceRefs: installDriftEvidenceRefs(drift), + } + case InstallDriftStatusMismatch: + return &ObservationCondition{ + Type: ConditionBlocked, + Status: "True", + Reason: installDriftReason(drift.Status), + Severity: "warning", + Message: "install evidence does not match desired release identity", + EvidenceRefs: installDriftEvidenceRefs(drift), + } + default: + return &ObservationCondition{ + Type: ConditionEvidenceStale, + Status: "True", + Reason: installDriftReason(drift.Status), + Severity: "warning", + Message: "install drift evidence is missing or incomplete", + EvidenceRefs: installDriftEvidenceRefs(drift), + } + } +} + +func installDriftEvidenceRefs(drift *InstallDriftEvidence) []string { + if drift == nil || drift.EvidenceRef == "" { + return nil + } + return []string{drift.EvidenceRef} +} + +func installDriftReason(status string) string { + switch status { + case InstallDriftStatusOK: + return ReasonInstallDriftAligned + case InstallDriftStatusMismatch: + return ReasonInstallDriftMismatch + default: + return ReasonInstallDriftEvidenceMissing + } +} + +func deriveInstallDriftStatus(drift *InstallDriftEvidence) string { + pairs := [][2]string{ + {drift.CurrentChartVersion, drift.DesiredChartVersion}, + {drift.CurrentAppVersion, drift.DesiredAppVersion}, + {drift.CurrentImage, drift.DesiredImage}, + {drift.CurrentCSIImage, drift.DesiredCSIImage}, + {drift.CurrentOperatorImage, drift.DesiredOperatorImage}, + } + observed := false + for _, pair := range pairs { + current := strings.TrimSpace(pair[0]) + desired := strings.TrimSpace(pair[1]) + if current == "" && desired == "" { + continue + } + observed = true + if current == "" || desired == "" || current != desired { + return InstallDriftStatusMismatch + } + } + if !observed { + return InstallDriftStatusUnknown + } + return InstallDriftStatusOK +} diff --git a/seaweed-block/core/ops/install_drift_test.go b/seaweed-block/core/ops/install_drift_test.go new file mode 100644 index 0000000000..d2d5a54664 --- /dev/null +++ b/seaweed-block/core/ops/install_drift_test.go @@ -0,0 +1,32 @@ +package ops + +import "testing" + +func TestInstallDriftEvidenceFromSummary_DerivesAlignedMismatchAndMissing(t *testing.T) { + aligned := InstallDriftEvidenceFromSummary(map[string]string{ + "current_image": "sw-block:sha-a", + "desired_image": "sw-block:sha-a", + "current_csi_image": "sw-block-csi:sha-a", + "desired_csi_image": "sw-block-csi:sha-a", + "current_chart_version": "0.3.5", + "desired_chart_version": "0.3.5", + }, "install-drift-summary.txt") + if aligned.Status != InstallDriftStatusOK || aligned.ReasonCode != ReasonInstallDriftAligned { + t.Fatalf("aligned=%+v", aligned) + } + + mismatch := InstallDriftEvidenceFromSummary(map[string]string{ + "current_image": "sw-block:old", + "desired_image": "sw-block:new", + }, "install-drift-summary.txt") + if mismatch.Status != InstallDriftStatusMismatch || mismatch.ReasonCode != ReasonInstallDriftMismatch { + t.Fatalf("mismatch=%+v", mismatch) + } + + missing := InstallDriftEvidenceFromSummary(map[string]string{ + "install_drift_status": InstallDriftStatusUnknown, + }, "install-drift-summary.txt") + if missing.Status != InstallDriftStatusUnknown || missing.ReasonCode != ReasonInstallDriftEvidenceMissing { + t.Fatalf("missing=%+v", missing) + } +} diff --git a/seaweed-block/core/ops/kubernetes_crd_manifests_test.go b/seaweed-block/core/ops/kubernetes_crd_manifests_test.go new file mode 100644 index 0000000000..5482c6cd39 --- /dev/null +++ b/seaweed-block/core/ops/kubernetes_crd_manifests_test.go @@ -0,0 +1,339 @@ +package ops + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "gopkg.in/yaml.v3" +) + +func TestPhase35D1CRDManifestsMatchManagedVolumeContract(t *testing.T) { + contract := ManagedVolumeCRDContractDefinition() + for _, tc := range []struct { + path string + name string + kind string + plural string + singular string + }{ + { + path: "charts/seaweed-block/crds/swblockclusters.block.seaweedfs.com.yaml", + name: "swblockclusters.block.seaweedfs.com", + kind: SwBlockClusterKind, + plural: "swblockclusters", + singular: "swblockcluster", + }, + { + path: "charts/seaweed-block/crds/swblockvolumes.block.seaweedfs.com.yaml", + name: "swblockvolumes.block.seaweedfs.com", + kind: SwBlockVolumeKind, + plural: "swblockvolumes", + singular: "swblockvolume", + }, + } { + t.Run(tc.kind, func(t *testing.T) { + doc := readYAMLMap(t, tc.path) + assertYAMLString(t, doc, "apiVersion", "apiextensions.k8s.io/v1") + assertYAMLString(t, doc, "kind", "CustomResourceDefinition") + + metadata := yamlMap(t, doc, "metadata") + assertYAMLString(t, metadata, "name", tc.name) + + spec := yamlMap(t, doc, "spec") + assertYAMLString(t, spec, "group", contract.Group) + assertYAMLString(t, spec, "scope", "Namespaced") + + names := yamlMap(t, spec, "names") + assertYAMLString(t, names, "kind", tc.kind) + assertYAMLString(t, names, "plural", tc.plural) + assertYAMLString(t, names, "singular", tc.singular) + + versions := yamlSlice(t, spec, "versions") + if len(versions) != 1 { + t.Fatalf("%s versions=%d want 1", tc.kind, len(versions)) + } + version := yamlMapFromValue(t, versions[0]) + assertYAMLString(t, version, "name", contract.Version) + assertYAMLBool(t, version, "served", true) + assertYAMLBool(t, version, "storage", true) + if _, ok := yamlMap(t, version, "subresources")["status"]; !ok { + t.Fatalf("%s missing status subresource", tc.kind) + } + + statusSchema := yamlMap(t, + yamlMap(t, + yamlMap(t, + yamlMap(t, version, "schema"), + "openAPIV3Schema"), + "properties"), + "status") + properties := yamlMap(t, statusSchema, "properties") + if _, ok := properties["conditions"]; !ok { + t.Fatalf("%s status schema missing conditions", tc.kind) + } + if _, ok := properties["evidenceRefs"]; !ok { + t.Fatalf("%s status schema missing evidenceRefs", tc.kind) + } + }) + } +} + +func TestPhase35D1SwBlockVolumeConditionEnumCoversContract(t *testing.T) { + doc := readYAMLMap(t, "charts/seaweed-block/crds/swblockvolumes.block.seaweedfs.com.yaml") + conditionType := yamlMap(t, + yamlMap(t, + yamlMap(t, + yamlMap(t, + yamlMap(t, + yamlMap(t, + yamlMap(t, + yamlMap(t, + yamlMap(t, + yamlSlice(t, yamlMap(t, doc, "spec"), "versions")[0].(map[string]any), + "schema"), + "openAPIV3Schema"), + "properties"), + "status"), + "properties"), + "conditions"), + "items"), + "properties"), + "type") + enum := yamlStringSet(t, conditionType, "enum") + for _, want := range []string{ + ConditionReady, + ConditionRecovered, + ConditionRecovering, + ConditionBlocked, + ConditionInvalid, + ConditionCleanupRequired, + ConditionEvidenceStale, + } { + if !enum[want] { + t.Fatalf("condition enum missing %s: %+v", want, enum) + } + } +} + +func TestPhase36D1SwBlockClusterActionabilitySchema(t *testing.T) { + doc := readYAMLMap(t, "charts/seaweed-block/crds/swblockclusters.block.seaweedfs.com.yaml") + statusProperties := crdStatusProperties(t, doc) + for _, want := range []string{"nodes", "cleanup", "supportBundleRefs", "safeNextSteps"} { + if _, ok := statusProperties[want]; !ok { + t.Fatalf("SwBlockCluster status schema missing %s", want) + } + } + + nodeProperties := yamlMap(t, yamlMap(t, statusProperties, "nodes"), "items") + nodeProperties = yamlMap(t, nodeProperties, "properties") + for _, want := range []string{"name", "kubernetesNode", "internalIP", "schedulable", "ready", "status", "reasonCode", "conditions", "evidenceRefs"} { + if _, ok := nodeProperties[want]; !ok { + t.Fatalf("SwBlockCluster.status.nodes[] schema missing %s", want) + } + } + + cleanupProperties := yamlMap(t, yamlMap(t, statusProperties, "cleanup"), "properties") + for _, want := range []string{"status", "k8sResidueCount", "iscsiResidueCount", "multipathResidueCount", "processResidueCount", "hostPathResidueCount", "failureCount", "evidenceRef"} { + if _, ok := cleanupProperties[want]; !ok { + t.Fatalf("SwBlockCluster.status.cleanup schema missing %s", want) + } + } + + installDriftProperties := yamlMap(t, yamlMap(t, statusProperties, "installDrift"), "properties") + for _, want := range []string{"status", "reasonCode", "currentImage", "desiredImage", "currentCsiImage", "desiredCsiImage", "evidenceRef"} { + if _, ok := installDriftProperties[want]; !ok { + t.Fatalf("SwBlockCluster.status.installDrift schema missing %s", want) + } + } + + stepProperties := yamlMap(t, yamlMap(t, yamlMap(t, statusProperties, "safeNextSteps"), "items"), "properties") + for _, want := range []string{"type", "mode", "command", "reasonCode", "mutationAllowed", "evidenceRefs"} { + if _, ok := stepProperties[want]; !ok { + t.Fatalf("SwBlockCluster.status.safeNextSteps[] schema missing %s", want) + } + } +} + +func TestPhase38D3SwBlockVolumeAllowedActionEvaluationSchema(t *testing.T) { + doc := readYAMLMap(t, "charts/seaweed-block/crds/swblockvolumes.block.seaweedfs.com.yaml") + statusProperties := crdStatusProperties(t, doc) + actionProperties := yamlMap(t, yamlMap(t, yamlMap(t, statusProperties, "allowedActions"), "items"), "properties") + for _, want := range []string{"type", "mode", "sideEffectClass", "ownerExecutor", "decision", "decisionReason", "missingFacts", "mutationAllowed", "preconditions", "invariantRefs", "evidenceRequired", "evidenceRefs"} { + if _, ok := actionProperties[want]; !ok { + t.Fatalf("SwBlockVolume.status.allowedActions[] schema missing %s", want) + } + } + if _, ok := actionProperties["evidence_required"]; ok { + t.Fatalf("SwBlockVolume.status.allowedActions[] schema leaked snake_case evidence_required") + } + modeEnum := yamlStringSet(t, yamlMap(t, actionProperties, "mode"), "enum") + for _, want := range []string{"read_only", "dry_run", "scripted"} { + if !modeEnum[want] { + t.Fatalf("SwBlockVolume.status.allowedActions[].mode enum missing %s: %+v", want, modeEnum) + } + } +} + +func TestPhase39D2SwBlockVolumeDeleteSafetySchema(t *testing.T) { + doc := readYAMLMap(t, "charts/seaweed-block/crds/swblockvolumes.block.seaweedfs.com.yaml") + statusProperties := crdStatusProperties(t, doc) + deleteSafetyProperties := yamlMap(t, yamlMap(t, statusProperties, "deleteSafety"), "properties") + for _, want := range []string{"actionType", "decision", "state", "reason", "finalizerReleaseAllowed", "missingFacts", "evidenceRefs", "safeNextAction"} { + if _, ok := deleteSafetyProperties[want]; !ok { + t.Fatalf("SwBlockVolume.status.deleteSafety schema missing %s", want) + } + } + for _, forbidden := range []string{"action_type", "finalizer_release_allowed", "safe_next_action"} { + if _, ok := deleteSafetyProperties[forbidden]; ok { + t.Fatalf("SwBlockVolume.status.deleteSafety schema leaked snake_case %s", forbidden) + } + } +} + +func TestOperatorStatusRBACIsStatusEventsOnly(t *testing.T) { + raw := readRepoFile(t, "charts/seaweed-block/templates/operator-status-rbac.yaml") + required := []string{ + `resources: ["nodes", "pods"]`, + `resources: ["csidrivers", "csinodes"]`, + `resources: ["swblockclusters", "swblockvolumes"]`, + `verbs: ["get", "list", "watch"]`, + `resources: ["swblockclusters/status", "swblockvolumes/status"]`, + `verbs: ["get", "update", "patch"]`, + `resources: ["events"]`, + `verbs: ["create"]`, + } + for _, want := range required { + if !strings.Contains(raw, want) { + t.Fatalf("operator RBAC missing %q\n%s", want, raw) + } + } + for _, forbidden := range []string{ + `resources: ["persistentvolumes"`, + `resources: ["persistentvolumeclaims"`, + `resources: ["deployments"`, + `resources: ["secrets"`, + `resources: ["storageclasses"`, + `resources: ["swblockvolumes/finalizers"]`, + `"delete"`, + } { + if strings.Contains(raw, forbidden) { + t.Fatalf("operator status RBAC contains forbidden fragment %q\n%s", forbidden, raw) + } + } +} + +func TestPhase35D1OperatorStatusRBACDefaultDisabled(t *testing.T) { + values := readYAMLMap(t, "charts/seaweed-block/values.yaml") + operatorStatus := yamlMap(t, values, "operatorStatus") + assertYAMLBool(t, operatorStatus, "create", false) + rbac := yamlMap(t, operatorStatus, "rbac") + assertYAMLBool(t, rbac, "create", true) +} + +func crdStatusProperties(t *testing.T, doc map[string]any) map[string]any { + t.Helper() + return yamlMap(t, + yamlMap(t, + yamlMap(t, + yamlMap(t, + yamlMap(t, + yamlSlice(t, yamlMap(t, doc, "spec"), "versions")[0].(map[string]any), + "schema"), + "openAPIV3Schema"), + "properties"), + "status"), + "properties") +} + +func TestPhase35D3OperatorStatusDeploymentCanRunDryRunOrStatusWriteMode(t *testing.T) { + raw := readRepoFile(t, "charts/seaweed-block/templates/operator-status.yaml") + for _, want := range []string{ + `kind: Deployment`, + `name: sw-block-operator-status`, + `serviceAccountName: {{ include "seaweed-block.fullname" . }}-operator-status`, + `command: ["/usr/local/bin/sw-block"]`, + `- "operator-status"`, + `{{- if .Values.operatorStatus.dryRun }}`, + `- "--dry-run"`, + `- "--master-api={{ include "seaweed-block.blockmasterAddress" . }}"`, + `- "--interval={{ .Values.operatorStatus.interval }}"`, + } { + if !strings.Contains(raw, want) { + t.Fatalf("operator-status deployment missing %q\n%s", want, raw) + } + } +} + +func readRepoFile(t *testing.T, repoPath string) string { + t.Helper() + raw, err := os.ReadFile(filepath.Join("..", "..", filepath.FromSlash(repoPath))) + if err != nil { + t.Fatalf("read %s: %v", repoPath, err) + } + return string(raw) +} + +func readYAMLMap(t *testing.T, repoPath string) map[string]any { + t.Helper() + var out map[string]any + if err := yaml.Unmarshal([]byte(readRepoFile(t, repoPath)), &out); err != nil { + t.Fatalf("unmarshal %s: %v", repoPath, err) + } + return out +} + +func yamlMap(t *testing.T, in map[string]any, key string) map[string]any { + t.Helper() + out, ok := in[key].(map[string]any) + if !ok { + t.Fatalf("key %q is %T, want map", key, in[key]) + } + return out +} + +func yamlMapFromValue(t *testing.T, in any) map[string]any { + t.Helper() + out, ok := in.(map[string]any) + if !ok { + t.Fatalf("value is %T, want map", in) + } + return out +} + +func yamlSlice(t *testing.T, in map[string]any, key string) []any { + t.Helper() + out, ok := in[key].([]any) + if !ok { + t.Fatalf("key %q is %T, want slice", key, in[key]) + } + return out +} + +func assertYAMLString(t *testing.T, in map[string]any, key, want string) { + t.Helper() + if got, _ := in[key].(string); got != want { + t.Fatalf("key %q=%q want %q", key, got, want) + } +} + +func assertYAMLBool(t *testing.T, in map[string]any, key string, want bool) { + t.Helper() + if got, _ := in[key].(bool); got != want { + t.Fatalf("key %q=%t want %t", key, got, want) + } +} + +func yamlStringSet(t *testing.T, in map[string]any, key string) map[string]bool { + t.Helper() + out := map[string]bool{} + for _, item := range yamlSlice(t, in, key) { + s, ok := item.(string) + if !ok { + t.Fatalf("enum item is %T, want string", item) + } + out[s] = true + } + return out +} diff --git a/seaweed-block/core/ops/kubernetes_node_evidence.go b/seaweed-block/core/ops/kubernetes_node_evidence.go new file mode 100644 index 0000000000..d03ae39cb6 --- /dev/null +++ b/seaweed-block/core/ops/kubernetes_node_evidence.go @@ -0,0 +1,439 @@ +package ops + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "sort" +) + +const csiNodeAppLabel = "sw-block-csi-node" + +func (c *KubernetesStatusClient) EnrichNodeEvidence(ctx context.Context, namespace string, cluster ClusterEvidence) (ClusterEvidence, error) { + nodes, err := c.readKubernetesNodes(ctx) + if err != nil { + return cluster, err + } + csiPods, err := c.readCSINodePods(ctx, namespace) + if err != nil { + return cluster, err + } + driverExists, err := c.csiDriverExists(ctx) + if err != nil { + return cluster, err + } + registered, err := c.readCSINodeDriverRegistrations(ctx) + if err != nil { + return cluster, err + } + return mergeLiveNodeEvidence(namespace, cluster, nodes, csiPods, driverExists, registered), nil +} + +func (c *KubernetesStatusClient) readKubernetesNodes(ctx context.Context) ([]kubernetesNodeFact, error) { + var list kubernetesNodeList + if err := c.getJSON(ctx, "/api/v1/nodes", &list); err != nil { + return nil, fmt.Errorf("read Kubernetes nodes: %w", err) + } + out := make([]kubernetesNodeFact, 0, len(list.Items)) + for _, item := range list.Items { + fact := kubernetesNodeFact{ + Name: item.Metadata.Name, + InternalIP: item.internalIP(), + Ready: item.ready(), + Schedulable: !item.Spec.Unschedulable, + } + out = append(out, fact) + } + sort.SliceStable(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + return out, nil +} + +func (c *KubernetesStatusClient) readCSINodePods(ctx context.Context, namespace string) (map[string]kubernetesPodFact, error) { + var list kubernetesPodList + path := "/api/v1/namespaces/" + pathEscape(namespace) + "/pods?labelSelector=app%3D" + pathEscape(csiNodeAppLabel) + if err := c.getJSON(ctx, path, &list); err != nil { + return nil, fmt.Errorf("read CSI node pods: %w", err) + } + out := map[string]kubernetesPodFact{} + for _, item := range list.Items { + nodeName := item.Spec.NodeName + if nodeName == "" { + continue + } + out[nodeName] = kubernetesPodFact{ + Name: item.Metadata.Name, + NodeName: nodeName, + Ready: item.ready(), + Namespace: namespace, + Images: item.images(), + MissingImages: item.imagePullMissingImages(), + } + } + return out, nil +} + +func (c *KubernetesStatusClient) csiDriverExists(ctx context.Context) (bool, error) { + var driver kubernetesMetadataObject + err := c.getJSON(ctx, "/apis/storage.k8s.io/v1/csidrivers/"+pathEscape(seaweedBlockCSIDriver), &driver) + if err == nil { + return true, nil + } + if isKubernetesNotFound(err) { + return false, nil + } + return false, fmt.Errorf("read CSIDriver: %w", err) +} + +func (c *KubernetesStatusClient) readCSINodeDriverRegistrations(ctx context.Context) (map[string]bool, error) { + var list kubernetesCSINodeList + if err := c.getJSON(ctx, "/apis/storage.k8s.io/v1/csinodes", &list); err != nil { + return nil, fmt.Errorf("read CSINodes: %w", err) + } + out := map[string]bool{} + for _, item := range list.Items { + for _, driver := range item.Spec.Drivers { + if driver.Name == seaweedBlockCSIDriver { + out[item.Metadata.Name] = true + break + } + } + } + return out, nil +} + +func (c *KubernetesStatusClient) getJSON(ctx context.Context, path string, out any) error { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.apiURL(path), nil) + if err != nil { + return err + } + req.Header.Set("Accept", "application/json") + if c.BearerToken != "" { + req.Header.Set("Authorization", "Bearer "+c.BearerToken) + } + client := c.HTTPClient + if client == nil { + client = http.DefaultClient + } + resp, err := client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode >= 200 && resp.StatusCode < 300 { + return json.NewDecoder(resp.Body).Decode(out) + } + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + return kubernetesAPIError{StatusCode: resp.StatusCode, Body: string(raw)} +} + +func (c *KubernetesStatusClient) apiURL(path string) string { + return stringsTrimRightSlash(c.BaseURL) + path +} + +func mergeLiveNodeEvidence(namespace string, cluster ClusterEvidence, nodes []kubernetesNodeFact, csiPods map[string]kubernetesPodFact, driverExists bool, registered map[string]bool) ClusterEvidence { + byKubernetesNode := map[string]int{} + for i, node := range cluster.Nodes { + if node.KubernetesNode != "" { + byKubernetesNode[node.KubernetesNode] = i + } + if node.NodeName != "" { + byKubernetesNode[node.NodeName] = i + } + } + for _, fact := range nodes { + idx, ok := byKubernetesNode[fact.Name] + if !ok { + cluster.Nodes = append(cluster.Nodes, NodeEvidence{NodeName: fact.Name, KubernetesNode: fact.Name}) + idx = len(cluster.Nodes) - 1 + } + node := cluster.Nodes[idx] + if node.NodeName == "" { + node.NodeName = fact.Name + } + node.KubernetesNode = fact.Name + node.InternalIP = firstNonEmptyString(node.InternalIP, fact.InternalIP) + node.Ready = fact.Ready + node.Schedulable = fact.Schedulable + node.RequiredImages = appendUniqueStrings(node.RequiredImages, csiPods[fact.Name].Images...) + node.MissingImages = appendUniqueStrings(node.MissingImages, csiPods[fact.Name].MissingImages...) + node.Conditions = mergeNodeKubernetesConditions(node.Conditions, fact) + node.Conditions = mergeNodeCSIEvidence(node.Conditions, namespace, fact.Name, csiPods[fact.Name], driverExists, registered[fact.Name]) + cluster.Nodes[idx] = node + } + sort.SliceStable(cluster.Nodes, func(i, j int) bool { + return firstNonEmptyString(cluster.Nodes[i].KubernetesNode, cluster.Nodes[i].NodeName) < + firstNonEmptyString(cluster.Nodes[j].KubernetesNode, cluster.Nodes[j].NodeName) + }) + return cluster +} + +func mergeNodeKubernetesConditions(conditions []ObservationCondition, fact kubernetesNodeFact) []ObservationCondition { + if !fact.Ready { + conditions = append(conditions, ObservationCondition{ + Type: ConditionReady, + Status: "Unknown", + Reason: ReasonNodeNotReady, + Severity: "warning", + Message: "Kubernetes node Ready condition is not True", + EvidenceRefs: []string{"kubernetes/node/" + fact.Name}, + }) + } + if !fact.Schedulable { + conditions = append(conditions, ObservationCondition{ + Type: ConditionBlocked, + Status: "True", + Reason: ReasonNodeSchedulingDisabled, + Severity: "warning", + Message: "Kubernetes node is marked unschedulable", + EvidenceRefs: []string{"kubernetes/node/" + fact.Name}, + }) + } + return conditions +} + +func mergeNodeCSIEvidence(conditions []ObservationCondition, namespace, nodeName string, pod kubernetesPodFact, driverExists, registered bool) []ObservationCondition { + if len(pod.MissingImages) > 0 { + conditions = append(conditions, ObservationCondition{ + Type: ConditionReady, + Status: "False", + Reason: ReasonImageMissingOnNode, + Severity: "warning", + Message: "Seaweed Block CSI node pod has image-pull failure", + EvidenceRefs: []string{"kubernetes/pod/" + firstNonEmptyString(pod.Namespace, namespace) + "/" + firstNonEmptyString(pod.Name, "missing")}, + }) + return conditions + } + if !driverExists || !registered { + conditions = append(conditions, ObservationCondition{ + Type: ConditionReady, + Status: "False", + Reason: ReasonCSIDriverNotRegistered, + Severity: "warning", + Message: "Seaweed Block CSI driver is not registered on this node", + EvidenceRefs: []string{"kubernetes/csidriver/" + seaweedBlockCSIDriver, "kubernetes/csinode/" + nodeName}, + }) + } + if !pod.Ready && len(pod.MissingImages) == 0 { + conditions = append(conditions, ObservationCondition{ + Type: ConditionReady, + Status: "False", + Reason: ReasonCSINodePodNotReady, + Severity: "warning", + Message: "Seaweed Block CSI node pod is not Ready on this node", + EvidenceRefs: []string{"kubernetes/pod/" + firstNonEmptyString(pod.Namespace, namespace) + "/" + firstNonEmptyString(pod.Name, "missing")}, + }) + } + return conditions +} + +func isKubernetesNotFound(err error) bool { + apiErr, ok := err.(kubernetesAPIError) + return ok && apiErr.StatusCode == http.StatusNotFound +} + +type kubernetesAPIError struct { + StatusCode int + Body string +} + +func (e kubernetesAPIError) Error() string { + return fmt.Sprintf("http %d %s", e.StatusCode, e.Body) +} + +type kubernetesNodeFact struct { + Name string + InternalIP string + Ready bool + Schedulable bool +} + +type kubernetesPodFact struct { + Name string + Namespace string + NodeName string + Ready bool + Images []string + MissingImages []string +} + +type kubernetesMetadataObject struct { + Metadata kubernetesObjectMeta `json:"metadata"` +} + +type kubernetesObjectMeta struct { + Name string `json:"name"` +} + +type kubernetesNodeList struct { + Items []kubernetesNodeObject `json:"items"` +} + +type kubernetesNodeObject struct { + Metadata kubernetesObjectMeta `json:"metadata"` + Spec struct { + Unschedulable bool `json:"unschedulable"` + } `json:"spec"` + Status struct { + Addresses []kubernetesNodeAddress `json:"addresses"` + Conditions []kubernetesNodeCondition `json:"conditions"` + } `json:"status"` +} + +type kubernetesNodeAddress struct { + Type string `json:"type"` + Address string `json:"address"` +} + +type kubernetesNodeCondition struct { + Type string `json:"type"` + Status string `json:"status"` +} + +func (n kubernetesNodeObject) internalIP() string { + for _, address := range n.Status.Addresses { + if address.Type == "InternalIP" { + return address.Address + } + } + return "" +} + +func (n kubernetesNodeObject) ready() bool { + for _, condition := range n.Status.Conditions { + if condition.Type == "Ready" { + return condition.Status == "True" + } + } + return false +} + +type kubernetesPodList struct { + Items []kubernetesPodObject `json:"items"` +} + +type kubernetesPodObject struct { + Metadata kubernetesObjectMeta `json:"metadata"` + Spec struct { + NodeName string `json:"nodeName"` + Containers []kubernetesContainer `json:"containers"` + InitContainers []kubernetesContainer `json:"initContainers"` + } `json:"spec"` + Status struct { + Conditions []kubernetesPodCondition `json:"conditions"` + ContainerStatuses []kubernetesContainerStatus `json:"containerStatuses"` + InitContainerStatuses []kubernetesContainerStatus `json:"initContainerStatuses"` + } `json:"status"` +} + +type kubernetesContainer struct { + Image string `json:"image"` +} + +type kubernetesContainerStatus struct { + Image string `json:"image"` + State struct { + Waiting *struct { + Reason string `json:"reason"` + } `json:"waiting"` + } `json:"state"` +} + +type kubernetesPodCondition struct { + Type string `json:"type"` + Status string `json:"status"` +} + +func (p kubernetesPodObject) ready() bool { + for _, condition := range p.Status.Conditions { + if condition.Type == "Ready" { + return condition.Status == "True" + } + } + return false +} + +func (p kubernetesPodObject) images() []string { + var images []string + for _, container := range p.Spec.InitContainers { + images = appendUniqueStrings(images, container.Image) + } + for _, container := range p.Spec.Containers { + images = appendUniqueStrings(images, container.Image) + } + return images +} + +func (p kubernetesPodObject) imagePullMissingImages() []string { + var images []string + for _, status := range p.Status.InitContainerStatuses { + if imagePullWaitingReason(status.State.Waiting) { + images = appendUniqueStrings(images, status.Image) + } + } + for _, status := range p.Status.ContainerStatuses { + if imagePullWaitingReason(status.State.Waiting) { + images = appendUniqueStrings(images, status.Image) + } + } + return images +} + +func imagePullWaitingReason(waiting *struct { + Reason string `json:"reason"` +}) bool { + if waiting == nil { + return false + } + return waiting.Reason == "ImagePullBackOff" || waiting.Reason == "ErrImagePull" || waiting.Reason == "ErrImageNeverPull" +} + +type kubernetesCSINodeList struct { + Items []kubernetesCSINodeObject `json:"items"` +} + +type kubernetesCSINodeObject struct { + Metadata kubernetesObjectMeta `json:"metadata"` + Spec struct { + Drivers []struct { + Name string `json:"name"` + } `json:"drivers"` + } `json:"spec"` +} + +func firstNonEmptyString(values ...string) string { + for _, value := range values { + if value != "" { + return value + } + } + return "" +} + +func appendUniqueStrings(values []string, add ...string) []string { + seen := map[string]struct{}{} + for _, value := range values { + if value != "" { + seen[value] = struct{}{} + } + } + for _, value := range add { + if value == "" { + continue + } + if _, ok := seen[value]; ok { + continue + } + seen[value] = struct{}{} + values = append(values, value) + } + return values +} + +func stringsTrimRightSlash(value string) string { + for len(value) > 0 && value[len(value)-1] == '/' { + value = value[:len(value)-1] + } + return value +} diff --git a/seaweed-block/core/ops/kubernetes_node_evidence_test.go b/seaweed-block/core/ops/kubernetes_node_evidence_test.go new file mode 100644 index 0000000000..4e4576a63c --- /dev/null +++ b/seaweed-block/core/ops/kubernetes_node_evidence_test.go @@ -0,0 +1,293 @@ +package ops + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestPhase37D2KubernetesNodeEvidenceEnrichesReadyAndBlockedNodes(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/v1/nodes": + _, _ = w.Write([]byte(`{"items":[ + {"metadata":{"name":"m01"},"spec":{},"status":{"addresses":[{"type":"InternalIP","address":"192.168.1.181"}],"conditions":[{"type":"Ready","status":"True"}]}}, + {"metadata":{"name":"m02"},"spec":{"unschedulable":true},"status":{"addresses":[{"type":"InternalIP","address":"192.168.1.184"}],"conditions":[{"type":"Ready","status":"False"}]}} + ]}`)) + case "/api/v1/namespaces/kube-system/pods": + if got := r.URL.Query().Get("labelSelector"); got != "app=sw-block-csi-node" { + t.Fatalf("labelSelector=%q", got) + } + _, _ = w.Write([]byte(`{"items":[ + {"metadata":{"name":"csi-m01"},"spec":{"nodeName":"m01"},"status":{"conditions":[{"type":"Ready","status":"True"}]}}, + {"metadata":{"name":"csi-m02"},"spec":{"nodeName":"m02"},"status":{"conditions":[{"type":"Ready","status":"True"}]}} + ]}`)) + case "/apis/storage.k8s.io/v1/csidrivers/block.csi.seaweedfs.com": + _, _ = w.Write([]byte(`{"metadata":{"name":"block.csi.seaweedfs.com"}}`)) + case "/apis/storage.k8s.io/v1/csinodes": + _, _ = w.Write([]byte(`{"items":[ + {"metadata":{"name":"m01"},"spec":{"drivers":[{"name":"block.csi.seaweedfs.com"}]}}, + {"metadata":{"name":"m02"},"spec":{"drivers":[{"name":"block.csi.seaweedfs.com"}]}} + ]}`)) + default: + t.Fatalf("unexpected Kubernetes API path %s", r.URL.String()) + } + })) + defer server.Close() + + client := &KubernetesStatusClient{BaseURL: server.URL, HTTPClient: server.Client()} + cluster := ClusterEvidence{ + CapturedAt: time.Date(2026, 6, 6, 12, 0, 0, 0, time.UTC), + Nodes: []NodeEvidence{{ + NodeName: "m01", + KubernetesNode: "m01", + LastHeartbeatAt: time.Date(2026, 6, 6, 11, 59, 0, 0, time.UTC), + ReplicaCount: 1, + }}, + } + + enriched, err := client.EnrichNodeEvidence(context.Background(), "kube-system", cluster) + if err != nil { + t.Fatalf("enrich: %v", err) + } + if len(enriched.Nodes) != 2 { + t.Fatalf("nodes=%+v", enriched.Nodes) + } + m01 := nodeByKubernetesName(t, enriched.Nodes, "m01") + if !m01.Ready || !m01.Schedulable || m01.InternalIP != "192.168.1.181" || m01.ReplicaCount != 1 { + t.Fatalf("m01 evidence=%+v", m01) + } + status, reason := classifyNodeReadiness(m01) + if status != ManagedVolumeStatusReady || reason != ReasonNodeReady { + t.Fatalf("m01 status=%s reason=%s", status, reason) + } + m02 := nodeByKubernetesName(t, enriched.Nodes, "m02") + if m02.Ready || m02.Schedulable { + t.Fatalf("m02 raw facts=%+v", m02) + } + status, reason = classifyNodeReadiness(m02) + if status != ManagedVolumeStatusUnknown || reason != ReasonNodeNotReady { + t.Fatalf("m02 status=%s reason=%s", status, reason) + } + if !conditionReason(m02.Conditions, ReasonNodeNotReady) || !conditionReason(m02.Conditions, ReasonNodeSchedulingDisabled) { + t.Fatalf("m02 conditions=%+v", m02.Conditions) + } + assertCRDSafeNodeConditions(t, m02.Conditions) +} + +func TestPhase37D2NodeNotReadyTakesPrecedenceOverCSIPodSymptoms(t *testing.T) { + node := NodeEvidence{ + NodeName: "tp01", + KubernetesNode: "tp01", + Ready: false, + Schedulable: true, + Conditions: []ObservationCondition{ + {Type: ConditionReady, Status: "Unknown", Reason: ReasonNodeNotReady, Severity: "warning"}, + {Type: ConditionReady, Status: "False", Reason: ReasonCSINodePodNotReady, Severity: "warning"}, + }, + } + status, reason := classifyNodeReadiness(node) + if status != ManagedVolumeStatusUnknown || reason != ReasonNodeNotReady { + t.Fatalf("status=%s reason=%s want unknown/%s", status, reason, ReasonNodeNotReady) + } + crd := swBlockNodeStatuses([]NodeEvidence{node})[0] + if crd.Status != ManagedVolumeStatusUnknown || crd.ReasonCode != ReasonNodeNotReady { + t.Fatalf("CRD status=%+v", crd) + } +} + +func TestPhase37D2KubernetesNodeEvidenceProjectsCSIRegistrationBlockers(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/v1/nodes": + _, _ = w.Write([]byte(`{"items":[ + {"metadata":{"name":"m01"},"spec":{},"status":{"conditions":[{"type":"Ready","status":"True"}]}}, + {"metadata":{"name":"m02"},"spec":{},"status":{"conditions":[{"type":"Ready","status":"True"}]}} + ]}`)) + case "/api/v1/namespaces/kube-system/pods": + _, _ = w.Write([]byte(`{"items":[ + {"metadata":{"name":"csi-m01"},"spec":{"nodeName":"m01"},"status":{"conditions":[{"type":"Ready","status":"True"}]}}, + {"metadata":{"name":"csi-m02"},"spec":{"nodeName":"m02"},"status":{"conditions":[{"type":"Ready","status":"False"}]}} + ]}`)) + case "/apis/storage.k8s.io/v1/csidrivers/block.csi.seaweedfs.com": + _, _ = w.Write([]byte(`{"metadata":{"name":"block.csi.seaweedfs.com"}}`)) + case "/apis/storage.k8s.io/v1/csinodes": + _, _ = w.Write([]byte(`{"items":[ + {"metadata":{"name":"m01"},"spec":{"drivers":[{"name":"block.csi.seaweedfs.com"}]}}, + {"metadata":{"name":"m02"},"spec":{"drivers":[]}} + ]}`)) + default: + t.Fatalf("unexpected Kubernetes API path %s", r.URL.String()) + } + })) + defer server.Close() + + client := &KubernetesStatusClient{BaseURL: server.URL, HTTPClient: server.Client()} + enriched, err := client.EnrichNodeEvidence(context.Background(), "kube-system", ClusterEvidence{}) + if err != nil { + t.Fatalf("enrich: %v", err) + } + m02 := nodeByKubernetesName(t, enriched.Nodes, "m02") + if !conditionReason(m02.Conditions, ReasonCSIDriverNotRegistered) || !conditionReason(m02.Conditions, ReasonCSINodePodNotReady) { + t.Fatalf("m02 conditions=%+v", m02.Conditions) + } + status, reason := classifyNodeReadiness(m02) + if status != ManagedVolumeStatusBlocked || reason != ReasonCSIDriverNotRegistered { + t.Fatalf("m02 status=%s reason=%s conditions=%+v", status, reason, m02.Conditions) + } + crd := swBlockNodeStatuses([]NodeEvidence{m02})[0] + if crd.Status != ManagedVolumeStatusBlocked || crd.ReasonCode != ReasonCSIDriverNotRegistered { + t.Fatalf("CRD node status=%+v", crd) + } + assertCondition(t, crd.Conditions, ConditionReady, "False", ReasonCSIDriverNotRegistered) + assertCondition(t, crd.Conditions, ConditionBlocked, "True", ReasonCSIDriverNotRegistered) + if len(crd.EvidenceRefs) == 0 || !strings.Contains(strings.Join(crd.EvidenceRefs, ","), "kubernetes/csinode/m02") { + t.Fatalf("missing CRD evidence refs: %+v", crd.EvidenceRefs) + } + assertCRDSafeNodeConditions(t, crd.Conditions) +} + +func TestPhase37D2KubernetesNodeEvidenceProjectsMissingCSIDriver(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/v1/nodes": + _, _ = w.Write([]byte(`{"items":[{"metadata":{"name":"m01"},"spec":{},"status":{"conditions":[{"type":"Ready","status":"True"}]}}]}`)) + case "/api/v1/namespaces/kube-system/pods": + _, _ = w.Write([]byte(`{"items":[{"metadata":{"name":"csi-m01"},"spec":{"nodeName":"m01"},"status":{"conditions":[{"type":"Ready","status":"True"}]}}]}`)) + case "/apis/storage.k8s.io/v1/csidrivers/block.csi.seaweedfs.com": + http.NotFound(w, r) + case "/apis/storage.k8s.io/v1/csinodes": + _, _ = w.Write([]byte(`{"items":[{"metadata":{"name":"m01"},"spec":{"drivers":[{"name":"block.csi.seaweedfs.com"}]}}]}`)) + default: + t.Fatalf("unexpected Kubernetes API path %s", r.URL.String()) + } + })) + defer server.Close() + + client := &KubernetesStatusClient{BaseURL: server.URL, HTTPClient: server.Client()} + enriched, err := client.EnrichNodeEvidence(context.Background(), "kube-system", ClusterEvidence{}) + if err != nil { + t.Fatalf("enrich: %v", err) + } + m01 := nodeByKubernetesName(t, enriched.Nodes, "m01") + if status, reason := classifyNodeReadiness(m01); status != ManagedVolumeStatusBlocked || reason != ReasonCSIDriverNotRegistered { + t.Fatalf("m01 status=%s reason=%s conditions=%+v", status, reason, m01.Conditions) + } + assertCRDSafeNodeConditions(t, m01.Conditions) +} + +func TestPhase37D3KubernetesNodeEvidenceProjectsCSIImagePullBlocker(t *testing.T) { + const missingImage = "ghcr.io/seaweedfs/seaweed-block-csi:sha-missing" + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/v1/nodes": + _, _ = w.Write([]byte(`{"items":[{"metadata":{"name":"m02"},"spec":{},"status":{"conditions":[{"type":"Ready","status":"True"}]}}]}`)) + case "/api/v1/namespaces/kube-system/pods": + _, _ = w.Write([]byte(`{"items":[{ + "metadata":{"name":"sw-block-csi-node-m02"}, + "spec":{ + "nodeName":"m02", + "initContainers":[{"image":"ghcr.io/seaweedfs/seaweed-block-csi:registrar"}], + "containers":[{"image":"` + missingImage + `"}] + }, + "status":{ + "conditions":[{"type":"Ready","status":"False"}], + "containerStatuses":[{"image":"` + missingImage + `","state":{"waiting":{"reason":"ImagePullBackOff"}}}] + } + }]}`)) + case "/apis/storage.k8s.io/v1/csidrivers/block.csi.seaweedfs.com": + _, _ = w.Write([]byte(`{"metadata":{"name":"block.csi.seaweedfs.com"}}`)) + case "/apis/storage.k8s.io/v1/csinodes": + _, _ = w.Write([]byte(`{"items":[{"metadata":{"name":"m02"},"spec":{"drivers":[]}}]}`)) + default: + t.Fatalf("unexpected Kubernetes API path %s", r.URL.String()) + } + })) + defer server.Close() + + client := &KubernetesStatusClient{BaseURL: server.URL, HTTPClient: server.Client()} + enriched, err := client.EnrichNodeEvidence(context.Background(), "kube-system", ClusterEvidence{}) + if err != nil { + t.Fatalf("enrich: %v", err) + } + node := nodeByKubernetesName(t, enriched.Nodes, "m02") + if len(node.MissingImages) != 1 || node.MissingImages[0] != missingImage { + t.Fatalf("missing images=%+v", node.MissingImages) + } + if len(node.RequiredImages) != 2 || !containsString(node.RequiredImages, missingImage) { + t.Fatalf("required images=%+v", node.RequiredImages) + } + status, reason := classifyNodeReadiness(node) + if status != ManagedVolumeStatusBlocked || reason != ReasonImageMissingOnNode { + t.Fatalf("node status=%s reason=%s conditions=%+v", status, reason, node.Conditions) + } + if conditionReason(node.Conditions, ReasonCSIDriverNotRegistered) || conditionReason(node.Conditions, ReasonCSINodePodNotReady) { + t.Fatalf("image-pull root cause should not be masked by CSI symptoms: %+v", node.Conditions) + } + crd := swBlockNodeStatuses([]NodeEvidence{node})[0] + if crd.Status != ManagedVolumeStatusBlocked || crd.ReasonCode != ReasonImageMissingOnNode { + t.Fatalf("CRD node status=%+v", crd) + } + assertCondition(t, crd.Conditions, ConditionReady, "False", ReasonImageMissingOnNode) + assertCondition(t, crd.Conditions, ConditionBlocked, "True", ReasonImageMissingOnNode) + if !strings.Contains(strings.Join(crd.EvidenceRefs, ","), "kubernetes/pod/kube-system/sw-block-csi-node-m02") { + t.Fatalf("missing pod evidence refs: %+v", crd.EvidenceRefs) + } + assertCRDSafeNodeConditions(t, crd.Conditions) +} + +func TestPhase37D3ImagePullEvidenceIncludesNeverPull(t *testing.T) { + pod := kubernetesPodObject{} + pod.Status.ContainerStatuses = []kubernetesContainerStatus{{ + Image: "sw-block-csi:local", + }} + pod.Status.ContainerStatuses[0].State.Waiting = &struct { + Reason string `json:"reason"` + }{Reason: "ErrImageNeverPull"} + + got := pod.imagePullMissingImages() + if len(got) != 1 || got[0] != "sw-block-csi:local" { + t.Fatalf("missing images=%+v", got) + } +} + +func assertCRDSafeNodeConditions(t *testing.T, conditions []ObservationCondition) { + t.Helper() + allowed := map[string]bool{ + ConditionReady: true, + ConditionRecovered: true, + ConditionRecovering: true, + ConditionBlocked: true, + ConditionInvalid: true, + ConditionCleanupRequired: true, + ConditionEvidenceStale: true, + } + for _, condition := range conditions { + if !allowed[condition.Type] { + t.Fatalf("condition type %q is not CRD-safe: %+v", condition.Type, conditions) + } + } +} + +func nodeByKubernetesName(t *testing.T, nodes []NodeEvidence, name string) NodeEvidence { + t.Helper() + for _, node := range nodes { + if node.KubernetesNode == name { + return node + } + } + t.Fatalf("missing node %s in %+v", name, nodes) + return NodeEvidence{} +} + +func conditionReason(conditions []ObservationCondition, reason string) bool { + for _, condition := range conditions { + if condition.Reason == reason { + return true + } + } + return false +} diff --git a/seaweed-block/core/ops/kubernetes_status_conformance_test.go b/seaweed-block/core/ops/kubernetes_status_conformance_test.go new file mode 100644 index 0000000000..d1733c85a8 --- /dev/null +++ b/seaweed-block/core/ops/kubernetes_status_conformance_test.go @@ -0,0 +1,520 @@ +package ops + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestPhase40D1KubernetesStatusClientConformsToCRDSchemaAndRBAC(t *testing.T) { + api := newStatusConformanceAPIServer(t) + defer api.Close() + + client := &KubernetesStatusClient{ + BaseURL: api.URL, + BearerToken: "operator-status-token", + HTTPClient: api.Client(), + } + observedAt := time.Date(2026, 6, 13, 10, 0, 0, 0, time.UTC) + if err := client.WriteClusterStatus(context.Background(), OperatorObjectRef{ + Namespace: "kube-system", + Name: "sw-block", + }, SwBlockClusterCRDStatus{ + ObservedAt: observedAt, + NodeCount: 1, + VolumeCount: 1, + BlockedVolumeCount: 1, + Nodes: []SwBlockNodeCRDStatus{{ + Name: "m02", + KubernetesNode: "m02", + InternalIP: "192.168.1.184", + Schedulable: true, + Ready: false, + Status: ManagedVolumeStatusUnknown, + ReasonCode: ReasonNodeNotReady, + Conditions: []ObservationCondition{{ + Type: ConditionReady, + Status: "Unknown", + Reason: ReasonNodeNotReady, + Severity: "warning", + }}, + EvidenceRefs: []string{"nodes/m02.txt"}, + }}, + Conditions: []ObservationCondition{{ + Type: ConditionBlocked, + Status: "True", + Reason: ReasonCleanupRequired, + Severity: "warning", + }}, + Cleanup: &SwBlockCleanupStatus{ + Status: "failed", + ISCSIResidueCount: 1, + FailureCount: 1, + ReasonCodes: []string{"iscsi_node_records_present"}, + EvidenceRef: "cleanup-summary.txt", + }, + InstallDrift: &SwBlockInstallDrift{ + Status: InstallDriftStatusMismatch, + ReasonCode: ReasonInstallDriftMismatch, + CurrentImage: "sw-block:old", + DesiredImage: "sw-block:new", + CurrentCSIImage: "sw-block-csi:old", + DesiredCSIImage: "sw-block-csi:new", + EvidenceRef: "install-drift-summary.txt", + }, + SafeNextSteps: []SwBlockSafeNextStep{{ + Type: ManagedVolumeActionVerifyCleanup, + Mode: ManagedVolumeActionModeScripted, + Command: "bash scripts/verify-helm-cleanup.sh", + ReasonCode: "iscsi_node_records_present", + MutationAllowed: false, + EvidenceRefs: []string{"cleanup-summary.txt"}, + }}, + MutationAllowed: false, + AllowedActionModes: []string{ManagedVolumeActionModeReadOnly, ManagedVolumeActionModeDryRun}, + NonClaims: []string{"no_finalizer_mutation"}, + }); err != nil { + t.Fatalf("write cluster status: %v", err) + } + if err := client.WriteVolumeStatus(context.Background(), OperatorObjectRef{ + Namespace: "kube-system", + Name: "pvc-a", + }, SwBlockVolumeCRDStatus{ + VolumeID: "pvc-a", + PVCName: "pvc-a", + Status: ManagedVolumeStatusBlocked, + ReasonCode: "iscsi_node_records_present", + ObservedAt: observedAt, + Conditions: []ObservationCondition{ + {Type: ConditionReady, Status: "False", Reason: "iscsi_node_records_present", Severity: "warning"}, + {Type: ConditionCleanupRequired, Status: "True", Reason: "iscsi_node_records_present", Severity: "warning"}, + }, + DeleteSafety: &SwBlockVolumeCRDDeleteSafety{ + ActionType: SwBlockVolumeDeleteActionReleaseFinalizer, + Decision: ManagedVolumeActionDecisionRejected, + State: DeleteSafetyStateBlocked, + Reason: "iscsi_node_records_present", + EvidenceRefs: []string{"cleanup-summary.txt"}, + SafeNextAction: ManagedVolumeActionVerifyCleanup, + }, + AllowedActions: []SwBlockVolumeCRDAction{{ + Type: ManagedVolumeActionVerifyCleanup, + Mode: ManagedVolumeActionModeScripted, + SideEffectClass: ManagedVolumeSideEffectObserve, + OwnerExecutor: "ops", + Decision: ManagedVolumeActionDecisionRejected, + DecisionReason: "iscsi_node_records_present", + MutationAllowed: false, + EvidenceRequired: "cleanup-summary.txt", + EvidenceRefs: []string{"cleanup-summary.txt"}, + }}, + NonClaims: []string{"no_automatic_cleanup_execution"}, + EvidenceRefs: []string{"cleanup-summary.txt"}, + }); err != nil { + t.Fatalf("write volume status: %v", err) + } + event := OperatorKubernetesEvent{ + InvolvedObject: OperatorObjectRef{ + APIVersion: SwBlockVolumeAPIVersion, + Kind: SwBlockVolumeKind, + Namespace: "kube-system", + Name: "pvc-a", + }, + Type: "Warning", + Reason: "iscsi_node_records_present", + Message: "delete-safety blocked by iSCSI residue", + ObservedAt: observedAt, + } + if err := client.EmitEvent(context.Background(), event); err != nil { + t.Fatalf("emit first event: %v", err) + } + if err := client.EmitEvent(context.Background(), event); err != nil { + t.Fatalf("duplicate event should be idempotent: %v", err) + } + if got, want := api.statusPatchCount, 2; got != want { + t.Fatalf("status patches=%d want %d", got, want) + } + if got, want := len(api.events), 1; got != want { + t.Fatalf("stored events=%d want %d", got, want) + } +} + +func TestPhase40D1StatusConformanceRejectsSchemaAndRBACDrift(t *testing.T) { + api := newStatusConformanceAPIServer(t) + defer api.Close() + + cases := []struct { + name string + path string + body map[string]any + want int + }{ + { + name: "snake-case action misses required camelCase mutationAllowed", + path: "/apis/block.seaweedfs.com/v1alpha1/namespaces/kube-system/swblockvolumes/pvc-a/status", + body: map[string]any{"status": map[string]any{ + "status": "blocked", + "allowedActions": []any{map[string]any{ + "type": ManagedVolumeActionVerifyCleanup, + "mode": ManagedVolumeActionModeScripted, + "mutation_allowed": false, + }}, + }}, + want: http.StatusUnprocessableEntity, + }, + { + name: "unsupported condition type is rejected", + path: "/apis/block.seaweedfs.com/v1alpha1/namespaces/kube-system/swblockclusters/sw-block/status", + body: map[string]any{"status": map[string]any{ + "nodeCount": 1, + "volumeCount": 0, + "readyVolumeCount": 0, + "blockedVolumeCount": 0, + "staleVolumeCount": 0, + "mutationAllowed": false, + "nodes": []any{map[string]any{ + "name": "m02", + "schedulable": true, + "ready": false, + "conditions": []any{map[string]any{ + "type": "KubernetesNodeReady", + "status": "False", + }}, + }}, + }}, + want: http.StatusUnprocessableEntity, + }, + { + name: "main resource patch is forbidden", + path: "/apis/block.seaweedfs.com/v1alpha1/namespaces/kube-system/swblockvolumes/pvc-a", + body: map[string]any{"metadata": map[string]any{"finalizers": []any{"block.seaweedfs.com/swblockvolume-protection"}}}, + want: http.StatusForbidden, + }, + { + name: "finalizers endpoint is forbidden", + path: "/apis/block.seaweedfs.com/v1alpha1/namespaces/kube-system/swblockvolumes/pvc-a/finalizers", + body: map[string]any{"metadata": map[string]any{"finalizers": []any{"block.seaweedfs.com/swblockvolume-protection"}}}, + want: http.StatusForbidden, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + raw, err := json.Marshal(tc.body) + if err != nil { + t.Fatalf("marshal body: %v", err) + } + req, err := http.NewRequest(http.MethodPatch, api.URL+tc.path, bytes.NewReader(raw)) + if err != nil { + t.Fatalf("new request: %v", err) + } + req.Header.Set("Content-Type", "application/merge-patch+json") + resp, err := api.Client().Do(req) + if err != nil { + t.Fatalf("do request: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != tc.want { + t.Fatalf("status=%d want %d", resp.StatusCode, tc.want) + } + }) + } +} + +func TestPhase41D2LifecycleOwnerFinalizerBoundary(t *testing.T) { + api := newStatusConformanceAPIServer(t) + defer api.Close() + + finalizerPatch := map[string]any{"metadata": map[string]any{ + "finalizers": []any{"block.seaweedfs.com/swblockvolume-protection"}, + }} + cases := []struct { + name string + token string + path string + body map[string]any + want int + }{ + { + name: "operator-status cannot patch finalizers through main object", + token: "operator-status-token", + path: "/apis/block.seaweedfs.com/v1alpha1/namespaces/kube-system/swblockvolumes/pvc-a", + body: finalizerPatch, + want: http.StatusForbidden, + }, + { + name: "lifecycle-owner can patch only finalizers through main object", + token: "lifecycle-owner-token", + path: "/apis/block.seaweedfs.com/v1alpha1/namespaces/kube-system/swblockvolumes/pvc-a", + body: finalizerPatch, + want: http.StatusOK, + }, + { + name: "lifecycle-owner still cannot use non-existent finalizers endpoint", + token: "lifecycle-owner-token", + path: "/apis/block.seaweedfs.com/v1alpha1/namespaces/kube-system/swblockvolumes/pvc-a/finalizers", + body: finalizerPatch, + want: http.StatusForbidden, + }, + { + name: "lifecycle-owner cannot patch spec", + token: "lifecycle-owner-token", + path: "/apis/block.seaweedfs.com/v1alpha1/namespaces/kube-system/swblockvolumes/pvc-a", + body: map[string]any{"spec": map[string]any{"volumeID": "pvc-a"}}, + want: http.StatusForbidden, + }, + { + name: "lifecycle-owner cannot patch unrelated metadata", + token: "lifecycle-owner-token", + path: "/apis/block.seaweedfs.com/v1alpha1/namespaces/kube-system/swblockvolumes/pvc-a", + body: map[string]any{"metadata": map[string]any{"labels": map[string]any{"changed": "true"}}}, + want: http.StatusForbidden, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + raw, err := json.Marshal(tc.body) + if err != nil { + t.Fatalf("marshal body: %v", err) + } + req, err := http.NewRequest(http.MethodPatch, api.URL+tc.path, bytes.NewReader(raw)) + if err != nil { + t.Fatalf("new request: %v", err) + } + req.Header.Set("Content-Type", "application/merge-patch+json") + if tc.token != "" { + req.Header.Set("Authorization", "Bearer "+tc.token) + } + resp, err := api.Client().Do(req) + if err != nil { + t.Fatalf("do request: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != tc.want { + t.Fatalf("status=%d want %d", resp.StatusCode, tc.want) + } + }) + } +} + +type statusConformanceAPIServer struct { + *httptest.Server + clusterStatusSchema map[string]any + volumeStatusSchema map[string]any + statusPatchCount int + events map[string]map[string]any +} + +func newStatusConformanceAPIServer(t *testing.T) *statusConformanceAPIServer { + t.Helper() + api := &statusConformanceAPIServer{ + clusterStatusSchema: crdStatusSchema(t, "charts/seaweed-block/crds/swblockclusters.block.seaweedfs.com.yaml"), + volumeStatusSchema: crdStatusSchema(t, "charts/seaweed-block/crds/swblockvolumes.block.seaweedfs.com.yaml"), + events: map[string]map[string]any{}, + } + api.Server = httptest.NewServer(http.HandlerFunc(api.handle)) + return api +} + +func (api *statusConformanceAPIServer) handle(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodPatch && strings.HasSuffix(r.URL.Path, "/status"): + api.handleStatusPatch(w, r) + case r.Method == http.MethodPatch && strings.Contains(r.URL.Path, "/swblockvolumes/") && !strings.HasSuffix(r.URL.Path, "/finalizers"): + api.handleLifecycleOwnerPatch(w, r) + case r.Method == http.MethodPost && strings.HasPrefix(r.URL.Path, "/api/v1/namespaces/") && strings.HasSuffix(r.URL.Path, "/events"): + api.handleEventCreate(w, r) + default: + http.Error(w, "operator-status RBAC forbids this request", http.StatusForbidden) + } +} + +func (api *statusConformanceAPIServer) handleLifecycleOwnerPatch(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer lifecycle-owner-token" { + http.Error(w, "main resource patch forbidden for observer", http.StatusForbidden) + return + } + if got := r.Header.Get("Content-Type"); got != "application/merge-patch+json" { + http.Error(w, "resource patches must use merge-patch", http.StatusUnsupportedMediaType) + return + } + var body map[string]any + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if !isFinalizerOnlyPatch(body) { + http.Error(w, "lifecycle-owner may patch only metadata.finalizers", http.StatusForbidden) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"kind":"SwBlockVolume","metadata":{"name":"pvc-a"}}`)) +} + +func isFinalizerOnlyPatch(body map[string]any) bool { + if len(body) != 1 { + return false + } + metadata, ok := body["metadata"].(map[string]any) + if !ok || len(metadata) != 1 { + return false + } + finalizers, ok := metadata["finalizers"].([]any) + if !ok { + return false + } + for _, item := range finalizers { + if _, ok := item.(string); !ok { + return false + } + } + return true +} + +func (api *statusConformanceAPIServer) handleStatusPatch(w http.ResponseWriter, r *http.Request) { + if got := r.Header.Get("Content-Type"); got != "application/merge-patch+json" { + http.Error(w, "status patches must use merge-patch", http.StatusUnsupportedMediaType) + return + } + var body map[string]any + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + status, ok := body["status"].(map[string]any) + if !ok { + http.Error(w, "missing status object", http.StatusUnprocessableEntity) + return + } + var schema map[string]any + switch { + case strings.Contains(r.URL.Path, "/swblockclusters/"): + schema = api.clusterStatusSchema + case strings.Contains(r.URL.Path, "/swblockvolumes/"): + schema = api.volumeStatusSchema + default: + http.Error(w, "unknown CRD resource", http.StatusNotFound) + return + } + if err := validateOpenAPISubset(schema, status, "status"); err != nil { + http.Error(w, err.Error(), http.StatusUnprocessableEntity) + return + } + api.statusPatchCount++ + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"kind":"Status","status":"Success"}`)) +} + +func (api *statusConformanceAPIServer) handleEventCreate(w http.ResponseWriter, r *http.Request) { + var body map[string]any + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + metadata, ok := body["metadata"].(map[string]any) + if !ok { + http.Error(w, "missing event metadata", http.StatusUnprocessableEntity) + return + } + name, _ := metadata["name"].(string) + if name == "" { + http.Error(w, "missing event metadata.name", http.StatusUnprocessableEntity) + return + } + if _, exists := api.events[name]; exists { + http.Error(w, "AlreadyExists", http.StatusConflict) + return + } + api.events[name] = body + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"kind":"Event"}`)) +} + +func crdStatusSchema(t *testing.T, repoPath string) map[string]any { + t.Helper() + doc := readYAMLMap(t, repoPath) + spec := yamlMap(t, doc, "spec") + version := yamlSlice(t, spec, "versions")[0].(map[string]any) + schema := yamlMap(t, version, "schema") + openAPI := yamlMap(t, schema, "openAPIV3Schema") + properties := yamlMap(t, openAPI, "properties") + return yamlMap(t, properties, "status") +} + +func validateOpenAPISubset(schema map[string]any, value any, path string) error { + if required, ok := schema["required"].([]any); ok { + valueMap, ok := value.(map[string]any) + if !ok { + return fmt.Errorf("%s: required fields on non-object %T", path, value) + } + for _, item := range required { + key, _ := item.(string) + if _, exists := valueMap[key]; !exists { + return fmt.Errorf("%s.%s: Required value", path, key) + } + } + } + if enum, ok := schema["enum"].([]any); ok { + got, _ := value.(string) + if got == "" { + return fmt.Errorf("%s: enum value is %T, want string", path, value) + } + for _, item := range enum { + if want, _ := item.(string); got == want { + return nil + } + } + return fmt.Errorf("%s: Unsupported value %q", path, got) + } + switch schema["type"] { + case "object": + valueMap, ok := value.(map[string]any) + if !ok { + return fmt.Errorf("%s: got %T, want object", path, value) + } + properties, _ := schema["properties"].(map[string]any) + for key, child := range valueMap { + if child == nil { + continue + } + childSchema, ok := properties[key].(map[string]any) + if !ok { + continue + } + if err := validateOpenAPISubset(childSchema, child, path+"."+key); err != nil { + return err + } + } + case "array": + values, ok := value.([]any) + if !ok { + return fmt.Errorf("%s: got %T, want array", path, value) + } + itemSchema, _ := schema["items"].(map[string]any) + for i, item := range values { + if err := validateOpenAPISubset(itemSchema, item, fmt.Sprintf("%s[%d]", path, i)); err != nil { + return err + } + } + case "string": + if _, ok := value.(string); !ok { + return fmt.Errorf("%s: got %T, want string", path, value) + } + case "integer": + switch value.(type) { + case float64, int, int64: + default: + return fmt.Errorf("%s: got %T, want integer", path, value) + } + case "boolean": + if _, ok := value.(bool); !ok { + return fmt.Errorf("%s: got %T, want boolean", path, value) + } + } + return nil +} diff --git a/seaweed-block/core/ops/kubernetes_status_writer.go b/seaweed-block/core/ops/kubernetes_status_writer.go new file mode 100644 index 0000000000..63981ef29f --- /dev/null +++ b/seaweed-block/core/ops/kubernetes_status_writer.go @@ -0,0 +1,339 @@ +package ops + +import ( + "bytes" + "context" + "crypto/tls" + "crypto/x509" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strings" + "time" +) + +const ( + SwBlockClusterPlural = "swblockclusters" + SwBlockVolumePlural = "swblockvolumes" + + serviceAccountTokenPath = "/var/run/secrets/kubernetes.io/serviceaccount/token" + serviceAccountCAPath = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt" +) + +// KubernetesStatusClient patches CRD status, emits Kubernetes Events, and +// supports the lifecycle owner's narrowly admitted SwBlockVolume finalizer +// patch. It deliberately has no methods for spec, workload, PVC/PV, Secret, +// StorageClass, or host mutation. +type KubernetesStatusClient struct { + BaseURL string + BearerToken string + HTTPClient *http.Client + EventComponent string +} + +func NewInClusterKubernetesStatusClient() (*KubernetesStatusClient, error) { + host := os.Getenv("KUBERNETES_SERVICE_HOST") + port := os.Getenv("KUBERNETES_SERVICE_PORT") + if host == "" || port == "" { + return nil, fmt.Errorf("KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT are required for non-dry-run operator status") + } + token, err := os.ReadFile(serviceAccountTokenPath) + if err != nil { + return nil, fmt.Errorf("read service account token: %w", err) + } + ca, err := os.ReadFile(serviceAccountCAPath) + if err != nil { + return nil, fmt.Errorf("read service account CA: %w", err) + } + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(ca) { + return nil, fmt.Errorf("service account CA bundle is empty or invalid") + } + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.TLSClientConfig = &tls.Config{RootCAs: pool} + return &KubernetesStatusClient{ + BaseURL: "https://" + netJoinHostPort(host, port), + BearerToken: strings.TrimSpace(string(token)), + HTTPClient: &http.Client{Transport: transport, Timeout: 10 * time.Second}, + }, nil +} + +func (c *KubernetesStatusClient) WriteClusterStatus(ctx context.Context, ref OperatorObjectRef, status SwBlockClusterCRDStatus) error { + return c.patchStatus(ctx, ref.Namespace, SwBlockClusterPlural, ref.Name, status) +} + +func (c *KubernetesStatusClient) WriteVolumeStatus(ctx context.Context, ref OperatorObjectRef, status SwBlockVolumeCRDStatus) error { + return c.patchStatus(ctx, ref.Namespace, SwBlockVolumePlural, ref.Name, status) +} + +func IsKubernetesStatusNotFound(err error) bool { + return err != nil && strings.Contains(err.Error(), "http 404") +} + +func (c *KubernetesStatusClient) ListSwBlockVolumes(ctx context.Context, namespace string) ([]SwBlockVolumeObject, error) { + if namespace == "" { + return nil, fmt.Errorf("namespace is required for SwBlockVolume list") + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.resourceCollectionURL(namespace, SwBlockVolumePlural), nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/json") + if c.BearerToken != "" { + req.Header.Set("Authorization", "Bearer "+c.BearerToken) + } + client := c.HTTPClient + if client == nil { + client = http.DefaultClient + } + resp, err := client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + return nil, fmt.Errorf("list %s failed: http %d %s", SwBlockVolumePlural, resp.StatusCode, strings.TrimSpace(string(raw))) + } + var list kubernetesSwBlockVolumeList + if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&list); err != nil { + return nil, fmt.Errorf("decode %s list: %w", SwBlockVolumePlural, err) + } + out := make([]SwBlockVolumeObject, 0, len(list.Items)) + for _, item := range list.Items { + refNamespace := item.Metadata.Namespace + if refNamespace == "" { + refNamespace = namespace + } + out = append(out, SwBlockVolumeObject{ + Ref: OperatorObjectRef{ + APIVersion: SwBlockVolumeAPIVersion, + Kind: SwBlockVolumeKind, + Namespace: refNamespace, + Name: item.Metadata.Name, + }, + Finalizers: append([]string(nil), item.Metadata.Finalizers...), + DeletionTimestamp: item.Metadata.DeletionTimestamp, + Spec: item.Spec, + Status: item.Status, + }) + } + return out, nil +} + +func (c *KubernetesStatusClient) PatchSwBlockVolumeFinalizers(ctx context.Context, ref OperatorObjectRef, finalizers []string) error { + if ref.Namespace == "" || ref.Name == "" { + return fmt.Errorf("namespace and name are required for SwBlockVolume finalizer patch") + } + body, err := json.Marshal(map[string]any{"metadata": map[string]any{"finalizers": finalizers}}) + if err != nil { + return fmt.Errorf("marshal finalizer patch: %w", err) + } + req, err := http.NewRequestWithContext(ctx, http.MethodPatch, c.resourceURL(ref.Namespace, SwBlockVolumePlural, ref.Name), bytes.NewReader(body)) + if err != nil { + return err + } + req.Header.Set("Accept", "application/json") + req.Header.Set("Content-Type", "application/merge-patch+json") + if c.BearerToken != "" { + req.Header.Set("Authorization", "Bearer "+c.BearerToken) + } + client := c.HTTPClient + if client == nil { + client = http.DefaultClient + } + resp, err := client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode >= 200 && resp.StatusCode < 300 { + return nil + } + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + return fmt.Errorf("patch %s/%s finalizers failed: http %d %s", SwBlockVolumePlural, ref.Name, resp.StatusCode, strings.TrimSpace(string(raw))) +} + +func (c *KubernetesStatusClient) patchStatus(ctx context.Context, namespace, resource, name string, status any) error { + if namespace == "" || resource == "" || name == "" { + return fmt.Errorf("namespace, resource, and name are required for status patch") + } + body, err := json.Marshal(map[string]any{"status": status}) + if err != nil { + return fmt.Errorf("marshal status patch: %w", err) + } + req, err := http.NewRequestWithContext(ctx, http.MethodPatch, c.statusURL(namespace, resource, name), bytes.NewReader(body)) + if err != nil { + return err + } + req.Header.Set("Accept", "application/json") + req.Header.Set("Content-Type", "application/merge-patch+json") + if c.BearerToken != "" { + req.Header.Set("Authorization", "Bearer "+c.BearerToken) + } + client := c.HTTPClient + if client == nil { + client = http.DefaultClient + } + resp, err := client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode >= 200 && resp.StatusCode < 300 { + return nil + } + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + return fmt.Errorf("patch %s/%s status failed: http %d %s", resource, name, resp.StatusCode, strings.TrimSpace(string(raw))) +} + +func (c *KubernetesStatusClient) EmitEvent(ctx context.Context, event OperatorKubernetesEvent) error { + namespace := event.InvolvedObject.Namespace + if namespace == "" { + namespace = "default" + } + now := event.ObservedAt + if now.IsZero() { + now = time.Now().UTC() + } + body := kubernetesCoreEvent{ + APIVersion: "v1", + Kind: "Event", + Metadata: kubernetesMetadata{Name: kubernetesEventName(event), Namespace: namespace}, + InvolvedObject: kubernetesObjectReferenceFromOperator(event.InvolvedObject), + Type: event.Type, + Reason: event.Reason, + Message: event.Message, + Source: kubernetesEventSource{Component: defaultString(c.EventComponent, "sw-block-operator-status")}, + FirstTimestamp: now.Format(time.RFC3339), + LastTimestamp: now.Format(time.RFC3339), + Count: 1, + } + raw, err := json.Marshal(body) + if err != nil { + return fmt.Errorf("marshal event: %w", err) + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.eventsURL(namespace), bytes.NewReader(raw)) + if err != nil { + return err + } + req.Header.Set("Accept", "application/json") + req.Header.Set("Content-Type", "application/json") + if c.BearerToken != "" { + req.Header.Set("Authorization", "Bearer "+c.BearerToken) + } + client := c.HTTPClient + if client == nil { + client = http.DefaultClient + } + resp, err := client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode >= 200 && resp.StatusCode < 300 { + return nil + } + if resp.StatusCode == http.StatusConflict { + return nil + } + rawResp, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + return fmt.Errorf("create event %s failed: http %d %s", event.Reason, resp.StatusCode, strings.TrimSpace(string(rawResp))) +} + +func (c *KubernetesStatusClient) statusURL(namespace, resource, name string) string { + return c.resourceURL(namespace, resource, name) + "/status" +} + +func (c *KubernetesStatusClient) resourcePath(namespace, resource, name string) string { + return "/apis/block.seaweedfs.com/v1alpha1/namespaces/" + + pathEscape(namespace) + "/" + pathEscape(resource) + "/" + pathEscape(name) +} + +func (c *KubernetesStatusClient) resourceCollectionURL(namespace, resource string) string { + base := strings.TrimRight(c.BaseURL, "/") + return base + "/apis/block.seaweedfs.com/v1alpha1/namespaces/" + + pathEscape(namespace) + "/" + pathEscape(resource) +} + +func (c *KubernetesStatusClient) resourceURL(namespace, resource, name string) string { + return strings.TrimRight(c.BaseURL, "/") + c.resourcePath(namespace, resource, name) +} + +func (c *KubernetesStatusClient) eventsURL(namespace string) string { + base := strings.TrimRight(c.BaseURL, "/") + return base + "/api/v1/namespaces/" + pathEscape(namespace) + "/events" +} + +func kubernetesObjectReferenceFromOperator(ref OperatorObjectRef) kubernetesObjectReference { + return kubernetesObjectReference{ + APIVersion: ref.APIVersion, + Kind: ref.Kind, + Namespace: ref.Namespace, + Name: ref.Name, + } +} + +func kubernetesEventName(event OperatorKubernetesEvent) string { + base := kubernetesName(event.InvolvedObject.Name + "-" + event.Type + "-" + event.Reason) + if base == "unknown-volume" { + base = "sw-block-event" + } + return base +} + +func pathEscape(value string) string { + return url.PathEscape(value) +} + +func netJoinHostPort(host, port string) string { + if strings.Contains(host, ":") && !strings.HasPrefix(host, "[") { + return "[" + host + "]:" + port + } + return host + ":" + port +} + +type kubernetesCoreEvent struct { + APIVersion string `json:"apiVersion"` + Kind string `json:"kind"` + Metadata kubernetesMetadata `json:"metadata"` + InvolvedObject kubernetesObjectReference `json:"involvedObject"` + Type string `json:"type"` + Reason string `json:"reason"` + Message string `json:"message"` + Source kubernetesEventSource `json:"source"` + FirstTimestamp string `json:"firstTimestamp"` + LastTimestamp string `json:"lastTimestamp"` + Count int `json:"count"` +} + +type kubernetesMetadata struct { + Name string `json:"name"` + Namespace string `json:"namespace"` + Finalizers []string `json:"finalizers,omitempty"` + DeletionTimestamp *time.Time `json:"deletionTimestamp,omitempty"` +} + +type kubernetesObjectReference struct { + APIVersion string `json:"apiVersion,omitempty"` + Kind string `json:"kind,omitempty"` + Namespace string `json:"namespace,omitempty"` + Name string `json:"name,omitempty"` +} + +type kubernetesEventSource struct { + Component string `json:"component"` +} + +type kubernetesSwBlockVolumeList struct { + Items []kubernetesSwBlockVolume `json:"items"` +} + +type kubernetesSwBlockVolume struct { + Metadata kubernetesMetadata `json:"metadata"` + Spec SwBlockVolumeSpec `json:"spec"` + Status SwBlockVolumeCRDStatus `json:"status"` +} diff --git a/seaweed-block/core/ops/kubernetes_status_writer_test.go b/seaweed-block/core/ops/kubernetes_status_writer_test.go new file mode 100644 index 0000000000..0b097d98cd --- /dev/null +++ b/seaweed-block/core/ops/kubernetes_status_writer_test.go @@ -0,0 +1,377 @@ +package ops + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestKubernetesStatusClientPatchesOnlyStatusSubresources(t *testing.T) { + var requests []recordedStatusPatch + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body map[string]any + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Fatalf("decode request body: %v", err) + } + requests = append(requests, recordedStatusPatch{ + Method: r.Method, + Path: r.URL.Path, + ContentType: r.Header.Get("Content-Type"), + Authorization: r.Header.Get("Authorization"), + Body: body, + }) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"ok":true}`)) + })) + defer server.Close() + + client := &KubernetesStatusClient{ + BaseURL: server.URL, + BearerToken: "test-token", + HTTPClient: server.Client(), + } + observedAt := time.Date(2026, 6, 3, 10, 0, 0, 0, time.UTC) + if err := client.WriteClusterStatus(context.Background(), OperatorObjectRef{ + Namespace: "kube-system", + Name: "sw-block", + }, SwBlockClusterCRDStatus{ + ObservedAt: observedAt, + VolumeCount: 1, + ReadyVolumeCount: 1, + MutationAllowed: false, + AllowedActionModes: []string{"read_only", "dry_run"}, + }); err != nil { + t.Fatalf("write cluster status: %v", err) + } + if err := client.WriteVolumeStatus(context.Background(), OperatorObjectRef{ + Namespace: "kube-system", + Name: "demo-pvc", + }, SwBlockVolumeCRDStatus{ + VolumeID: "pvc-123", + PVCName: "demo-pvc", + Status: ManagedVolumeStatusReady, + ReasonCode: ReasonFirstVolumeVerified, + ObservedAt: observedAt, + DeleteSafety: &SwBlockVolumeCRDDeleteSafety{ + ActionType: SwBlockVolumeDeleteActionReleaseFinalizer, + Decision: ManagedVolumeActionDecisionAllowed, + State: DeleteSafetyStateReleasable, + Reason: ReasonDeleteFinalizerReleasable, + FinalizerReleaseAllowed: true, + EvidenceRefs: []string{"cleanup-summary.txt"}, + }, + AllowedActions: []SwBlockVolumeCRDAction{{ + Type: "observe.collect_bundle", + Mode: "read_only", + SideEffectClass: "none", + OwnerExecutor: "ops", + Decision: ManagedVolumeActionDecisionAllowed, + DecisionReason: "", + MutationAllowed: false, + EvidenceRequired: "projection_inputs_or_bundle", + }}, + }); err != nil { + t.Fatalf("write volume status: %v", err) + } + + if len(requests) != 2 { + t.Fatalf("requests=%d want 2: %+v", len(requests), requests) + } + wantPaths := []string{ + "/apis/block.seaweedfs.com/v1alpha1/namespaces/kube-system/swblockclusters/sw-block/status", + "/apis/block.seaweedfs.com/v1alpha1/namespaces/kube-system/swblockvolumes/demo-pvc/status", + } + for i, req := range requests { + if req.Method != http.MethodPatch { + t.Fatalf("request %d method=%s want PATCH", i, req.Method) + } + if req.Path != wantPaths[i] { + t.Fatalf("request %d path=%s want %s", i, req.Path, wantPaths[i]) + } + if req.ContentType != "application/merge-patch+json" { + t.Fatalf("request %d content-type=%s", i, req.ContentType) + } + if req.Authorization != "Bearer test-token" { + t.Fatalf("request %d authorization=%s", i, req.Authorization) + } + if _, ok := req.Body["status"]; !ok { + t.Fatalf("request %d missing status patch: %+v", i, req.Body) + } + if _, ok := req.Body["spec"]; ok { + t.Fatalf("request %d must not patch spec: %+v", i, req.Body) + } + } + volumeStatus := requests[1].Body["status"].(map[string]any) + actions := volumeStatus["allowedActions"].([]any) + action := actions[0].(map[string]any) + if _, ok := action["mutationAllowed"]; !ok { + t.Fatalf("volume action missing camelCase mutationAllowed: %+v", action) + } + if _, ok := action["decision"]; !ok { + t.Fatalf("volume action missing decision: %+v", action) + } + if _, ok := action["evidenceRequired"]; !ok { + t.Fatalf("volume action missing camelCase evidenceRequired: %+v", action) + } + if _, ok := action["mutation_allowed"]; ok { + t.Fatalf("volume action leaked snake_case mutation_allowed: %+v", action) + } + if _, ok := action["evidence_required"]; ok { + t.Fatalf("volume action leaked snake_case evidence_required: %+v", action) + } + deleteSafety := volumeStatus["deleteSafety"].(map[string]any) + if _, ok := deleteSafety["finalizerReleaseAllowed"]; !ok { + t.Fatalf("deleteSafety missing camelCase finalizerReleaseAllowed: %+v", deleteSafety) + } + if _, ok := deleteSafety["actionType"]; !ok { + t.Fatalf("deleteSafety missing camelCase actionType: %+v", deleteSafety) + } + for _, forbidden := range []string{"finalizer_release_allowed", "action_type", "safe_next_action"} { + if _, ok := deleteSafety[forbidden]; ok { + t.Fatalf("deleteSafety leaked snake_case %s: %+v", forbidden, deleteSafety) + } + } +} + +func TestKubernetesStatusClientCreatesCoreEvents(t *testing.T) { + var eventBody map[string]any + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + t.Fatalf("method=%s want POST", r.Method) + } + if r.URL.Path != "/api/v1/namespaces/kube-system/events" { + t.Fatalf("path=%s", r.URL.Path) + } + if got := r.Header.Get("Authorization"); got != "Bearer event-token" { + t.Fatalf("authorization=%s", got) + } + if err := json.NewDecoder(r.Body).Decode(&eventBody); err != nil { + t.Fatalf("decode event body: %v", err) + } + w.WriteHeader(http.StatusCreated) + })) + defer server.Close() + + err := (&KubernetesStatusClient{ + BaseURL: server.URL, + BearerToken: "event-token", + HTTPClient: server.Client(), + }).EmitEvent(context.Background(), OperatorKubernetesEvent{ + InvolvedObject: OperatorObjectRef{ + APIVersion: SwBlockVolumeAPIVersion, + Kind: SwBlockVolumeKind, + Namespace: "kube-system", + Name: "blocked-pvc", + }, + Type: "Warning", + Reason: ReasonCSINodeImagePullFailed, + Message: "CSI node image pull failed", + ObservedAt: time.Date(2026, 6, 3, 12, 0, 0, 0, time.UTC), + }) + if err != nil { + t.Fatalf("emit event: %v", err) + } + if eventBody["kind"] != "Event" || eventBody["type"] != "Warning" || eventBody["reason"] != ReasonCSINodeImagePullFailed { + t.Fatalf("event body=%+v", eventBody) + } + involved := eventBody["involvedObject"].(map[string]any) + if involved["kind"] != SwBlockVolumeKind || involved["name"] != "blocked-pvc" { + t.Fatalf("involvedObject=%+v", involved) + } + metadata := eventBody["metadata"].(map[string]any) + if metadata["name"] != "blocked-pvc-warning-csi-node-image-pull-failed" { + t.Fatalf("event name=%s", metadata["name"]) + } +} + +func TestKubernetesStatusClientTreatsPersistentEventAsIdempotentSuccess(t *testing.T) { + seen := map[string]bool{} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body map[string]any + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Fatalf("decode event body: %v", err) + } + name := body["metadata"].(map[string]any)["name"].(string) + if seen[name] { + w.WriteHeader(http.StatusConflict) + _, _ = w.Write([]byte(`{"reason":"AlreadyExists"}`)) + return + } + seen[name] = true + w.WriteHeader(http.StatusCreated) + })) + defer server.Close() + + client := &KubernetesStatusClient{ + BaseURL: server.URL, + HTTPClient: server.Client(), + } + event := OperatorKubernetesEvent{ + InvolvedObject: OperatorObjectRef{ + APIVersion: SwBlockVolumeAPIVersion, + Kind: SwBlockVolumeKind, + Namespace: "kube-system", + Name: "unknown", + }, + Type: "Warning", + Reason: ReasonCSINodeImagePullFailed, + Message: "managed volume is blocked", + ObservedAt: time.Date(2026, 6, 4, 1, 0, 0, 0, time.UTC), + } + if err := client.EmitEvent(context.Background(), event); err != nil { + t.Fatalf("first event: %v", err) + } + event.ObservedAt = event.ObservedAt.Add(time.Minute) + if err := client.EmitEvent(context.Background(), event); err != nil { + t.Fatalf("persistent event must be idempotent success: %v", err) + } + if len(seen) != 1 { + t.Fatalf("seen events=%+v", seen) + } +} + +func TestKubernetesStatusClientListsSwBlockVolumesForLifecycleOwner(t *testing.T) { + deletingAt := "2026-06-15T01:02:03Z" + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + t.Fatalf("method=%s want GET", r.Method) + } + if r.URL.Path != "/apis/block.seaweedfs.com/v1alpha1/namespaces/kube-system/swblockvolumes" { + t.Fatalf("path=%s", r.URL.Path) + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{ + "items": [ + { + "metadata":{"name":"a","namespace":"kube-system","finalizers":["example.com/foreign"]}, + "spec":{"pvcName":"pvc-a","storageClass":"seaweed-block"}, + "status":{"status":"ready","deleteSafety":{"state":"releasable","decision":"allowed","finalizerReleaseAllowed":true}} + }, + {"metadata":{"name":"b","deletionTimestamp":"` + deletingAt + `"}} + ] + }`)) + })) + defer server.Close() + + volumes, err := (&KubernetesStatusClient{ + BaseURL: server.URL, + HTTPClient: server.Client(), + }).ListSwBlockVolumes(context.Background(), "kube-system") + if err != nil { + t.Fatalf("list: %v", err) + } + if len(volumes) != 2 { + t.Fatalf("volumes=%+v", volumes) + } + if volumes[0].Ref.Name != "a" || volumes[0].Ref.Namespace != "kube-system" || + !stringSliceContains(volumes[0].Finalizers, "example.com/foreign") { + t.Fatalf("volume a=%+v", volumes[0]) + } + if volumes[0].Spec.PVCName != "pvc-a" || volumes[0].Spec.StorageClass != "seaweed-block" { + t.Fatalf("volume a spec=%+v", volumes[0].Spec) + } + if volumes[0].Status.DeleteSafety == nil || !volumes[0].Status.DeleteSafety.FinalizerReleaseAllowed { + t.Fatalf("volume a status=%+v", volumes[0].Status) + } + if volumes[1].Ref.Name != "b" || volumes[1].Ref.Namespace != "kube-system" || volumes[1].DeletionTimestamp == nil { + t.Fatalf("volume b=%+v", volumes[1]) + } +} + +func TestKubernetesStatusClientPatchesOnlySwBlockVolumeFinalizers(t *testing.T) { + var request recordedStatusPatch + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if err := json.NewDecoder(r.Body).Decode(&request.Body); err != nil { + t.Fatalf("decode request body: %v", err) + } + request.Method = r.Method + request.Path = r.URL.Path + request.ContentType = r.Header.Get("Content-Type") + request.Authorization = r.Header.Get("Authorization") + w.WriteHeader(http.StatusOK) + })) + defer server.Close() + + err := (&KubernetesStatusClient{ + BaseURL: server.URL, + BearerToken: "owner-token", + HTTPClient: server.Client(), + }).PatchSwBlockVolumeFinalizers(context.Background(), OperatorObjectRef{ + Namespace: "kube-system", + Name: "demo", + }, []string{"example.com/foreign", SwBlockVolumeFinalizerName}) + if err != nil { + t.Fatalf("patch finalizers: %v", err) + } + if request.Method != http.MethodPatch { + t.Fatalf("method=%s", request.Method) + } + if request.Path != "/apis/block.seaweedfs.com/v1alpha1/namespaces/kube-system/swblockvolumes/demo" { + t.Fatalf("path=%s", request.Path) + } + if request.ContentType != "application/merge-patch+json" { + t.Fatalf("content-type=%s", request.ContentType) + } + if request.Authorization != "Bearer owner-token" { + t.Fatalf("authorization=%s", request.Authorization) + } + metadata := request.Body["metadata"].(map[string]any) + if _, ok := request.Body["spec"]; ok { + t.Fatalf("finalizer patch must not include spec: %+v", request.Body) + } + if _, ok := request.Body["status"]; ok { + t.Fatalf("finalizer patch must not include status: %+v", request.Body) + } + if len(request.Body) != 1 || len(metadata) != 1 { + t.Fatalf("finalizer patch must contain only metadata.finalizers: %+v", request.Body) + } +} + +func TestKubernetesEventNameSeparatesTypeAndReason(t *testing.T) { + base := OperatorKubernetesEvent{ + InvolvedObject: OperatorObjectRef{Name: "demo-pvc"}, + Reason: ReasonFirstVolumeVerified, + } + normal := base + normal.Type = "Normal" + warning := base + warning.Type = "Warning" + if kubernetesEventName(normal) == kubernetesEventName(warning) { + t.Fatalf("event names must separate type: normal=%s warning=%s", kubernetesEventName(normal), kubernetesEventName(warning)) + } + if got := kubernetesEventName(normal); strings.Contains(got, ".") { + t.Fatalf("event name must be stable and not timestamp-suffixed: %s", got) + } +} + +func TestKubernetesStatusClientReturnsHTTPFailure(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte("missing swblockvolume")) + })) + defer server.Close() + + err := (&KubernetesStatusClient{ + BaseURL: server.URL, + HTTPClient: server.Client(), + }).WriteVolumeStatus(context.Background(), OperatorObjectRef{ + Namespace: "default", + Name: "missing", + }, SwBlockVolumeCRDStatus{Status: ManagedVolumeStatusReady}) + if err == nil || !strings.Contains(err.Error(), "http 404") || !strings.Contains(err.Error(), "missing swblockvolume") { + t.Fatalf("err=%v", err) + } +} + +type recordedStatusPatch struct { + Method string + Path string + ContentType string + Authorization string + Body map[string]any +} diff --git a/seaweed-block/core/ops/lifecycle_owner_controller.go b/seaweed-block/core/ops/lifecycle_owner_controller.go new file mode 100644 index 0000000000..f205c58fcd --- /dev/null +++ b/seaweed-block/core/ops/lifecycle_owner_controller.go @@ -0,0 +1,166 @@ +package ops + +import ( + "context" + "fmt" + "time" +) + +type LifecycleOwnerClient interface { + ListSwBlockVolumes(ctx context.Context, namespace string) ([]SwBlockVolumeObject, error) + PatchSwBlockVolumeFinalizers(ctx context.Context, ref OperatorObjectRef, finalizers []string) error +} + +type SwBlockVolumeObject struct { + Ref OperatorObjectRef `json:"ref"` + Finalizers []string `json:"finalizers,omitempty"` + DeletionTimestamp *time.Time `json:"deletionTimestamp,omitempty"` + Spec SwBlockVolumeSpec `json:"spec,omitempty"` + Status SwBlockVolumeCRDStatus +} + +type SwBlockVolumeSpec struct { + PVCName string `json:"pvcName,omitempty"` + StorageClass string `json:"storageClass,omitempty"` +} + +type LifecycleOwnerReconciler struct { + Namespace string + Client LifecycleOwnerClient + EventSink OperatorEventSink + DryRun bool + Now func() time.Time +} + +type LifecycleOwnerReconcileResult struct { + VolumeCount int `json:"volumeCount"` + FinalizerPatchCount int `json:"finalizerPatchCount"` + FinalizerAddedCount int `json:"finalizerAddedCount"` + FinalizerHeldCount int `json:"finalizerHeldCount"` + FinalizerReleasedCount int `json:"finalizerReleasedCount"` + EventCount int `json:"eventCount"` +} + +func (r LifecycleOwnerReconciler) Reconcile(ctx context.Context) (LifecycleOwnerReconcileResult, error) { + if r.Client == nil { + return LifecycleOwnerReconcileResult{}, fmt.Errorf("lifecycle owner client is required") + } + namespace := defaultString(r.Namespace, "default") + volumes, err := r.Client.ListSwBlockVolumes(ctx, namespace) + if err != nil { + return LifecycleOwnerReconcileResult{}, err + } + result := LifecycleOwnerReconcileResult{VolumeCount: len(volumes)} + for _, volume := range volumes { + hasFinalizer := lifecycleOwnerStringSliceContains(volume.Finalizers, SwBlockVolumeFinalizerName) + if volume.DeletionTimestamp != nil { + if !hasFinalizer { + continue + } + decision := volume.Status.DeleteSafety + if lifecycleOwnerReleaseAllowed(decision) { + next := lifecycleOwnerRemoveString(volume.Finalizers, SwBlockVolumeFinalizerName) + if !r.DryRun { + if err := r.Client.PatchSwBlockVolumeFinalizers(ctx, volume.Ref, next); err != nil { + return LifecycleOwnerReconcileResult{}, err + } + result.FinalizerPatchCount++ + } + result.FinalizerReleasedCount++ + if r.EventSink != nil && !r.DryRun { + if err := r.EventSink.EmitEvent(ctx, OperatorKubernetesEvent{ + InvolvedObject: volume.Ref, + Type: "Normal", + Reason: ReasonDeleteFinalizerReleased, + Message: "Seaweed Block protection finalizer released after clean delete-safety evidence", + EvidenceRefs: append([]string(nil), decision.EvidenceRefs...), + ObservedAt: r.now()(), + }); err == nil { + result.EventCount++ + } + } + continue + } + result.FinalizerHeldCount++ + if r.EventSink != nil && !r.DryRun { + holdReason, evidenceRefs := lifecycleOwnerHoldReason(decision) + if err := r.EventSink.EmitEvent(ctx, OperatorKubernetesEvent{ + InvolvedObject: volume.Ref, + Type: "Warning", + Reason: holdReason, + Message: "Seaweed Block protection finalizer held until delete-safety evidence allows release", + EvidenceRefs: evidenceRefs, + ObservedAt: r.now()(), + }); err == nil { + result.EventCount++ + } + } + continue + } + if hasFinalizer { + continue + } + next := append([]string(nil), volume.Finalizers...) + next = append(next, SwBlockVolumeFinalizerName) + if !r.DryRun { + if err := r.Client.PatchSwBlockVolumeFinalizers(ctx, volume.Ref, next); err != nil { + return LifecycleOwnerReconcileResult{}, err + } + result.FinalizerPatchCount++ + } + result.FinalizerAddedCount++ + if r.EventSink == nil || r.DryRun { + continue + } + if err := r.EventSink.EmitEvent(ctx, OperatorKubernetesEvent{ + InvolvedObject: volume.Ref, + Type: "Normal", + Reason: ReasonDeleteFinalizerAdded, + Message: "Seaweed Block protection finalizer added", + ObservedAt: r.now()(), + }); err == nil { + result.EventCount++ + } + } + return result, nil +} + +func lifecycleOwnerReleaseAllowed(decision *SwBlockVolumeCRDDeleteSafety) bool { + return decision != nil && + decision.FinalizerReleaseAllowed && + decision.Decision == ManagedVolumeActionDecisionAllowed && + decision.State == DeleteSafetyStateReleasable +} + +func lifecycleOwnerHoldReason(decision *SwBlockVolumeCRDDeleteSafety) (string, []string) { + if decision == nil || decision.Reason == "" { + return ReasonCleanupEvidenceMissing, nil + } + return decision.Reason, append([]string(nil), decision.EvidenceRefs...) +} + +func (r LifecycleOwnerReconciler) now() func() time.Time { + if r.Now != nil { + return r.Now + } + return time.Now +} + +func lifecycleOwnerStringSliceContains(values []string, want string) bool { + for _, value := range values { + if value == want { + return true + } + } + return false +} + +func lifecycleOwnerRemoveString(values []string, remove string) []string { + out := make([]string, 0, len(values)) + for _, value := range values { + if value != remove { + out = append(out, value) + } + } + return out +} diff --git a/seaweed-block/core/ops/lifecycle_owner_controller_test.go b/seaweed-block/core/ops/lifecycle_owner_controller_test.go new file mode 100644 index 0000000000..49a1409ecc --- /dev/null +++ b/seaweed-block/core/ops/lifecycle_owner_controller_test.go @@ -0,0 +1,187 @@ +package ops + +import ( + "context" + "reflect" + "testing" + "time" +) + +func TestLifecycleOwnerReconcilerAddsProtectionFinalizerOnly(t *testing.T) { + client := &fakeLifecycleOwnerClient{volumes: []SwBlockVolumeObject{{ + Ref: OperatorObjectRef{ + APIVersion: SwBlockVolumeAPIVersion, + Kind: SwBlockVolumeKind, + Namespace: "kube-system", + Name: "demo", + }, + Finalizers: []string{"example.com/foreign"}, + }}} + events := &fakeOperatorEventSink{} + result, err := (LifecycleOwnerReconciler{ + Namespace: "kube-system", + Client: client, + EventSink: events, + Now: func() time.Time { return time.Date(2026, 6, 15, 1, 0, 0, 0, time.UTC) }, + }).Reconcile(context.Background()) + if err != nil { + t.Fatalf("reconcile: %v", err) + } + if result.FinalizerPatchCount != 1 || result.FinalizerAddedCount != 1 { + t.Fatalf("result=%+v", result) + } + want := []string{"example.com/foreign", SwBlockVolumeFinalizerName} + if !reflect.DeepEqual(client.patches[0].finalizers, want) { + t.Fatalf("finalizers=%+v want %+v", client.patches[0].finalizers, want) + } + if events.countByReason(ReasonDeleteFinalizerAdded) != 1 { + t.Fatalf("events=%+v", events.events) + } +} + +func TestLifecycleOwnerReconcilerIsIdempotent(t *testing.T) { + client := &fakeLifecycleOwnerClient{volumes: []SwBlockVolumeObject{{ + Ref: OperatorObjectRef{Namespace: "kube-system", Name: "demo"}, + }}} + reconciler := LifecycleOwnerReconciler{Namespace: "kube-system", Client: client} + if _, err := reconciler.Reconcile(context.Background()); err != nil { + t.Fatalf("first reconcile: %v", err) + } + client.volumes[0].Finalizers = append([]string(nil), client.patches[0].finalizers...) + result, err := reconciler.Reconcile(context.Background()) + if err != nil { + t.Fatalf("second reconcile: %v", err) + } + if result.FinalizerPatchCount != 0 || len(client.patches) != 1 { + t.Fatalf("result=%+v patches=%+v", result, client.patches) + } +} + +func TestLifecycleOwnerReconcilerSkipsDeletingObjectsInAddSlice(t *testing.T) { + deletingAt := time.Date(2026, 6, 15, 1, 0, 0, 0, time.UTC) + client := &fakeLifecycleOwnerClient{volumes: []SwBlockVolumeObject{{ + Ref: OperatorObjectRef{Namespace: "kube-system", Name: "deleting"}, + DeletionTimestamp: &deletingAt, + }}} + result, err := (LifecycleOwnerReconciler{Namespace: "kube-system", Client: client}).Reconcile(context.Background()) + if err != nil { + t.Fatalf("reconcile: %v", err) + } + if result.FinalizerPatchCount != 0 || result.FinalizerAddedCount != 0 || len(client.patches) != 0 { + t.Fatalf("result=%+v patches=%+v", result, client.patches) + } +} + +func TestLifecycleOwnerReconcilerHoldsDeletingObjectWithoutReleaseEvidence(t *testing.T) { + deletingAt := time.Date(2026, 6, 15, 1, 0, 0, 0, time.UTC) + client := &fakeLifecycleOwnerClient{volumes: []SwBlockVolumeObject{{ + Ref: OperatorObjectRef{Namespace: "kube-system", Name: "deleting"}, + Finalizers: []string{SwBlockVolumeFinalizerName}, + DeletionTimestamp: &deletingAt, + }}} + events := &fakeOperatorEventSink{} + result, err := (LifecycleOwnerReconciler{ + Namespace: "kube-system", + Client: client, + EventSink: events, + }).Reconcile(context.Background()) + if err != nil { + t.Fatalf("reconcile: %v", err) + } + if result.FinalizerPatchCount != 0 || result.FinalizerHeldCount != 1 || len(client.patches) != 0 { + t.Fatalf("result=%+v patches=%+v", result, client.patches) + } + if events.countByReason(ReasonCleanupEvidenceMissing) != 1 { + t.Fatalf("events=%+v", events.events) + } +} + +func TestLifecycleOwnerReconcilerHoldsBlockedDeletingObject(t *testing.T) { + deletingAt := time.Date(2026, 6, 15, 1, 0, 0, 0, time.UTC) + client := &fakeLifecycleOwnerClient{volumes: []SwBlockVolumeObject{{ + Ref: OperatorObjectRef{Namespace: "kube-system", Name: "blocked"}, + Finalizers: []string{SwBlockVolumeFinalizerName}, + DeletionTimestamp: &deletingAt, + Status: SwBlockVolumeCRDStatus{DeleteSafety: &SwBlockVolumeCRDDeleteSafety{ + Decision: ManagedVolumeActionDecisionRejected, + State: DeleteSafetyStateBlocked, + Reason: "iscsi_node_records_present", + }}, + }}} + result, err := (LifecycleOwnerReconciler{Namespace: "kube-system", Client: client}).Reconcile(context.Background()) + if err != nil { + t.Fatalf("reconcile: %v", err) + } + if result.FinalizerPatchCount != 0 || result.FinalizerHeldCount != 1 || len(client.patches) != 0 { + t.Fatalf("result=%+v patches=%+v", result, client.patches) + } +} + +func TestLifecycleOwnerReconcilerReleasesOnlyProtectionFinalizerWhenAllowed(t *testing.T) { + deletingAt := time.Date(2026, 6, 15, 1, 0, 0, 0, time.UTC) + client := &fakeLifecycleOwnerClient{volumes: []SwBlockVolumeObject{{ + Ref: OperatorObjectRef{Namespace: "kube-system", Name: "clean"}, + Finalizers: []string{"example.com/foreign", SwBlockVolumeFinalizerName}, + DeletionTimestamp: &deletingAt, + Status: SwBlockVolumeCRDStatus{DeleteSafety: &SwBlockVolumeCRDDeleteSafety{ + Decision: ManagedVolumeActionDecisionAllowed, + State: DeleteSafetyStateReleasable, + Reason: ReasonDeleteFinalizerReleasable, + FinalizerReleaseAllowed: true, + EvidenceRefs: []string{"cleanup-summary.txt"}, + }}, + }}} + events := &fakeOperatorEventSink{} + result, err := (LifecycleOwnerReconciler{ + Namespace: "kube-system", + Client: client, + EventSink: events, + }).Reconcile(context.Background()) + if err != nil { + t.Fatalf("reconcile: %v", err) + } + if result.FinalizerPatchCount != 1 || result.FinalizerReleasedCount != 1 || result.FinalizerHeldCount != 0 { + t.Fatalf("result=%+v", result) + } + if want := []string{"example.com/foreign"}; !reflect.DeepEqual(client.patches[0].finalizers, want) { + t.Fatalf("finalizers=%+v want %+v", client.patches[0].finalizers, want) + } + if events.countByReason(ReasonDeleteFinalizerReleased) != 1 { + t.Fatalf("events=%+v", events.events) + } +} + +func TestLifecycleOwnerReconcilerDryRunDoesNotPatch(t *testing.T) { + client := &fakeLifecycleOwnerClient{volumes: []SwBlockVolumeObject{{ + Ref: OperatorObjectRef{Namespace: "kube-system", Name: "demo"}, + }}} + result, err := (LifecycleOwnerReconciler{Namespace: "kube-system", Client: client, DryRun: true}).Reconcile(context.Background()) + if err != nil { + t.Fatalf("reconcile: %v", err) + } + if result.FinalizerPatchCount != 0 || result.FinalizerAddedCount != 1 || len(client.patches) != 0 { + t.Fatalf("result=%+v patches=%+v", result, client.patches) + } +} + +type fakeLifecycleOwnerClient struct { + volumes []SwBlockVolumeObject + patches []fakeLifecycleOwnerPatch +} + +type fakeLifecycleOwnerPatch struct { + ref OperatorObjectRef + finalizers []string +} + +func (f *fakeLifecycleOwnerClient) ListSwBlockVolumes(context.Context, string) ([]SwBlockVolumeObject, error) { + return append([]SwBlockVolumeObject(nil), f.volumes...), nil +} + +func (f *fakeLifecycleOwnerClient) PatchSwBlockVolumeFinalizers(_ context.Context, ref OperatorObjectRef, finalizers []string) error { + f.patches = append(f.patches, fakeLifecycleOwnerPatch{ + ref: ref, + finalizers: append([]string(nil), finalizers...), + }) + return nil +} diff --git a/seaweed-block/core/ops/managed_volume_action_evaluator.go b/seaweed-block/core/ops/managed_volume_action_evaluator.go new file mode 100644 index 0000000000..dcfc28b084 --- /dev/null +++ b/seaweed-block/core/ops/managed_volume_action_evaluator.go @@ -0,0 +1,188 @@ +package ops + +import ( + "fmt" + "strings" +) + +const ( + ManagedVolumeActionDecisionAllowed = "allowed" + ManagedVolumeActionDecisionRejected = "rejected" + ManagedVolumeActionDecisionUnknown = "unknown" + + ManagedVolumeActionRejectUnknownAction = "unknown_action" + ManagedVolumeActionRejectDisabled = "policy_disabled" + ManagedVolumeActionRejectMissingFacts = "missing_required_facts" + ManagedVolumeActionRejectMutation = "mutation_not_allowed" +) + +// ManagedVolumeActionEvaluation is the executable contract for action hints. +// It does not perform the action. It decides whether the latest facts permit a +// read-only/dry-run action to be surfaced as executable by a future bounded +// executor, and it explains why not. +type ManagedVolumeActionEvaluation struct { + ActionType string `json:"action_type"` + Decision string `json:"decision"` + Mode string `json:"mode,omitempty"` + SideEffectClass string `json:"side_effect_class,omitempty"` + OwnerExecutor string `json:"owner_executor,omitempty"` + MutationAllowed bool `json:"mutation_allowed"` + Reason string `json:"reason,omitempty"` + MissingFacts []string `json:"missing_facts,omitempty"` + InvariantRefs []string `json:"invariant_refs,omitempty"` + EvidenceRequired string `json:"evidence_required,omitempty"` +} + +// EvaluateManagedVolumeAction evaluates one action against the latest +// ManagedVolume facts. The result is intentionally fail-closed: unknown actions, +// disabled policy gates, mutating actions, and missing required facts are +// rejected before any executor can be considered. +func EvaluateManagedVolumeAction(actionType string, facts ManagedVolumeFacts) ManagedVolumeActionEvaluation { + contract, ok := managedVolumeActionContractEntry(actionType) + if !ok { + return ManagedVolumeActionEvaluation{ + ActionType: actionType, + Decision: ManagedVolumeActionDecisionRejected, + Reason: ManagedVolumeActionRejectUnknownAction, + } + } + evaluation := ManagedVolumeActionEvaluation{ + ActionType: actionType, + Mode: contract.Mode, + SideEffectClass: contract.SideEffectClass, + OwnerExecutor: contract.OwnerExecutor, + MutationAllowed: contract.MutationAllowed, + InvariantRefs: append([]string(nil), contract.InvariantRefs...), + EvidenceRequired: contract.EvidenceRequired, + } + if contract.PolicyGate == ActionPolicyDisabled { + evaluation.Decision = ManagedVolumeActionDecisionRejected + evaluation.Reason = ManagedVolumeActionRejectDisabled + return evaluation + } + if contract.MutationAllowed { + evaluation.Decision = ManagedVolumeActionDecisionRejected + evaluation.Reason = ManagedVolumeActionRejectMutation + return evaluation + } + missing := missingManagedVolumeActionFacts(contract.RequiredFacts, facts) + if len(missing) > 0 { + evaluation.Decision = ManagedVolumeActionDecisionRejected + evaluation.Reason = ManagedVolumeActionRejectMissingFacts + evaluation.MissingFacts = missing + return evaluation + } + evaluation.Decision = ManagedVolumeActionDecisionAllowed + return evaluation +} + +func managedVolumeActionContractEntry(actionType string) (ManagedVolumeActionContractEntry, bool) { + for _, entry := range ManagedVolumeActionContract() { + if entry.Type == actionType { + return entry, true + } + } + return ManagedVolumeActionContractEntry{}, false +} + +func missingManagedVolumeActionFacts(required []string, facts ManagedVolumeFacts) []string { + var missing []string + for _, requiredFact := range required { + if !managedVolumeActionFactPresent(requiredFact, facts) { + missing = append(missing, requiredFact) + } + } + return missing +} + +func managedVolumeActionFactPresent(requiredFact string, facts ManagedVolumeFacts) bool { + switch requiredFact { + case "evidence.reason_code": + return facts.ProductReason != "" || facts.EvidenceStaleReason != "" || len(facts.EvidenceRefs) > 0 + case "identity.pvc_name": + return facts.PVCName != "" + case "kubernetes.pvc_phase": + return facts.PVC != nil && facts.PVC.Phase != "" + case "csi.staged_target": + for _, stage := range facts.CSIStages { + if stage.Target != "" { + return true + } + } + return false + case "host_path.rtpg_aas": + for _, path := range facts.HostPaths { + if path.ALUAState != "" || path.ANAState != "" { + return true + } + } + return false + case "host_path.stale_path_probe": + for _, path := range facts.HostPaths { + if path.StaleFenced { + return true + } + } + return false + case "authority.publish_target": + return facts.Authority != nil && facts.Authority.PublishTarget != "" + case "placement.replica_node": + for _, replica := range facts.Replicas { + if replica.KubernetesNode != "" || replica.ServerID != "" || replica.PhysicalHost != "" { + return true + } + } + return false + case "authority.primary_replica": + return facts.Authority != nil && facts.Authority.PrimaryReplica != "" + case "replica.durable_frontier_lsn": + for _, replica := range facts.Replicas { + if replica.DurableFrontierKnown { + return true + } + } + return false + default: + // Unknown fact names are treated as missing so new contract entries + // must be deliberately wired into this executable evaluator. + return false + } +} + +func (e ManagedVolumeActionEvaluation) String() string { + if e.Decision == ManagedVolumeActionDecisionAllowed { + return fmt.Sprintf("%s %s mode=%s executor=%s", e.ActionType, e.Decision, e.Mode, e.OwnerExecutor) + } + if len(e.MissingFacts) == 0 { + return fmt.Sprintf("%s %s reason=%s", e.ActionType, e.Decision, e.Reason) + } + return fmt.Sprintf("%s %s reason=%s missing=%s", e.ActionType, e.Decision, e.Reason, strings.Join(e.MissingFacts, ",")) +} + +func RenderManagedVolumeActionEvaluationText(e ManagedVolumeActionEvaluation) string { + var b strings.Builder + fmt.Fprintf(&b, "managed_volume_action_evaluation %s decision=%s", emptyAsDash(e.ActionType), emptyAsDash(e.Decision)) + if e.Mode != "" { + fmt.Fprintf(&b, " mode=%s", e.Mode) + } + if e.SideEffectClass != "" { + fmt.Fprintf(&b, " side_effect=%s", e.SideEffectClass) + } + if e.OwnerExecutor != "" { + fmt.Fprintf(&b, " executor=%s", e.OwnerExecutor) + } + if e.Reason != "" { + fmt.Fprintf(&b, " reason=%s", e.Reason) + } + fmt.Fprintf(&b, " mutation_allowed=%t\n", e.MutationAllowed) + if len(e.MissingFacts) > 0 { + fmt.Fprintf(&b, "managed_volume_action_evaluation_missing_facts %s %s\n", emptyAsDash(e.ActionType), strings.Join(e.MissingFacts, ",")) + } + if len(e.InvariantRefs) > 0 { + fmt.Fprintf(&b, "managed_volume_action_evaluation_invariants %s %s\n", emptyAsDash(e.ActionType), strings.Join(e.InvariantRefs, ",")) + } + if e.EvidenceRequired != "" { + fmt.Fprintf(&b, "managed_volume_action_evaluation_evidence_required %s %s\n", emptyAsDash(e.ActionType), e.EvidenceRequired) + } + return b.String() +} diff --git a/seaweed-block/core/ops/managed_volume_action_evaluator_test.go b/seaweed-block/core/ops/managed_volume_action_evaluator_test.go new file mode 100644 index 0000000000..94f2633dbe --- /dev/null +++ b/seaweed-block/core/ops/managed_volume_action_evaluator_test.go @@ -0,0 +1,162 @@ +package ops + +import ( + "strings" + "testing" +) + +func TestEvaluateManagedVolumeAction_AllowsDryRunWhenFactsPresent(t *testing.T) { + evaluation := EvaluateManagedVolumeAction(ManagedVolumeActionReinstallExternalISCSI, ManagedVolumeFacts{ + Authority: &AuthorityFact{PublishTarget: "127.0.0.1:3260"}, + Replicas: []ReplicaFact{{ + ReplicaID: "r1", + KubernetesNode: "m02", + }}, + }) + + if evaluation.Decision != ManagedVolumeActionDecisionAllowed { + t.Fatalf("decision=%s reason=%s missing=%v", evaluation.Decision, evaluation.Reason, evaluation.MissingFacts) + } + if evaluation.Mode != ManagedVolumeActionModeDryRun { + t.Fatalf("mode=%s want %s", evaluation.Mode, ManagedVolumeActionModeDryRun) + } + if evaluation.SideEffectClass != ManagedVolumeSideEffectSafeK8S { + t.Fatalf("side_effect_class=%s want %s", evaluation.SideEffectClass, ManagedVolumeSideEffectSafeK8S) + } + if evaluation.OwnerExecutor != "installer_or_operator" { + t.Fatalf("owner_executor=%q", evaluation.OwnerExecutor) + } + if evaluation.MutationAllowed { + t.Fatal("dry-run evaluation must not allow mutation") + } + if len(evaluation.InvariantRefs) == 0 || evaluation.EvidenceRequired == "" { + t.Fatalf("evaluation missing invariant/evidence contract: %+v", evaluation) + } +} + +func TestEvaluateManagedVolumeAction_RejectsMissingRequiredFacts(t *testing.T) { + evaluation := EvaluateManagedVolumeAction(ManagedVolumeActionReinstallExternalISCSI, ManagedVolumeFacts{ + Authority: &AuthorityFact{PublishTarget: "127.0.0.1:3260"}, + }) + + if evaluation.Decision != ManagedVolumeActionDecisionRejected { + t.Fatalf("decision=%s want rejected", evaluation.Decision) + } + if evaluation.Reason != ManagedVolumeActionRejectMissingFacts { + t.Fatalf("reason=%s want %s", evaluation.Reason, ManagedVolumeActionRejectMissingFacts) + } + if len(evaluation.MissingFacts) != 1 || evaluation.MissingFacts[0] != "placement.replica_node" { + t.Fatalf("missing facts=%v", evaluation.MissingFacts) + } + if evaluation.MutationAllowed { + t.Fatal("rejected evaluation must not allow mutation") + } +} + +func TestEvaluateManagedVolumeAction_RejectsDisabledAuthorityMutation(t *testing.T) { + evaluation := EvaluateManagedVolumeAction(ManagedVolumeActionRequestPromotion, ManagedVolumeFacts{ + Authority: &AuthorityFact{PrimaryReplica: "r1"}, + Replicas: []ReplicaFact{{ + ReplicaID: "r2", + DurableFrontierKnown: true, + DurableFrontierLSN: 42, + }}, + }) + + if evaluation.Decision != ManagedVolumeActionDecisionRejected { + t.Fatalf("decision=%s want rejected", evaluation.Decision) + } + if evaluation.Reason != ManagedVolumeActionRejectDisabled { + t.Fatalf("reason=%s want %s", evaluation.Reason, ManagedVolumeActionRejectDisabled) + } + if evaluation.SideEffectClass != ManagedVolumeSideEffectAuthorityMutating { + t.Fatalf("side_effect_class=%s want %s", evaluation.SideEffectClass, ManagedVolumeSideEffectAuthorityMutating) + } + if evaluation.MutationAllowed { + t.Fatal("disabled authority action must not allow mutation") + } +} + +func TestEvaluateManagedVolumeAction_RejectsUnknownAction(t *testing.T) { + evaluation := EvaluateManagedVolumeAction("delete.everything", ManagedVolumeFacts{}) + + if evaluation.Decision != ManagedVolumeActionDecisionRejected { + t.Fatalf("decision=%s want rejected", evaluation.Decision) + } + if evaluation.Reason != ManagedVolumeActionRejectUnknownAction { + t.Fatalf("reason=%s want %s", evaluation.Reason, ManagedVolumeActionRejectUnknownAction) + } +} + +func TestManagedVolumeActionEvaluator_CoversEveryContractEntry(t *testing.T) { + for _, entry := range ManagedVolumeActionContract() { + evaluation := EvaluateManagedVolumeAction(entry.Type, factsSatisfyingActionContract(entry)) + if entry.PolicyGate == ActionPolicyDisabled { + if evaluation.Decision != ManagedVolumeActionDecisionRejected || evaluation.Reason != ManagedVolumeActionRejectDisabled { + t.Fatalf("disabled action %s evaluation=%+v", entry.Type, evaluation) + } + continue + } + if evaluation.Decision != ManagedVolumeActionDecisionAllowed { + t.Fatalf("action %s should be evaluable with satisfying facts: %+v", entry.Type, evaluation) + } + if evaluation.Mode != entry.Mode || evaluation.SideEffectClass != entry.SideEffectClass || evaluation.OwnerExecutor != entry.OwnerExecutor { + t.Fatalf("action %s evaluation boundary=%+v contract=%+v", entry.Type, evaluation, entry) + } + } +} + +func TestRenderManagedVolumeActionEvaluationText_ShowsRejectedAction(t *testing.T) { + text := RenderManagedVolumeActionEvaluationText(EvaluateManagedVolumeAction(ManagedVolumeActionRequestPromotion, ManagedVolumeFacts{ + Authority: &AuthorityFact{PrimaryReplica: "r1"}, + Replicas: []ReplicaFact{{ + ReplicaID: "r2", + DurableFrontierKnown: true, + DurableFrontierLSN: 42, + }}, + })) + + for _, want := range []string{ + "managed_volume_action_evaluation authority.request_promotion decision=rejected", + "side_effect=authority_mutating", + "executor=authority_recovery_executor", + "reason=policy_disabled", + "mutation_allowed=false", + "managed_volume_action_evaluation_evidence_required authority.request_promotion promotion_readiness_evidence", + } { + if !strings.Contains(text, want) { + t.Fatalf("rendered evaluation missing %q:\n%s", want, text) + } + } +} + +func factsSatisfyingActionContract(entry ManagedVolumeActionContractEntry) ManagedVolumeFacts { + facts := ManagedVolumeFacts{ + VolumeID: "pvc-action", + PVCName: "demo-pvc", + ProductReason: ReasonPublishTargetLoopbackCrossNode, + EvidenceRefs: []string{"action-evidence.txt"}, + PVC: &PVCFact{Phase: "Bound"}, + Authority: &AuthorityFact{ + PrimaryReplica: "r1", + PublishTarget: "127.0.0.1:3260", + }, + Replicas: []ReplicaFact{{ + ReplicaID: "r1", + ServerID: "m02", + KubernetesNode: "m02", + DurableFrontierKnown: true, + DurableFrontierLSN: 42, + }}, + CSIStages: []CSIStageFact{{ + NodeName: "m01", + Target: "127.0.0.1:3260", + }}, + HostPaths: []HostPathFact{{ + Protocol: "iscsi", + ALUAState: "0x00", + StaleFenced: true, + }}, + } + return facts +} diff --git a/seaweed-block/core/ops/managed_volume_conditions_test.go b/seaweed-block/core/ops/managed_volume_conditions_test.go index 823bae239e..45d23c091d 100644 --- a/seaweed-block/core/ops/managed_volume_conditions_test.go +++ b/seaweed-block/core/ops/managed_volume_conditions_test.go @@ -1,6 +1,9 @@ package ops -import "testing" +import ( + "strings" + "testing" +) func TestManagedVolumeProjection_ReadyConditionForFirstVolume(t *testing.T) { projection := ProjectManagedVolume(ManagedVolumeFacts{ @@ -121,6 +124,91 @@ func TestManagedVolumeProjection_EvidenceStaleIsNotReady(t *testing.T) { } } +func TestManagedVolumeProjection_StatusEndpointUnreachableIsNotReady(t *testing.T) { + projection := ProjectManagedVolume(ManagedVolumeFacts{ + VolumeID: "pvc-unreachable", + ProductStatus: ObservationStatusUnavailable, + ProductReason: ReasonStatusEndpointUnreachable, + EvidenceRefs: []string{"ops-inventory/volume-inventory.json"}, + }) + + ready := findObservationCondition(projection.Conditions, "Ready") + stale := findObservationCondition(projection.Conditions, "EvidenceStale") + if ready == nil || stale == nil { + t.Fatalf("conditions=%+v", projection.Conditions) + } + if ready.Status != "Unknown" || ready.Reason != ReasonStatusEndpointUnreachable || ready.Severity != "warning" { + t.Fatalf("ready=%+v", ready) + } + if stale.Status != "True" || stale.Reason != ReasonStatusEndpointUnreachable || stale.Severity != "warning" { + t.Fatalf("stale=%+v", stale) + } + if projection.Status != ManagedVolumeStatusUnknown || projection.ReasonCode != ReasonStatusEndpointUnreachable { + t.Fatalf("projection=%+v", projection) + } +} + +func TestManagedVolumeProjection_WALIntegrityFaultIsBlockedNotReady(t *testing.T) { + projection := ProjectManagedVolume(ManagedVolumeFacts{ + VolumeID: "pvc-corrupt", + ProductStatus: ObservationStatusBlocked, + ProductReason: ReasonWALIntegrityFault, + EvidenceRefs: []string{"status/report/cluster-evidence.json"}, + }) + + ready := findObservationCondition(projection.Conditions, "Ready") + blocked := findObservationCondition(projection.Conditions, "Blocked") + if ready == nil || blocked == nil { + t.Fatalf("conditions=%+v", projection.Conditions) + } + if ready.Status != "False" || ready.Reason != ReasonWALIntegrityFault || ready.Severity != "warning" { + t.Fatalf("ready=%+v", ready) + } + if blocked.Status != "True" || blocked.Reason != ReasonWALIntegrityFault { + t.Fatalf("blocked=%+v", blocked) + } + if projection.Status != ManagedVolumeStatusBlocked || projection.ReasonCode != ReasonWALIntegrityFault { + t.Fatalf("projection=%+v", projection) + } +} + +func TestReasonFromIssueList_WALIntegrityFault(t *testing.T) { + got := reasonFromIssueList([]string{ + "ops_status=unhealthy reason=durable_pvc_r1_operational_false_evidence_recover_failed_storage_walintegrity_crc_mismatch", + }) + if got != ReasonWALIntegrityFault { + t.Fatalf("reason=%s want %s", got, ReasonWALIntegrityFault) + } +} + +func TestVolumeStatusReportIssues_CarriesDurableEvidence(t *testing.T) { + issues := VolumeStatusReportIssues(VolumeStatusReport{ + SchemaVersion: VolumeStatusReportSchemaVersion, + ProductRevision: "test", + Volume: VolumeReport{ + VolumeID: "pvc-corrupt", + ReplicaID: "r1", + }, + Authority: AuthorityReport{ + AuthorityRole: "primary", + Healthy: true, + FrontendPrimaryReady: true, + }, + Replication: ReplicationReport{ReplicationRole: "none"}, + Durable: []DurableReport{{ + VolumeID: "pvc-corrupt", + ReplicaID: "r1", + Latched: true, + Operational: false, + Evidence: "recover failed: storage: WALIntegrity: CRC mismatch", + }}, + }) + joined := strings.Join(issues, "\n") + if !strings.Contains(joined, "WALIntegrity") { + t.Fatalf("issues missing WALIntegrity evidence: %v", issues) + } +} + func findObservationCondition(conditions []ObservationCondition, conditionType string) *ObservationCondition { for i := range conditions { if conditions[i].Type == conditionType { diff --git a/seaweed-block/core/ops/managed_volume_contract.go b/seaweed-block/core/ops/managed_volume_contract.go index 186ab0e21b..7d3bf41e36 100644 --- a/seaweed-block/core/ops/managed_volume_contract.go +++ b/seaweed-block/core/ops/managed_volume_contract.go @@ -360,6 +360,125 @@ func ManagedVolumeFactContract() []ManagedVolumeFactContractEntry { } } +func LiveNodeEvidenceFactContract() []ManagedVolumeFactContractEntry { + return []ManagedVolumeFactContractEntry{ + { + Path: "node.kubernetes_ready", + Stability: ManagedVolumeFieldStable, + Participant: "kubernetes_node_watcher", + FactAuthority: FactAuthorityKubernetesObject, + Master: MasterManagedVolume, + AggregationMode: FactAggregationPassive, + ConditionSurface: "SwBlockCluster.status.nodes[].Ready", + EvidenceRequired: "kubernetes_node_ready_condition", + }, + { + Path: "node.scheduling_disabled", + Stability: ManagedVolumeFieldStable, + Participant: "kubernetes_node_watcher", + FactAuthority: FactAuthorityKubernetesObject, + Master: MasterManagedVolume, + AggregationMode: FactAggregationPassive, + ConditionSurface: "SwBlockCluster.status.nodes[].Blocked", + EvidenceRequired: "kubernetes_node_unschedulable_field", + }, + { + Path: "node.csi_node_pod_ready", + Stability: ManagedVolumeFieldStable, + Participant: "kubernetes_pod_watcher", + FactAuthority: FactAuthorityKubernetesObject, + Master: MasterManagedVolume, + AggregationMode: FactAggregationPassive, + ConditionSurface: "SwBlockCluster.status.nodes[].Blocked", + EvidenceRequired: "csi_node_daemonset_pod_status", + }, + { + Path: "node.csi_driver_exists", + Stability: ManagedVolumeFieldStable, + Participant: "kubernetes_csi_watcher", + FactAuthority: FactAuthorityKubernetesObject, + Master: MasterManagedVolume, + AggregationMode: FactAggregationPassive, + ConditionSurface: "SwBlockCluster.status.nodes[].Blocked", + EvidenceRequired: "csidriver_object", + }, + { + Path: "node.csi_node_driver_registered", + Stability: ManagedVolumeFieldStable, + Participant: "kubernetes_csi_watcher", + FactAuthority: FactAuthorityKubernetesObject, + Master: MasterManagedVolume, + AggregationMode: FactAggregationPassive, + ConditionSurface: "SwBlockCluster.status.nodes[].Blocked", + EvidenceRequired: "csinode_driver_entry", + }, + { + Path: "node.required_image_presence", + Stability: ManagedVolumeFieldProvisional, + Participant: "image_inventory_observer", + FactAuthority: FactAuthorityObservation, + Master: MasterManagedVolume, + AggregationMode: FactAggregationPassive, + ConditionSurface: "SwBlockCluster.status.nodes[].Blocked", + EvidenceRequired: "node_image_inventory_or_pod_image_pull_status", + }, + { + Path: "node.image_pull_status", + Stability: ManagedVolumeFieldStable, + Participant: "kubernetes_pod_watcher", + FactAuthority: FactAuthorityKubernetesObject, + Master: MasterManagedVolume, + AggregationMode: FactAggregationPassive, + ConditionSurface: "SwBlockCluster.status.nodes[].Blocked", + EvidenceRequired: "pod_container_waiting_reason", + }, + { + Path: "node.iscsi_prereq", + Stability: ManagedVolumeFieldProvisional, + Participant: "host_prereq_observer", + FactAuthority: FactAuthorityHostPath, + Master: MasterManagedVolume, + AggregationMode: FactAggregationPassive, + ConditionSurface: "SwBlockCluster.status.nodes[].Blocked", + EvidenceRequired: "iscsiadm_or_preflight_artifact", + }, + { + Path: "node.multipath_prereq", + Stability: ManagedVolumeFieldProvisional, + Participant: "host_prereq_observer", + FactAuthority: FactAuthorityHostPath, + Master: MasterManagedVolume, + AggregationMode: FactAggregationPassive, + ConditionSurface: "SwBlockCluster.status.nodes[].Blocked", + EvidenceRequired: "multipath_or_preflight_artifact", + }, + { + Path: "node.loopback_publish_target_cross_node", + Stability: ManagedVolumeFieldStable, + Participant: "managed_volume_projector", + FactAuthority: FactAuthorityObservation, + Master: MasterManagedVolume, + AggregationMode: FactAggregationPassive, + ConditionSurface: "SwBlockCluster.status.nodes[].Blocked", + EvidenceRequired: "publish_target_and_consumer_node_evidence", + }, + } +} + +func LiveNodeEvidenceReasonCodes() []string { + return []string{ + ReasonNodeReady, + ReasonNodeNotReady, + ReasonNodeSchedulingDisabled, + ReasonCSINodePodNotReady, + ReasonCSIDriverNotRegistered, + ReasonImageMissingOnNode, + ReasonISCSIPrereqMissing, + ReasonMultipathPrereqMissing, + ReasonPublishTargetLoopbackCrossNode, + } +} + func ManagedVolumeActionContract() []ManagedVolumeActionContractEntry { return []ManagedVolumeActionContractEntry{ { diff --git a/seaweed-block/core/ops/managed_volume_crd_contract.go b/seaweed-block/core/ops/managed_volume_crd_contract.go index abb495abb3..907c1faaf4 100644 --- a/seaweed-block/core/ops/managed_volume_crd_contract.go +++ b/seaweed-block/core/ops/managed_volume_crd_contract.go @@ -63,7 +63,10 @@ func ManagedVolumeCRDContractDefinition() ManagedVolumeCRDContract { "repair", "rebuild", "failback", + "create_pvc", + "delete_pvc", "delete_storage", + "delete_iscsi_session", "cleanup_live_state", }, MutatingStorageVerbsAllowed: false, @@ -84,12 +87,16 @@ func ManagedVolumeCRDContractDefinition() ManagedVolumeCRDContract { "status.conditions", "status.observedAt", "status.nodeCount", + "status.nodes", "status.volumeCount", "status.readyVolumeCount", "status.blockedVolumeCount", "status.staleVolumeCount", "status.observedGeneration", "status.evidenceRefs", + "status.supportBundleRefs", + "status.cleanup", + "status.safeNextSteps", }, NonClaims: []string{ "no_mutating_storage_actions", diff --git a/seaweed-block/core/ops/managed_volume_crd_contract_test.go b/seaweed-block/core/ops/managed_volume_crd_contract_test.go index 156ffbe386..08c2921b1d 100644 --- a/seaweed-block/core/ops/managed_volume_crd_contract_test.go +++ b/seaweed-block/core/ops/managed_volume_crd_contract_test.go @@ -48,6 +48,43 @@ func TestManagedVolumeCRDContract_StatusOnlyResources(t *testing.T) { } } +func TestManagedVolumeCRDContract_Phase36ActionabilityFields(t *testing.T) { + contract := ManagedVolumeCRDContractDefinition() + var cluster ManagedVolumeCRDKind + for _, resource := range contract.Resources { + if resource.Kind == SwBlockClusterKind { + cluster = resource + break + } + } + if cluster.Kind == "" { + t.Fatalf("missing %s resource", SwBlockClusterKind) + } + for _, want := range []string{ + "status.nodes", + "status.cleanup", + "status.supportBundleRefs", + "status.safeNextSteps", + } { + if !stringSliceContains(cluster.StatusPaths, want) { + t.Fatalf("cluster status contract missing %s in %+v", want, cluster.StatusPaths) + } + } + for _, forbidden := range []string{ + "create_pvc", + "delete_pvc", + "delete_iscsi_session", + "cleanup_live_state", + "repair", + "rebuild", + "failback", + } { + if !stringSliceContains(contract.RBAC.ForbiddenActions, forbidden) { + t.Fatalf("phase36 forbidden action %s missing from %+v", forbidden, contract.RBAC.ForbiddenActions) + } + } +} + func TestManagedVolumeCRDContract_ConditionVocabularyCoversProjection(t *testing.T) { contract := ManagedVolumeCRDContractDefinition() for _, condition := range []string{ diff --git a/seaweed-block/core/ops/managed_volume_evidence_test.go b/seaweed-block/core/ops/managed_volume_evidence_test.go index 6d60004d76..a046dfa316 100644 --- a/seaweed-block/core/ops/managed_volume_evidence_test.go +++ b/seaweed-block/core/ops/managed_volume_evidence_test.go @@ -83,3 +83,39 @@ func TestProjectManagedVolumeFromEvidence_ImagePullBlocked(t *testing.T) { t.Fatalf("missing import action: %+v", projection.Actions) } } + +func TestProjectManagedVolumeFromEvidence_PrimaryReadinessBlockIsNotReady(t *testing.T) { + projection := ProjectManagedVolumeFromEvidence(VolumeEvidence{ + VolumeID: "pvc-corrupt", + Namespace: "default", + PVCName: "demo-pvc", + PVName: "pvc-corrupt", + Status: ObservationStatusDegraded, + Reason: ReasonNoPromotionReadyCandidate, + PrimaryReplica: "r1", + PublishTarget: "192.168.1.184:3260", + Replicas: []ReplicaEvidence{{ + ReplicaID: "r1", + KubernetesNode: "m02", + Observed: true, + Role: "primary", + CandidateReady: false, + CandidateReadyReason: ReasonNoPromotionReadyCandidate, + FrontendAddr: "192.168.1.184:3260", + }}, + Conditions: []ObservationCondition{{ + Type: "PrimaryReady", + Status: "false", + Reason: ReasonNoPromotionReadyCandidate, + Severity: "warning", + }}, + }) + + if projection.Status == ManagedVolumeStatusReady { + t.Fatalf("primary readiness block projected Ready: %+v", projection) + } + ready := findObservationCondition(projection.Conditions, "Ready") + if ready != nil && ready.Status == "True" { + t.Fatalf("primary readiness block emitted Ready=True: %+v", projection.Conditions) + } +} diff --git a/seaweed-block/core/ops/managed_volume_model.go b/seaweed-block/core/ops/managed_volume_model.go index ef3fdfa48e..eb253eed09 100644 --- a/seaweed-block/core/ops/managed_volume_model.go +++ b/seaweed-block/core/ops/managed_volume_model.go @@ -46,6 +46,7 @@ const ( ManagedVolumeActionModeReadOnly = "read_only" ManagedVolumeActionModeDryRun = "dry_run" + ManagedVolumeActionModeScripted = "scripted" ManagedVolumeSideEffectObserve = "observe" ManagedVolumeSideEffectSafeK8S = "safe_k8s" @@ -55,6 +56,7 @@ const ( ManagedVolumeSideEffectDestructive = "destructive" ManagedVolumeActionCollectBundle = "observe.collect_bundle" + ManagedVolumeActionVerifyCleanup = "observe.verify_cleanup" ManagedVolumeActionReinstallExternalISCSI = "safe_k8s.reinstall_external_iscsi" ManagedVolumeActionWaitForPVCBound = "observe.wait_for_pvc_bound" ManagedVolumeActionInspectMountFailure = "observe.inspect_mount_failure" @@ -195,21 +197,22 @@ type WorkloadCheckFact struct { } type ManagedVolumeProjection struct { - VolumeID string `json:"volume_id,omitempty"` - Namespace string `json:"namespace,omitempty"` - PVCName string `json:"pvc_name,omitempty"` - PVName string `json:"pv_name,omitempty"` - StorageClass string `json:"storage_class,omitempty"` - ReplicationFactor int `json:"replication_factor,omitempty"` - AckProfile string `json:"ack_profile,omitempty"` - ClaimProfile string `json:"claim_profile,omitempty"` - Status string `json:"status"` - ReasonCode string `json:"reason_code,omitempty"` - States ManagedVolumeStates `json:"states"` - Actions []ManagedVolumeAction `json:"actions,omitempty"` - Conditions []ObservationCondition `json:"conditions,omitempty"` - NonClaims []string `json:"non_claims,omitempty"` - EvidenceRefs []string `json:"evidence_refs,omitempty"` + VolumeID string `json:"volume_id,omitempty"` + Namespace string `json:"namespace,omitempty"` + PVCName string `json:"pvc_name,omitempty"` + PVName string `json:"pv_name,omitempty"` + StorageClass string `json:"storage_class,omitempty"` + ReplicationFactor int `json:"replication_factor,omitempty"` + AckProfile string `json:"ack_profile,omitempty"` + ClaimProfile string `json:"claim_profile,omitempty"` + Status string `json:"status"` + ReasonCode string `json:"reason_code,omitempty"` + States ManagedVolumeStates `json:"states"` + Actions []ManagedVolumeAction `json:"actions,omitempty"` + Conditions []ObservationCondition `json:"conditions,omitempty"` + DeleteSafety *SwBlockVolumeDeleteSafetyDecision `json:"delete_safety,omitempty"` + NonClaims []string `json:"non_claims,omitempty"` + EvidenceRefs []string `json:"evidence_refs,omitempty"` } type ManagedVolumeStates struct { @@ -222,14 +225,18 @@ type ManagedVolumeStates struct { } type ManagedVolumeAction struct { - Type string `json:"type"` - Target string `json:"target,omitempty"` - Mode string `json:"mode"` - SideEffectClass string `json:"side_effect_class"` - OwnerExecutor string `json:"owner_executor,omitempty"` - Preconditions []string `json:"preconditions,omitempty"` - InvariantRefs []string `json:"invariant_refs,omitempty"` - EvidenceRefs []string `json:"evidence_refs,omitempty"` + Type string `json:"type"` + Target string `json:"target,omitempty"` + Mode string `json:"mode"` + SideEffectClass string `json:"side_effect_class"` + OwnerExecutor string `json:"owner_executor,omitempty"` + Decision string `json:"decision,omitempty"` + DecisionReason string `json:"decision_reason,omitempty"` + MissingFacts []string `json:"missing_facts,omitempty"` + Preconditions []string `json:"preconditions,omitempty"` + InvariantRefs []string `json:"invariant_refs,omitempty"` + EvidenceRequired string `json:"evidence_required,omitempty"` + EvidenceRefs []string `json:"evidence_refs,omitempty"` } type ManagedVolumeArtifactHints struct { @@ -258,6 +265,20 @@ func RenderManagedVolumeProjectionText(projection ManagedVolumeProjection) strin emptyAsDash(projection.States.HostPath), emptyAsDash(projection.States.Recovery), emptyAsDash(projection.States.Workload)) + if projection.DeleteSafety != nil { + fmt.Fprintf(&b, "managed_volume_delete_safety state=%s decision=%s reason=%s release_allowed=%t action=%s\n", + emptyAsDash(projection.DeleteSafety.State), + emptyAsDash(projection.DeleteSafety.Decision), + emptyAsDash(projection.DeleteSafety.Reason), + projection.DeleteSafety.FinalizerReleaseAllowed, + emptyAsDash(projection.DeleteSafety.ActionType)) + if projection.DeleteSafety.SafeNextAction != "" { + fmt.Fprintf(&b, "managed_volume_delete_safety_safe_next_action %s\n", projection.DeleteSafety.SafeNextAction) + } + if len(projection.DeleteSafety.EvidenceRefs) > 0 { + fmt.Fprintf(&b, "managed_volume_delete_safety_evidence %s\n", strings.Join(projection.DeleteSafety.EvidenceRefs, ",")) + } + } for _, condition := range projection.Conditions { fmt.Fprintf(&b, "managed_volume_condition %s status=%s reason=%s severity=%s", emptyAsDash(condition.Type), @@ -275,11 +296,21 @@ func RenderManagedVolumeProjectionText(projection ManagedVolumeProjection) strin } } for _, action := range projection.Actions { - fmt.Fprintf(&b, "managed_volume_action %s mode=%s side_effect=%s executor=%s\n", + fmt.Fprintf(&b, "managed_volume_action %s mode=%s side_effect=%s executor=%s decision=%s", emptyAsDash(action.Type), emptyAsDash(action.Mode), emptyAsDash(action.SideEffectClass), - emptyAsDash(action.OwnerExecutor)) + emptyAsDash(action.OwnerExecutor), + emptyAsDash(action.Decision)) + if action.DecisionReason != "" { + fmt.Fprintf(&b, " reason=%s", action.DecisionReason) + } + b.WriteByte('\n') + if len(action.MissingFacts) > 0 { + fmt.Fprintf(&b, "managed_volume_action_missing_facts %s %s\n", + emptyAsDash(action.Type), + strings.Join(action.MissingFacts, ",")) + } if len(action.Preconditions) > 0 { fmt.Fprintf(&b, "managed_volume_action_preconditions %s %s\n", emptyAsDash(action.Type), @@ -295,6 +326,11 @@ func RenderManagedVolumeProjectionText(projection ManagedVolumeProjection) strin emptyAsDash(action.Type), strings.Join(action.EvidenceRefs, ",")) } + if action.EvidenceRequired != "" { + fmt.Fprintf(&b, "managed_volume_action_evidence_required %s %s\n", + emptyAsDash(action.Type), + action.EvidenceRequired) + } } for _, nonClaim := range projection.NonClaims { fmt.Fprintf(&b, "managed_volume_non_claim %s\n", nonClaim) @@ -523,6 +559,9 @@ func classifyManagedVolume(p ManagedVolumeProjection, facts ManagedVolumeFacts) if facts.ProductReason == ReasonCSINodeImagePullFailed { return ManagedVolumeStatusBlocked, ReasonCSINodeImagePullFailed } + if facts.ProductReason == ReasonWALIntegrityFault { + return ManagedVolumeStatusBlocked, ReasonWALIntegrityFault + } if hasBlockedCSINode(facts.KubernetesNodes) { return ManagedVolumeStatusBlocked, ReasonCSINodeImagePullFailed } @@ -541,6 +580,9 @@ func classifyManagedVolume(p ManagedVolumeProjection, facts ManagedVolumeFacts) if facts.EvidenceStale || facts.ProductReason == ReasonEvidenceStale { return ManagedVolumeStatusUnknown, defaultString(facts.EvidenceStaleReason, ReasonEvidenceStale) } + if facts.ProductReason == ReasonStatusEndpointUnreachable { + return ManagedVolumeStatusUnknown, ReasonStatusEndpointUnreachable + } if p.States.HostPath == ManagedVolumeHostPathTransparentReady && facts.Workload != nil && facts.Workload.WriterVerified && @@ -637,6 +679,16 @@ func managedVolumeActionsForProjection(p ManagedVolumeProjection, facts ManagedV EvidenceRefs: append([]string(nil), p.EvidenceRefs...), }) } + for i := range actions { + evaluation := EvaluateManagedVolumeAction(actions[i].Type, facts) + actions[i].Decision = evaluation.Decision + actions[i].DecisionReason = evaluation.Reason + actions[i].MissingFacts = append([]string(nil), evaluation.MissingFacts...) + actions[i].EvidenceRequired = evaluation.EvidenceRequired + if len(actions[i].InvariantRefs) == 0 { + actions[i].InvariantRefs = append([]string(nil), evaluation.InvariantRefs...) + } + } return actions } @@ -744,7 +796,7 @@ func managedVolumeConditionsForProjection(p ManagedVolumeProjection) []Observati Message: "insufficient managed volume facts", EvidenceRefs: append([]string(nil), p.EvidenceRefs...), }} - if reason == ReasonEvidenceStale { + if reason == ReasonEvidenceStale || reason == ReasonStatusEndpointUnreachable { conditions[0].Severity = "warning" conditions[0].Message = "managed volume evidence is stale or unreachable; readiness is not claimed" conditions = append(conditions, ObservationCondition{ diff --git a/seaweed-block/core/ops/managed_volume_model_test.go b/seaweed-block/core/ops/managed_volume_model_test.go index 855ec18d9b..9c7cc1bf03 100644 --- a/seaweed-block/core/ops/managed_volume_model_test.go +++ b/seaweed-block/core/ops/managed_volume_model_test.go @@ -373,6 +373,12 @@ func TestManagedVolumeProjection_ActionInvariantRefs(t *testing.T) { if action.OwnerExecutor != "installer_or_operator" || action.SideEffectClass != ManagedVolumeSideEffectSafeK8S || action.Mode != ManagedVolumeActionModeDryRun { t.Fatalf("action boundary=%+v", action) } + if action.Decision != ManagedVolumeActionDecisionAllowed { + t.Fatalf("action decision=%s reason=%s missing=%v", action.Decision, action.DecisionReason, action.MissingFacts) + } + if action.EvidenceRequired != "loopback_cross_node_evidence" { + t.Fatalf("evidence_required=%q", action.EvidenceRequired) + } } func TestManagedVolumeProjection_NonClaimsDerivedFromFacts(t *testing.T) { diff --git a/seaweed-block/core/ops/managed_volume_operator_contract.go b/seaweed-block/core/ops/managed_volume_operator_contract.go index f7335b8fcc..863559eb7f 100644 --- a/seaweed-block/core/ops/managed_volume_operator_contract.go +++ b/seaweed-block/core/ops/managed_volume_operator_contract.go @@ -9,13 +9,14 @@ type ManagedVolumeOperatorContract struct { } type ManagedVolumeOperatorStatus struct { - VolumeID string `json:"volume_id,omitempty"` - PVCName string `json:"pvc_name,omitempty"` - Status string `json:"status"` - ReasonCode string `json:"reason_code,omitempty"` - Conditions []ObservationCondition `json:"conditions,omitempty"` - NonClaims []string `json:"non_claims,omitempty"` - EvidenceRefs []string `json:"evidence_refs,omitempty"` + VolumeID string `json:"volume_id,omitempty"` + PVCName string `json:"pvc_name,omitempty"` + Status string `json:"status"` + ReasonCode string `json:"reason_code,omitempty"` + Conditions []ObservationCondition `json:"conditions,omitempty"` + DeleteSafety *SwBlockVolumeDeleteSafetyDecision `json:"delete_safety,omitempty"` + NonClaims []string `json:"non_claims,omitempty"` + EvidenceRefs []string `json:"evidence_refs,omitempty"` } type ManagedVolumeOperatorEvent struct { @@ -26,14 +27,18 @@ type ManagedVolumeOperatorEvent struct { } type ManagedVolumeOperatorAction struct { - Type string `json:"type"` - Mode string `json:"mode"` - SideEffectClass string `json:"side_effect_class"` - OwnerExecutor string `json:"owner_executor,omitempty"` - MutationAllowed bool `json:"mutation_allowed"` - Preconditions []string `json:"preconditions,omitempty"` - InvariantRefs []string `json:"invariant_refs,omitempty"` - EvidenceRefs []string `json:"evidence_refs,omitempty"` + Type string `json:"type"` + Mode string `json:"mode"` + SideEffectClass string `json:"side_effect_class"` + OwnerExecutor string `json:"owner_executor,omitempty"` + Decision string `json:"decision,omitempty"` + DecisionReason string `json:"decision_reason,omitempty"` + MissingFacts []string `json:"missing_facts,omitempty"` + MutationAllowed bool `json:"mutation_allowed"` + Preconditions []string `json:"preconditions,omitempty"` + InvariantRefs []string `json:"invariant_refs,omitempty"` + EvidenceRequired string `json:"evidence_required,omitempty"` + EvidenceRefs []string `json:"evidence_refs,omitempty"` } func ManagedVolumeOperatorContractFromProjection(projection ManagedVolumeProjection) ManagedVolumeOperatorContract { @@ -46,6 +51,7 @@ func ManagedVolumeOperatorContractFromProjection(projection ManagedVolumeProject Status: projection.Status, ReasonCode: projection.ReasonCode, Conditions: append([]ObservationCondition(nil), projection.Conditions...), + DeleteSafety: cloneSwBlockVolumeDeleteSafetyDecision(projection.DeleteSafety), NonClaims: append([]string(nil), projection.NonClaims...), EvidenceRefs: append([]string(nil), projection.EvidenceRefs...), }, @@ -55,19 +61,62 @@ func ManagedVolumeOperatorContractFromProjection(projection ManagedVolumeProject } for _, action := range projection.Actions { contract.AllowedActions = append(contract.AllowedActions, ManagedVolumeOperatorAction{ - Type: action.Type, - Mode: action.Mode, - SideEffectClass: action.SideEffectClass, - OwnerExecutor: action.OwnerExecutor, - MutationAllowed: false, - Preconditions: append([]string(nil), action.Preconditions...), - InvariantRefs: append([]string(nil), action.InvariantRefs...), - EvidenceRefs: append([]string(nil), action.EvidenceRefs...), + Type: action.Type, + Mode: action.Mode, + SideEffectClass: action.SideEffectClass, + OwnerExecutor: action.OwnerExecutor, + Decision: action.Decision, + DecisionReason: action.DecisionReason, + MissingFacts: append([]string(nil), action.MissingFacts...), + MutationAllowed: false, + Preconditions: append([]string(nil), action.Preconditions...), + InvariantRefs: append([]string(nil), action.InvariantRefs...), + EvidenceRequired: action.EvidenceRequired, + EvidenceRefs: append([]string(nil), action.EvidenceRefs...), }) } + if projection.DeleteSafety != nil && !hasManagedVolumeOperatorAction(contract.AllowedActions, projection.DeleteSafety.ActionType) { + contract.AllowedActions = append(contract.AllowedActions, managedVolumeOperatorActionFromDeleteSafety(*projection.DeleteSafety)) + } return contract } +func managedVolumeOperatorActionFromDeleteSafety(decision SwBlockVolumeDeleteSafetyDecision) ManagedVolumeOperatorAction { + return ManagedVolumeOperatorAction{ + Type: decision.ActionType, + Mode: ManagedVolumeActionModeDryRun, + SideEffectClass: ManagedVolumeSideEffectSafeK8S, + OwnerExecutor: "lifecycle_owner", + Decision: decision.Decision, + DecisionReason: decision.Reason, + MissingFacts: append([]string(nil), decision.MissingFacts...), + MutationAllowed: false, + Preconditions: []string{"delete_safety_evidence_current", "cleanup_residue_absent"}, + InvariantRefs: []string{"INV-LIFECYCLE-FINALIZER-001"}, + EvidenceRequired: "cleanup-summary.txt", + EvidenceRefs: append([]string(nil), decision.EvidenceRefs...), + } +} + +func hasManagedVolumeOperatorAction(actions []ManagedVolumeOperatorAction, actionType string) bool { + for _, action := range actions { + if action.Type == actionType { + return true + } + } + return false +} + +func cloneSwBlockVolumeDeleteSafetyDecision(in *SwBlockVolumeDeleteSafetyDecision) *SwBlockVolumeDeleteSafetyDecision { + if in == nil { + return nil + } + out := *in + out.MissingFacts = append([]string(nil), in.MissingFacts...) + out.EvidenceRefs = append([]string(nil), in.EvidenceRefs...) + return &out +} + func managedVolumeOperatorEventFromCondition(condition ObservationCondition) ManagedVolumeOperatorEvent { eventType := "Normal" if condition.Severity == "warning" { diff --git a/seaweed-block/core/ops/observation.go b/seaweed-block/core/ops/observation.go index 1d948f2c0e..ae1f2b2ee3 100644 --- a/seaweed-block/core/ops/observation.go +++ b/seaweed-block/core/ops/observation.go @@ -25,11 +25,22 @@ const ( ReasonCandidateFrontierBehind = "candidate_frontier_behind" ReasonStatusEndpointUnreachable = "status_endpoint_unreachable" ReasonCSINodeImagePullFailed = "csi_node_image_pull_failed" + ReasonCSIDriverNotRegistered = "csi_driver_not_registered" + ReasonCSINodePodNotReady = "csi_node_pod_not_ready" ReasonImageMissingOnNode = "image_missing_on_node" + ReasonISCSIPrereqMissing = "iscsi_prereq_missing" + ReasonMultipathPrereqMissing = "multipath_prereq_missing" + ReasonNodeReady = "node_ready" + ReasonNodeNotReady = "node_not_ready" + ReasonNodeSchedulingDisabled = "node_scheduling_disabled" ReasonGeneratedDeploymentMissing = "generated_deployment_missing" ReasonObservedReplicasBelowDesired = "observed_replicas_below_desired" ReasonLoopbackFrontendRejected = "loopback_frontend_rejected" ReasonStalePrimaryFenced = "stale_primary_fenced" + ReasonWALIntegrityFault = "wal_integrity_fault" + ReasonInstallDriftAligned = "install_drift_aligned" + ReasonInstallDriftMismatch = "install_drift_mismatch" + ReasonInstallDriftEvidenceMissing = "install_drift_evidence_missing" EventTypeCSIReattachObserved = "csi_reattach_observed" ) @@ -52,22 +63,41 @@ type ClusterEvidence struct { Volumes []VolumeEvidence `json:"volumes"` ManagedVolumes []ManagedVolumeProjection `json:"managed_volumes,omitempty"` Cleanup *CleanupEvidence `json:"cleanup,omitempty"` + InstallDrift *InstallDriftEvidence `json:"install_drift,omitempty"` Conditions []ObservationCondition `json:"conditions,omitempty"` Events []ClusterEvent `json:"events,omitempty"` NonClaims []string `json:"non_claims,omitempty"` } +type InstallDriftEvidence struct { + Status string `json:"status"` + ReasonCode string `json:"reason_code,omitempty"` + ChartName string `json:"chart_name,omitempty"` + CurrentChartVersion string `json:"current_chart_version,omitempty"` + DesiredChartVersion string `json:"desired_chart_version,omitempty"` + CurrentAppVersion string `json:"current_app_version,omitempty"` + DesiredAppVersion string `json:"desired_app_version,omitempty"` + CurrentImage string `json:"current_image,omitempty"` + DesiredImage string `json:"desired_image,omitempty"` + CurrentCSIImage string `json:"current_csi_image,omitempty"` + DesiredCSIImage string `json:"desired_csi_image,omitempty"` + CurrentOperatorImage string `json:"current_operator_image,omitempty"` + DesiredOperatorImage string `json:"desired_operator_image,omitempty"` + EvidenceRef string `json:"evidence_ref,omitempty"` +} + type CleanupEvidence struct { - Status string `json:"status"` - KubernetesResidueCount int `json:"k8s_residue_count,omitempty"` - ISCSIResidueCount int `json:"iscsi_residue_count,omitempty"` - MultipathResidueCount int `json:"multipath_residue_count,omitempty"` - ProcessResidueCount int `json:"process_residue_count,omitempty"` - HostPathResidueCount int `json:"hostpath_residue_count,omitempty"` - FailureCount int `json:"failure_count,omitempty"` - FailedPhase string `json:"failed_phase,omitempty"` - ReasonCodes []string `json:"reason_codes,omitempty"` - EvidenceRef string `json:"evidence_ref,omitempty"` + Status string `json:"status"` + ObservedAt time.Time `json:"observed_at,omitempty"` + KubernetesResidueCount int `json:"k8s_residue_count,omitempty"` + ISCSIResidueCount int `json:"iscsi_residue_count,omitempty"` + MultipathResidueCount int `json:"multipath_residue_count,omitempty"` + ProcessResidueCount int `json:"process_residue_count,omitempty"` + HostPathResidueCount int `json:"hostpath_residue_count,omitempty"` + FailureCount int `json:"failure_count,omitempty"` + FailedPhase string `json:"failed_phase,omitempty"` + ReasonCodes []string `json:"reason_codes,omitempty"` + EvidenceRef string `json:"evidence_ref,omitempty"` } type NodeEvidence struct { diff --git a/seaweed-block/core/ops/observation_bundle.go b/seaweed-block/core/ops/observation_bundle.go index 19c2c3c827..44fb8a2be2 100644 --- a/seaweed-block/core/ops/observation_bundle.go +++ b/seaweed-block/core/ops/observation_bundle.go @@ -20,6 +20,10 @@ const ( ObservationReportTextArtifact = "summary.txt" ObservationReportJSONLArtifact = "timeline.jsonl" ObservationCleanupSummaryArtifact = "cleanup-summary.txt" + ObservationHostPrereqArtifact = "host-prereq-summary.txt" + ObservationLoopbackAttachArtifact = "unsupported-cross-node-loopback-attach.txt" + ObservationDeleteSafetyArtifact = "swblockvolume-delete-summary.txt" + ObservationInstallDriftArtifact = "install-drift-summary.txt" NodeLossRecoverySummaryArtifact = "node-loss-recovery-summary.txt" PrimaryFailureRecoveryArtifact = "primary-failure-recovery.txt" @@ -79,6 +83,25 @@ func BuildObservationFromBundle(opts ObservationBundleOptions) (ClusterEvidence, if len(cleanup) > 0 { cluster.Cleanup = CleanupEvidenceFromSummary(cleanup, cleanupPath) } + installDrift, installDriftPath, _ := loadKeyValueArtifact(opts.Dir, ObservationInstallDriftArtifact) + if len(installDrift) > 0 { + cluster.InstallDrift = InstallDriftEvidenceFromSummary(installDrift, installDriftPath) + sourceLoaded = true + } + hostPrereq, hostPrereqPath, _ := loadTextArtifact(opts.Dir, ObservationHostPrereqArtifact) + if hostPrereq != "" { + applyHostPrereqSummary(&cluster, hostPrereq, hostPrereqPath) + sourceLoaded = true + } + loopbackAttach, loopbackAttachPath, _ := loadKeyValueArtifact(opts.Dir, ObservationLoopbackAttachArtifact) + if len(loopbackAttach) > 0 { + applyUnsupportedLoopbackAttachSummary(&cluster, loopbackAttach, loopbackAttachPath) + sourceLoaded = true + } + deleteSafety, deleteSafetyPath, _ := loadKeyValueArtifact(opts.Dir, ObservationDeleteSafetyArtifact) + if len(deleteSafety) > 0 { + sourceLoaded = true + } if blocked, blockedVolume := buildImagePullBlockedEvidence(opts.Dir); blocked { cluster.Status = ObservationStatusBlocked sourceLoaded = true @@ -102,6 +125,9 @@ func BuildObservationFromBundle(opts ObservationBundleOptions) (ClusterEvidence, NodeLoss: summary, PrimaryFailure: primaryFailure, }) + if len(deleteSafety) > 0 { + applyDeleteSafetySummary(&cluster, deleteSafety, deleteSafetyPath) + } return cluster, nil } @@ -129,8 +155,17 @@ func RenderObservationExplainText(cluster ClusterEvidence) string { cluster = NormalizeObservationCluster(cluster) var b strings.Builder b.WriteString(RenderClusterEvidenceText(cluster)) + renderedManaged := map[string]bool{} for _, volume := range cluster.Volumes { - b.WriteString(RenderManagedVolumeProjectionText(managedProjectionForVolume(cluster.ManagedVolumes, volume.VolumeID))) + managed := managedProjectionForVolume(cluster.ManagedVolumes, volume.VolumeID) + b.WriteString(RenderManagedVolumeProjectionText(managed)) + renderedManaged[managedProjectionKey(managed)] = true + } + for _, managed := range cluster.ManagedVolumes { + if renderedManaged[managedProjectionKey(managed)] { + continue + } + b.WriteString(RenderManagedVolumeProjectionText(managed)) } if len(cluster.Events) > 0 { b.WriteString("timeline:\n") @@ -437,6 +472,290 @@ func applyPrimaryFailureSummary(cluster *ClusterEvidence, summary map[string]str cluster.Volumes[0] = volume } +func applyHostPrereqSummary(cluster *ClusterEvidence, text, evidencePath string) { + scanner := bufio.NewScanner(strings.NewReader(text)) + for scanner.Scan() { + fields := parseSpaceKeyValues(scanner.Text()) + nodeName := firstNonEmpty(fields["node"], fields["kubernetes_node"], fields["host"]) + if nodeName == "" { + continue + } + idx := ensureObservationNode(cluster, nodeName) + node := cluster.Nodes[idx] + node.NodeName = defaultString(node.NodeName, nodeName) + node.KubernetesNode = defaultString(node.KubernetesNode, nodeName) + if hostPrereqMissing(fields["iscsi_prereq"]) { + node.Conditions = append(node.Conditions, hostPrereqCondition(ReasonISCSIPrereqMissing, "iSCSI host prerequisite evidence is missing", evidencePath)) + } + if hostPrereqMissing(fields["multipath_prereq"]) { + node.Conditions = append(node.Conditions, hostPrereqCondition(ReasonMultipathPrereqMissing, "multipath host prerequisite evidence is missing", evidencePath)) + } + cluster.Nodes[idx] = node + } +} + +func applyUnsupportedLoopbackAttachSummary(cluster *ClusterEvidence, summary map[string]string, evidencePath string) { + if summary["issue"] != "unsupported_cross_node_loopback_attach" { + return + } + idx := ensureObservationVolumeIndex(cluster, summary["volume_id"]) + volume := cluster.Volumes[idx] + volume.VolumeID = defaultString(volume.VolumeID, summary["volume_id"]) + volume.Status = ObservationStatusBlocked + volume.Reason = ReasonPublishTargetLoopbackCrossNode + volume.PrimaryNode = defaultString(volume.PrimaryNode, summary["blockvolume_node"]) + volume.PublishTarget = defaultString(volume.PublishTarget, summary["frontend"]) + volume.SupportBundleHint = evidencePath + if replicaID := summary["replica_id"]; replicaID != "" && len(volume.Replicas) == 0 { + volume.PrimaryReplica = defaultString(volume.PrimaryReplica, replicaID) + volume.Replicas = append(volume.Replicas, ReplicaEvidence{ + ReplicaID: replicaID, + KubernetesNode: summary["blockvolume_node"], + Observed: true, + Role: "primary", + FrontendAddr: summary["frontend"], + }) + } + message := "loopback frontend requires app pod and blockvolume on the same node" + if summary["app_node"] != "" || summary["blockvolume_node"] != "" { + message = fmt.Sprintf("app node %s differs from blockvolume node %s; loopback frontend is not cross-node reachable", + emptyAsDash(summary["app_node"]), + emptyAsDash(summary["blockvolume_node"])) + } + volume.Conditions = append(volume.Conditions, ObservationCondition{ + Type: ConditionBlocked, + Status: "True", + Reason: ReasonPublishTargetLoopbackCrossNode, + Severity: "warning", + Message: message, + EvidenceRefs: []string{evidencePath}, + }) + volume.NextActions = []string{"reinstall with external iSCSI target or schedule the app pod on the blockvolume node"} + cluster.Volumes[idx] = volume + cluster.Status = ObservationStatusBlocked +} + +func applyDeleteSafetySummary(cluster *ClusterEvidence, summary map[string]string, evidencePath string) { + applyDeleteSafetyFacts(cluster, deleteSafetyProjectionFacts{ + VolumeID: strings.TrimSpace(summary["volume_id"]), + PVCName: strings.TrimSpace(summary["pvc_name"]), + PVName: strings.TrimSpace(summary["pv_name"]), + DeleteRequested: boolFromSummaryDefault(summary, "delete_requested", true), + FinalizerPresent: boolFromSummaryDefault(summary, "finalizer_present", true), + EvidencePath: evidencePath, + }) +} + +type deleteSafetyProjectionFacts struct { + VolumeID string + PVCName string + PVName string + DeleteRequested bool + FinalizerPresent bool + EvidencePath string +} + +func applyDeleteSafetyFacts(cluster *ClusterEvidence, facts deleteSafetyProjectionFacts) { + if len(cluster.ManagedVolumes) == 0 && len(cluster.Volumes) > 0 { + *cluster = NormalizeObservationCluster(*cluster) + } + idx := findManagedVolumeIndex(cluster.ManagedVolumes, facts.VolumeID, facts.PVCName) + if idx < 0 { + cluster.ManagedVolumes = append(cluster.ManagedVolumes, ManagedVolumeProjection{ + VolumeID: facts.VolumeID, + PVCName: facts.PVCName, + PVName: facts.PVName, + Status: ManagedVolumeStatusUnknown, + ReasonCode: ReasonCleanupEvidenceMissing, + States: ManagedVolumeStates{ + Kubernetes: ManagedVolumeKubernetesUnknown, + Authority: ManagedVolumeAuthorityUnknown, + CSI: ManagedVolumeCSIUnknown, + HostPath: ManagedVolumeHostPathUnknown, + Recovery: ManagedVolumeRecoveryNone, + Workload: ManagedVolumeWorkloadUnknown, + }, + }) + idx = len(cluster.ManagedVolumes) - 1 + } + managed := &cluster.ManagedVolumes[idx] + if managed.VolumeID == "" { + managed.VolumeID = facts.VolumeID + } + if managed.PVCName == "" { + managed.PVCName = facts.PVCName + } + if managed.PVName == "" { + managed.PVName = facts.PVName + } + decision := EvaluateSwBlockVolumeDeleteSafety(SwBlockVolumeDeleteSafetyFacts{ + DeleteRequested: facts.DeleteRequested, + FinalizerPresent: facts.FinalizerPresent, + Cleanup: cluster.Cleanup, + ObservedAt: cluster.CapturedAt, + MaxEvidenceAge: 15 * time.Minute, + }) + if facts.EvidencePath != "" { + decision.EvidenceRefs = appendUniqueStrings(decision.EvidenceRefs, facts.EvidencePath) + } + managed.DeleteSafety = &decision + managed.EvidenceRefs = appendUniqueStrings(managed.EvidenceRefs, decision.EvidenceRefs...) + managed.Actions = ensureManagedVolumeAction(managed.Actions, managedVolumeActionFromDeleteSafety(decision)) + switch decision.State { + case DeleteSafetyStateRequested: + if decision.Decision == ManagedVolumeActionDecisionUnknown { + managed.Status = ManagedVolumeStatusUnknown + managed.ReasonCode = decision.Reason + managed.Conditions = ensureCondition(removeConditionType(managed.Conditions, ConditionReady), ObservationCondition{ + Type: ConditionReady, + Status: "Unknown", + Reason: decision.Reason, + Severity: "warning", + Message: "delete is held until cleanup evidence is available and fresh", + EvidenceRefs: append([]string(nil), decision.EvidenceRefs...), + }) + managed.Conditions = ensureCondition(managed.Conditions, ObservationCondition{ + Type: ConditionEvidenceStale, + Status: "True", + Reason: decision.Reason, + Severity: "warning", + Message: "delete-safety evidence is missing or stale", + EvidenceRefs: append([]string(nil), decision.EvidenceRefs...), + }) + } + case DeleteSafetyStateBlocked: + managed.Status = ManagedVolumeStatusBlocked + managed.ReasonCode = decision.Reason + managed.Conditions = ensureCondition(removeConditionType(managed.Conditions, ConditionReady), ObservationCondition{ + Type: ConditionReady, + Status: "False", + Reason: decision.Reason, + Severity: "warning", + Message: "delete is blocked until cleanup evidence is clean", + EvidenceRefs: append([]string(nil), decision.EvidenceRefs...), + }) + managed.Conditions = ensureCondition(managed.Conditions, ObservationCondition{ + Type: ConditionBlocked, + Status: "True", + Reason: decision.Reason, + Severity: "warning", + Message: "delete-safety evidence blocks finalizer release", + EvidenceRefs: append([]string(nil), decision.EvidenceRefs...), + }) + managed.Conditions = ensureCondition(managed.Conditions, ObservationCondition{ + Type: ConditionCleanupRequired, + Status: "True", + Reason: decision.Reason, + Severity: "warning", + Message: "delete is blocked until cleanup evidence is clean", + EvidenceRefs: append([]string(nil), decision.EvidenceRefs...), + }) + managed.Actions = ensureManagedVolumeAction(managed.Actions, ManagedVolumeAction{ + Type: ManagedVolumeActionVerifyCleanup, + Mode: ManagedVolumeActionModeScripted, + SideEffectClass: ManagedVolumeSideEffectObserve, + OwnerExecutor: "ops", + Decision: ManagedVolumeActionDecisionAllowed, + EvidenceRequired: "cleanup-summary.txt", + EvidenceRefs: append([]string(nil), decision.EvidenceRefs...), + }) + case DeleteSafetyStateReleasable: + managed.Conditions = ensureCondition(managed.Conditions, ObservationCondition{ + Type: ConditionCleanupRequired, + Status: "False", + Reason: ReasonCleanupVerified, + Severity: "info", + Message: "delete finalizer is releasable; cleanup evidence is clean", + EvidenceRefs: append([]string(nil), decision.EvidenceRefs...), + }) + } +} + +func managedVolumeActionFromDeleteSafety(decision SwBlockVolumeDeleteSafetyDecision) ManagedVolumeAction { + return ManagedVolumeAction{ + Type: decision.ActionType, + Mode: ManagedVolumeActionModeDryRun, + SideEffectClass: ManagedVolumeSideEffectSafeK8S, + OwnerExecutor: "lifecycle_owner", + Decision: decision.Decision, + DecisionReason: decision.Reason, + MissingFacts: append([]string(nil), decision.MissingFacts...), + Preconditions: []string{"delete_safety_evidence_current", "cleanup_residue_absent"}, + InvariantRefs: []string{"INV-LIFECYCLE-FINALIZER-001"}, + EvidenceRequired: "cleanup-summary.txt", + EvidenceRefs: append([]string(nil), decision.EvidenceRefs...), + } +} + +func findManagedVolumeIndex(volumes []ManagedVolumeProjection, volumeID, pvcName string) int { + for i := range volumes { + if volumeID != "" && volumes[i].VolumeID == volumeID { + return i + } + if pvcName != "" && volumes[i].PVCName == pvcName { + return i + } + } + return -1 +} + +func boolFromSummaryDefault(summary map[string]string, key string, defaultValue bool) bool { + value := strings.TrimSpace(summary[key]) + if value == "" { + return defaultValue + } + parsed, err := strconv.ParseBool(value) + if err != nil { + return defaultValue + } + return parsed +} + +func ensureManagedVolumeAction(actions []ManagedVolumeAction, action ManagedVolumeAction) []ManagedVolumeAction { + for i := range actions { + if actions[i].Type == action.Type { + actions[i] = action + return actions + } + } + return append(actions, action) +} + +func ensureObservationNode(cluster *ClusterEvidence, nodeName string) int { + for i, node := range cluster.Nodes { + if node.NodeName == nodeName || node.KubernetesNode == nodeName || node.PhysicalHost == nodeName { + return i + } + } + cluster.Nodes = append(cluster.Nodes, NodeEvidence{ + NodeName: nodeName, + KubernetesNode: nodeName, + Ready: true, + Schedulable: true, + }) + return len(cluster.Nodes) - 1 +} + +func hostPrereqMissing(value string) bool { + switch strings.ToLower(strings.TrimSpace(value)) { + case "missing", "failed", "false", "no": + return true + default: + return false + } +} + +func hostPrereqCondition(reason, message, evidencePath string) ObservationCondition { + return ObservationCondition{ + Type: ConditionReady, + Status: "False", + Reason: reason, + Severity: "warning", + Message: message, + EvidenceRefs: []string{evidencePath}, + } +} + func applyManagedVolumeArtifactHints(cluster ClusterEvidence, hints ManagedVolumeArtifactHints) ClusterEvidence { cluster.ManagedVolumes = nil for _, volume := range cluster.Volumes { @@ -559,6 +878,18 @@ func loadKeyValueArtifact(root, name string) (map[string]string, string, error) return out, paths[0], scanner.Err() } +func loadTextArtifact(root, name string) (string, string, error) { + paths, err := findArtifactPaths(root, name) + if err != nil || len(paths) == 0 { + return "", "", err + } + raw, err := os.ReadFile(paths[0]) + if err != nil { + return "", paths[0], err + } + return string(raw), paths[0], nil +} + func findArtifactPaths(root, name string) ([]string, error) { var paths []string err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error { @@ -578,13 +909,24 @@ func findArtifactPaths(root, name string) ([]string, error) { } func ensureObservationVolume(cluster *ClusterEvidence, volumeID string) VolumeEvidence { + return cluster.Volumes[ensureObservationVolumeIndex(cluster, volumeID)] +} + +func ensureObservationVolumeIndex(cluster *ClusterEvidence, volumeID string) int { + if volumeID != "" { + for i, volume := range cluster.Volumes { + if volume.VolumeID == volumeID { + return i + } + } + } if len(cluster.Volumes) == 0 { if volumeID == "" { volumeID = "unknown" } cluster.Volumes = append(cluster.Volumes, VolumeEvidence{VolumeID: volumeID, Status: ObservationStatusUnavailable}) } - return cluster.Volumes[0] + return 0 } func observationStatusFromInventoryStatus(status string) string { @@ -614,6 +956,10 @@ func observationStatusFromInventoryCode(code int) string { func reasonFromIssueList(issues []string) string { joined := strings.Join(issues, "\n") switch { + case strings.Contains(joined, "unsupported_cross_node_loopback_attach") || strings.Contains(joined, "cross-node loopback") || strings.Contains(joined, "loopback frontend requires"): + return ReasonPublishTargetLoopbackCrossNode + case strings.Contains(joined, "WALIntegrity") || strings.Contains(joined, "walintegrity") || strings.Contains(joined, "wal_integrity") || strings.Contains(joined, "WAL integrity"): + return ReasonWALIntegrityFault case strings.Contains(joined, "status_endpoint_unreachable"): return ReasonStatusEndpointUnreachable case strings.Contains(joined, "generated_deployment_missing"): diff --git a/seaweed-block/core/ops/observation_bundle_test.go b/seaweed-block/core/ops/observation_bundle_test.go index e84036245d..b5e8142363 100644 --- a/seaweed-block/core/ops/observation_bundle_test.go +++ b/seaweed-block/core/ops/observation_bundle_test.go @@ -153,6 +153,43 @@ deployment.apps/sw-block-csi-controller 1/1 1 1 2m3s block-csi sw-block-csi:loca } } +func TestObservationBundle_ReplaysInstallDriftSummary(t *testing.T) { + dir := t.TempDir() + mustWrite(t, filepath.Join(dir, "demo", ObservationInstallDriftArtifact), strings.Join([]string{ + "chart_name=seaweed-block", + "current_chart_version=0.3.5", + "desired_chart_version=0.4.0", + "current_image=sw-block:old", + "desired_image=sw-block:new", + "current_csi_image=sw-block-csi:old", + "desired_csi_image=sw-block-csi:new", + }, "\n")) + + cluster, err := BuildObservationFromBundle(ObservationBundleOptions{Dir: dir}) + if err != nil { + t.Fatal(err) + } + if cluster.InstallDrift == nil || cluster.InstallDrift.Status != InstallDriftStatusMismatch { + t.Fatalf("install drift=%+v", cluster.InstallDrift) + } + snapshot := BuildOperatorFoundationSnapshot(cluster) + if snapshot.Cluster.InstallDrift == nil || snapshot.Cluster.InstallDrift.ReasonCode != ReasonInstallDriftMismatch { + t.Fatalf("snapshot install drift=%+v", snapshot.Cluster.InstallDrift) + } + assertCondition(t, snapshot.Cluster.Conditions, ConditionBlocked, "True", ReasonInstallDriftMismatch) + summary := RenderObservationReportSummary(cluster) + for _, want := range []string{ + "install_drift_status=mismatch reason=install_drift_mismatch evidence=", + "install-drift-summary.txt", + "install_drift_chart current=0.3.5 desired=0.4.0", + "install_drift_image current=sw-block:old desired=sw-block:new csi_current=sw-block-csi:old csi_desired=sw-block-csi:new", + } { + if !strings.Contains(summary, want) { + t.Fatalf("summary missing %q:\n%s", want, summary) + } + } +} + func TestObservationBundle_ManagedVolumeUsesPrimaryFailureArtifactHints(t *testing.T) { dir := t.TempDir() productDir := filepath.Join(dir, "demo", "product-observation") @@ -322,6 +359,515 @@ func TestObservationBundle_CarriesCleanupEvidenceIntoReportSurfaces(t *testing.T } } +func TestObservationBundle_CarriesHostPrereqEvidenceIntoNodeStatus(t *testing.T) { + dir := t.TempDir() + cluster := NewClusterEvidence(time.Date(2026, 6, 8, 13, 0, 0, 0, time.UTC)) + cluster.Nodes = []NodeEvidence{{ + NodeName: "m02", + KubernetesNode: "m02", + Ready: true, + Schedulable: true, + }, { + NodeName: "tp01", + KubernetesNode: "tp01", + Ready: true, + Schedulable: true, + }} + writeClusterEvidenceArtifact(t, filepath.Join(dir, "status", ClusterEvidenceArtifact), cluster) + mustWrite(t, filepath.Join(dir, "host", ObservationHostPrereqArtifact), strings.Join([]string{ + "node=m02 iscsi_prereq=missing multipath_prereq=ok command_iscsiadm=missing", + "node=tp01 iscsi_prereq=ok multipath_prereq=missing command_multipath=missing", + }, "\n")) + + out, err := BuildObservationFromBundle(ObservationBundleOptions{Dir: dir}) + if err != nil { + t.Fatal(err) + } + snapshot := BuildOperatorFoundationSnapshot(out) + if len(snapshot.Cluster.Nodes) != 2 { + t.Fatalf("nodes=%+v", snapshot.Cluster.Nodes) + } + if snapshot.Cluster.Nodes[0].Status != ManagedVolumeStatusBlocked || + snapshot.Cluster.Nodes[0].ReasonCode != ReasonISCSIPrereqMissing { + t.Fatalf("m02 node=%+v", snapshot.Cluster.Nodes[0]) + } + if snapshot.Cluster.Nodes[1].Status != ManagedVolumeStatusBlocked || + snapshot.Cluster.Nodes[1].ReasonCode != ReasonMultipathPrereqMissing { + t.Fatalf("tp01 node=%+v", snapshot.Cluster.Nodes[1]) + } + summary := RenderObservationReportSummary(out) + for _, want := range []string{ + "node=m02 k8s=m02 status=blocked reason=iscsi_prereq_missing", + "node=tp01 k8s=tp01 status=blocked reason=multipath_prereq_missing", + } { + if !strings.Contains(summary, want) { + t.Fatalf("summary missing %q:\n%s", want, summary) + } + } +} + +func TestObservationBundle_CarriesUnsupportedLoopbackAttachIntoManagedStatus(t *testing.T) { + dir := t.TempDir() + writeProductClusterEvidence(t, dir, []VolumeEvidence{{ + VolumeID: "pvc-loopback", + Namespace: "default", + PVCName: "demo-pvc", + ReplicationFactor: 1, + Status: ObservationStatusOK, + PrimaryReplica: "r1", + PrimaryNode: "m01", + PublishTarget: "127.0.0.1:3260", + Replicas: []ReplicaEvidence{{ + ReplicaID: "r1", + KubernetesNode: "m01", + Observed: true, + Role: "primary", + FrontendAddr: "127.0.0.1:3260", + }}, + }}) + mustWrite(t, filepath.Join(dir, "demo", ObservationLoopbackAttachArtifact), strings.Join([]string{ + "issue=unsupported_cross_node_loopback_attach", + "app_node=m02", + "blockvolume_node=m01", + "frontend=127.0.0.1:3260", + "volume_id=pvc-loopback", + "replica_id=r1", + "reason=loopback frontend requires app pod and blockvolume on the same node", + }, "\n")) + + cluster, err := BuildObservationFromBundle(ObservationBundleOptions{Dir: dir, VolumeID: "pvc-loopback"}) + if err != nil { + t.Fatal(err) + } + if cluster.Status != ObservationStatusBlocked { + t.Fatalf("cluster status=%s", cluster.Status) + } + if len(cluster.ManagedVolumes) != 1 { + t.Fatalf("managed_volumes=%+v", cluster.ManagedVolumes) + } + managed := cluster.ManagedVolumes[0] + if managed.Status != ManagedVolumeStatusBlocked || managed.ReasonCode != ReasonPublishTargetLoopbackCrossNode { + t.Fatalf("managed=%+v", managed) + } + action := findManagedVolumeAction(managed.Actions, ManagedVolumeActionReinstallExternalISCSI) + if action == nil { + t.Fatalf("missing external iSCSI dry-run action: %+v", managed.Actions) + } + if action.Decision != ManagedVolumeActionDecisionAllowed || + action.Mode != ManagedVolumeActionModeDryRun || + action.SideEffectClass != ManagedVolumeSideEffectSafeK8S || + action.OwnerExecutor != "installer_or_operator" || + action.EvidenceRequired != "loopback_cross_node_evidence" { + t.Fatalf("unexpected external iSCSI action evaluation: %+v", *action) + } + + contract := ManagedVolumeOperatorContractFromProjection(managed) + operatorAction := findManagedVolumeOperatorAction(contract.AllowedActions, ManagedVolumeActionReinstallExternalISCSI) + if operatorAction == nil { + t.Fatalf("missing operator action: %+v", contract.AllowedActions) + } + if operatorAction.Decision != ManagedVolumeActionDecisionAllowed || + operatorAction.MutationAllowed || + operatorAction.EvidenceRequired != "loopback_cross_node_evidence" { + t.Fatalf("unexpected operator action contract: %+v", *operatorAction) + } + + snapshot := BuildOperatorFoundationSnapshot(cluster) + snapshotAction := findManagedVolumeOperatorAction(snapshot.Volumes[0].AllowedActions, ManagedVolumeActionReinstallExternalISCSI) + if snapshotAction == nil { + t.Fatalf("missing snapshot action: %+v", snapshot.Volumes[0].AllowedActions) + } + if snapshotAction.Decision != ManagedVolumeActionDecisionAllowed || + snapshotAction.MutationAllowed || + snapshot.Mutation.MutationAllowed { + t.Fatalf("unexpected snapshot action/boundary: action=%+v mutation=%+v", *snapshotAction, snapshot.Mutation) + } + + summary := RenderObservationReportSummary(cluster) + for _, want := range []string{ + "volume=pvc-loopback status=blocked pvc=default/demo-pvc primary=r1@m01 frontend=127.0.0.1:3260", + "managed_volume=pvc-loopback status=blocked reason=publish_target_loopback_cross_node", + "managed_volume_condition=Ready status=False reason=publish_target_loopback_cross_node severity=warning", + "managed_volume_action=safe_k8s.reinstall_external_iscsi mode=dry_run side_effect=safe_k8s executor=installer_or_operator decision=allowed", + "managed_volume_action_evidence_required=safe_k8s.reinstall_external_iscsi loopback_cross_node_evidence", + } { + if !strings.Contains(summary, want) { + t.Fatalf("summary missing %q:\n%s", want, summary) + } + } + + explain := RenderObservationExplainText(cluster) + for _, want := range []string{ + "managed_volume_action safe_k8s.reinstall_external_iscsi mode=dry_run side_effect=safe_k8s executor=installer_or_operator decision=allowed", + "managed_volume_action_evidence_required safe_k8s.reinstall_external_iscsi loopback_cross_node_evidence", + } { + if !strings.Contains(explain, want) { + t.Fatalf("explain missing %q:\n%s", want, explain) + } + } + + server := httptest.NewServer(NewObservationDashboardHandler(cluster)) + defer server.Close() + assertDashboardEndpointContains(t, server.URL+"/"+ObservationOperatorSnapshotArtifact, `"reason_code": "publish_target_loopback_cross_node"`) + assertDashboardEndpointContains(t, server.URL+"/"+ObservationOperatorSnapshotArtifact, `"decision": "allowed"`) + assertDashboardEndpointContains(t, server.URL+"/"+ObservationOperatorSnapshotArtifact, `"mutation_allowed": false`) + assertDashboardEndpointContains(t, server.URL+"/"+ObservationOperatorSnapshotArtifact, `"evidence_required": "loopback_cross_node_evidence"`) + assertDashboardEndpointContains(t, server.URL+"/"+ObservationReportTextArtifact, "managed_volume=pvc-loopback status=blocked reason=publish_target_loopback_cross_node") +} + +func TestObservationBundle_DeleteSafetyBlocksWithResidue(t *testing.T) { + dir := t.TempDir() + writeProductClusterEvidence(t, dir, []VolumeEvidence{{ + VolumeID: "pvc-delete", + Namespace: "default", + PVCName: "delete-pvc", + PVName: "pv-delete", + ReplicationFactor: 1, + Status: ObservationStatusOK, + PrimaryReplica: "r1", + PrimaryNode: "m01", + PublishTarget: "192.168.1.181:3260", + Replicas: []ReplicaEvidence{{ + ReplicaID: "r1", + KubernetesNode: "m01", + Observed: true, + Role: "primary", + FrontendAddr: "192.168.1.181:3260", + }}, + }}) + mustWrite(t, filepath.Join(dir, ObservationCleanupSummaryArtifact), strings.Join([]string{ + "cleanup_status=failed", + "iscsi_residue_count=1", + "reason_codes=iscsi_node_records_present", + }, "\n")) + mustWrite(t, filepath.Join(dir, ObservationDeleteSafetyArtifact), strings.Join([]string{ + "delete_requested=true", + "finalizer_present=true", + "volume_id=pvc-delete", + "pvc_name=delete-pvc", + "pv_name=pv-delete", + }, "\n")) + + cluster, err := BuildObservationFromBundle(ObservationBundleOptions{Dir: dir, VolumeID: "pvc-delete"}) + if err != nil { + t.Fatal(err) + } + managed := managedProjectionForVolume(cluster.ManagedVolumes, "pvc-delete") + if managed.DeleteSafety == nil { + t.Fatalf("missing delete safety: %+v", managed) + } + if managed.Status != ManagedVolumeStatusBlocked || + managed.ReasonCode != "iscsi_node_records_present" || + managed.DeleteSafety.State != DeleteSafetyStateBlocked || + managed.DeleteSafety.Decision != ManagedVolumeActionDecisionRejected || + managed.DeleteSafety.FinalizerReleaseAllowed { + t.Fatalf("managed=%+v delete=%+v", managed, managed.DeleteSafety) + } + if !hasManagedVolumeAction(managed.Actions, ManagedVolumeActionVerifyCleanup) { + t.Fatalf("missing verify cleanup action: %+v", managed.Actions) + } + if condition := findObservationCondition(managed.Conditions, ConditionCleanupRequired); condition == nil || + condition.Status != "True" || + condition.Reason != "iscsi_node_records_present" { + t.Fatalf("cleanup condition=%+v", condition) + } + + summary := RenderObservationReportSummary(cluster) + for _, want := range []string{ + "managed_volume_delete_safety=pvc-delete state=blocked decision=rejected reason=iscsi_node_records_present release_allowed=false action=safe_k8s.release_swblockvolume_finalizer", + "managed_volume_delete_safety_safe_next_action=pvc-delete observe.verify_cleanup", + "managed_volume_action=safe_k8s.release_swblockvolume_finalizer mode=dry_run side_effect=safe_k8s executor=lifecycle_owner decision=rejected reason=iscsi_node_records_present", + "managed_volume_action_evidence_required=safe_k8s.release_swblockvolume_finalizer cleanup-summary.txt", + } { + if !strings.Contains(summary, want) { + t.Fatalf("summary missing %q:\n%s", want, summary) + } + } + explain := RenderObservationExplainText(cluster) + if !strings.Contains(explain, "managed_volume_delete_safety state=blocked decision=rejected reason=iscsi_node_records_present release_allowed=false action=safe_k8s.release_swblockvolume_finalizer") { + t.Fatalf("explain missing delete safety:\n%s", explain) + } + snapshot := BuildOperatorFoundationSnapshot(cluster) + if snapshot.Volumes[0].Status.DeleteSafety == nil || + snapshot.Volumes[0].Status.DeleteSafety.State != DeleteSafetyStateBlocked { + t.Fatalf("snapshot delete safety=%+v", snapshot.Volumes[0].Status.DeleteSafety) + } + server := httptest.NewServer(NewObservationDashboardHandler(cluster)) + defer server.Close() + assertDashboardEndpointContains(t, server.URL+"/"+ObservationOperatorSnapshotArtifact, `"delete_safety": {`) + assertDashboardEndpointContains(t, server.URL+"/"+ObservationOperatorSnapshotArtifact, `"state": "blocked"`) + assertDashboardEndpointContains(t, server.URL+"/"+ObservationOperatorSnapshotArtifact, `"reason": "iscsi_node_records_present"`) +} + +func TestObservationBundle_DeleteSafetyUnknownWithoutCleanupEvidence(t *testing.T) { + dir := t.TempDir() + writeProductClusterEvidence(t, dir, []VolumeEvidence{{ + VolumeID: "pvc-missing-cleanup", + Namespace: "default", + PVCName: "missing-cleanup-pvc", + PVName: "pv-missing-cleanup", + ReplicationFactor: 1, + Status: ObservationStatusOK, + PrimaryReplica: "r1", + PrimaryNode: "m01", + PublishTarget: "192.168.1.181:3260", + Replicas: []ReplicaEvidence{{ + ReplicaID: "r1", + KubernetesNode: "m01", + Observed: true, + Role: "primary", + FrontendAddr: "192.168.1.181:3260", + }}, + }}) + mustWrite(t, filepath.Join(dir, ObservationDeleteSafetyArtifact), strings.Join([]string{ + "delete_requested=true", + "finalizer_present=true", + "volume_id=pvc-missing-cleanup", + "pvc_name=missing-cleanup-pvc", + "pv_name=pv-missing-cleanup", + }, "\n")) + + cluster, err := BuildObservationFromBundle(ObservationBundleOptions{Dir: dir, VolumeID: "pvc-missing-cleanup"}) + if err != nil { + t.Fatal(err) + } + managed := managedProjectionForVolume(cluster.ManagedVolumes, "pvc-missing-cleanup") + if managed.DeleteSafety == nil || + managed.DeleteSafety.State != DeleteSafetyStateRequested || + managed.DeleteSafety.Decision != ManagedVolumeActionDecisionUnknown || + managed.DeleteSafety.Reason != ReasonCleanupEvidenceMissing || + managed.DeleteSafety.FinalizerReleaseAllowed { + t.Fatalf("managed=%+v delete=%+v", managed, managed.DeleteSafety) + } + if managed.Status != ManagedVolumeStatusUnknown || managed.ReasonCode != ReasonCleanupEvidenceMissing { + t.Fatalf("missing cleanup evidence must not claim Ready: %+v", managed) + } + + summary := RenderObservationReportSummary(cluster) + if !strings.Contains(summary, "managed_volume_delete_safety=pvc-missing-cleanup state=requested decision=unknown reason=cleanup_evidence_missing release_allowed=false action=safe_k8s.release_swblockvolume_finalizer") { + t.Fatalf("summary missing unknown delete safety:\n%s", summary) + } + if !strings.Contains(summary, "managed_volume_action=safe_k8s.release_swblockvolume_finalizer mode=dry_run side_effect=safe_k8s executor=lifecycle_owner decision=unknown reason=cleanup_evidence_missing") { + t.Fatalf("summary missing unknown lifecycle-owner action:\n%s", summary) + } + snapshot := BuildOperatorFoundationSnapshot(cluster) + if snapshot.Volumes[0].Status.DeleteSafety == nil || + snapshot.Volumes[0].Status.DeleteSafety.Decision != ManagedVolumeActionDecisionUnknown || + snapshot.Volumes[0].Status.DeleteSafety.State != DeleteSafetyStateRequested { + t.Fatalf("snapshot delete safety=%+v", snapshot.Volumes[0].Status.DeleteSafety) + } + server := httptest.NewServer(NewObservationDashboardHandler(cluster)) + defer server.Close() + assertDashboardEndpointContains(t, server.URL+"/"+ObservationOperatorSnapshotArtifact, `"decision": "unknown"`) + assertDashboardEndpointContains(t, server.URL+"/"+ObservationOperatorSnapshotArtifact, `"reason": "cleanup_evidence_missing"`) +} + +func TestObservationBundle_DeleteSafetyUnknownWithStaleCleanupEvidence(t *testing.T) { + dir := t.TempDir() + writeProductClusterEvidence(t, dir, []VolumeEvidence{{ + VolumeID: "pvc-stale-cleanup", + Namespace: "default", + PVCName: "stale-cleanup-pvc", + PVName: "pv-stale-cleanup", + ReplicationFactor: 1, + Status: ObservationStatusOK, + PrimaryReplica: "r1", + PrimaryNode: "m01", + PublishTarget: "192.168.1.181:3260", + Replicas: []ReplicaEvidence{{ + ReplicaID: "r1", + KubernetesNode: "m01", + Observed: true, + Role: "primary", + FrontendAddr: "192.168.1.181:3260", + }}, + }}) + mustWrite(t, filepath.Join(dir, ObservationCleanupSummaryArtifact), strings.Join([]string{ + "cleanup_status=ok", + "cleanup_observed_at=2026-06-14T11:44:00Z", + }, "\n")) + mustWrite(t, filepath.Join(dir, ObservationDeleteSafetyArtifact), strings.Join([]string{ + "delete_requested=true", + "finalizer_present=true", + "volume_id=pvc-stale-cleanup", + "pvc_name=stale-cleanup-pvc", + "pv_name=pv-stale-cleanup", + }, "\n")) + + cluster, err := BuildObservationFromBundle(ObservationBundleOptions{Dir: dir, VolumeID: "pvc-stale-cleanup"}) + if err != nil { + t.Fatal(err) + } + cluster.CapturedAt = time.Date(2026, 6, 14, 12, 0, 0, 0, time.UTC) + applyDeleteSafetySummary(&cluster, map[string]string{ + "delete_requested": "true", + "finalizer_present": "true", + "volume_id": "pvc-stale-cleanup", + "pvc_name": "stale-cleanup-pvc", + "pv_name": "pv-stale-cleanup", + }, ObservationDeleteSafetyArtifact) + + managed := managedProjectionForVolume(cluster.ManagedVolumes, "pvc-stale-cleanup") + if managed.DeleteSafety == nil || + managed.DeleteSafety.State != DeleteSafetyStateRequested || + managed.DeleteSafety.Decision != ManagedVolumeActionDecisionUnknown || + managed.DeleteSafety.Reason != ReasonCleanupEvidenceStale || + managed.DeleteSafety.FinalizerReleaseAllowed { + t.Fatalf("managed=%+v delete=%+v", managed, managed.DeleteSafety) + } + + summary := RenderObservationReportSummary(cluster) + if !strings.Contains(summary, "managed_volume_delete_safety=pvc-stale-cleanup state=requested decision=unknown reason=cleanup_evidence_stale release_allowed=false action=safe_k8s.release_swblockvolume_finalizer") { + t.Fatalf("summary missing stale delete safety:\n%s", summary) + } + snapshot := BuildOperatorFoundationSnapshot(cluster) + if snapshot.Volumes[0].Status.DeleteSafety == nil || + snapshot.Volumes[0].Status.DeleteSafety.Reason != ReasonCleanupEvidenceStale { + t.Fatalf("snapshot delete safety=%+v", snapshot.Volumes[0].Status.DeleteSafety) + } + server := httptest.NewServer(NewObservationDashboardHandler(cluster)) + defer server.Close() + assertDashboardEndpointContains(t, server.URL+"/"+ObservationOperatorSnapshotArtifact, `"decision": "unknown"`) + assertDashboardEndpointContains(t, server.URL+"/"+ObservationOperatorSnapshotArtifact, `"reason": "cleanup_evidence_stale"`) +} + +func TestObservationBundle_DeleteSafetyReleasableWithCleanCleanupEvidence(t *testing.T) { + dir := t.TempDir() + writeProductClusterEvidence(t, dir, []VolumeEvidence{{ + VolumeID: "pvc-clean-delete", + Namespace: "default", + PVCName: "clean-pvc", + PVName: "pv-clean", + ReplicationFactor: 1, + Status: ObservationStatusOK, + PrimaryReplica: "r1", + PrimaryNode: "m01", + PublishTarget: "192.168.1.181:3260", + Replicas: []ReplicaEvidence{{ + ReplicaID: "r1", + KubernetesNode: "m01", + Observed: true, + Role: "primary", + FrontendAddr: "192.168.1.181:3260", + }}, + }}) + mustWrite(t, filepath.Join(dir, ObservationCleanupSummaryArtifact), "cleanup_status=ok") + mustWrite(t, filepath.Join(dir, ObservationDeleteSafetyArtifact), strings.Join([]string{ + "delete_requested=true", + "finalizer_present=true", + "volume_id=pvc-clean-delete", + "pvc_name=clean-pvc", + "pv_name=pv-clean", + }, "\n")) + + cluster, err := BuildObservationFromBundle(ObservationBundleOptions{Dir: dir, VolumeID: "pvc-clean-delete"}) + if err != nil { + t.Fatal(err) + } + managed := managedProjectionForVolume(cluster.ManagedVolumes, "pvc-clean-delete") + if managed.DeleteSafety == nil || + managed.DeleteSafety.State != DeleteSafetyStateReleasable || + managed.DeleteSafety.Decision != ManagedVolumeActionDecisionAllowed || + !managed.DeleteSafety.FinalizerReleaseAllowed { + t.Fatalf("managed=%+v delete=%+v", managed, managed.DeleteSafety) + } + if managed.Status == ManagedVolumeStatusBlocked { + t.Fatalf("clean delete evidence must not block managed volume: %+v", managed) + } + if condition := findObservationCondition(managed.Conditions, ConditionCleanupRequired); condition == nil || + condition.Status != "False" || + condition.Reason != ReasonCleanupVerified { + t.Fatalf("cleanup condition=%+v", condition) + } + summary := RenderObservationReportSummary(cluster) + if !strings.Contains(summary, "managed_volume_delete_safety=pvc-clean-delete state=releasable decision=allowed reason=finalizer_releasable release_allowed=true action=safe_k8s.release_swblockvolume_finalizer") { + t.Fatalf("summary missing releasable delete safety:\n%s", summary) + } + if !strings.Contains(summary, "managed_volume_action=safe_k8s.release_swblockvolume_finalizer mode=dry_run side_effect=safe_k8s executor=lifecycle_owner decision=allowed reason=finalizer_releasable") { + t.Fatalf("summary missing releasable lifecycle-owner action:\n%s", summary) + } + snapshot := BuildOperatorFoundationSnapshot(cluster) + if snapshot.Volumes[0].Status.DeleteSafety == nil || + !snapshot.Volumes[0].Status.DeleteSafety.FinalizerReleaseAllowed { + t.Fatalf("snapshot delete safety=%+v", snapshot.Volumes[0].Status.DeleteSafety) + } +} + +func TestObservationBundle_LoopbackAttachTargetsNamedVolume(t *testing.T) { + dir := t.TempDir() + writeProductClusterEvidence(t, dir, []VolumeEvidence{ + { + VolumeID: "pvc-a", + Namespace: "default", + PVCName: "pvc-a", + Status: ObservationStatusOK, + PrimaryReplica: "r1", + PrimaryNode: "m01", + PublishTarget: "192.168.1.181:3260", + }, + { + VolumeID: "pvc-b", + Namespace: "default", + PVCName: "pvc-b", + Status: ObservationStatusOK, + PrimaryReplica: "r1", + PrimaryNode: "m01", + PublishTarget: "127.0.0.1:3260", + }, + }) + mustWrite(t, filepath.Join(dir, "demo", ObservationLoopbackAttachArtifact), strings.Join([]string{ + "issue=unsupported_cross_node_loopback_attach", + "app_node=m02", + "blockvolume_node=m01", + "frontend=127.0.0.1:3260", + "volume_id=pvc-b", + "replica_id=r1", + }, "\n")) + + cluster, err := BuildObservationFromBundle(ObservationBundleOptions{Dir: dir}) + if err != nil { + t.Fatal(err) + } + if len(cluster.ManagedVolumes) != 2 { + t.Fatalf("managed_volumes=%+v", cluster.ManagedVolumes) + } + statusByVolume := map[string]string{} + reasonByVolume := map[string]string{} + for _, managed := range cluster.ManagedVolumes { + statusByVolume[managed.VolumeID] = managed.Status + reasonByVolume[managed.VolumeID] = managed.ReasonCode + } + if statusByVolume["pvc-a"] != ManagedVolumeStatusReady || reasonByVolume["pvc-a"] != ReasonFirstVolumeVerified { + t.Fatalf("pvc-a status=%s reason=%s", statusByVolume["pvc-a"], reasonByVolume["pvc-a"]) + } + if statusByVolume["pvc-b"] != ManagedVolumeStatusBlocked || reasonByVolume["pvc-b"] != ReasonPublishTargetLoopbackCrossNode { + t.Fatalf("pvc-b status=%s reason=%s", statusByVolume["pvc-b"], reasonByVolume["pvc-b"]) + } +} + +func TestManagedVolumeFactsFromEvidence_AllowsSameNodeLoopback(t *testing.T) { + projection := ProjectManagedVolume(ManagedVolumeFactsFromEvidence(VolumeEvidence{ + VolumeID: "pvc-loopback-ok", + Namespace: "default", + PVCName: "demo-pvc", + Status: ObservationStatusOK, + PrimaryReplica: "r1", + PrimaryNode: "m02", + PublishTarget: "127.0.0.1:3260", + Replicas: []ReplicaEvidence{{ + ReplicaID: "r1", + KubernetesNode: "m02", + Observed: true, + Role: "primary", + FrontendAddr: "127.0.0.1:3260", + }}, + }, ManagedVolumeArtifactHints{})) + + if projection.Status != ManagedVolumeStatusReady || projection.ReasonCode != ReasonFirstVolumeVerified { + t.Fatalf("same-node loopback projection=%+v", projection) + } +} + func TestObservationBundle_D6ReplayGate_FirstVolumeBlockedAndRecovery(t *testing.T) { cases := []struct { name string @@ -350,6 +896,15 @@ deployment.apps/sw-block-csi-controller 1/1 1 1 2m3s block-csi sw-block-csi:loca wantReason: ReasonCSINodeImagePullFailed, wantEvent: "Warning", }, + { + name: "status-endpoint-unreachable", + build: func(t *testing.T, dir string) { + writeStatusEndpointUnreachableInventory(t, dir) + }, + wantStatus: ManagedVolumeStatusUnknown, + wantReason: ReasonStatusEndpointUnreachable, + wantEvent: "Warning", + }, { name: "stage2-recovery", build: func(t *testing.T, dir string) { @@ -464,6 +1019,16 @@ deployment.apps/sw-block-csi-controller 1/1 1 1 2m3s block-csi sw-block-csi:loca wantText: "managed_volume=pvc-blocked status=blocked reason=csi_node_image_pull_failed", wantStatus: ManagedVolumeStatusBlocked, }, + { + name: "status-endpoint-unreachable", + build: func(t *testing.T, dir string) { + writeStatusEndpointUnreachableInventory(t, dir) + }, + wantHTML: ReasonStatusEndpointUnreachable, + wantJSON: `"reason_code": "status_endpoint_unreachable"`, + wantText: "managed_volume=pvc-unreachable status=unknown reason=status_endpoint_unreachable", + wantStatus: ManagedVolumeStatusUnknown, + }, { name: "stage2-recovery", build: func(t *testing.T, dir string) { @@ -595,6 +1160,47 @@ func mustWriteInventory(t *testing.T, dir string, inventory VolumeInventory) { mustWrite(t, filepath.Join(dir, VolumeInventoryArtifact), string(raw)) } +func writeStatusEndpointUnreachableInventory(t *testing.T, dir string) { + t.Helper() + inventoryDir := filepath.Join(dir, "demo", "ops-inventory-status-unreachable") + inventory := BuildVolumeInventory(VolumeInventoryInput{ + CapturedAt: time.Date(2026, 5, 27, 12, 0, 0, 0, time.UTC), + Source: ReportSource{Component: "component-test"}, + ProductRevision: "product-rev", + Volumes: []VolumeInventoryVolumeInput{{ + VolumeID: "pvc-unreachable", + Namespace: "default", + PVCName: "demo-pvc", + PVName: "pvc-unreachable", + ReplicationFactor: 1, + Replicas: []VolumeInventoryReplicaInput{{ + ReplicaID: "r1", + ServerID: "node-r1", + NodeName: "m01", + Protocol: "iscsi", + FrontendAddress: "192.168.1.181:3260", + StatusAddress: "192.168.1.181:23260", + Observed: true, + AuthorityRole: "primary", + Healthy: true, + FrontendPrimaryReady: true, + ReplicationRole: "none", + Issues: []string{"status_endpoint_unreachable=192.168.1.181:23260"}, + }}, + }}, + }) + mustWriteInventory(t, inventoryDir, inventory) +} + +func findManagedVolumeOperatorAction(actions []ManagedVolumeOperatorAction, actionType string) *ManagedVolumeOperatorAction { + for i := range actions { + if actions[i].Type == actionType { + return &actions[i] + } + } + return nil +} + func mustWrite(t *testing.T, path, content string) { t.Helper() if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { diff --git a/seaweed-block/core/ops/observation_report.go b/seaweed-block/core/ops/observation_report.go index 5665c8b1ff..b62f74742a 100644 --- a/seaweed-block/core/ops/observation_report.go +++ b/seaweed-block/core/ops/observation_report.go @@ -59,6 +59,55 @@ func RenderObservationReportSummary(cluster ClusterEvidence) string { fmt.Fprintf(&b, "%s\n", line) } } + if cluster.InstallDrift != nil { + fmt.Fprintf(&b, "install_drift_status=%s reason=%s evidence=%s\n", + emptyAsDash(cluster.InstallDrift.Status), + emptyAsDash(cluster.InstallDrift.ReasonCode), + emptyAsDash(cluster.InstallDrift.EvidenceRef)) + fmt.Fprintf(&b, "install_drift_chart current=%s desired=%s app_current=%s app_desired=%s\n", + emptyAsDash(cluster.InstallDrift.CurrentChartVersion), + emptyAsDash(cluster.InstallDrift.DesiredChartVersion), + emptyAsDash(cluster.InstallDrift.CurrentAppVersion), + emptyAsDash(cluster.InstallDrift.DesiredAppVersion)) + fmt.Fprintf(&b, "install_drift_image current=%s desired=%s csi_current=%s csi_desired=%s operator_current=%s operator_desired=%s\n", + emptyAsDash(cluster.InstallDrift.CurrentImage), + emptyAsDash(cluster.InstallDrift.DesiredImage), + emptyAsDash(cluster.InstallDrift.CurrentCSIImage), + emptyAsDash(cluster.InstallDrift.DesiredCSIImage), + emptyAsDash(cluster.InstallDrift.CurrentOperatorImage), + emptyAsDash(cluster.InstallDrift.DesiredOperatorImage)) + } + supportRefs := supportBundleRefsFromCluster(cluster) + for _, ref := range supportRefs { + fmt.Fprintf(&b, "support_bundle_ref=%s\n", ref) + } + for _, step := range safeNextStepsFromCluster(cluster, supportRefs) { + fmt.Fprintf(&b, "safe_next_step=%s mode=%s mutation_allowed=%t command=%q reason=%s\n", + emptyAsDash(step.Type), + emptyAsDash(step.Mode), + step.MutationAllowed, + step.Command, + emptyAsDash(step.ReasonCode)) + } + operatorSnapshot := BuildOperatorFoundationSnapshot(cluster) + for _, condition := range operatorSnapshot.Cluster.Conditions { + fmt.Fprintf(&b, "cluster_condition=%s status=%s reason=%s severity=%s\n", + emptyAsDash(condition.Type), + emptyAsDash(condition.Status), + emptyAsDash(condition.Reason), + emptyAsDash(condition.Severity)) + } + for _, node := range operatorSnapshot.Cluster.Nodes { + fmt.Fprintf(&b, "node=%s k8s=%s status=%s reason=%s ready=%t schedulable=%t missing_images=%s\n", + emptyAsDash(node.Name), + emptyAsDash(node.KubernetesNode), + emptyAsDash(node.Status), + emptyAsDash(node.ReasonCode), + node.Ready, + node.Schedulable, + emptyAsDash(strings.Join(node.MissingImages, ","))) + } + renderedManaged := map[string]bool{} for _, volume := range cluster.Volumes { fmt.Fprintf(&b, "volume=%s status=%s pvc=%s/%s primary=%s@%s frontend=%s rf=%d ack=%s\n", emptyAsDash(volume.VolumeID), @@ -71,29 +120,68 @@ func RenderObservationReportSummary(cluster ClusterEvidence) string { volume.ReplicationFactor, emptyAsDash(volume.AckProfile)) managed := managedProjectionForVolume(cluster.ManagedVolumes, volume.VolumeID) - fmt.Fprintf(&b, "managed_volume=%s status=%s reason=%s\n", - emptyAsDash(managed.VolumeID), - emptyAsDash(managed.Status), - emptyAsDash(managed.ReasonCode)) - for _, condition := range managed.Conditions { - fmt.Fprintf(&b, "managed_volume_condition=%s status=%s reason=%s severity=%s\n", - emptyAsDash(condition.Type), - emptyAsDash(condition.Status), - emptyAsDash(condition.Reason), - emptyAsDash(condition.Severity)) - } - for _, action := range managed.Actions { - fmt.Fprintf(&b, "managed_volume_action=%s mode=%s side_effect=%s executor=%s\n", - emptyAsDash(action.Type), - emptyAsDash(action.Mode), - emptyAsDash(action.SideEffectClass), - emptyAsDash(action.OwnerExecutor)) + renderManagedProjectionSummary(&b, managed) + renderedManaged[managedProjectionKey(managed)] = true + } + for _, managed := range cluster.ManagedVolumes { + if renderedManaged[managedProjectionKey(managed)] { + continue } + renderManagedProjectionSummary(&b, managed) } fmt.Fprintf(&b, "read_only=true\n") return b.String() } +func renderManagedProjectionSummary(b *strings.Builder, managed ManagedVolumeProjection) { + fmt.Fprintf(b, "managed_volume=%s status=%s reason=%s\n", + emptyAsDash(managed.VolumeID), + emptyAsDash(managed.Status), + emptyAsDash(managed.ReasonCode)) + for _, condition := range managed.Conditions { + fmt.Fprintf(b, "managed_volume_condition=%s status=%s reason=%s severity=%s\n", + emptyAsDash(condition.Type), + emptyAsDash(condition.Status), + emptyAsDash(condition.Reason), + emptyAsDash(condition.Severity)) + } + if managed.DeleteSafety != nil { + fmt.Fprintf(b, "managed_volume_delete_safety=%s state=%s decision=%s reason=%s release_allowed=%t action=%s\n", + emptyAsDash(managed.VolumeID), + emptyAsDash(managed.DeleteSafety.State), + emptyAsDash(managed.DeleteSafety.Decision), + emptyAsDash(managed.DeleteSafety.Reason), + managed.DeleteSafety.FinalizerReleaseAllowed, + emptyAsDash(managed.DeleteSafety.ActionType)) + if managed.DeleteSafety.SafeNextAction != "" { + fmt.Fprintf(b, "managed_volume_delete_safety_safe_next_action=%s %s\n", + emptyAsDash(managed.VolumeID), + managed.DeleteSafety.SafeNextAction) + } + } + for _, action := range managed.Actions { + fmt.Fprintf(b, "managed_volume_action=%s mode=%s side_effect=%s executor=%s decision=%s", + emptyAsDash(action.Type), + emptyAsDash(action.Mode), + emptyAsDash(action.SideEffectClass), + emptyAsDash(action.OwnerExecutor), + emptyAsDash(action.Decision)) + if action.DecisionReason != "" { + fmt.Fprintf(b, " reason=%s", action.DecisionReason) + } + b.WriteByte('\n') + if action.EvidenceRequired != "" { + fmt.Fprintf(b, "managed_volume_action_evidence_required=%s %s\n", + emptyAsDash(action.Type), + action.EvidenceRequired) + } + } +} + +func managedProjectionKey(managed ManagedVolumeProjection) string { + return defaultString(managed.VolumeID, managed.PVCName) +} + func RenderObservationReportHTML(cluster ClusterEvidence) string { cluster = NormalizeObservationCluster(cluster) events := append([]ClusterEvent(nil), cluster.Events...) @@ -144,6 +232,42 @@ func RenderObservationReportHTML(cluster ClusterEvidence) string { b.WriteString("") } + if cluster.InstallDrift != nil { + b.WriteString("

Install Drift

") + fmt.Fprintf(&b, "", + esc(emptyAsDash(cluster.InstallDrift.Status)), + esc(emptyAsDash(cluster.InstallDrift.ReasonCode)), + esc(emptyAsDash(cluster.InstallDrift.CurrentChartVersion)), + esc(emptyAsDash(cluster.InstallDrift.DesiredChartVersion)), + esc(emptyAsDash(cluster.InstallDrift.CurrentAppVersion)), + esc(emptyAsDash(cluster.InstallDrift.DesiredAppVersion)), + esc(emptyAsDash(cluster.InstallDrift.CurrentImage)), + esc(emptyAsDash(cluster.InstallDrift.DesiredImage)), + esc(emptyAsDash(cluster.InstallDrift.CurrentCSIImage)), + esc(emptyAsDash(cluster.InstallDrift.DesiredCSIImage)), + esc(emptyAsDash(cluster.InstallDrift.CurrentOperatorImage)), + esc(emptyAsDash(cluster.InstallDrift.DesiredOperatorImage)), + esc(emptyAsDash(cluster.InstallDrift.EvidenceRef))) + b.WriteString("
StatusReasonChartAppImageCSI ImageOperator ImageEvidence
%s%s%s -> %s%s -> %s%s -> %s%s -> %s%s -> %s%s
") + } + + supportRefs := supportBundleRefsFromCluster(cluster) + if len(supportRefs) > 0 { + b.WriteString("

Support Evidence

") + for _, ref := range supportRefs { + fmt.Fprintf(&b, "", esc(ref)) + } + b.WriteString("
Evidence Ref
%s
") + } + if steps := safeNextStepsFromCluster(cluster, supportRefs); len(steps) > 0 { + b.WriteString("

Safe Next Steps

") + for _, step := range steps { + fmt.Fprintf(&b, "", + esc(step.Type), esc(step.Mode), step.MutationAllowed, esc(emptyAsDash(step.ReasonCode)), esc(step.Command)) + } + b.WriteString("
TypeModeMutationReasonCommand
%s%s%t%s%s
") + } + b.WriteString("

Managed Volumes

") for _, managed := range cluster.ManagedVolumes { class := "ok" diff --git a/seaweed-block/core/ops/observation_report_test.go b/seaweed-block/core/ops/observation_report_test.go index 940dc3d845..c3a6efc675 100644 --- a/seaweed-block/core/ops/observation_report_test.go +++ b/seaweed-block/core/ops/observation_report_test.go @@ -97,6 +97,7 @@ func TestObservationReportHTML_IncludesManagedVolumeConditions(t *testing.T) { KubernetesResidueCount: 1, MultipathResidueCount: 2, FailureCount: 2, + ReasonCodes: []string{"multipath_residue_present"}, EvidenceRef: "cleanup-summary.txt", } cluster.Volumes = []VolumeEvidence{{ @@ -120,9 +121,13 @@ func TestObservationReportHTML_IncludesManagedVolumeConditions(t *testing.T) { html := RenderObservationReportHTML(cluster) for _, want := range []string{ "Lifecycle Cleanup", + "Support Evidence", + "Safe Next Steps", "Managed Volumes", "Managed Volume Conditions", "cleanup-summary.txt", + "collect-helm-support-bundle.sh", + "verify-helm-cleanup.sh", "pvc-loopback", "publish_target_loopback_cross_node", "safe_k8s.reinstall_external_iscsi", @@ -133,6 +138,90 @@ func TestObservationReportHTML_IncludesManagedVolumeConditions(t *testing.T) { } } +func TestObservationReportSummary_IncludesCleanupVisibilityNextStep(t *testing.T) { + cluster := NewClusterEvidence(time.Date(2026, 6, 5, 19, 15, 0, 0, time.UTC)) + cluster.Cleanup = &CleanupEvidence{ + Status: "failed", + ISCSIResidueCount: 1, + FailureCount: 1, + ReasonCodes: []string{"iscsi_node_records_present"}, + EvidenceRef: "cleanup-summary.txt", + } + + summary := RenderObservationReportSummary(cluster) + for _, want := range []string{ + "cleanup_status=failed", + "iscsi_residue_count=1", + "support_bundle_ref=cleanup-summary.txt", + "safe_next_step=observe.collect_bundle mode=read_only mutation_allowed=false", + "safe_next_step=observe.verify_cleanup mode=scripted mutation_allowed=false", + "verify-helm-cleanup.sh", + "reason=iscsi_node_records_present", + } { + if !strings.Contains(summary, want) { + t.Fatalf("summary missing %q:\n%s", want, summary) + } + } +} + +func TestObservationReportSummary_IncludesSupportBundlePointers(t *testing.T) { + cluster := NewClusterEvidence(time.Date(2026, 6, 5, 18, 45, 0, 0, time.UTC)) + cluster.Status = ObservationStatusBlocked + cluster.Volumes = []VolumeEvidence{{ + VolumeID: "pvc-blocked", + Namespace: "default", + PVCName: "blocked-pvc", + Status: ObservationStatusBlocked, + Reason: ReasonCSINodeImagePullFailed, + SupportBundleHint: "support/bundle", + }} + cluster.ManagedVolumes = []ManagedVolumeProjection{ProjectManagedVolume(ManagedVolumeFacts{ + VolumeID: "pvc-blocked", + PVCName: "blocked-pvc", + ProductStatus: ObservationStatusBlocked, + ProductReason: ReasonCSINodeImagePullFailed, + EvidenceRefs: []string{"support/bundle/replayed-report/summary.txt"}, + })} + + summary := RenderObservationReportSummary(cluster) + for _, want := range []string{ + "support_bundle_ref=support/bundle", + "support_bundle_ref=support/bundle/replayed-report/summary.txt", + "safe_next_step=observe.collect_bundle mode=read_only mutation_allowed=false", + "collect-helm-support-bundle.sh", + } { + if !strings.Contains(summary, want) { + t.Fatalf("summary missing %q:\n%s", want, summary) + } + } +} + +func TestObservationReport_IncludesInstallDrift(t *testing.T) { + cluster := NewClusterEvidence(time.Date(2026, 6, 13, 13, 10, 0, 0, time.UTC)) + cluster.InstallDrift = &InstallDriftEvidence{ + Status: InstallDriftStatusMismatch, + ReasonCode: ReasonInstallDriftMismatch, + CurrentImage: "sw-block:old", + DesiredImage: "sw-block:new", + EvidenceRef: "install-drift-summary.txt", + } + + summary := RenderObservationReportSummary(cluster) + for _, want := range []string{ + "install_drift_status=mismatch reason=install_drift_mismatch evidence=install-drift-summary.txt", + "install_drift_image current=sw-block:old desired=sw-block:new", + "cluster_condition=Blocked status=True reason=install_drift_mismatch severity=warning", + } { + if !strings.Contains(summary, want) { + t.Fatalf("summary missing %q:\n%s", want, summary) + } + } + html := RenderObservationReportHTML(cluster) + if !strings.Contains(html, "Install Drift") || !strings.Contains(html, "sw-block:old") || !strings.Contains(html, "sw-block:new") { + t.Fatalf("html missing install drift:\n%s", html) + } +} + func TestObservationReportArtifacts_JSONIncludesManagedVolumeProjection(t *testing.T) { dir := t.TempDir() cluster := NewClusterEvidence(time.Date(2026, 5, 20, 12, 0, 0, 0, time.UTC)) diff --git a/seaweed-block/core/ops/operator_snapshot.go b/seaweed-block/core/ops/operator_snapshot.go index 45eac3d8f3..fda27dde13 100644 --- a/seaweed-block/core/ops/operator_snapshot.go +++ b/seaweed-block/core/ops/operator_snapshot.go @@ -1,5 +1,7 @@ package ops +import "time" + const ObservationOperatorSnapshotArtifact = "operator-snapshot.json" type OperatorFoundationSnapshot struct { @@ -20,17 +22,48 @@ type OperatorMutationBoundary struct { type OperatorClusterStatus struct { Status string `json:"status"` + NodeCount int `json:"node_count"` + Nodes []OperatorNodeStatus `json:"nodes,omitempty"` VolumeCount int `json:"volume_count"` ReadyVolumeCount int `json:"ready_volume_count"` BlockedVolumeCount int `json:"blocked_volume_count"` StaleVolumeCount int `json:"stale_volume_count"` Cleanup *CleanupEvidence `json:"cleanup,omitempty"` + InstallDrift *InstallDriftEvidence `json:"install_drift,omitempty"` + SupportBundleRefs []string `json:"support_bundle_refs,omitempty"` + SafeNextSteps []OperatorSafeNextStep `json:"safe_next_steps,omitempty"` Conditions []ObservationCondition `json:"conditions,omitempty"` NonClaims []string `json:"non_claims,omitempty"` } +type OperatorNodeStatus struct { + Name string `json:"name"` + KubernetesNode string `json:"kubernetes_node,omitempty"` + InternalIP string `json:"internal_ip,omitempty"` + Schedulable bool `json:"schedulable"` + Ready bool `json:"ready"` + Status string `json:"status,omitempty"` + ReasonCode string `json:"reason_code,omitempty"` + LastHeartbeatAt time.Time `json:"last_heartbeat_at,omitempty"` + ReplicaCount int `json:"replica_count,omitempty"` + RequiredImages []string `json:"required_images,omitempty"` + MissingImages []string `json:"missing_images,omitempty"` + Conditions []ObservationCondition `json:"conditions,omitempty"` + EvidenceRefs []string `json:"evidence_refs,omitempty"` +} + +type OperatorSafeNextStep struct { + Type string `json:"type"` + Mode string `json:"mode"` + Command string `json:"command,omitempty"` + ReasonCode string `json:"reason_code,omitempty"` + MutationAllowed bool `json:"mutation_allowed"` + EvidenceRefs []string `json:"evidence_refs,omitempty"` +} + func BuildOperatorFoundationSnapshot(cluster ClusterEvidence) OperatorFoundationSnapshot { cluster = NormalizeObservationCluster(cluster) + supportRefs := supportBundleRefsFromCluster(cluster) snapshot := OperatorFoundationSnapshot{ APIVersion: SwBlockVolumeAPIVersion, Kind: "ReadOnlyOperatorFoundationSnapshot", @@ -40,6 +73,7 @@ func BuildOperatorFoundationSnapshot(cluster ClusterEvidence) OperatorFoundation AllowedModes: []string{ ManagedVolumeActionModeReadOnly, ManagedVolumeActionModeDryRun, + ManagedVolumeActionModeScripted, }, NonClaims: []string{ "no_promote", @@ -48,14 +82,20 @@ func BuildOperatorFoundationSnapshot(cluster ClusterEvidence) OperatorFoundation "no_failback", "no_delete", "no_cleanup_mutation", + "no_upgrade_execution", }, }, CRDContract: ManagedVolumeCRDContractDefinition(), Cluster: OperatorClusterStatus{ - Status: cluster.Status, - Cleanup: cluster.Cleanup, - Conditions: append([]ObservationCondition(nil), cluster.Conditions...), - NonClaims: append([]string(nil), cluster.NonClaims...), + Status: cluster.Status, + NodeCount: len(cluster.Nodes), + Nodes: operatorNodeStatuses(cluster.Nodes), + Cleanup: cluster.Cleanup, + InstallDrift: cluster.InstallDrift, + SupportBundleRefs: supportRefs, + SafeNextSteps: operatorSafeNextSteps(safeNextStepsFromCluster(cluster, supportRefs)), + Conditions: append([]ObservationCondition(nil), cluster.Conditions...), + NonClaims: append([]string(nil), cluster.NonClaims...), }, } @@ -82,9 +122,59 @@ func BuildOperatorFoundationSnapshot(cluster ClusterEvidence) OperatorFoundation Message: "one or more managed volumes have stale or unreachable evidence", }) } + if condition := cleanupCondition(cluster.Cleanup); condition != nil { + snapshot.Cluster.Conditions = ensureCondition(snapshot.Cluster.Conditions, *condition) + } + if condition := installDriftCondition(cluster.InstallDrift); condition != nil { + snapshot.Cluster.Conditions = ensureCondition(snapshot.Cluster.Conditions, *condition) + } return snapshot } +func operatorSafeNextSteps(steps []SwBlockSafeNextStep) []OperatorSafeNextStep { + if len(steps) == 0 { + return nil + } + out := make([]OperatorSafeNextStep, 0, len(steps)) + for _, step := range steps { + out = append(out, OperatorSafeNextStep{ + Type: step.Type, + Mode: step.Mode, + Command: step.Command, + ReasonCode: step.ReasonCode, + MutationAllowed: step.MutationAllowed, + EvidenceRefs: append([]string(nil), step.EvidenceRefs...), + }) + } + return out +} + +func operatorNodeStatuses(nodes []NodeEvidence) []OperatorNodeStatus { + if len(nodes) == 0 { + return nil + } + out := make([]OperatorNodeStatus, 0, len(nodes)) + for _, node := range nodes { + status, reason := classifyNodeReadiness(node) + out = append(out, OperatorNodeStatus{ + Name: defaultString(node.NodeName, node.KubernetesNode), + KubernetesNode: node.KubernetesNode, + InternalIP: node.InternalIP, + Schedulable: node.Schedulable, + Ready: node.Ready, + Status: status, + ReasonCode: reason, + LastHeartbeatAt: node.LastHeartbeatAt, + ReplicaCount: node.ReplicaCount, + RequiredImages: append([]string(nil), node.RequiredImages...), + MissingImages: append([]string(nil), node.MissingImages...), + Conditions: nodeReadinessConditions(node, status, reason), + EvidenceRefs: nodeEvidenceRefs(node), + }) + } + return out +} + func hasCondition(conditions []ObservationCondition, conditionType, status string) bool { for _, condition := range conditions { if condition.Type == conditionType && (status == "" || condition.Status == status) { diff --git a/seaweed-block/core/ops/operator_snapshot_test.go b/seaweed-block/core/ops/operator_snapshot_test.go index a190744fba..81026a96a6 100644 --- a/seaweed-block/core/ops/operator_snapshot_test.go +++ b/seaweed-block/core/ops/operator_snapshot_test.go @@ -32,6 +32,9 @@ func TestOperatorFoundationSnapshot_ReadOnlyBoundary(t *testing.T) { if snapshot.Cluster.Cleanup == nil || snapshot.Cluster.Cleanup.Status != "ok" || snapshot.Cluster.Cleanup.EvidenceRef != "cleanup-summary.txt" { t.Fatalf("missing cleanup evidence: %+v", snapshot.Cluster.Cleanup) } + if condition := findObservationCondition(snapshot.Cluster.Conditions, ConditionCleanupRequired); condition == nil || condition.Status != "False" || condition.Reason != ReasonCleanupVerified { + t.Fatalf("missing clean cleanup condition: %+v", snapshot.Cluster.Conditions) + } if len(snapshot.Volumes) != 1 { t.Fatalf("volumes=%+v", snapshot.Volumes) } @@ -45,6 +48,42 @@ func TestOperatorFoundationSnapshot_ReadOnlyBoundary(t *testing.T) { } } +func TestOperatorFoundationSnapshot_ProjectsCleanupResidue(t *testing.T) { + cluster := NewClusterEvidence(time.Date(2026, 6, 5, 19, 0, 0, 0, time.UTC)) + cluster.Cleanup = &CleanupEvidence{ + Status: "failed", + KubernetesResidueCount: 1, + ISCSIResidueCount: 2, + MultipathResidueCount: 3, + ProcessResidueCount: 4, + HostPathResidueCount: 5, + FailureCount: 6, + ReasonCodes: []string{"iscsi_node_records_present"}, + EvidenceRef: "cleanup-summary.txt", + } + + snapshot := BuildOperatorFoundationSnapshot(cluster) + if snapshot.Cluster.Cleanup == nil || snapshot.Cluster.Cleanup.ISCSIResidueCount != 2 { + t.Fatalf("cleanup=%+v", snapshot.Cluster.Cleanup) + } + if condition := findObservationCondition(snapshot.Cluster.Conditions, ConditionCleanupRequired); condition == nil || condition.Status != "True" || condition.Reason != "iscsi_node_records_present" { + t.Fatalf("missing cleanup required condition: %+v", snapshot.Cluster.Conditions) + } + foundCleanupStep := false + for _, step := range snapshot.Cluster.SafeNextSteps { + if step.Type != ManagedVolumeActionVerifyCleanup { + continue + } + foundCleanupStep = true + if step.Mode != ManagedVolumeActionModeScripted || step.MutationAllowed { + t.Fatalf("cleanup step=%+v", step) + } + } + if !foundCleanupStep { + t.Fatalf("missing cleanup safe next step: %+v", snapshot.Cluster.SafeNextSteps) + } +} + func TestOperatorFoundationSnapshot_BlockedVolumeCarriesWarningEvent(t *testing.T) { cluster := NewClusterEvidence(time.Date(2026, 5, 23, 20, 0, 0, 0, time.UTC)) cluster.Status = ObservationStatusBlocked @@ -111,3 +150,101 @@ func TestOperatorFoundationSnapshot_CountsStaleEvidenceVolumes(t *testing.T) { t.Fatalf("missing cluster EvidenceStale condition: %+v", snapshot.Cluster.Conditions) } } + +func TestOperatorFoundationSnapshot_IncludesNodeReadiness(t *testing.T) { + cluster := NewClusterEvidence(time.Date(2026, 6, 5, 16, 30, 0, 0, time.UTC)) + cluster.Nodes = []NodeEvidence{{ + NodeName: "m02", + KubernetesNode: "m02", + InternalIP: "192.168.1.184", + Schedulable: true, + Ready: true, + ReplicaCount: 1, + RequiredImages: []string{"sw-block:local"}, + }, { + NodeName: "tp01", + KubernetesNode: "tp01", + InternalIP: "192.168.1.188", + Schedulable: true, + Ready: true, + MissingImages: []string{"sw-block-csi:local"}, + }} + + snapshot := BuildOperatorFoundationSnapshot(cluster) + if snapshot.Cluster.NodeCount != 2 || len(snapshot.Cluster.Nodes) != 2 { + t.Fatalf("node status=%+v", snapshot.Cluster) + } + ready := snapshot.Cluster.Nodes[0] + if ready.Status != ManagedVolumeStatusReady || ready.ReasonCode != ReasonNodeReady { + t.Fatalf("ready node=%+v", ready) + } + blocked := snapshot.Cluster.Nodes[1] + if blocked.Status != ManagedVolumeStatusBlocked || blocked.ReasonCode != ReasonImageMissingOnNode { + t.Fatalf("blocked node=%+v", blocked) + } + if len(blocked.MissingImages) != 1 { + t.Fatalf("blocked missing images=%+v", blocked) + } +} + +func TestOperatorFoundationSnapshot_IncludesSupportBundlePointers(t *testing.T) { + cluster := NewClusterEvidence(time.Date(2026, 6, 5, 18, 30, 0, 0, time.UTC)) + cluster.Status = ObservationStatusBlocked + cluster.Volumes = []VolumeEvidence{{ + VolumeID: "pvc-blocked", + Namespace: "default", + PVCName: "blocked-pvc", + Status: ObservationStatusBlocked, + Reason: ReasonCSINodeImagePullFailed, + SupportBundleHint: "support/bundle", + Replicas: []ReplicaEvidence{{ + ReplicaID: "r1", + SupportBundlePath: "support/bundle/volumes/pvc-blocked/r1", + }}, + }} + cluster.ManagedVolumes = []ManagedVolumeProjection{ProjectManagedVolume(ManagedVolumeFacts{ + VolumeID: "pvc-blocked", + PVCName: "blocked-pvc", + ProductStatus: ObservationStatusBlocked, + ProductReason: ReasonCSINodeImagePullFailed, + EvidenceRefs: []string{"support/bundle/replayed-report/summary.txt"}, + })} + + snapshot := BuildOperatorFoundationSnapshot(cluster) + for _, want := range []string{"support/bundle", "support/bundle/volumes/pvc-blocked/r1"} { + if !stringSliceContains(snapshot.Cluster.SupportBundleRefs, want) { + t.Fatalf("support refs missing %q: %+v", want, snapshot.Cluster.SupportBundleRefs) + } + } + if len(snapshot.Cluster.SafeNextSteps) == 0 { + t.Fatalf("missing safe next steps: %+v", snapshot.Cluster) + } + step := snapshot.Cluster.SafeNextSteps[0] + if step.Type != ManagedVolumeActionCollectBundle || step.Mode != ManagedVolumeActionModeReadOnly || step.MutationAllowed { + t.Fatalf("safe next step=%+v", step) + } +} + +func TestOperatorFoundationSnapshot_IncludesInstallDrift(t *testing.T) { + cluster := NewClusterEvidence(time.Date(2026, 6, 13, 13, 0, 0, 0, time.UTC)) + cluster.InstallDrift = &InstallDriftEvidence{ + Status: InstallDriftStatusMismatch, + ReasonCode: ReasonInstallDriftMismatch, + CurrentImage: "sw-block:old", + DesiredImage: "sw-block:new", + CurrentCSIImage: "sw-block-csi:old", + DesiredCSIImage: "sw-block-csi:new", + EvidenceRef: "install-drift-summary.txt", + } + + snapshot := BuildOperatorFoundationSnapshot(cluster) + if snapshot.Cluster.InstallDrift == nil || + snapshot.Cluster.InstallDrift.Status != InstallDriftStatusMismatch || + snapshot.Cluster.InstallDrift.ReasonCode != ReasonInstallDriftMismatch { + t.Fatalf("install drift=%+v", snapshot.Cluster.InstallDrift) + } + if condition := findObservationCondition(snapshot.Cluster.Conditions, ConditionBlocked); condition == nil || + condition.Reason != ReasonInstallDriftMismatch { + t.Fatalf("missing install drift condition: %+v", snapshot.Cluster.Conditions) + } +} diff --git a/seaweed-block/core/ops/operator_status_controller.go b/seaweed-block/core/ops/operator_status_controller.go new file mode 100644 index 0000000000..c16190a869 --- /dev/null +++ b/seaweed-block/core/ops/operator_status_controller.go @@ -0,0 +1,663 @@ +package ops + +import ( + "context" + "fmt" + "strings" + "time" + "unicode" +) + +const DefaultSwBlockClusterName = "sw-block" + +type OperatorStatusSource interface { + ClusterEvidence(ctx context.Context) (ClusterEvidence, error) +} + +type OperatorNodeEvidenceEnricher interface { + EnrichNodeEvidence(ctx context.Context, namespace string, cluster ClusterEvidence) (ClusterEvidence, error) +} + +type OperatorStatusWriter interface { + WriteClusterStatus(ctx context.Context, ref OperatorObjectRef, status SwBlockClusterCRDStatus) error + WriteVolumeStatus(ctx context.Context, ref OperatorObjectRef, status SwBlockVolumeCRDStatus) error +} + +type OperatorSwBlockVolumeSource interface { + ListSwBlockVolumes(ctx context.Context, namespace string) ([]SwBlockVolumeObject, error) +} + +type OperatorEventSink interface { + EmitEvent(ctx context.Context, event OperatorKubernetesEvent) error +} + +type OperatorObjectRef struct { + APIVersion string `json:"apiVersion"` + Kind string `json:"kind"` + Namespace string `json:"namespace"` + Name string `json:"name"` +} + +type SwBlockClusterCRDStatus struct { + ObservedAt time.Time `json:"observedAt,omitempty"` + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + NodeCount int `json:"nodeCount"` + Nodes []SwBlockNodeCRDStatus `json:"nodes,omitempty"` + VolumeCount int `json:"volumeCount"` + ReadyVolumeCount int `json:"readyVolumeCount"` + BlockedVolumeCount int `json:"blockedVolumeCount"` + StaleVolumeCount int `json:"staleVolumeCount"` + Conditions []ObservationCondition `json:"conditions,omitempty"` + EvidenceRefs []string `json:"evidenceRefs,omitempty"` + SupportBundleRefs []string `json:"supportBundleRefs,omitempty"` + Cleanup *SwBlockCleanupStatus `json:"cleanup,omitempty"` + InstallDrift *SwBlockInstallDrift `json:"installDrift,omitempty"` + SafeNextSteps []SwBlockSafeNextStep `json:"safeNextSteps,omitempty"` + MutationAllowed bool `json:"mutationAllowed"` + AllowedActionModes []string `json:"allowedActionModes,omitempty"` + NonClaims []string `json:"nonClaims,omitempty"` +} + +type SwBlockNodeCRDStatus struct { + Name string `json:"name"` + KubernetesNode string `json:"kubernetesNode,omitempty"` + InternalIP string `json:"internalIP,omitempty"` + Schedulable bool `json:"schedulable"` + Ready bool `json:"ready"` + Status string `json:"status,omitempty"` + ReasonCode string `json:"reasonCode,omitempty"` + LastHeartbeatAt time.Time `json:"lastHeartbeatAt,omitempty"` + ReplicaCount int `json:"replicaCount,omitempty"` + RequiredImages []string `json:"requiredImages,omitempty"` + MissingImages []string `json:"missingImages,omitempty"` + Conditions []ObservationCondition `json:"conditions,omitempty"` + EvidenceRefs []string `json:"evidenceRefs,omitempty"` +} + +type SwBlockSafeNextStep struct { + Type string `json:"type"` + Mode string `json:"mode"` + Command string `json:"command,omitempty"` + ReasonCode string `json:"reasonCode,omitempty"` + MutationAllowed bool `json:"mutationAllowed"` + EvidenceRefs []string `json:"evidenceRefs,omitempty"` +} + +type SwBlockCleanupStatus struct { + Status string `json:"status"` + KubernetesResidueCount int `json:"k8sResidueCount,omitempty"` + ISCSIResidueCount int `json:"iscsiResidueCount,omitempty"` + MultipathResidueCount int `json:"multipathResidueCount,omitempty"` + ProcessResidueCount int `json:"processResidueCount,omitempty"` + HostPathResidueCount int `json:"hostPathResidueCount,omitempty"` + FailureCount int `json:"failureCount,omitempty"` + FailedPhase string `json:"failedPhase,omitempty"` + ReasonCodes []string `json:"reasonCodes,omitempty"` + EvidenceRef string `json:"evidenceRef,omitempty"` +} + +type SwBlockInstallDrift struct { + Status string `json:"status"` + ReasonCode string `json:"reasonCode,omitempty"` + ChartName string `json:"chartName,omitempty"` + CurrentChartVersion string `json:"currentChartVersion,omitempty"` + DesiredChartVersion string `json:"desiredChartVersion,omitempty"` + CurrentAppVersion string `json:"currentAppVersion,omitempty"` + DesiredAppVersion string `json:"desiredAppVersion,omitempty"` + CurrentImage string `json:"currentImage,omitempty"` + DesiredImage string `json:"desiredImage,omitempty"` + CurrentCSIImage string `json:"currentCsiImage,omitempty"` + DesiredCSIImage string `json:"desiredCsiImage,omitempty"` + CurrentOperatorImage string `json:"currentOperatorImage,omitempty"` + DesiredOperatorImage string `json:"desiredOperatorImage,omitempty"` + EvidenceRef string `json:"evidenceRef,omitempty"` +} + +func swBlockCleanupStatus(cleanup *CleanupEvidence) *SwBlockCleanupStatus { + if cleanup == nil { + return nil + } + return &SwBlockCleanupStatus{ + Status: cleanup.Status, + KubernetesResidueCount: cleanup.KubernetesResidueCount, + ISCSIResidueCount: cleanup.ISCSIResidueCount, + MultipathResidueCount: cleanup.MultipathResidueCount, + ProcessResidueCount: cleanup.ProcessResidueCount, + HostPathResidueCount: cleanup.HostPathResidueCount, + FailureCount: cleanup.FailureCount, + FailedPhase: cleanup.FailedPhase, + ReasonCodes: append([]string(nil), cleanup.ReasonCodes...), + EvidenceRef: cleanup.EvidenceRef, + } +} + +func swBlockInstallDriftStatus(drift *InstallDriftEvidence) *SwBlockInstallDrift { + if drift == nil { + return nil + } + return &SwBlockInstallDrift{ + Status: drift.Status, + ReasonCode: drift.ReasonCode, + ChartName: drift.ChartName, + CurrentChartVersion: drift.CurrentChartVersion, + DesiredChartVersion: drift.DesiredChartVersion, + CurrentAppVersion: drift.CurrentAppVersion, + DesiredAppVersion: drift.DesiredAppVersion, + CurrentImage: drift.CurrentImage, + DesiredImage: drift.DesiredImage, + CurrentCSIImage: drift.CurrentCSIImage, + DesiredCSIImage: drift.DesiredCSIImage, + CurrentOperatorImage: drift.CurrentOperatorImage, + DesiredOperatorImage: drift.DesiredOperatorImage, + EvidenceRef: drift.EvidenceRef, + } +} + +func supportBundleRefsFromCluster(cluster ClusterEvidence) []string { + seen := map[string]struct{}{} + var refs []string + add := func(ref string) { + ref = strings.TrimSpace(ref) + if ref == "" { + return + } + if _, ok := seen[ref]; ok { + return + } + seen[ref] = struct{}{} + refs = append(refs, ref) + } + if cluster.Cleanup != nil { + add(cluster.Cleanup.EvidenceRef) + } + if cluster.InstallDrift != nil { + add(cluster.InstallDrift.EvidenceRef) + } + for _, volume := range cluster.Volumes { + add(volume.SupportBundleHint) + for _, condition := range volume.Conditions { + for _, ref := range condition.EvidenceRefs { + add(ref) + } + } + for _, replica := range volume.Replicas { + add(replica.SupportBundlePath) + for _, condition := range replica.Conditions { + for _, ref := range condition.EvidenceRefs { + add(ref) + } + } + } + } + for _, managed := range cluster.ManagedVolumes { + for _, ref := range managed.EvidenceRefs { + add(ref) + } + for _, condition := range managed.Conditions { + for _, ref := range condition.EvidenceRefs { + add(ref) + } + } + for _, action := range managed.Actions { + for _, ref := range action.EvidenceRefs { + add(ref) + } + } + } + for _, node := range cluster.Nodes { + for _, ref := range nodeEvidenceRefs(node) { + add(ref) + } + } + return refs +} + +func safeNextStepsFromCluster(cluster ClusterEvidence, evidenceRefs []string) []SwBlockSafeNextStep { + var steps []SwBlockSafeNextStep + if shouldSuggestCollectBundle(cluster, evidenceRefs) { + steps = append(steps, SwBlockSafeNextStep{ + Type: ManagedVolumeActionCollectBundle, + Mode: ManagedVolumeActionModeReadOnly, + Command: `bash scripts/collect-helm-support-bundle.sh "$PWD"`, + ReasonCode: supportBundleReason(cluster), + MutationAllowed: false, + EvidenceRefs: append([]string(nil), evidenceRefs...), + }) + } + if step := cleanupSafeNextStep(cluster.Cleanup); step != nil { + steps = append(steps, *step) + } + return steps +} + +func shouldSuggestCollectBundle(cluster ClusterEvidence, evidenceRefs []string) bool { + if cluster.Status != ObservationStatusOK || cleanupRequired(cluster.Cleanup) { + return true + } + if len(evidenceRefs) == 0 { + return false + } + if cluster.Cleanup != nil && !cleanupRequired(cluster.Cleanup) && len(evidenceRefs) == 1 && evidenceRefs[0] == cluster.Cleanup.EvidenceRef { + return false + } + return true +} + +func supportBundleReason(cluster ClusterEvidence) string { + if cluster.Cleanup != nil && cluster.Cleanup.Status != "" && cluster.Cleanup.Status != "ok" { + if len(cluster.Cleanup.ReasonCodes) > 0 { + return cluster.Cleanup.ReasonCodes[0] + } + return ConditionCleanupRequired + } + if cluster.Status != "" && cluster.Status != ObservationStatusOK { + return cluster.Status + } + for _, node := range cluster.Nodes { + status, reason := classifyNodeReadiness(node) + if status != ManagedVolumeStatusReady && reason != "" { + return reason + } + } + return "support_evidence_available" +} + +type SwBlockVolumeCRDStatus struct { + VolumeID string `json:"volumeID,omitempty"` + PVCName string `json:"pvcName,omitempty"` + Status string `json:"status"` + ReasonCode string `json:"reasonCode,omitempty"` + ObservedAt time.Time `json:"observedAt,omitempty"` + Conditions []ObservationCondition `json:"conditions,omitempty"` + DeleteSafety *SwBlockVolumeCRDDeleteSafety `json:"deleteSafety"` + NonClaims []string `json:"nonClaims,omitempty"` + EvidenceRefs []string `json:"evidenceRefs,omitempty"` + AllowedActions []SwBlockVolumeCRDAction `json:"allowedActions,omitempty"` +} + +type SwBlockVolumeCRDDeleteSafety struct { + ActionType string `json:"actionType,omitempty"` + Decision string `json:"decision,omitempty"` + State string `json:"state,omitempty"` + Reason string `json:"reason,omitempty"` + FinalizerReleaseAllowed bool `json:"finalizerReleaseAllowed"` + MissingFacts []string `json:"missingFacts,omitempty"` + EvidenceRefs []string `json:"evidenceRefs,omitempty"` + SafeNextAction string `json:"safeNextAction,omitempty"` +} + +type SwBlockVolumeCRDAction struct { + Type string `json:"type"` + Mode string `json:"mode"` + SideEffectClass string `json:"sideEffectClass,omitempty"` + OwnerExecutor string `json:"ownerExecutor,omitempty"` + Decision string `json:"decision,omitempty"` + DecisionReason string `json:"decisionReason,omitempty"` + MissingFacts []string `json:"missingFacts,omitempty"` + MutationAllowed bool `json:"mutationAllowed"` + Preconditions []string `json:"preconditions,omitempty"` + InvariantRefs []string `json:"invariantRefs,omitempty"` + EvidenceRequired string `json:"evidenceRequired,omitempty"` + EvidenceRefs []string `json:"evidenceRefs,omitempty"` +} + +type OperatorKubernetesEvent struct { + InvolvedObject OperatorObjectRef `json:"involvedObject"` + Type string `json:"type"` + Reason string `json:"reason"` + Message string `json:"message"` + EvidenceRefs []string `json:"evidenceRefs,omitempty"` + ObservedAt time.Time `json:"observedAt,omitempty"` +} + +type OperatorStatusReconciler struct { + Namespace string + ClusterName string + Source OperatorStatusSource + Writer OperatorStatusWriter + Volumes OperatorSwBlockVolumeSource + EventSink OperatorEventSink + Now func() time.Time +} + +type OperatorStatusReconcileResult struct { + ClusterRef OperatorObjectRef `json:"clusterRef"` + VolumeRefs []OperatorObjectRef `json:"volumeRefs"` + EventCount int `json:"eventCount"` + FinalizerPatchCount int `json:"finalizerPatchCount"` +} + +func (r OperatorStatusReconciler) Reconcile(ctx context.Context) (OperatorStatusReconcileResult, error) { + if r.Source == nil { + return OperatorStatusReconcileResult{}, fmt.Errorf("operator status source is required") + } + if r.Writer == nil { + return OperatorStatusReconcileResult{}, fmt.Errorf("operator status writer is required") + } + cluster, err := r.Source.ClusterEvidence(ctx) + if err != nil { + return OperatorStatusReconcileResult{}, err + } + cluster = NormalizeObservationCluster(cluster) + namespace := defaultString(r.Namespace, "default") + if r.Volumes != nil { + volumes, err := r.Volumes.ListSwBlockVolumes(ctx, namespace) + if err != nil { + return OperatorStatusReconcileResult{}, err + } + cluster = ProjectSwBlockVolumeDeleteSafety(cluster, volumes) + } + snapshot := BuildOperatorFoundationSnapshot(cluster) + observedAt := cluster.CapturedAt + if observedAt.IsZero() { + observedAt = r.now()() + } + + clusterName := defaultString(r.ClusterName, DefaultSwBlockClusterName) + clusterRef := OperatorObjectRef{ + APIVersion: SwBlockVolumeAPIVersion, + Kind: SwBlockClusterKind, + Namespace: namespace, + Name: clusterName, + } + clusterStatus := SwBlockClusterCRDStatus{ + ObservedAt: observedAt, + NodeCount: len(cluster.Nodes), + Nodes: swBlockNodeStatuses(cluster.Nodes), + VolumeCount: snapshot.Cluster.VolumeCount, + ReadyVolumeCount: snapshot.Cluster.ReadyVolumeCount, + BlockedVolumeCount: snapshot.Cluster.BlockedVolumeCount, + StaleVolumeCount: snapshot.Cluster.StaleVolumeCount, + Conditions: append([]ObservationCondition(nil), snapshot.Cluster.Conditions...), + MutationAllowed: snapshot.Mutation.MutationAllowed, + AllowedActionModes: append([]string(nil), snapshot.Mutation.AllowedModes...), + NonClaims: append([]string(nil), snapshot.Mutation.NonClaims...), + } + clusterStatus.SupportBundleRefs = supportBundleRefsFromCluster(cluster) + clusterStatus.SafeNextSteps = safeNextStepsFromCluster(cluster, clusterStatus.SupportBundleRefs) + if snapshot.Cluster.Cleanup != nil && snapshot.Cluster.Cleanup.EvidenceRef != "" { + clusterStatus.EvidenceRefs = append(clusterStatus.EvidenceRefs, snapshot.Cluster.Cleanup.EvidenceRef) + } + clusterStatus.Cleanup = swBlockCleanupStatus(snapshot.Cluster.Cleanup) + clusterStatus.InstallDrift = swBlockInstallDriftStatus(snapshot.Cluster.InstallDrift) + if err := r.Writer.WriteClusterStatus(ctx, clusterRef, clusterStatus); err != nil { + return OperatorStatusReconcileResult{}, err + } + + result := OperatorStatusReconcileResult{ClusterRef: clusterRef} + for _, volume := range snapshot.Volumes { + volumeRef := OperatorObjectRef{ + APIVersion: SwBlockVolumeAPIVersion, + Kind: SwBlockVolumeKind, + Namespace: namespace, + Name: SwBlockVolumeObjectName(volume.Status), + } + volumeStatus := SwBlockVolumeCRDStatus{ + VolumeID: volume.Status.VolumeID, + PVCName: volume.Status.PVCName, + Status: volume.Status.Status, + ReasonCode: volume.Status.ReasonCode, + ObservedAt: observedAt, + Conditions: append([]ObservationCondition(nil), volume.Status.Conditions...), + DeleteSafety: swBlockVolumeCRDDeleteSafety(volume.Status.DeleteSafety), + NonClaims: append([]string(nil), volume.Status.NonClaims...), + EvidenceRefs: append([]string(nil), volume.Status.EvidenceRefs...), + AllowedActions: swBlockVolumeCRDActions(volume.AllowedActions), + } + if err := r.Writer.WriteVolumeStatus(ctx, volumeRef, volumeStatus); err != nil { + if IsKubernetesStatusNotFound(err) { + continue + } + return OperatorStatusReconcileResult{}, err + } + result.VolumeRefs = append(result.VolumeRefs, volumeRef) + if r.EventSink == nil { + continue + } + for _, event := range volume.Events { + if err := r.EventSink.EmitEvent(ctx, OperatorKubernetesEvent{ + InvolvedObject: volumeRef, + Type: event.Type, + Reason: event.Reason, + Message: event.Message, + EvidenceRefs: append([]string(nil), event.EvidenceRefs...), + ObservedAt: observedAt, + }); err == nil { + result.EventCount++ + } + } + } + return result, nil +} + +func ProjectSwBlockVolumeDeleteSafety(cluster ClusterEvidence, volumes []SwBlockVolumeObject) ClusterEvidence { + cluster = NormalizeObservationCluster(cluster) + for _, volume := range volumes { + if volume.DeletionTimestamp == nil { + continue + } + volumeID := volume.Status.VolumeID + pvcName := firstNonEmpty(volume.Status.PVCName, volume.Spec.PVCName, volume.Ref.Name) + applyDeleteSafetyFacts(&cluster, deleteSafetyProjectionFacts{ + VolumeID: volumeID, + PVCName: pvcName, + DeleteRequested: true, + FinalizerPresent: lifecycleOwnerStringSliceContains(volume.Finalizers, SwBlockVolumeFinalizerName), + EvidencePath: "swblockvolume/" + volume.Ref.Namespace + "/" + volume.Ref.Name, + }) + } + return NormalizeObservationCluster(cluster) +} + +func swBlockVolumeCRDDeleteSafety(decision *SwBlockVolumeDeleteSafetyDecision) *SwBlockVolumeCRDDeleteSafety { + if decision == nil { + return nil + } + return &SwBlockVolumeCRDDeleteSafety{ + ActionType: decision.ActionType, + Decision: decision.Decision, + State: decision.State, + Reason: decision.Reason, + FinalizerReleaseAllowed: decision.FinalizerReleaseAllowed, + MissingFacts: append([]string(nil), decision.MissingFacts...), + EvidenceRefs: append([]string(nil), decision.EvidenceRefs...), + SafeNextAction: decision.SafeNextAction, + } +} + +func swBlockVolumeCRDActions(actions []ManagedVolumeOperatorAction) []SwBlockVolumeCRDAction { + if len(actions) == 0 { + return nil + } + out := make([]SwBlockVolumeCRDAction, 0, len(actions)) + for _, action := range actions { + out = append(out, SwBlockVolumeCRDAction{ + Type: action.Type, + Mode: action.Mode, + SideEffectClass: action.SideEffectClass, + OwnerExecutor: action.OwnerExecutor, + Decision: action.Decision, + DecisionReason: action.DecisionReason, + MissingFacts: append([]string(nil), action.MissingFacts...), + MutationAllowed: action.MutationAllowed, + Preconditions: append([]string(nil), action.Preconditions...), + InvariantRefs: append([]string(nil), action.InvariantRefs...), + EvidenceRequired: action.EvidenceRequired, + EvidenceRefs: append([]string(nil), action.EvidenceRefs...), + }) + } + return out +} + +func swBlockNodeStatuses(nodes []NodeEvidence) []SwBlockNodeCRDStatus { + if len(nodes) == 0 { + return nil + } + out := make([]SwBlockNodeCRDStatus, 0, len(nodes)) + for _, node := range nodes { + status, reason := classifyNodeReadiness(node) + out = append(out, SwBlockNodeCRDStatus{ + Name: defaultString(node.NodeName, node.KubernetesNode), + KubernetesNode: node.KubernetesNode, + InternalIP: node.InternalIP, + Schedulable: node.Schedulable, + Ready: node.Ready, + Status: status, + ReasonCode: reason, + LastHeartbeatAt: node.LastHeartbeatAt, + ReplicaCount: node.ReplicaCount, + RequiredImages: append([]string(nil), node.RequiredImages...), + MissingImages: append([]string(nil), node.MissingImages...), + Conditions: nodeReadinessConditions(node, status, reason), + EvidenceRefs: nodeEvidenceRefs(node), + }) + } + return out +} + +func classifyNodeReadiness(node NodeEvidence) (string, string) { + switch { + case !node.Ready: + return ManagedVolumeStatusUnknown, ReasonNodeNotReady + case !node.Schedulable: + return ManagedVolumeStatusBlocked, ReasonNodeSchedulingDisabled + case len(node.MissingImages) > 0: + return ManagedVolumeStatusBlocked, ReasonImageMissingOnNode + case nodeHasConditionReason(node, ReasonCSIDriverNotRegistered): + return ManagedVolumeStatusBlocked, ReasonCSIDriverNotRegistered + case nodeHasConditionReason(node, ReasonCSINodePodNotReady): + return ManagedVolumeStatusBlocked, ReasonCSINodePodNotReady + case nodeHasConditionReason(node, ReasonISCSIPrereqMissing): + return ManagedVolumeStatusBlocked, ReasonISCSIPrereqMissing + case nodeHasConditionReason(node, ReasonMultipathPrereqMissing): + return ManagedVolumeStatusBlocked, ReasonMultipathPrereqMissing + default: + return ManagedVolumeStatusReady, ReasonNodeReady + } +} + +func nodeHasConditionReason(node NodeEvidence, reason string) bool { + for _, condition := range node.Conditions { + if condition.Reason == reason { + return true + } + } + return false +} + +func nodeReadinessConditions(node NodeEvidence, status, reason string) []ObservationCondition { + conditions := removeConditionType(node.Conditions, ConditionReady) + switch status { + case ManagedVolumeStatusReady: + return ensureCondition(conditions, ObservationCondition{ + Type: ConditionReady, + Status: "True", + Reason: reason, + Severity: "info", + Message: "node is ready for Seaweed Block", + }) + case ManagedVolumeStatusBlocked: + conditions = ensureCondition(conditions, ObservationCondition{ + Type: ConditionReady, + Status: "False", + Reason: reason, + Severity: "warning", + Message: "node is blocked for Seaweed Block", + }) + return ensureCondition(conditions, ObservationCondition{ + Type: ConditionBlocked, + Status: "True", + Reason: reason, + Severity: "warning", + Message: "node requires operator attention before scheduling Seaweed Block workloads", + }) + default: + conditions = ensureCondition(conditions, ObservationCondition{ + Type: ConditionReady, + Status: "Unknown", + Reason: reason, + Severity: "warning", + Message: "node readiness evidence is unavailable or not ready", + }) + return ensureCondition(conditions, ObservationCondition{ + Type: ConditionEvidenceStale, + Status: "True", + Reason: reason, + Severity: "warning", + Message: "node readiness evidence is insufficient", + }) + } +} + +func removeConditionType(conditions []ObservationCondition, typ string) []ObservationCondition { + if len(conditions) == 0 { + return nil + } + out := make([]ObservationCondition, 0, len(conditions)) + for _, condition := range conditions { + if condition.Type == typ { + continue + } + out = append(out, condition) + } + return out +} + +func ensureCondition(conditions []ObservationCondition, condition ObservationCondition) []ObservationCondition { + if hasCondition(conditions, condition.Type, condition.Status) { + return conditions + } + return append(conditions, condition) +} + +func nodeEvidenceRefs(node NodeEvidence) []string { + var refs []string + for _, condition := range node.Conditions { + refs = append(refs, condition.EvidenceRefs...) + } + return refs +} + +func (r OperatorStatusReconciler) now() func() time.Time { + if r.Now != nil { + return r.Now + } + return time.Now +} + +func SwBlockVolumeObjectName(status ManagedVolumeOperatorStatus) string { + if status.PVCName != "" { + return kubernetesName(status.PVCName) + } + if status.VolumeID != "" { + return kubernetesName(status.VolumeID) + } + return "unknown-volume" +} + +func kubernetesName(in string) string { + var b strings.Builder + for _, r := range strings.ToLower(in) { + switch { + case r >= 'a' && r <= 'z': + b.WriteRune(r) + case r >= '0' && r <= '9': + b.WriteRune(r) + case r == '-' || r == '.': + b.WriteRune('-') + case unicode.IsSpace(r) || r == '_' || r == ':': + b.WriteRune('-') + } + } + out := strings.Trim(b.String(), "-") + if out == "" { + return "unknown-volume" + } + if len(out) > 63 { + out = strings.TrimRight(out[:63], "-") + } + if out == "" { + return "unknown-volume" + } + return out +} diff --git a/seaweed-block/core/ops/operator_status_controller_test.go b/seaweed-block/core/ops/operator_status_controller_test.go new file mode 100644 index 0000000000..2f05042821 --- /dev/null +++ b/seaweed-block/core/ops/operator_status_controller_test.go @@ -0,0 +1,1136 @@ +package ops + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "testing" + "time" +) + +func TestOperatorStatusReconcilerWritesStatusOnlyProjection(t *testing.T) { + capturedAt := time.Date(2026, 6, 2, 22, 30, 0, 0, time.UTC) + source := fakeOperatorStatusSource{cluster: ClusterEvidence{ + SchemaVersion: ObservationSchemaVersion, + CapturedAt: capturedAt, + Status: ObservationStatusOK, + Nodes: []NodeEvidence{{ + NodeName: "m02", + Ready: true, + }}, + InstallDrift: &InstallDriftEvidence{ + Status: InstallDriftStatusMismatch, + ReasonCode: ReasonInstallDriftMismatch, + CurrentImage: "sw-block:old", + DesiredImage: "sw-block:new", + CurrentCSIImage: "sw-block-csi:old", + DesiredCSIImage: "sw-block-csi:new", + EvidenceRef: "install-drift-summary.txt", + }, + ManagedVolumes: []ManagedVolumeProjection{ + ProjectManagedVolume(ManagedVolumeFacts{ + VolumeID: "pvc-ready", + PVCName: "demo-pvc", + PVC: &PVCFact{Phase: "Bound"}, + Authority: &AuthorityFact{ + PrimaryReplica: "r1", + PublishTarget: "192.168.1.184:3260", + }, + Replicas: []ReplicaFact{{ + ReplicaID: "r1", + KubernetesNode: "m02", + Role: "primary", + Observed: true, + }}, + CSIStages: []CSIStageFact{{NodeName: "m02", Target: "192.168.1.184:3260"}}, + Workload: &WorkloadCheckFact{WriterVerified: true, ReaderVerified: true}, + }), + ProjectManagedVolume(ManagedVolumeFacts{ + VolumeID: "pvc-blocked", + PVCName: "blocked-pvc", + ProductStatus: ObservationStatusBlocked, + ProductReason: ReasonCSINodeImagePullFailed, + EvidenceRefs: []string{"diagnostics/events.txt"}, + }), + }, + }} + writer := &fakeOperatorStatusWriter{} + events := &fakeOperatorEventSink{} + + result, err := (OperatorStatusReconciler{ + Namespace: "kube-system", + ClusterName: "sw-block", + Source: source, + Writer: writer, + EventSink: events, + }).Reconcile(context.Background()) + if err != nil { + t.Fatalf("reconcile: %v", err) + } + if result.ClusterRef.Kind != SwBlockClusterKind || result.ClusterRef.Name != "sw-block" { + t.Fatalf("cluster ref=%+v", result.ClusterRef) + } + if len(result.VolumeRefs) != 2 || len(writer.volumes) != 2 { + t.Fatalf("volume refs=%+v writes=%+v", result.VolumeRefs, writer.volumes) + } + if writer.cluster.NodeCount != 1 || writer.cluster.VolumeCount != 2 || writer.cluster.ReadyVolumeCount != 1 || writer.cluster.BlockedVolumeCount != 1 { + t.Fatalf("cluster status=%+v", writer.cluster) + } + if writer.cluster.MutationAllowed { + t.Fatalf("cluster status must not allow mutation: %+v", writer.cluster) + } + if writer.cluster.InstallDrift == nil || + writer.cluster.InstallDrift.Status != InstallDriftStatusMismatch || + writer.cluster.InstallDrift.ReasonCode != ReasonInstallDriftMismatch || + writer.cluster.InstallDrift.CurrentImage != "sw-block:old" || + writer.cluster.InstallDrift.DesiredImage != "sw-block:new" || + writer.cluster.InstallDrift.CurrentCSIImage != "sw-block-csi:old" || + writer.cluster.InstallDrift.DesiredCSIImage != "sw-block-csi:new" { + t.Fatalf("install drift status=%+v", writer.cluster.InstallDrift) + } + if len(writer.cluster.Nodes) != 1 || writer.cluster.Nodes[0].Name != "m02" { + t.Fatalf("cluster nodes=%+v", writer.cluster.Nodes) + } + if got := writer.volumes[0].status.Status; got != ManagedVolumeStatusReady { + t.Fatalf("ready volume status=%s", got) + } + if got := writer.volumes[1].status.ReasonCode; got != ReasonCSINodeImagePullFailed { + t.Fatalf("blocked volume reason=%s", got) + } + for _, write := range writer.volumes { + for _, action := range write.status.AllowedActions { + if action.MutationAllowed { + t.Fatalf("mutating action leaked into status: %+v", action) + } + } + } + rawStatus, err := json.Marshal(writer.volumes[0].status) + if err != nil { + t.Fatalf("marshal volume status: %v", err) + } + if !strings.Contains(string(rawStatus), `"mutationAllowed":false`) { + t.Fatalf("CRD volume status must use camelCase mutationAllowed: %s", string(rawStatus)) + } + if strings.Contains(string(rawStatus), "mutation_allowed") { + t.Fatalf("CRD volume status must not use operator-snapshot snake_case fields: %s", string(rawStatus)) + } + if events.countByReason(ReasonFirstVolumeVerified) == 0 { + t.Fatalf("missing ready event: %+v", events.events) + } + if events.countByReason(ReasonCSINodeImagePullFailed) == 0 { + t.Fatalf("missing blocked event: %+v", events.events) + } + for _, event := range events.events { + if event.Reason == ReasonCSINodeImagePullFailed { + if event.Type != "Warning" || event.InvolvedObject.Kind != SwBlockVolumeKind || event.InvolvedObject.Name != "blocked-pvc" { + t.Fatalf("blocked event shape=%+v", event) + } + } + } + if result.EventCount != len(events.events) { + t.Fatalf("event count=%d events=%d", result.EventCount, len(events.events)) + } +} + +func TestOperatorStatusReconcilerProjectsNodeReadiness(t *testing.T) { + heartbeat := time.Date(2026, 6, 5, 16, 0, 0, 0, time.UTC) + source := fakeOperatorStatusSource{cluster: ClusterEvidence{ + SchemaVersion: ObservationSchemaVersion, + CapturedAt: time.Date(2026, 6, 5, 16, 1, 0, 0, time.UTC), + Status: ObservationStatusOK, + Nodes: []NodeEvidence{{ + NodeName: "node-loss-r1", + KubernetesNode: "m01", + InternalIP: "192.168.1.181", + Schedulable: true, + Ready: true, + LastHeartbeatAt: heartbeat, + ReplicaCount: 2, + RequiredImages: []string{"sw-block:local", "sw-block-csi:local"}, + Conditions: []ObservationCondition{{ + Type: ConditionReady, + Status: "True", + Reason: ReasonNodeReady, + Severity: "info", + Message: "node is ready for Seaweed Block", + }}, + }}, + }} + writer := &fakeOperatorStatusWriter{} + + _, err := (OperatorStatusReconciler{ + Source: source, + Writer: writer, + }).Reconcile(context.Background()) + if err != nil { + t.Fatalf("reconcile: %v", err) + } + if writer.cluster.NodeCount != 1 || len(writer.cluster.Nodes) != 1 { + t.Fatalf("cluster node status=%+v", writer.cluster) + } + node := writer.cluster.Nodes[0] + if node.Name != "node-loss-r1" || node.KubernetesNode != "m01" || node.InternalIP != "192.168.1.181" { + t.Fatalf("node identity=%+v", node) + } + if !node.Schedulable || !node.Ready || node.Status != ManagedVolumeStatusReady || node.ReasonCode != ReasonNodeReady { + t.Fatalf("node readiness=%+v", node) + } + if !node.LastHeartbeatAt.Equal(heartbeat) || node.ReplicaCount != 2 || len(node.RequiredImages) != 2 { + t.Fatalf("node details=%+v", node) + } + assertCondition(t, node.Conditions, ConditionReady, "True", ReasonNodeReady) + rawStatus, err := json.Marshal(writer.cluster) + if err != nil { + t.Fatalf("marshal cluster status: %v", err) + } + raw := string(rawStatus) + for _, want := range []string{`"kubernetesNode":"m01"`, `"internalIP":"192.168.1.181"`, `"lastHeartbeatAt":"2026-06-05T16:00:00Z"`, `"requiredImages":["sw-block:local","sw-block-csi:local"]`} { + if !strings.Contains(raw, want) { + t.Fatalf("cluster node status missing %s: %s", want, raw) + } + } + for _, forbidden := range []string{"kubernetes_node", "internal_ip", "last_heartbeat_at", "required_images"} { + if strings.Contains(raw, forbidden) { + t.Fatalf("CRD node status must not use observation snake_case field %q: %s", forbidden, raw) + } + } +} + +func TestOperatorStatusReconcilerProjectsImageMissingNodeAsBlocked(t *testing.T) { + source := fakeOperatorStatusSource{cluster: ClusterEvidence{ + SchemaVersion: ObservationSchemaVersion, + CapturedAt: time.Date(2026, 6, 5, 16, 5, 0, 0, time.UTC), + Status: ObservationStatusOK, + Nodes: []NodeEvidence{{ + NodeName: "m02", + KubernetesNode: "m02", + InternalIP: "192.168.1.184", + Schedulable: true, + Ready: true, + RequiredImages: []string{"ghcr.io/seaweedfs/seaweed-block:sha-test"}, + MissingImages: []string{"ghcr.io/seaweedfs/seaweed-block:sha-test"}, + Conditions: []ObservationCondition{{ + Type: ConditionBlocked, + Status: "True", + Reason: ReasonImageMissingOnNode, + Severity: "warning", + Message: "required image is missing on node", + }}, + }}, + }} + writer := &fakeOperatorStatusWriter{} + + _, err := (OperatorStatusReconciler{ + Source: source, + Writer: writer, + }).Reconcile(context.Background()) + if err != nil { + t.Fatalf("reconcile: %v", err) + } + if len(writer.cluster.Nodes) != 1 { + t.Fatalf("cluster nodes=%+v", writer.cluster.Nodes) + } + node := writer.cluster.Nodes[0] + if node.Status != ManagedVolumeStatusBlocked || node.ReasonCode != ReasonImageMissingOnNode { + t.Fatalf("node status=%+v", node) + } + if len(node.MissingImages) != 1 || node.MissingImages[0] != "ghcr.io/seaweedfs/seaweed-block:sha-test" { + t.Fatalf("missing images=%+v", node.MissingImages) + } + assertCondition(t, node.Conditions, ConditionReady, "False", ReasonImageMissingOnNode) + assertCondition(t, node.Conditions, ConditionBlocked, "True", ReasonImageMissingOnNode) + if writer.cluster.ReadyVolumeCount != 0 { + t.Fatalf("node blocker must not synthesize ready volumes: %+v", writer.cluster) + } +} + +func TestPhase40D2NodeReadinessReplacesStaleReadyCondition(t *testing.T) { + source := fakeOperatorStatusSource{cluster: ClusterEvidence{ + SchemaVersion: ObservationSchemaVersion, + CapturedAt: time.Date(2026, 6, 13, 12, 0, 0, 0, time.UTC), + Status: ObservationStatusOK, + Nodes: []NodeEvidence{{ + NodeName: "m02", + Schedulable: true, + Ready: true, + MissingImages: []string{ + "sw-block-csi:local", + }, + Conditions: []ObservationCondition{ + {Type: ConditionReady, Status: "True", Reason: ReasonNodeReady, Severity: "info"}, + {Type: ConditionReady, Status: "Unknown", Reason: ReasonNodeNotReady, Severity: "warning"}, + }, + }}, + }} + writer := &fakeOperatorStatusWriter{} + + _, err := (OperatorStatusReconciler{ + Source: source, + Writer: writer, + }).Reconcile(context.Background()) + if err != nil { + t.Fatalf("reconcile: %v", err) + } + if len(writer.cluster.Nodes) != 1 { + t.Fatalf("cluster nodes=%+v", writer.cluster.Nodes) + } + node := writer.cluster.Nodes[0] + assertCondition(t, node.Conditions, ConditionReady, "False", ReasonImageMissingOnNode) + if got := countConditionsByType(node.Conditions, ConditionReady); got != 1 { + t.Fatalf("Ready conditions=%d want 1: %+v", got, node.Conditions) + } +} + +func TestOperatorStatusReconcilerStaleEvidenceProjectsUnknownAndWarningEvent(t *testing.T) { + source := fakeOperatorStatusSource{cluster: ClusterEvidence{ + SchemaVersion: ObservationSchemaVersion, + CapturedAt: time.Date(2026, 6, 2, 23, 0, 0, 0, time.UTC), + Status: ObservationStatusUnavailable, + ManagedVolumes: []ManagedVolumeProjection{ProjectManagedVolume(ManagedVolumeFacts{ + VolumeID: "pvc-stale", + PVCName: "stale_pvc", + EvidenceStale: true, + EvidenceStaleReason: ReasonEvidenceStale, + EvidenceRefs: []string{"product/unreachable.txt"}, + })}, + }} + writer := &fakeOperatorStatusWriter{} + events := &fakeOperatorEventSink{} + + _, err := (OperatorStatusReconciler{ + Source: source, + Writer: writer, + EventSink: events, + }).Reconcile(context.Background()) + if err != nil { + t.Fatalf("reconcile: %v", err) + } + if writer.cluster.StaleVolumeCount != 1 { + t.Fatalf("cluster status=%+v", writer.cluster) + } + if len(writer.volumes) != 1 { + t.Fatalf("volume writes=%+v", writer.volumes) + } + volume := writer.volumes[0] + if volume.ref.Name != "stale-pvc" { + t.Fatalf("volume name=%q", volume.ref.Name) + } + if volume.status.Status != ManagedVolumeStatusUnknown || volume.status.ReasonCode != ReasonEvidenceStale { + t.Fatalf("volume status=%+v", volume.status) + } + foundUnknownReady := false + for _, condition := range volume.status.Conditions { + if condition.Type == ConditionReady && condition.Status == "Unknown" && condition.Reason == ReasonEvidenceStale { + foundUnknownReady = true + } + } + if !foundUnknownReady { + t.Fatalf("missing Ready=Unknown condition: %+v", volume.status.Conditions) + } + if events.countByReason(ReasonEvidenceStale) == 0 { + t.Fatalf("missing EvidenceStale event: %+v", events.events) + } + for _, event := range events.events { + if event.Reason == ReasonEvidenceStale && event.Type != "Warning" { + t.Fatalf("EvidenceStale event type=%s want Warning", event.Type) + } + } +} + +func TestOperatorStatusReconcilerStatusEndpointUnreachableIsUnknownNotBlocked(t *testing.T) { + source := fakeOperatorStatusSource{cluster: ClusterEvidence{ + SchemaVersion: ObservationSchemaVersion, + CapturedAt: time.Date(2026, 6, 4, 2, 0, 0, 0, time.UTC), + Status: ObservationStatusUnavailable, + ManagedVolumes: []ManagedVolumeProjection{ProjectManagedVolume(ManagedVolumeFacts{ + VolumeID: "pvc-unreachable", + PVCName: "status-unreachable-pvc", + ProductStatus: ObservationStatusUnavailable, + ProductReason: ReasonStatusEndpointUnreachable, + EvidenceRefs: []string{"diagnostics/status-endpoint-unreachable.txt"}, + })}, + }} + writer := &fakeOperatorStatusWriter{} + events := &fakeOperatorEventSink{} + + _, err := (OperatorStatusReconciler{ + Source: source, + Writer: writer, + EventSink: events, + }).Reconcile(context.Background()) + if err != nil { + t.Fatalf("reconcile: %v", err) + } + if writer.cluster.StaleVolumeCount != 1 || writer.cluster.BlockedVolumeCount != 0 { + t.Fatalf("cluster status=%+v", writer.cluster) + } + if len(writer.volumes) != 1 { + t.Fatalf("volume writes=%+v", writer.volumes) + } + volume := writer.volumes[0] + if volume.status.Status != ManagedVolumeStatusUnknown || volume.status.ReasonCode != ReasonStatusEndpointUnreachable { + t.Fatalf("volume status=%+v", volume.status) + } + assertCondition(t, volume.status.Conditions, ConditionReady, "Unknown", ReasonStatusEndpointUnreachable) + assertCondition(t, volume.status.Conditions, ConditionEvidenceStale, "True", ReasonStatusEndpointUnreachable) + if condition := findObservationCondition(volume.status.Conditions, ConditionBlocked); condition != nil && condition.Status == "True" { + t.Fatalf("pure unreachable status must not become Blocked=True: %+v", volume.status.Conditions) + } + if events.countByReason(ReasonStatusEndpointUnreachable) == 0 { + t.Fatalf("missing status_endpoint_unreachable event: %+v", events.events) + } + for _, event := range events.events { + if event.Reason == ReasonStatusEndpointUnreachable && event.Type != "Warning" { + t.Fatalf("status endpoint event type=%s want Warning", event.Type) + } + } +} + +func TestOperatorStatusReconcilerWALIntegrityFaultIsNeverReady(t *testing.T) { + source := fakeOperatorStatusSource{cluster: ClusterEvidence{ + SchemaVersion: ObservationSchemaVersion, + CapturedAt: time.Date(2026, 6, 4, 2, 15, 0, 0, time.UTC), + Status: ObservationStatusBlocked, + ManagedVolumes: []ManagedVolumeProjection{ProjectManagedVolume(ManagedVolumeFacts{ + VolumeID: "pvc-corrupt", + PVCName: "wal-corrupt-pvc", + ProductStatus: ObservationStatusBlocked, + ProductReason: ReasonWALIntegrityFault, + EvidenceRefs: []string{"status/report/cluster-evidence.json", "blockvolume.log"}, + })}, + }} + writer := &fakeOperatorStatusWriter{} + events := &fakeOperatorEventSink{} + + _, err := (OperatorStatusReconciler{ + Source: source, + Writer: writer, + EventSink: events, + }).Reconcile(context.Background()) + if err != nil { + t.Fatalf("reconcile: %v", err) + } + if writer.cluster.ReadyVolumeCount != 0 || writer.cluster.BlockedVolumeCount != 1 { + t.Fatalf("cluster status=%+v", writer.cluster) + } + if len(writer.volumes) != 1 { + t.Fatalf("volume writes=%+v", writer.volumes) + } + volume := writer.volumes[0] + if volume.status.Status == ManagedVolumeStatusReady { + t.Fatalf("wal integrity fault must never be Ready: %+v", volume.status) + } + if volume.status.ReasonCode != ReasonWALIntegrityFault { + t.Fatalf("volume status=%+v", volume.status) + } + assertCondition(t, volume.status.Conditions, ConditionReady, "False", ReasonWALIntegrityFault) + assertCondition(t, volume.status.Conditions, ConditionBlocked, "True", ReasonWALIntegrityFault) + if events.countByReason(ReasonWALIntegrityFault) == 0 { + t.Fatalf("missing wal_integrity_fault event: %+v", events.events) + } +} + +func TestOperatorStatusReconcilerCleanupStatusUsesCRDFieldNames(t *testing.T) { + source := fakeOperatorStatusSource{cluster: ClusterEvidence{ + SchemaVersion: ObservationSchemaVersion, + CapturedAt: time.Date(2026, 6, 5, 12, 0, 0, 0, time.UTC), + Status: ObservationStatusOK, + Cleanup: &CleanupEvidence{ + Status: "failed", + KubernetesResidueCount: 1, + ISCSIResidueCount: 2, + MultipathResidueCount: 3, + ProcessResidueCount: 4, + HostPathResidueCount: 5, + FailureCount: 6, + FailedPhase: "verify", + ReasonCodes: []string{"iscsi_node_records_present"}, + EvidenceRef: "cleanup-summary.txt", + }, + }} + writer := &fakeOperatorStatusWriter{} + + _, err := (OperatorStatusReconciler{ + Source: source, + Writer: writer, + }).Reconcile(context.Background()) + if err != nil { + t.Fatalf("reconcile: %v", err) + } + if writer.cluster.Cleanup == nil || writer.cluster.Cleanup.ISCSIResidueCount != 2 { + t.Fatalf("cleanup status=%+v", writer.cluster.Cleanup) + } + assertCondition(t, writer.cluster.Conditions, ConditionCleanupRequired, "True", "iscsi_node_records_present") + foundCleanupStep := false + for _, step := range writer.cluster.SafeNextSteps { + if step.Type != ManagedVolumeActionVerifyCleanup { + continue + } + foundCleanupStep = true + if step.Mode != ManagedVolumeActionModeScripted || step.MutationAllowed { + t.Fatalf("cleanup next step=%+v", step) + } + if !strings.Contains(step.Command, "verify-helm-cleanup.sh") || step.ReasonCode != "iscsi_node_records_present" { + t.Fatalf("cleanup next step=%+v", step) + } + } + if !foundCleanupStep { + t.Fatalf("missing cleanup safe next step: %+v", writer.cluster.SafeNextSteps) + } + rawStatus, err := json.Marshal(writer.cluster) + if err != nil { + t.Fatalf("marshal cluster status: %v", err) + } + raw := string(rawStatus) + for _, want := range []string{`"k8sResidueCount":1`, `"iscsiResidueCount":2`, `"hostPathResidueCount":5`, `"evidenceRef":"cleanup-summary.txt"`} { + if !strings.Contains(raw, want) { + t.Fatalf("cluster cleanup status missing %s: %s", want, raw) + } + } + for _, forbidden := range []string{"k8s_residue_count", "iscsi_residue_count", "hostpath_residue_count", "evidence_ref"} { + if strings.Contains(raw, forbidden) { + t.Fatalf("CRD cleanup status must not use report snake_case field %q: %s", forbidden, raw) + } + } +} + +func TestOperatorStatusReconcilerProjectsCleanCleanupCondition(t *testing.T) { + source := fakeOperatorStatusSource{cluster: ClusterEvidence{ + SchemaVersion: ObservationSchemaVersion, + CapturedAt: time.Date(2026, 6, 5, 12, 15, 0, 0, time.UTC), + Status: ObservationStatusOK, + Cleanup: &CleanupEvidence{ + Status: ObservationStatusOK, + EvidenceRef: "cleanup-summary.txt", + }, + }} + writer := &fakeOperatorStatusWriter{} + + _, err := (OperatorStatusReconciler{ + Source: source, + Writer: writer, + }).Reconcile(context.Background()) + if err != nil { + t.Fatalf("reconcile: %v", err) + } + assertCondition(t, writer.cluster.Conditions, ConditionCleanupRequired, "False", ReasonCleanupVerified) + if len(writer.cluster.SafeNextSteps) != 0 { + t.Fatalf("clean cleanup evidence must not suggest next steps: %+v", writer.cluster.SafeNextSteps) + } +} + +func TestOperatorStatusReconcilerProjectsSupportBundlePointers(t *testing.T) { + source := fakeOperatorStatusSource{cluster: ClusterEvidence{ + SchemaVersion: ObservationSchemaVersion, + CapturedAt: time.Date(2026, 6, 5, 18, 0, 0, 0, time.UTC), + Status: ObservationStatusBlocked, + Volumes: []VolumeEvidence{{ + VolumeID: "pvc-blocked", + Namespace: "default", + PVCName: "blocked-pvc", + Status: ObservationStatusBlocked, + Reason: ReasonCSINodeImagePullFailed, + SupportBundleHint: "support/bundle", + Replicas: []ReplicaEvidence{{ + ReplicaID: "r1", + SupportBundlePath: "support/bundle/volumes/pvc-blocked/r1", + }}, + }}, + ManagedVolumes: []ManagedVolumeProjection{ProjectManagedVolume(ManagedVolumeFacts{ + VolumeID: "pvc-blocked", + PVCName: "blocked-pvc", + ProductStatus: ObservationStatusBlocked, + ProductReason: ReasonCSINodeImagePullFailed, + EvidenceRefs: []string{"support/bundle/replayed-report/summary.txt"}, + })}, + }} + writer := &fakeOperatorStatusWriter{} + + _, err := (OperatorStatusReconciler{ + Source: source, + Writer: writer, + }).Reconcile(context.Background()) + if err != nil { + t.Fatalf("reconcile: %v", err) + } + for _, want := range []string{ + "support/bundle", + "support/bundle/volumes/pvc-blocked/r1", + } { + if !stringSliceContains(writer.cluster.SupportBundleRefs, want) { + t.Fatalf("cluster support refs missing %q: %+v", want, writer.cluster.SupportBundleRefs) + } + } + if len(writer.cluster.SafeNextSteps) == 0 { + t.Fatalf("missing safe next steps: %+v", writer.cluster) + } + step := writer.cluster.SafeNextSteps[0] + if step.Type != ManagedVolumeActionCollectBundle || step.Mode != ManagedVolumeActionModeReadOnly || step.MutationAllowed { + t.Fatalf("support next step=%+v", step) + } + if step.Command == "" || !strings.Contains(step.Command, "collect-helm-support-bundle.sh") { + t.Fatalf("support next step command=%+v", step) + } +} + +func TestOperatorStatusReconcilerEventFailureDoesNotBlockLaterStatusWrites(t *testing.T) { + source := fakeOperatorStatusSource{cluster: ClusterEvidence{ + SchemaVersion: ObservationSchemaVersion, + CapturedAt: time.Date(2026, 6, 4, 1, 30, 0, 0, time.UTC), + ManagedVolumes: []ManagedVolumeProjection{ + ProjectManagedVolume(ManagedVolumeFacts{ + VolumeID: "pvc-blocked", + PVCName: "blocked-pvc", + ProductStatus: ObservationStatusBlocked, + ProductReason: ReasonCSINodeImagePullFailed, + EvidenceRefs: []string{"blocked/events.txt"}, + }), + ProjectManagedVolume(ManagedVolumeFacts{ + VolumeID: "pvc-ready", + PVCName: "ready-pvc", + PVC: &PVCFact{Phase: "Bound"}, + Authority: &AuthorityFact{ + PrimaryReplica: "r1", + PublishTarget: "192.168.1.184:3260", + }, + Replicas: []ReplicaFact{{ + ReplicaID: "r1", + KubernetesNode: "m02", + Role: "primary", + Observed: true, + }}, + CSIStages: []CSIStageFact{{NodeName: "m02", Target: "192.168.1.184:3260"}}, + Workload: &WorkloadCheckFact{WriterVerified: true, ReaderVerified: true}, + }), + }, + }} + writer := &fakeOperatorStatusWriter{} + events := &failingOperatorEventSink{} + + result, err := (OperatorStatusReconciler{ + Namespace: "kube-system", + Source: source, + Writer: writer, + EventSink: events, + }).Reconcile(context.Background()) + if err != nil { + t.Fatalf("event failure must not abort reconcile: %v", err) + } + if len(writer.volumes) != 2 { + t.Fatalf("status writes=%+v", writer.volumes) + } + if writer.volumes[0].status.Status != ManagedVolumeStatusBlocked || writer.volumes[1].status.Status != ManagedVolumeStatusReady { + t.Fatalf("volume statuses=%+v", writer.volumes) + } + if events.count == 0 { + t.Fatalf("expected event attempts") + } + if result.EventCount != 0 { + t.Fatalf("successful event count=%d want 0", result.EventCount) + } +} + +func TestOperatorStatusReconcilerProjectsDeleteSafetyWithoutFinalizerMutation(t *testing.T) { + source := fakeOperatorStatusSource{cluster: ClusterEvidence{ + SchemaVersion: ObservationSchemaVersion, + CapturedAt: time.Date(2026, 6, 10, 12, 10, 0, 0, time.UTC), + Status: ObservationStatusBlocked, + ManagedVolumes: []ManagedVolumeProjection{{ + VolumeID: "pvc-held", + PVCName: "held-pvc", + Status: ManagedVolumeStatusBlocked, + ReasonCode: "iscsi_node_records_present", + Conditions: []ObservationCondition{{ + Type: ConditionCleanupRequired, + Status: "True", + Reason: "iscsi_node_records_present", + Severity: "warning", + }}, + DeleteSafety: &SwBlockVolumeDeleteSafetyDecision{ + ActionType: SwBlockVolumeDeleteActionReleaseFinalizer, + Decision: ManagedVolumeActionDecisionRejected, + State: DeleteSafetyStateBlocked, + Reason: "iscsi_node_records_present", + FinalizerReleaseAllowed: false, + SafeNextAction: ManagedVolumeActionVerifyCleanup, + EvidenceRefs: []string{"cleanup-summary.txt"}, + }, + }}, + }} + writer := &fakeOperatorStatusWriter{} + events := &fakeOperatorEventSink{} + result, err := (OperatorStatusReconciler{ + Namespace: "kube-system", + ClusterName: "sw-block", + Source: source, + Writer: writer, + EventSink: events, + }).Reconcile(context.Background()) + if err != nil { + t.Fatalf("reconcile: %v", err) + } + if result.FinalizerPatchCount != 0 { + t.Fatalf("finalizer patches=%d", result.FinalizerPatchCount) + } + if len(writer.volumes) != 1 || writer.volumes[0].status.DeleteSafety == nil { + t.Fatalf("volume status writes=%+v", writer.volumes) + } + if writer.volumes[0].status.DeleteSafety.State != DeleteSafetyStateBlocked || + writer.volumes[0].status.DeleteSafety.Decision != ManagedVolumeActionDecisionRejected { + t.Fatalf("delete safety status=%+v", writer.volumes[0].status.DeleteSafety) + } + action := findCRDAction(writer.volumes[0].status.AllowedActions, SwBlockVolumeDeleteActionReleaseFinalizer) + if action == nil || + action.Mode != ManagedVolumeActionModeDryRun || + action.OwnerExecutor != "lifecycle_owner" || + action.MutationAllowed || + action.Decision != ManagedVolumeActionDecisionRejected { + t.Fatalf("lifecycle-owner dry-run action=%+v", action) + } + if events.countByReason(ReasonDeleteFinalizerAdded) != 0 || + events.countByReason(ReasonDeleteFinalizerReleased) != 0 { + t.Fatalf("operator-status must not emit finalizer mutation events: %+v", events.events) + } +} + +func findCRDAction(actions []SwBlockVolumeCRDAction, typ string) *SwBlockVolumeCRDAction { + for i := range actions { + if actions[i].Type == typ { + return &actions[i] + } + } + return nil +} + +func TestOperatorStatusReconcilerDeleteSafetyDoesNotContaminateOtherVolumes(t *testing.T) { + source := fakeOperatorStatusSource{cluster: ClusterEvidence{ + SchemaVersion: ObservationSchemaVersion, + CapturedAt: time.Date(2026, 6, 12, 10, 0, 0, 0, time.UTC), + Status: ObservationStatusBlocked, + ManagedVolumes: []ManagedVolumeProjection{ + { + VolumeID: "pvc-a", + PVCName: "delete-a", + Status: ManagedVolumeStatusBlocked, + ReasonCode: "iscsi_node_records_present", + Conditions: []ObservationCondition{{ + Type: ConditionCleanupRequired, + Status: "True", + Reason: "iscsi_node_records_present", + Severity: "warning", + }}, + DeleteSafety: &SwBlockVolumeDeleteSafetyDecision{ + ActionType: SwBlockVolumeDeleteActionReleaseFinalizer, + Decision: ManagedVolumeActionDecisionRejected, + State: DeleteSafetyStateBlocked, + Reason: "iscsi_node_records_present", + FinalizerReleaseAllowed: false, + SafeNextAction: ManagedVolumeActionVerifyCleanup, + EvidenceRefs: []string{"cleanup-a.txt"}, + }, + }, + { + VolumeID: "pvc-b", + PVCName: "healthy-b", + Status: ManagedVolumeStatusReady, + ReasonCode: ReasonFirstVolumeVerified, + Conditions: []ObservationCondition{{ + Type: ConditionReady, + Status: "True", + Reason: ReasonFirstVolumeVerified, + Severity: "info", + }}, + }, + { + VolumeID: "pvc-c", + PVCName: "clean-c", + Status: ManagedVolumeStatusReady, + ReasonCode: ReasonFirstVolumeVerified, + DeleteSafety: &SwBlockVolumeDeleteSafetyDecision{ + ActionType: SwBlockVolumeDeleteActionReleaseFinalizer, + Decision: ManagedVolumeActionDecisionAllowed, + State: DeleteSafetyStateReleasable, + Reason: ReasonDeleteFinalizerReleasable, + FinalizerReleaseAllowed: true, + EvidenceRefs: []string{"cleanup-c.txt"}, + }, + }, + { + VolumeID: "pvc-d", + PVCName: "stale-d", + Status: ManagedVolumeStatusReady, + ReasonCode: ReasonFirstVolumeVerified, + DeleteSafety: &SwBlockVolumeDeleteSafetyDecision{ + ActionType: SwBlockVolumeDeleteActionReleaseFinalizer, + Decision: ManagedVolumeActionDecisionUnknown, + State: DeleteSafetyStateRequested, + Reason: ReasonCleanupEvidenceStale, + FinalizerReleaseAllowed: false, + MissingFacts: []string{"cleanup.freshness"}, + EvidenceRefs: []string{"cleanup-d.txt"}, + }, + }, + }, + }} + writer := &fakeOperatorStatusWriter{} + events := &fakeOperatorEventSink{} + result, err := (OperatorStatusReconciler{ + Namespace: "kube-system", + ClusterName: "sw-block", + Source: source, + Writer: writer, + EventSink: events, + }).Reconcile(context.Background()) + if err != nil { + t.Fatalf("reconcile: %v", err) + } + if result.FinalizerPatchCount != 0 { + t.Fatalf("finalizer patches=%d", result.FinalizerPatchCount) + } + if len(writer.volumes) != 4 { + t.Fatalf("volume writes=%+v", writer.volumes) + } + byName := map[string]SwBlockVolumeCRDStatus{} + for _, record := range writer.volumes { + byName[record.ref.Name] = record.status + } + if got := byName["delete-a"]; got.Status != ManagedVolumeStatusBlocked || + got.ReasonCode != "iscsi_node_records_present" || + got.DeleteSafety == nil || + got.DeleteSafety.State != DeleteSafetyStateBlocked { + t.Fatalf("volume A status=%+v", got) + } + if got := byName["healthy-b"]; got.Status != ManagedVolumeStatusReady || + got.ReasonCode != ReasonFirstVolumeVerified || + got.DeleteSafety != nil { + t.Fatalf("volume B contaminated status=%+v", got) + } + if got := byName["clean-c"]; got.Status != ManagedVolumeStatusReady || + got.ReasonCode != ReasonFirstVolumeVerified || + got.DeleteSafety == nil || + got.DeleteSafety.State != DeleteSafetyStateReleasable || + got.DeleteSafety.Decision != ManagedVolumeActionDecisionAllowed { + t.Fatalf("volume C status=%+v", got) + } + if got := byName["stale-d"]; got.Status != ManagedVolumeStatusReady || + got.ReasonCode != ReasonFirstVolumeVerified || + got.DeleteSafety == nil || + got.DeleteSafety.State != DeleteSafetyStateRequested || + got.DeleteSafety.Decision != ManagedVolumeActionDecisionUnknown || + got.DeleteSafety.Reason != ReasonCleanupEvidenceStale { + t.Fatalf("volume D status=%+v", got) + } + for name, wantDecision := range map[string]string{ + "delete-a": ManagedVolumeActionDecisionRejected, + "clean-c": ManagedVolumeActionDecisionAllowed, + "stale-d": ManagedVolumeActionDecisionUnknown, + } { + action := findCRDAction(byName[name].AllowedActions, SwBlockVolumeDeleteActionReleaseFinalizer) + if action == nil || + action.OwnerExecutor != "lifecycle_owner" || + action.Mode != ManagedVolumeActionModeDryRun || + action.MutationAllowed || + action.Decision != wantDecision { + t.Fatalf("volume %s lifecycle-owner action=%+v want decision=%s", name, action, wantDecision) + } + } + for _, event := range events.events { + if event.Reason == ReasonDeleteFinalizerAdded || event.Reason == ReasonDeleteFinalizerReleased { + t.Fatalf("finalizer mutation event emitted: %+v", event) + } + } +} + +func TestPhase44OperatorStatusReconcilerProjectsLiveDeletingVolumeHold(t *testing.T) { + deletingAt := time.Date(2026, 6, 16, 10, 0, 0, 0, time.UTC) + source := fakeOperatorStatusSource{cluster: ClusterEvidence{ + SchemaVersion: ObservationSchemaVersion, + CapturedAt: deletingAt, + Status: ObservationStatusOK, + ManagedVolumes: []ManagedVolumeProjection{{ + VolumeID: "pvc-live", + PVCName: "live-pvc", + Status: ManagedVolumeStatusReady, + ReasonCode: ReasonFirstVolumeVerified, + Conditions: []ObservationCondition{{ + Type: ConditionReady, + Status: "True", + Reason: ReasonFirstVolumeVerified, + Severity: "info", + }}, + }}, + }} + writer := &fakeOperatorStatusWriter{} + result, err := (OperatorStatusReconciler{ + Namespace: "kube-system", + Source: source, + Writer: writer, + Volumes: fakeOperatorSwBlockVolumeSource{volumes: []SwBlockVolumeObject{{ + Ref: OperatorObjectRef{ + Namespace: "kube-system", + Name: "live-pvc", + }, + Finalizers: []string{SwBlockVolumeFinalizerName}, + DeletionTimestamp: &deletingAt, + Spec: SwBlockVolumeSpec{PVCName: "live-pvc"}, + Status: SwBlockVolumeCRDStatus{ + VolumeID: "pvc-live", + PVCName: "live-pvc", + }, + }}}, + }).Reconcile(context.Background()) + if err != nil { + t.Fatalf("reconcile: %v", err) + } + if result.FinalizerPatchCount != 0 { + t.Fatalf("operator-status must not patch finalizers: %d", result.FinalizerPatchCount) + } + if len(writer.volumes) != 1 { + t.Fatalf("volume writes=%+v", writer.volumes) + } + got := writer.volumes[0].status + if got.Status != ManagedVolumeStatusUnknown || got.ReasonCode != ReasonCleanupEvidenceMissing { + t.Fatalf("deleting volume with missing evidence must not stay ready: %+v", got) + } + if got.DeleteSafety == nil || + got.DeleteSafety.Decision != ManagedVolumeActionDecisionUnknown || + got.DeleteSafety.State != DeleteSafetyStateRequested || + got.DeleteSafety.Reason != ReasonCleanupEvidenceMissing { + t.Fatalf("delete safety=%+v", got.DeleteSafety) + } + action := findCRDAction(got.AllowedActions, SwBlockVolumeDeleteActionReleaseFinalizer) + if action == nil || + action.Decision != ManagedVolumeActionDecisionUnknown || + action.MutationAllowed || + action.Mode != ManagedVolumeActionModeDryRun { + t.Fatalf("release action=%+v", action) + } +} + +func TestPhase44OperatorStatusReconcilerProjectsLiveDeletingVolumeRelease(t *testing.T) { + observedAt := time.Date(2026, 6, 16, 10, 5, 0, 0, time.UTC) + source := fakeOperatorStatusSource{cluster: ClusterEvidence{ + SchemaVersion: ObservationSchemaVersion, + CapturedAt: observedAt, + Status: ObservationStatusOK, + Cleanup: &CleanupEvidence{ + Status: ObservationStatusOK, + EvidenceRef: "cleanup-summary.txt", + ObservedAt: observedAt, + }, + ManagedVolumes: []ManagedVolumeProjection{{ + VolumeID: "pvc-clean", + PVCName: "clean-pvc", + Status: ManagedVolumeStatusReady, + ReasonCode: ReasonFirstVolumeVerified, + }}, + }} + writer := &fakeOperatorStatusWriter{} + _, err := (OperatorStatusReconciler{ + Namespace: "kube-system", + Source: source, + Writer: writer, + Volumes: fakeOperatorSwBlockVolumeSource{volumes: []SwBlockVolumeObject{{ + Ref: OperatorObjectRef{ + Namespace: "kube-system", + Name: "clean-pvc", + }, + Finalizers: []string{"example.com/foreign", SwBlockVolumeFinalizerName}, + DeletionTimestamp: &observedAt, + Spec: SwBlockVolumeSpec{PVCName: "clean-pvc"}, + Status: SwBlockVolumeCRDStatus{ + VolumeID: "pvc-clean", + PVCName: "clean-pvc", + }, + }}}, + }).Reconcile(context.Background()) + if err != nil { + t.Fatalf("reconcile: %v", err) + } + got := writer.volumes[0].status + if got.DeleteSafety == nil || + !got.DeleteSafety.FinalizerReleaseAllowed || + got.DeleteSafety.Decision != ManagedVolumeActionDecisionAllowed || + got.DeleteSafety.State != DeleteSafetyStateReleasable { + t.Fatalf("delete safety=%+v", got.DeleteSafety) + } + action := findCRDAction(got.AllowedActions, SwBlockVolumeDeleteActionReleaseFinalizer) + if action == nil || action.Decision != ManagedVolumeActionDecisionAllowed || action.MutationAllowed { + t.Fatalf("release action=%+v", action) + } +} + +func TestPhase44OperatorStatusReconcilerSkipsDeletedCRDuringStatusPatch(t *testing.T) { + source := fakeOperatorStatusSource{cluster: ClusterEvidence{ + SchemaVersion: ObservationSchemaVersion, + CapturedAt: time.Date(2026, 6, 16, 10, 15, 0, 0, time.UTC), + Status: ObservationStatusOK, + ManagedVolumes: []ManagedVolumeProjection{ + { + VolumeID: "pvc-gone", + PVCName: "gone-pvc", + Status: ManagedVolumeStatusReady, + ReasonCode: ReasonFirstVolumeVerified, + }, + { + VolumeID: "pvc-live", + PVCName: "live-pvc", + Status: ManagedVolumeStatusReady, + ReasonCode: ReasonFirstVolumeVerified, + }, + }, + }} + writer := ¬FoundOnceOperatorStatusWriter{missingName: "gone-pvc"} + result, err := (OperatorStatusReconciler{ + Namespace: "kube-system", + Source: source, + Writer: writer, + }).Reconcile(context.Background()) + if err != nil { + t.Fatalf("404 on deleted volume CR must not abort reconcile: %v", err) + } + if len(result.VolumeRefs) != 1 || result.VolumeRefs[0].Name != "live-pvc" { + t.Fatalf("volume refs=%+v", result.VolumeRefs) + } + if len(writer.volumes) != 1 || writer.volumes[0].ref.Name != "live-pvc" { + t.Fatalf("written volumes=%+v", writer.volumes) + } +} + +func TestPhase40D2VolumeStatusClearsStaleDeleteSafety(t *testing.T) { + status := SwBlockVolumeCRDStatus{ + VolumeID: "pvc-ready", + PVCName: "ready-pvc", + Status: ManagedVolumeStatusReady, + ReasonCode: ReasonFirstVolumeVerified, + DeleteSafety: nil, + } + raw, err := json.Marshal(status) + if err != nil { + t.Fatalf("marshal status: %v", err) + } + if !strings.Contains(string(raw), `"deleteSafety":null`) { + t.Fatalf("status patch must clear stale deleteSafety with null: %s", string(raw)) + } +} + +func TestSwBlockVolumeObjectNameIsDNSLabelLike(t *testing.T) { + cases := map[string]string{ + "Demo_PVC": "demo-pvc", + "pvc:1234.5678": "pvc-1234-5678", + "---": "unknown-volume", + "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnop": "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk", + } + for in, want := range cases { + got := SwBlockVolumeObjectName(ManagedVolumeOperatorStatus{PVCName: in}) + if got != want { + t.Fatalf("name %q=%q want %q", in, got, want) + } + } +} + +type fakeOperatorStatusSource struct { + cluster ClusterEvidence +} + +func (f fakeOperatorStatusSource) ClusterEvidence(context.Context) (ClusterEvidence, error) { + return f.cluster, nil +} + +type fakeOperatorSwBlockVolumeSource struct { + volumes []SwBlockVolumeObject +} + +func (f fakeOperatorSwBlockVolumeSource) ListSwBlockVolumes(context.Context, string) ([]SwBlockVolumeObject, error) { + return append([]SwBlockVolumeObject(nil), f.volumes...), nil +} + +type fakeOperatorStatusWriter struct { + cluster OperatorStatusWriterClusterRecord + volumes []OperatorStatusWriterVolumeRecord +} + +type OperatorStatusWriterClusterRecord = SwBlockClusterCRDStatus + +type OperatorStatusWriterVolumeRecord struct { + ref OperatorObjectRef + status SwBlockVolumeCRDStatus +} + +func (f *fakeOperatorStatusWriter) WriteClusterStatus(_ context.Context, _ OperatorObjectRef, status SwBlockClusterCRDStatus) error { + f.cluster = status + return nil +} + +func (f *fakeOperatorStatusWriter) WriteVolumeStatus(_ context.Context, ref OperatorObjectRef, status SwBlockVolumeCRDStatus) error { + f.volumes = append(f.volumes, OperatorStatusWriterVolumeRecord{ref: ref, status: status}) + return nil +} + +type notFoundOnceOperatorStatusWriter struct { + fakeOperatorStatusWriter + missingName string +} + +func (f *notFoundOnceOperatorStatusWriter) WriteVolumeStatus(ctx context.Context, ref OperatorObjectRef, status SwBlockVolumeCRDStatus) error { + if ref.Name == f.missingName { + return fmt.Errorf("patch swblockvolumes/%s status failed: http 404 not found", ref.Name) + } + return f.fakeOperatorStatusWriter.WriteVolumeStatus(ctx, ref, status) +} + +type fakeOperatorEventSink struct { + events []OperatorKubernetesEvent +} + +func (f *fakeOperatorEventSink) EmitEvent(_ context.Context, event OperatorKubernetesEvent) error { + f.events = append(f.events, event) + return nil +} + +type failingOperatorEventSink struct { + count int +} + +func (f *failingOperatorEventSink) EmitEvent(context.Context, OperatorKubernetesEvent) error { + f.count++ + return errOperatorEventSinkFailed{} +} + +type errOperatorEventSinkFailed struct{} + +func (errOperatorEventSinkFailed) Error() string { + return "event sink failed" +} + +func (f *fakeOperatorEventSink) countByReason(reason string) int { + count := 0 + for _, event := range f.events { + if event.Reason == reason { + count++ + } + } + return count +} + +func assertCondition(t *testing.T, conditions []ObservationCondition, typ, status, reason string) { + t.Helper() + condition := findObservationCondition(conditions, typ) + if condition == nil { + t.Fatalf("missing %s condition: %+v", typ, conditions) + } + if condition.Status != status || condition.Reason != reason { + t.Fatalf("%s condition=%+v want status=%s reason=%s", typ, *condition, status, reason) + } +} + +func countConditionsByType(conditions []ObservationCondition, typ string) int { + count := 0 + for _, condition := range conditions { + if condition.Type == typ { + count++ + } + } + return count +} diff --git a/seaweed-block/core/ops/phase36_status_surface_test.go b/seaweed-block/core/ops/phase36_status_surface_test.go new file mode 100644 index 0000000000..728fde98d2 --- /dev/null +++ b/seaweed-block/core/ops/phase36_status_surface_test.go @@ -0,0 +1,244 @@ +package ops + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestPhase36D5NodeStatusSurfacesAgree(t *testing.T) { + cluster := NewClusterEvidence(time.Date(2026, 6, 5, 20, 0, 0, 0, time.UTC)) + cluster.Nodes = []NodeEvidence{{ + NodeName: "m02", + KubernetesNode: "m02", + InternalIP: "192.168.1.184", + Schedulable: true, + Ready: true, + RequiredImages: []string{"sw-block:local"}, + MissingImages: []string{"sw-block-csi:local"}, + }} + + summary := RenderObservationReportSummary(cluster) + for _, want := range []string{ + "node=m02 k8s=m02 status=blocked reason=image_missing_on_node ready=true schedulable=true missing_images=sw-block-csi:local", + } { + if !strings.Contains(summary, want) { + t.Fatalf("summary missing %q:\n%s", want, summary) + } + } + + snapshot := BuildOperatorFoundationSnapshot(cluster) + if snapshot.Cluster.NodeCount != 1 || len(snapshot.Cluster.Nodes) != 1 { + t.Fatalf("snapshot nodes=%+v", snapshot.Cluster) + } + node := snapshot.Cluster.Nodes[0] + if node.Status != ManagedVolumeStatusBlocked || node.ReasonCode != ReasonImageMissingOnNode { + t.Fatalf("node status=%+v", node) + } + + dashboard := phase36DashboardSnapshot(t, cluster) + if dashboard.Cluster.Nodes[0].Status != ManagedVolumeStatusBlocked || + dashboard.Cluster.Nodes[0].ReasonCode != ReasonImageMissingOnNode { + t.Fatalf("dashboard node=%+v", dashboard.Cluster.Nodes[0]) + } +} + +func TestPhase37D4HostPrereqNodeStatusSurfacesAgree(t *testing.T) { + for _, tc := range []struct { + name string + reason string + }{ + {name: "iscsi", reason: ReasonISCSIPrereqMissing}, + {name: "multipath", reason: ReasonMultipathPrereqMissing}, + } { + t.Run(tc.name, func(t *testing.T) { + cluster := NewClusterEvidence(time.Date(2026, 6, 8, 12, 0, 0, 0, time.UTC)) + cluster.Nodes = []NodeEvidence{{ + NodeName: "m02", + KubernetesNode: "m02", + InternalIP: "192.168.1.184", + Schedulable: true, + Ready: true, + Conditions: []ObservationCondition{{ + Type: ConditionReady, + Status: "False", + Reason: tc.reason, + Severity: "warning", + Message: "host prerequisite evidence is missing", + EvidenceRefs: []string{"host/m02/prereq.txt"}, + }}, + }} + + summary := RenderObservationReportSummary(cluster) + want := "node=m02 k8s=m02 status=blocked reason=" + tc.reason + " ready=true schedulable=true" + if !strings.Contains(summary, want) { + t.Fatalf("summary missing %q:\n%s", want, summary) + } + step := "safe_next_step=observe.collect_bundle mode=read_only mutation_allowed=false" + if !strings.Contains(summary, step) || !strings.Contains(summary, "reason="+tc.reason) { + t.Fatalf("summary missing safe host-prereq next step:\n%s", summary) + } + + snapshot := BuildOperatorFoundationSnapshot(cluster) + if snapshot.Cluster.NodeCount != 1 || len(snapshot.Cluster.Nodes) != 1 { + t.Fatalf("snapshot nodes=%+v", snapshot.Cluster) + } + node := snapshot.Cluster.Nodes[0] + if node.Status != ManagedVolumeStatusBlocked || node.ReasonCode != tc.reason { + t.Fatalf("snapshot node=%+v", node) + } + if !phase37HasNodeCondition(node.Conditions, ConditionReady, "False", tc.reason) || + !phase37HasNodeCondition(node.Conditions, ConditionBlocked, "True", tc.reason) { + t.Fatalf("snapshot conditions=%+v", node.Conditions) + } + + dashboard := phase36DashboardSnapshot(t, cluster) + if dashboard.Cluster.Nodes[0].Status != ManagedVolumeStatusBlocked || + dashboard.Cluster.Nodes[0].ReasonCode != tc.reason { + t.Fatalf("dashboard node=%+v", dashboard.Cluster.Nodes[0]) + } + }) + } +} + +func TestPhase36D5CleanupRequiredSurfacesAgree(t *testing.T) { + cluster := NewClusterEvidence(time.Date(2026, 6, 5, 20, 5, 0, 0, time.UTC)) + cluster.Cleanup = &CleanupEvidence{ + Status: "failed", + ISCSIResidueCount: 1, + FailureCount: 1, + EvidenceRef: "cleanup-summary.txt", + } + + summary := RenderObservationReportSummary(cluster) + for _, want := range []string{ + "cleanup_status=failed", + "iscsi_residue_count=1", + "cluster_condition=CleanupRequired status=True reason=cleanup_required severity=warning", + "safe_next_step=observe.verify_cleanup mode=scripted mutation_allowed=false", + } { + if !strings.Contains(summary, want) { + t.Fatalf("summary missing %q:\n%s", want, summary) + } + } + + snapshot := BuildOperatorFoundationSnapshot(cluster) + if snapshot.Cluster.Cleanup == nil || snapshot.Cluster.Cleanup.ISCSIResidueCount != 1 { + t.Fatalf("snapshot cleanup=%+v", snapshot.Cluster.Cleanup) + } + if !phase36HasClusterCondition(snapshot, ConditionCleanupRequired, "True", ReasonCleanupRequired) { + t.Fatalf("snapshot conditions=%+v", snapshot.Cluster.Conditions) + } + verifyStep := false + for _, step := range snapshot.Cluster.SafeNextSteps { + if step.Type == ManagedVolumeActionVerifyCleanup { + verifyStep = true + if step.Mode != ManagedVolumeActionModeScripted || step.MutationAllowed { + t.Fatalf("cleanup step=%+v", step) + } + } + } + if !verifyStep { + t.Fatalf("missing cleanup step: %+v", snapshot.Cluster.SafeNextSteps) + } + + dashboard := phase36DashboardSnapshot(t, cluster) + if dashboard.Cluster.Cleanup == nil || dashboard.Cluster.Cleanup.ISCSIResidueCount != 1 { + t.Fatalf("dashboard cleanup=%+v", dashboard.Cluster.Cleanup) + } + if !phase36HasClusterCondition(dashboard, ConditionCleanupRequired, "True", ReasonCleanupRequired) { + t.Fatalf("dashboard conditions=%+v", dashboard.Cluster.Conditions) + } +} + +func TestPhase36D5StaleEvidenceSurfacesDoNotClaimReady(t *testing.T) { + cluster := NewClusterEvidence(time.Date(2026, 6, 5, 20, 10, 0, 0, time.UTC)) + cluster.Status = ObservationStatusUnavailable + cluster.ManagedVolumes = []ManagedVolumeProjection{ProjectManagedVolume(ManagedVolumeFacts{ + VolumeID: "pvc-unreachable", + PVCName: "status-unreachable-pvc", + ProductStatus: ObservationStatusUnavailable, + ProductReason: ReasonStatusEndpointUnreachable, + EvidenceRefs: []string{"diagnostics/status-endpoint-unreachable.txt"}, + })} + + summary := RenderObservationReportSummary(cluster) + for _, want := range []string{ + "managed_volume=pvc-unreachable status=unknown reason=status_endpoint_unreachable", + "managed_volume_condition=Ready status=Unknown reason=status_endpoint_unreachable severity=warning", + "managed_volume_condition=EvidenceStale status=True reason=status_endpoint_unreachable severity=warning", + "cluster_condition=EvidenceStale status=True reason=evidence_stale severity=warning", + } { + if !strings.Contains(summary, want) { + t.Fatalf("summary missing %q:\n%s", want, summary) + } + } + if strings.Contains(summary, "managed_volume_condition=Ready status=True") { + t.Fatalf("stale summary must not claim Ready=True:\n%s", summary) + } + + explain := RenderObservationExplainText(cluster) + if !strings.Contains(explain, "managed_volume pvc-unreachable status=unknown reason=status_endpoint_unreachable") || + !strings.Contains(explain, "managed_volume_condition EvidenceStale status=True reason=status_endpoint_unreachable") { + t.Fatalf("explain missing stale reason:\n%s", explain) + } + + snapshot := BuildOperatorFoundationSnapshot(cluster) + if snapshot.Cluster.ReadyVolumeCount != 0 || snapshot.Cluster.StaleVolumeCount != 1 { + t.Fatalf("snapshot cluster=%+v", snapshot.Cluster) + } + volume := snapshot.Volumes[0] + if volume.Status.Status != ManagedVolumeStatusUnknown || volume.Status.ReasonCode != ReasonStatusEndpointUnreachable { + t.Fatalf("snapshot volume=%+v", volume.Status) + } + if operatorContractHasCondition(volume, ConditionReady, "True", "") { + t.Fatalf("snapshot stale volume must not be Ready=True: %+v", volume.Status.Conditions) + } + + dashboard := phase36DashboardSnapshot(t, cluster) + if dashboard.Cluster.ReadyVolumeCount != 0 || dashboard.Cluster.StaleVolumeCount != 1 { + t.Fatalf("dashboard cluster=%+v", dashboard.Cluster) + } + if dashboard.Volumes[0].Status.Status != ManagedVolumeStatusUnknown || + dashboard.Volumes[0].Status.ReasonCode != ReasonStatusEndpointUnreachable { + t.Fatalf("dashboard volume=%+v", dashboard.Volumes[0].Status) + } +} + +func phase36DashboardSnapshot(t *testing.T, cluster ClusterEvidence) OperatorFoundationSnapshot { + t.Helper() + recorder := httptest.NewRecorder() + NewObservationDashboardHandler(cluster).ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/operator-snapshot.json", nil)) + if recorder.Code != http.StatusOK { + t.Fatalf("dashboard code=%d body=%s", recorder.Code, recorder.Body.String()) + } + var snapshot OperatorFoundationSnapshot + if err := json.Unmarshal(recorder.Body.Bytes(), &snapshot); err != nil { + t.Fatalf("decode dashboard snapshot: %v\n%s", err, recorder.Body.String()) + } + if !snapshot.ReadOnly || snapshot.Mutation.MutationAllowed { + t.Fatalf("dashboard mutation boundary=%+v", snapshot.Mutation) + } + return snapshot +} + +func phase36HasClusterCondition(snapshot OperatorFoundationSnapshot, typ, status, reason string) bool { + for _, condition := range snapshot.Cluster.Conditions { + if condition.Type == typ && condition.Status == status && condition.Reason == reason { + return true + } + } + return false +} + +func phase37HasNodeCondition(conditions []ObservationCondition, typ, status, reason string) bool { + for _, condition := range conditions { + if condition.Type == typ && condition.Status == status && condition.Reason == reason { + return true + } + } + return false +} diff --git a/seaweed-block/core/ops/phase37_node_evidence_contract_test.go b/seaweed-block/core/ops/phase37_node_evidence_contract_test.go new file mode 100644 index 0000000000..526355626d --- /dev/null +++ b/seaweed-block/core/ops/phase37_node_evidence_contract_test.go @@ -0,0 +1,77 @@ +package ops + +import "testing" + +func TestPhase37D1LiveNodeEvidenceContractCoversRequiredFacts(t *testing.T) { + byPath := managedVolumeContractByPath(LiveNodeEvidenceFactContract()) + required := map[string]string{ + "node.kubernetes_ready": FactAuthorityKubernetesObject, + "node.scheduling_disabled": FactAuthorityKubernetesObject, + "node.csi_node_pod_ready": FactAuthorityKubernetesObject, + "node.csi_driver_exists": FactAuthorityKubernetesObject, + "node.csi_node_driver_registered": FactAuthorityKubernetesObject, + "node.required_image_presence": FactAuthorityObservation, + "node.image_pull_status": FactAuthorityKubernetesObject, + "node.iscsi_prereq": FactAuthorityHostPath, + "node.multipath_prereq": FactAuthorityHostPath, + "node.loopback_publish_target_cross_node": FactAuthorityObservation, + } + for path, authority := range required { + entry, ok := byPath[path] + if !ok { + t.Fatalf("missing live node evidence contract path %q", path) + } + if entry.FactAuthority != authority { + t.Fatalf("path %s authority=%s want %s", path, entry.FactAuthority, authority) + } + if entry.Master != MasterManagedVolume { + t.Fatalf("path %s master=%s want %s", path, entry.Master, MasterManagedVolume) + } + if entry.EvidenceRequired == "" || entry.ConditionSurface == "" { + t.Fatalf("path %s missing evidence/surface contract: %+v", path, entry) + } + } +} + +func TestPhase37D1LiveNodeEvidenceContractIsReadOnlyPassiveObservation(t *testing.T) { + for _, entry := range LiveNodeEvidenceFactContract() { + if entry.Path == "" || entry.Participant == "" || entry.FactAuthority == "" { + t.Fatalf("incomplete live node evidence entry: %+v", entry) + } + if entry.AggregationMode != FactAggregationPassive { + t.Fatalf("phase37 node evidence must be passive observation, got %+v", entry) + } + if entry.ProbeAllowed || entry.ProbeTrigger != "" { + t.Fatalf("phase37 D1 must not authorize active mutation/probe behavior: %+v", entry) + } + switch entry.Stability { + case ManagedVolumeFieldStable, ManagedVolumeFieldProvisional, ManagedVolumeFieldTestOnly: + default: + t.Fatalf("path %s has invalid stability %q", entry.Path, entry.Stability) + } + } +} + +func TestPhase37D1LiveNodeEvidenceReasonVocabulary(t *testing.T) { + reasons := LiveNodeEvidenceReasonCodes() + for _, want := range []string{ + ReasonNodeReady, + ReasonNodeNotReady, + ReasonNodeSchedulingDisabled, + ReasonCSINodePodNotReady, + ReasonCSIDriverNotRegistered, + ReasonImageMissingOnNode, + ReasonISCSIPrereqMissing, + ReasonMultipathPrereqMissing, + ReasonPublishTargetLoopbackCrossNode, + } { + if !stringSliceContains(reasons, want) { + t.Fatalf("missing phase37 node reason %s in %+v", want, reasons) + } + } + for _, reason := range reasons { + if reason == "" { + t.Fatalf("empty phase37 node reason in %+v", reasons) + } + } +} diff --git a/seaweed-block/core/ops/volume_status_summary.go b/seaweed-block/core/ops/volume_status_summary.go index eb35d78068..8f565ce58e 100644 --- a/seaweed-block/core/ops/volume_status_summary.go +++ b/seaweed-block/core/ops/volume_status_summary.go @@ -156,7 +156,11 @@ func VolumeStatusReportIssues(r VolumeStatusReport) []string { issues = append(issues, fmt.Sprintf("durable %s/%s latched=false", d.VolumeID, d.ReplicaID)) } if !d.Operational { - issues = append(issues, fmt.Sprintf("durable %s/%s operational=false", d.VolumeID, d.ReplicaID)) + issue := fmt.Sprintf("durable %s/%s operational=false", d.VolumeID, d.ReplicaID) + if d.Evidence != "" { + issue += " evidence=" + d.Evidence + } + issues = append(issues, issue) } if d.Closed { issues = append(issues, fmt.Sprintf("durable %s/%s closed=true", d.VolumeID, d.ReplicaID)) diff --git a/seaweed-block/core/storage/recovery_contract.go b/seaweed-block/core/storage/recovery_contract.go index b6ea0fec0d..09909ce967 100644 --- a/seaweed-block/core/storage/recovery_contract.go +++ b/seaweed-block/core/storage/recovery_contract.go @@ -56,6 +56,12 @@ const ( // G-1 §3 row #8 placement decision §4.3). var ErrWALRecycled = errors.New("storage: WAL recycled past requested LSN") +// ErrWALIntegrityFault is returned when recovery detects that WAL metadata and +// durable extent contents disagree. Callers MUST NOT treat this as a clean +// torn-tail skip because doing so can claim readiness after a committed record +// was detected as corrupt. +var ErrWALIntegrityFault = errors.New("storage: WAL integrity fault") + // RecoveryEntry is one entry emitted by `LogicalStorage.ScanLBAs`. // Carries enough information for the catch-up sender to write a // wire frame to the replica. @@ -110,6 +116,12 @@ const ( // StorageRecoveryFailureSubstrateIO — substrate IO error // (read failure, decode failure mid-scan, etc.). Retryable. StorageRecoveryFailureSubstrateIO + + // StorageRecoveryFailureWALIntegrity — recovery detected that WAL + // metadata and durable extent contents disagree. Not a clean + // readiness path; surface as an integrity blocker until repaired or + // rebuilt. + StorageRecoveryFailureWALIntegrity ) // String returns the human-readable kind name for diagnostics. NOT @@ -120,6 +132,8 @@ func (k StorageRecoveryFailureKind) String() string { return "WALRecycled" case StorageRecoveryFailureSubstrateIO: return "SubstrateIO" + case StorageRecoveryFailureWALIntegrity: + return "WALIntegrity" default: return "Unknown" } @@ -178,6 +192,20 @@ func NewSubstrateIOFailure(cause error, detail string) *RecoveryFailure { } } +// NewWALIntegrityFailure wraps a recovery-time WAL/extent integrity mismatch in +// the typed envelope. Substrates call this when recovery detects corruption and +// must fail closed instead of claiming a clean frontier. +func NewWALIntegrityFailure(cause error, detail string) *RecoveryFailure { + if cause == nil { + cause = ErrWALIntegrityFault + } + return &RecoveryFailure{ + Kind: StorageRecoveryFailureWALIntegrity, + Cause: cause, + Detail: detail, + } +} + // --- T4d-1 Option C hybrid: per-LBA applied-LSN exposure --- // --- G7-redo priority 2.5: WAL recycle gate via pin floor --- diff --git a/seaweed-block/core/storage/smartwal/layout.go b/seaweed-block/core/storage/smartwal/layout.go new file mode 100644 index 0000000000..b605ffe861 --- /dev/null +++ b/seaweed-block/core/storage/smartwal/layout.go @@ -0,0 +1,161 @@ +package smartwal + +import ( + "encoding/hex" + "fmt" + "io" + "os" + "sort" +) + +// Layout describes the on-disk SmartWAL geometry parsed from the file header. +// It is intentionally read-only; fault injection must use these offsets instead +// of legacy WALStore constants. +type Layout struct { + HeaderSize int64 + RecordSize int64 + WALOffset int64 + WALLength int64 + WALEnd int64 + ExtentStart int64 + ExtentBytes int64 + FileSize int64 + + BlockSize uint32 + NumBlocks uint32 + WALSlots uint64 + ImplKind uint8 + ImplVersion uint32 +} + +// RecordInfo describes one valid record currently present in the SmartWAL ring. +type RecordInfo struct { + Slot uint64 + Offset int64 + LSN uint64 + LBA uint32 + Flags uint8 + DataCRC32 uint32 + BytesHex string +} + +// InspectLayout opens path read-only and returns the SmartWAL layout described +// by its header. It fails closed for non-SmartWAL files or truncated files. +func InspectLayout(path string) (Layout, error) { + f, err := os.Open(path) + if err != nil { + return Layout{}, fmt.Errorf("smartwal: inspect open %s: %w", path, err) + } + defer f.Close() + + hdr, err := readHeader(f) + if err != nil { + return Layout{}, err + } + if err := hdr.validate(); err != nil { + return Layout{}, err + } + st, err := f.Stat() + if err != nil { + return Layout{}, fmt.Errorf("smartwal: inspect stat %s: %w", path, err) + } + + walOffset := int64(headerSize) + walLength := int64(hdr.WALSlots) * int64(recordSize) + extentStart := walOffset + walLength + extentBytes := int64(hdr.NumBlocks) * int64(hdr.BlockSize) + required := extentStart + extentBytes + if st.Size() < required { + return Layout{}, fmt.Errorf("smartwal: truncated file: size=%d required=%d", st.Size(), required) + } + + return Layout{ + HeaderSize: int64(headerSize), + RecordSize: int64(recordSize), + WALOffset: walOffset, + WALLength: walLength, + WALEnd: walOffset + walLength, + ExtentStart: extentStart, + ExtentBytes: extentBytes, + FileSize: st.Size(), + BlockSize: hdr.BlockSize, + NumBlocks: hdr.NumBlocks, + WALSlots: hdr.WALSlots, + ImplKind: hdr.ImplKind, + ImplVersion: hdr.ImplVersion, + }, nil +} + +// RecordOffset returns the absolute file offset for the slot used by lsn. +func (l Layout) RecordOffset(lsn uint64) (int64, error) { + if l.WALSlots == 0 || l.RecordSize == 0 { + return 0, fmt.Errorf("smartwal: invalid layout: WALSlots=%d RecordSize=%d", l.WALSlots, l.RecordSize) + } + slot := lsn % l.WALSlots + return l.WALOffset + int64(slot)*l.RecordSize, nil +} + +// ContainsWALOffset reports whether off lands inside the SmartWAL ring. +func (l Layout) ContainsWALOffset(off int64) bool { + return off >= l.WALOffset && off < l.WALEnd +} + +// ContainsExtentOffset reports whether off lands inside the extent region. +func (l Layout) ContainsExtentOffset(off int64) bool { + return off >= l.ExtentStart && off < l.ExtentStart+l.ExtentBytes +} + +// InspectRecords returns all valid records found in the SmartWAL ring, sorted +// by LSN ascending. Torn/empty records are intentionally omitted; corruption +// tools use this to pick a real record before mutating it. +func InspectRecords(path string) (Layout, []RecordInfo, error) { + layout, err := InspectLayout(path) + if err != nil { + return Layout{}, nil, err + } + f, err := os.Open(path) + if err != nil { + return Layout{}, nil, fmt.Errorf("smartwal: inspect records open %s: %w", path, err) + } + defer f.Close() + + buf := make([]byte, layout.RecordSize) + records := make([]RecordInfo, 0) + for slot := uint64(0); slot < layout.WALSlots; slot++ { + offset := layout.WALOffset + int64(slot)*layout.RecordSize + if _, err := f.ReadAt(buf, offset); err != nil && err != io.EOF { + return Layout{}, nil, fmt.Errorf("smartwal: inspect records read slot %d: %w", slot, err) + } + rec, ok := decode(buf) + if !ok { + continue + } + raw := make([]byte, len(buf)) + copy(raw, buf) + records = append(records, RecordInfo{ + Slot: slot, + Offset: offset, + LSN: rec.LSN, + LBA: rec.LBA, + Flags: rec.Flags, + DataCRC32: rec.DataCRC32, + BytesHex: hex.EncodeToString(raw), + }) + } + sort.Slice(records, func(i, j int) bool { + return records[i].LSN < records[j].LSN + }) + return layout, records, nil +} + +// LatestRecord returns the highest-LSN valid record in the SmartWAL ring. +func LatestRecord(path string) (Layout, RecordInfo, error) { + layout, records, err := InspectRecords(path) + if err != nil { + return Layout{}, RecordInfo{}, err + } + if len(records) == 0 { + return Layout{}, RecordInfo{}, fmt.Errorf("smartwal: no valid records in WAL ring") + } + return layout, records[len(records)-1], nil +} diff --git a/seaweed-block/core/storage/smartwal/layout_test.go b/seaweed-block/core/storage/smartwal/layout_test.go new file mode 100644 index 0000000000..e54f0ac186 --- /dev/null +++ b/seaweed-block/core/storage/smartwal/layout_test.go @@ -0,0 +1,140 @@ +package smartwal + +import ( + "os" + "path/filepath" + "testing" +) + +func TestInspectLayoutReadsSmartWALGeometry(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "store.sw") + s, err := CreateStoreWithSlots(path, 4, 4096, 8) + if err != nil { + t.Fatalf("CreateStoreWithSlots: %v", err) + } + if err := s.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + + layout, err := InspectLayout(path) + if err != nil { + t.Fatalf("InspectLayout: %v", err) + } + + if layout.HeaderSize != 4096 { + t.Fatalf("HeaderSize=%d want 4096", layout.HeaderSize) + } + if layout.RecordSize != 32 { + t.Fatalf("RecordSize=%d want 32", layout.RecordSize) + } + if layout.WALOffset != 4096 { + t.Fatalf("WALOffset=%d want 4096", layout.WALOffset) + } + if layout.WALLength != 8*32 { + t.Fatalf("WALLength=%d want %d", layout.WALLength, 8*32) + } + if layout.ExtentStart != 4096+8*32 { + t.Fatalf("ExtentStart=%d want %d", layout.ExtentStart, 4096+8*32) + } + if layout.ExtentBytes != 4*4096 { + t.Fatalf("ExtentBytes=%d want %d", layout.ExtentBytes, 4*4096) + } + if layout.FileSize != layout.ExtentStart+layout.ExtentBytes { + t.Fatalf("FileSize=%d want %d", layout.FileSize, layout.ExtentStart+layout.ExtentBytes) + } + + off, err := layout.RecordOffset(9) + if err != nil { + t.Fatalf("RecordOffset: %v", err) + } + // slot = 9 % 8 = 1 + if off != layout.WALOffset+layout.RecordSize { + t.Fatalf("RecordOffset(9)=%d want %d", off, layout.WALOffset+layout.RecordSize) + } + if !layout.ContainsWALOffset(off) { + t.Fatalf("record offset %d should be inside WAL ring", off) + } + if !layout.ContainsExtentOffset(layout.ExtentStart) { + t.Fatalf("extent start should be inside extent") + } +} + +func TestInspectLayoutRejectsNonSmartWAL(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "not-smartwal.bin") + if err := os.WriteFile(path, []byte("not a smartwal file"), 0o644); err != nil { + t.Fatalf("WriteFile: %v", err) + } + if _, err := InspectLayout(path); err == nil { + t.Fatal("InspectLayout should reject non-SmartWAL files") + } +} + +func TestInspectLayoutRejectsTruncatedFile(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "store.sw") + s, err := CreateStoreWithSlots(path, 4, 4096, 8) + if err != nil { + t.Fatalf("CreateStoreWithSlots: %v", err) + } + if err := s.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + if err := os.Truncate(path, 4096+8*32+1); err != nil { + t.Fatalf("Truncate: %v", err) + } + if _, err := InspectLayout(path); err == nil { + t.Fatal("InspectLayout should reject truncated SmartWAL files") + } +} + +func TestInspectRecordsFindsLatestValidRecord(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "store.sw") + s, err := CreateStoreWithSlots(path, 8, 4096, 8) + if err != nil { + t.Fatalf("CreateStoreWithSlots: %v", err) + } + for i := uint32(0); i < 3; i++ { + data := make([]byte, 4096) + data[0] = byte(i + 1) + if _, err := s.Write(i, data); err != nil { + t.Fatalf("Write: %v", err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatalf("Sync: %v", err) + } + if err := s.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + + layout, records, err := InspectRecords(path) + if err != nil { + t.Fatalf("InspectRecords: %v", err) + } + if len(records) != 3 { + t.Fatalf("records=%d want 3", len(records)) + } + for i, rec := range records { + wantLSN := uint64(i + 1) + if rec.LSN != wantLSN { + t.Fatalf("record[%d].LSN=%d want %d", i, rec.LSN, wantLSN) + } + if !layout.ContainsWALOffset(rec.Offset) { + t.Fatalf("record[%d] offset %d should be inside WAL", i, rec.Offset) + } + if rec.BytesHex == "" { + t.Fatalf("record[%d] missing byte sample", i) + } + } + + _, latest, err := LatestRecord(path) + if err != nil { + t.Fatalf("LatestRecord: %v", err) + } + if latest.LSN != 3 || latest.LBA != 2 { + t.Fatalf("latest=%+v want LSN=3 LBA=2", latest) + } +} diff --git a/seaweed-block/core/storage/smartwal/recovery.go b/seaweed-block/core/storage/smartwal/recovery.go index a8d11e3b47..8558abb010 100644 --- a/seaweed-block/core/storage/smartwal/recovery.go +++ b/seaweed-block/core/storage/smartwal/recovery.go @@ -5,6 +5,8 @@ import ( "hash/crc32" "log" "os" + + "github.com/seaweedfs/seaweed-block/core/storage" ) // runRecovery rebuilds the LSN frontier from a smartwal store's ring @@ -18,16 +20,13 @@ import ( // 2. Build a map LBA → highest-LSN record. Older records for the // same LBA are dominated and ignored. // 3. For each surviving record: -// - Trim record: counts as recovered (its CRC32 covers a zero -// block; if the extent matches that, the trim is durable). -// - Write record: read the extent block, compute its CRC32, -// compare to record.DataCRC32. If they match, the write is -// durable and counts toward the recovered frontier. If they -// do NOT match, this is a torn pre-Sync write — skip the -// record so the LBA reads as whatever the extent currently -// holds (which is either the pre-write bytes, if the rollback -// path ran, or torn bytes if it didn't; either way the -// metadata no longer claims authority over them). +// - Trim record: counts as recovered (its CRC32 covers a zero +// block; if the extent matches that, the trim is durable). +// - Write record: read the extent block, compute its CRC32, +// compare to record.DataCRC32. If they match, the write is +// durable and counts toward the recovered frontier. If they +// do NOT match, fail closed with a WAL integrity error so the +// volume cannot report Ready=True after detecting corruption. // 4. The recovered frontier is the highest LSN among VALIDATED // records, not just the highest LSN seen in the ring. A record // whose CRC didn't verify cannot advance the frontier. @@ -56,7 +55,7 @@ func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64, } } - var recovered, torn int + var recovered int var highestVerifiedLSN uint64 for _, rec := range lastWrite { if rec.Flags&flagTrim != 0 { @@ -69,10 +68,9 @@ func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64, return 0, fmt.Errorf("smartwal: recovery read trim LBA %d: %w", rec.LBA, err) } if crc32.ChecksumIEEE(data) != rec.DataCRC32 { - log.Printf("smartwal: recovery trim CRC mismatch LSN=%d LBA=%d — skipping", - rec.LSN, rec.LBA) - torn++ - continue + detail := fmt.Sprintf("trim CRC mismatch LSN=%d LBA=%d", rec.LSN, rec.LBA) + log.Printf("smartwal: recovery %s — failing closed", detail) + return 0, storage.NewWALIntegrityFailure(nil, detail) } recovered++ if rec.LSN > highestVerifiedLSN { @@ -88,10 +86,10 @@ func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64, } actual := crc32.ChecksumIEEE(data) if actual != rec.DataCRC32 { - log.Printf("smartwal: recovery CRC mismatch LSN=%d LBA=%d expected=%08x actual=%08x — skipping", + detail := fmt.Sprintf("CRC mismatch LSN=%d LBA=%d expected=%08x actual=%08x", rec.LSN, rec.LBA, rec.DataCRC32, actual) - torn++ - continue + log.Printf("smartwal: recovery %s — failing closed", detail) + return 0, storage.NewWALIntegrityFailure(nil, detail) } recovered++ if rec.LSN > highestVerifiedLSN { @@ -99,7 +97,7 @@ func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64, } } - log.Printf("smartwal: recovery: %d LBAs verified, %d torn, frontier=%d", - recovered, torn, highestVerifiedLSN) + log.Printf("smartwal: recovery: %d LBAs verified, frontier=%d", + recovered, highestVerifiedLSN) return highestVerifiedLSN, nil } diff --git a/seaweed-block/core/storage/smartwal/smartwal_typed_failure_test.go b/seaweed-block/core/storage/smartwal/smartwal_typed_failure_test.go index cf6acff481..5043a34fe5 100644 --- a/seaweed-block/core/storage/smartwal/smartwal_typed_failure_test.go +++ b/seaweed-block/core/storage/smartwal/smartwal_typed_failure_test.go @@ -2,6 +2,7 @@ package smartwal import ( "errors" + "os" "path/filepath" "testing" @@ -50,6 +51,65 @@ func TestStorageRecoveryFailureKind_Smartwal_RecycleWrappedAsKind(t *testing.T) } } +func TestStorageRecoveryFailureKind_Smartwal_CRCMismatchWrappedAsWALIntegrity(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "smartwal-integrity.sw") + s, err := CreateStore(path, 16, 4096) + if err != nil { + t.Fatalf("CreateStore: %v", err) + } + for i := uint32(0); i < 3; i++ { + data := make([]byte, 4096) + data[0] = byte(0xA0 + i) + if _, werr := s.Write(i, data); werr != nil { + t.Fatal(werr) + } + } + if _, err := s.Sync(); err != nil { + t.Fatalf("Sync: %v", err) + } + if err := s.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + + layout, rec, err := LatestRecord(path) + if err != nil { + t.Fatalf("LatestRecord: %v", err) + } + extentOffset := layout.ExtentStart + int64(rec.LBA)*int64(layout.BlockSize) + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatalf("OpenFile: %v", err) + } + if _, err := f.WriteAt([]byte{0x5A}, extentOffset); err != nil { + _ = f.Close() + t.Fatalf("corrupt extent: %v", err) + } + if err := f.Close(); err != nil { + t.Fatalf("close corrupted file: %v", err) + } + + reopened, err := OpenStore(path) + if err != nil { + t.Fatalf("OpenStore: %v", err) + } + defer reopened.Close() + _, recoverErr := reopened.Recover() + if recoverErr == nil { + t.Fatal("expected WAL integrity failure after extent/WAL CRC mismatch") + } + if !errors.Is(recoverErr, storage.ErrWALIntegrityFault) { + t.Fatalf("Recover error must satisfy errors.Is(_, ErrWALIntegrityFault); got: %v", recoverErr) + } + var rf *storage.RecoveryFailure + if !errors.As(recoverErr, &rf) { + t.Fatalf("Recover error must be *storage.RecoveryFailure via errors.As; got: %v", recoverErr) + } + if rf.Kind != storage.StorageRecoveryFailureWALIntegrity { + t.Fatalf("Kind = %v, want StorageRecoveryFailureWALIntegrity", rf.Kind) + } +} + // TestSmartwal_AppliedLSNs_ReportsRingEntries pins smartwal's // AppliedLSNs (ring-based reduction). func TestSmartwal_AppliedLSNs_ReportsRingEntries(t *testing.T) { diff --git a/seaweed-block/deploy/k8s/g15b/Dockerfile.sw-block b/seaweed-block/deploy/k8s/g15b/Dockerfile.sw-block index b9ecfca464..690b14f3b3 100644 --- a/seaweed-block/deploy/k8s/g15b/Dockerfile.sw-block +++ b/seaweed-block/deploy/k8s/g15b/Dockerfile.sw-block @@ -5,11 +5,13 @@ COPY go.mod go.sum ./ RUN go mod download COPY . . RUN CGO_ENABLED=0 go build -o /out/blockmaster ./cmd/blockmaster && \ - CGO_ENABLED=0 go build -o /out/blockvolume ./cmd/blockvolume + CGO_ENABLED=0 go build -o /out/blockvolume ./cmd/blockvolume && \ + CGO_ENABLED=0 go build -o /out/sw-block ./cmd/sw-block FROM debian:bookworm-slim COPY --from=build /out/blockmaster /usr/local/bin/blockmaster COPY --from=build /out/blockvolume /usr/local/bin/blockvolume +COPY --from=build /out/sw-block /usr/local/bin/sw-block USER 65532:65532 diff --git a/seaweed-block/docs/quickstart-kubernetes.md b/seaweed-block/docs/quickstart-kubernetes.md index 3b44b6b725..b33ed3b4a6 100644 --- a/seaweed-block/docs/quickstart-kubernetes.md +++ b/seaweed-block/docs/quickstart-kubernetes.md @@ -31,11 +31,16 @@ The quickstart proves: read-only dashboard are available. - The report/dashboard include `operator-snapshot.json`, a read-only operator-facing status projection. It is not a mutating operator. +- The gated operator-status path can publish the same read-only vocabulary into + `SwBlockCluster` / `SwBlockVolume` `.status` and Kubernetes Events. It is + status/events only and does not create CR objects or mutate storage. - The example resources and host-side residue are cleaned up. It does not prove production HA, backup/restore, broad upgrade safety, broad -platform compatibility, mutating operator lifecycle, mutating admin workflows, -or production UI. +platform compatibility, broad mutating operator lifecycle, mutating admin +workflows, or production UI. The separate v0.5 beta-candidate lifecycle-owner +path is limited to the Seaweed Block `SwBlockVolume` protection finalizer and +requires matching release images. ## Prerequisites @@ -85,8 +90,8 @@ From the repository root: export KUBECONFIG="${KUBECONFIG:-/etc/rancher/k3s/k3s.yaml}" sw-block ops generate-helm-values \ --out values.day1.yaml \ - --image ghcr.io/seaweedfs/seaweed-block:sha-6260e46fd3be \ - --csi-image ghcr.io/seaweedfs/seaweed-block-csi:sha-6260e46fd3be + --image ghcr.io/seaweedfs/seaweed-block:sha-dc2972d0059b \ + --csi-image ghcr.io/seaweedfs/seaweed-block-csi:sha-dc2972d0059b ``` The `KUBECONFIG` fallback above is the common k3s path. Non-k3s users should @@ -134,18 +139,23 @@ sw-block ops generate-helm-values \ --csi-image ghcr.io/seaweedfs/seaweed-block-csi:sha- ``` -Current validated alpha image tag: -`sha-6260e46fd3be`. +Current validated published quickstart image tag: +`sha-dc2972d0059b`. + +This tag covers the v0.4 read-only/status foundation path. The v0.5 +bounded lifecycle-owner path requires matching `sw-block` and `sw-block-csi` +images published from the Phase 44 release commit; do not use the older +quickstart tag to validate lifecycle-owner behavior. Published image digests: ```text seaweed-block - index: sha256:ef9c60f82c36f22360b10faafd32caf807f98ac0ea86c0365c0d0836e5f67110 - linux/amd64: sha256:36481cbc1fc98fafdfa386823e0e5906785cb6f35748ef698ff1cec39bb40464 + index: sha256:b8da5ca4e2bbe2f0f630fee0468790c444362615d68807a1be31fd237c84928f + linux/amd64: sha256:677f6321ea5199b14792345b8691358860bb9ca7376f4e4a2f3a7c0113d5db9b seaweed-block-csi - index: sha256:b160ceee874dc6743074ef6b6735ccf05914c1de5951972922f6d3779bc73592 - linux/amd64: sha256:82e41b7ef92ad8db38b6927e334cc1d564b1012ad916e9bde2e882cece680be8 + index: sha256:b5942cd68d28aecdfebec1f1e5ec55a9cafe746169fee3b6c35916c93fffcaa6 + linux/amd64: sha256:1fc636a4e0e63cc8cbee39e6775053c5d1aba7213ca9182a084e1bb6fe71474c ``` Mutable `:alpha` is a smoke/demo tag only. Do not use it as release evidence diff --git a/seaweed-block/docs/releases/README.md b/seaweed-block/docs/releases/README.md index dd95094011..d764707305 100644 --- a/seaweed-block/docs/releases/README.md +++ b/seaweed-block/docs/releases/README.md @@ -11,6 +11,10 @@ is still outside the supported boundary. - [v0.3.2 Alpha — Multi-Volume HA Independence](v0.3.2-alpha.md) - [v0.3.3 Alpha — Productized Operations And Read-Only Operator Foundation](v0.3.3-alpha.md) - [v0.3.4 Alpha — Status Surface Hardening And Strict New-User Path](v0.3.4-alpha.md) +- [v0.3.5 Alpha — Failure-Path Evidence And Cleanup Hardening](v0.3.5-alpha.md) +- [v0.3.6 Alpha — Test Realism And Dirty-Failure Hardening](v0.3.6-alpha.md) +- [v0.4 Beta — Kubernetes-Native Read-Only Operator Foundation](v0.4-beta-candidate.md) +- [v0.5 Beta Candidate — Bounded SwBlockVolume Lifecycle Owner](v0.5-beta-candidate.md) ## Version Boundary @@ -39,8 +43,27 @@ is still outside the supported boundary. happy/blocked/restart/multi-volume/stale-evidence surfaces agree, support bundle replay prefers the freshest evidence, and the documented cleanup path scrubs iSCSI node DB residue. +- `v0.3.5-alpha` hardens failure-path evidence and cleanup confidence: + blocked CSI image-pull evidence, status endpoint unreachable replay, corrupt + evidence replay, support-bundle/failure-snapshot diagnostics, and cleanup + residue gates all follow the negative-first rule. +- `v0.3.6-alpha` hardens test realism and dirty-failure behavior: + live status endpoint unreachable, restart convergence, and real V3 SmartWAL + corruption gates prove no false `Ready=True` is projected from weak or dirty + evidence. +- `v0.4-beta` adds a Kubernetes-native read-only status foundation and + actionability layer: `SwBlockCluster` and `SwBlockVolume` CRDs, status-only + reconciliation, Conditions, Events, node readiness, support evidence refs, + cleanup/delete-safety visibility, install drift visibility, safe next-step + hints, cross-surface agreement, CRD/RBAC conformance gates, and read-only RBAC + proof. It is not a mutating operator lifecycle. +- `v0.5-beta-candidate` adds the first bounded mutating lifecycle-owner: + CSI-created `SwBlockVolume` identity CRs, a Seaweed Block protection + finalizer, admission-confined finalizer add/release, evidence-driven + delete-safety hold/release, multi-volume isolation, and zero-residue close + gates. It does not execute cleanup or own PVC/PV/workload deletion. -Mutating operator packaging is not included in these alphas. v0.3 introduces -Helm as the preferred Kubernetes alpha install path; the script path remains -available for development and fallback validation. The first operator-facing -surface is read-only/status-first. +v0.3 introduces Helm as the preferred Kubernetes alpha install path; the script +path remains available for development and fallback validation. v0.4 is the +read-only/status-first operator surface. v0.5 beta candidate adds only a bounded +`SwBlockVolume` protection-finalizer lifecycle, not broad operator automation. diff --git a/seaweed-block/docs/releases/v0.3.5-alpha.md b/seaweed-block/docs/releases/v0.3.5-alpha.md new file mode 100644 index 0000000000..ebca4ef3dd --- /dev/null +++ b/seaweed-block/docs/releases/v0.3.5-alpha.md @@ -0,0 +1,84 @@ +# v0.3.5 Alpha - Failure-Path Evidence And Cleanup Hardening + +Status: alpha release note for Phase 33 TestOps failure hardening. + +## Summary + +Seaweed Block v0.3.5 alpha hardens the existing Helm/PVC/read-only-ops alpha +loop when things fail: + +```text +blocked or unreachable evidence +-> no false Ready=True +-> stable reason code +-> cold-readable support evidence +-> deterministic cleanup +``` + +This is not a new storage feature release. It is a release-confidence pass over +negative status, support bundles, replay, and cleanup. + +## User-Visible Improvements + +- Support bundles distinguish required captures from optional diagnostics. + Expected empty states such as no active iSCSI session no longer make a bundle + look failed. +- Failure snapshots use the same rule for previous logs, iSCSI state, + multipath/dmsetup, and kubelet mount diagnostics. +- Status endpoint unreachable evidence is rendered as + `Ready=Unknown reason=status_endpoint_unreachable`, not `Ready=True`. +- Bundle replay skips corrupt evidence candidates and uses the newest valid + snapshot. +- Cleanup residue reporting keeps stable counters for Kubernetes, iSCSI + sessions, iSCSI node DB, multipath, dmsetup, product processes, and hostPath + residue. + +## Validated Evidence + +| Scenario | Run | Result | +|---|---:|---| +| CSI image-pull blocked path + support bundle | `20260528-190738-51a2` | PASS, 49/49 | +| Status endpoint unreachable replay | `20260529-155016-e9a5` | PASS, 17/17 | +| Cleanup residue gate | `20260529-155040-4519` | PASS, 13/13 | +| Minimal Helm first-volume regression | `20260529-155216-0d9d` | PASS, 34/34 | + +Scoped tests: + +```text +go test ./scripts ./core/ops ./cmd/sw-block +``` + +## Current Claim + +Seaweed Block v0.3.5 alpha may claim: + +- The Helm/PVC/read-only-ops alpha path still passes after failure-hardening + changes. +- A CSI image-pull blocked path surfaces stable + `reason=csi_node_image_pull_failed` and does not report false readiness. +- Status endpoint unreachable replay surfaces + `reason=status_endpoint_unreachable` and `Ready=Unknown`. +- Support bundles and failure snapshots are cold-readable and read-only. +- Cleanup verification reports zero residue across the existing residue + dimensions after gated scenarios. + +## Explicit Non-Claims + +- Not production-ready. +- No new HA behavior. +- No production Kubernetes operator or controller-manager lifecycle. +- No mutating admin/operator/dashboard actions. +- No promote, repair, rebuild, failback, delete, backup, restore, or cleanup + mutation through UI/API/operator. +- No backup/snapshot/restore workflow. +- No returned-replica rebuild or automated failback. +- No transparent Kubernetes node-loss failover without pod recreate. +- No NVMe ANA parity expansion. +- No broad distro/kernel/initiator compatibility matrix. +- No performance, RTO, RPO, or SLO claim. + +## Image Guidance + +Use the immutable image tag published for the release commit once the release is +cut. Mutable `:alpha` remains a smoke/demo tag only and should not be used as +release evidence. diff --git a/seaweed-block/docs/releases/v0.3.6-alpha.md b/seaweed-block/docs/releases/v0.3.6-alpha.md new file mode 100644 index 0000000000..cb73339b0a --- /dev/null +++ b/seaweed-block/docs/releases/v0.3.6-alpha.md @@ -0,0 +1,76 @@ +# v0.3.6 Alpha - Test Realism And Dirty-Failure Hardening + +Status: alpha release note for Phase 34. + +## Summary + +Seaweed Block v0.3.6 alpha hardens the existing Helm/PVC/read-only-ops alpha +loop against false readiness from weak evidence: + +```text +unreachable status endpoint -> no false Ready=True +k3s restart -> transient Unknown allowed, final stable Ready required +SmartWAL corruption -> no false Ready=True +``` + +This is not a new storage feature release. It is a correctness and release-trust +pass over negative-first status behavior. + +## User-Visible Improvements + +- A status endpoint that cannot be reached is not allowed to become false + `Ready=True`. +- Restart status checks now require convergence to stable `Ready=True`; a + single flicker is not enough. +- Real SmartWAL corruption is injected into the V3 WAL region, not a legacy V2 + offset. +- SmartWAL corruption now fails closed through the product chain: + storage recovery fails closed, blockvolume withholds local readiness, and + master projection refuses Ready without positive primary readiness evidence. + +## Validated Evidence + +| Gate | Evidence | Result | +|---|---|---| +| Self-proof audit | `phase34-self-proof-audit.md` | PASS | +| Live status endpoint unreachable | `phase34-d2-live-status-endpoint-unreachable-signoff.md` | PASS | +| Restart convergence | `phase34-d3-restart-convergence-signoff.md` | PASS | +| SmartWAL dirty-failure | run `20260601-020747-5a1f` | PASS, 30/30 | + +Final Phase 34 close: + +- `internal/docs/finished-plans/phase34_finishedplan_test_realism_dirty_failure_hardening.md` + +## Current Claim + +Seaweed Block v0.3.6 alpha may claim: + +- Selected negative-path checks use live evidence instead of replay-only or + helper-summary-only proof. +- Status endpoint unreachable evidence does not produce false Ready. +- Restart evidence must converge to stable Ready before the surface claims + healthy. +- Real V3 SmartWAL corruption does not produce false Ready. +- `Ready=True` requires positive primary readiness evidence; heartbeat alone is + not enough. + +## Explicit Non-Claims + +- Not production-ready. +- No new HA behavior. +- No production Kubernetes operator or controller-manager lifecycle. +- No mutating admin/operator/dashboard actions. +- No promote, repair, rebuild, failback, delete, backup, restore, or cleanup + mutation through UI/API/operator. +- No backup/snapshot/restore workflow. +- No returned-replica rebuild or automated failback. +- No NVMe ANA parity expansion. +- No broad chaos matrix. +- No performance, RTO, RPO, or SLO claim. + +## Known Follow-Up + +SmartWAL corruption currently surfaces as non-ready generic `unknown` in the +operator snapshot/report. A future hardening slice should surface the specific +`reason=wal_integrity_fault` so cold operators do not need blockvolume logs to +understand the failure cause. diff --git a/seaweed-block/docs/releases/v0.4-beta-candidate.md b/seaweed-block/docs/releases/v0.4-beta-candidate.md new file mode 100644 index 0000000000..f0d604b60e --- /dev/null +++ b/seaweed-block/docs/releases/v0.4-beta-candidate.md @@ -0,0 +1,169 @@ +# v0.4 Beta - Kubernetes-Native Read-Only Operator Foundation + +Status: release-clear beta note for Phases 35-40. QA D6 passed on +2026-06-14 against the published `sha-dc2972d0059b` images. + +## Summary + +Seaweed Block v0.4 beta adds Kubernetes-native read-only visibility +and actionable status on top of the Helm/PVC/read-only-ops path: + +```text +SwBlockCluster CRD +SwBlockVolume CRD +status-only operator-status controller +Kubernetes Conditions +Kubernetes Events +node readiness status +support evidence refs +cleanup visibility +delete-safety visibility +install drift visibility +safe next-step hints +status/events-only RBAC +CRD/RBAC conformance gate +``` + +This is the first operator foundation slice plus its read-only actionability +layer. It is not the full operator lifecycle and it does not add mutating admin +actions. + +## User-Visible Improvements + +- `SwBlockCluster` and `SwBlockVolume` CRDs provide normal Kubernetes objects + for status inspection. +- The operator-status controller can publish existing ManagedVolume facts into + CRD `.status`. +- `Ready`, `Blocked`, `Recovered`, `Recovering`, `CleanupRequired`, and + `EvidenceStale` are part of the Kubernetes Condition vocabulary. +- Known blocked states such as `csi_node_image_pull_failed` publish + `Ready=False` and `Blocked=True`, not false readiness. +- Stale or unreachable evidence publishes `Ready=Unknown` and + `EvidenceStale=True`, not an inappropriate hard block. +- SmartWAL integrity faults publish non-ready status with + `reason=wal_integrity_fault`. +- Kubernetes Events are emitted with stable object/type/reason identity so a + persistent condition does not create an unbounded stream of new Event objects. +- `SwBlockCluster.status.nodes[]` exposes Kubernetes node readiness and + Seaweed Block node-preflight judgments where evidence is available. +- Blocked or unknown status can point to support-bundle evidence refs and safe + read-only/scripted next steps. +- Cleanup verifier evidence projects `CleanupRequired=True|False`, residue + counters, and safe scripted verification hints without performing cleanup. +- Delete-safety evidence projects blocked/releasable status and safe scripted + verification hints without adding or removing finalizers. +- Install drift evidence reports current versus desired chart/app/image identity + without running upgrade or rollback commands. +- CRD/RBAC status-writer conformance coverage catches casing drift, enum drift, + wrong endpoint usage, and RBAC boundary broadening before release QA. +- CRD status, Events, report, dashboard, operator-snapshot, and `ops explain` + agree across healthy, blocked, stale, cleanup-required, and multi-volume + paths. +- The operator-status ServiceAccount is constrained to CRD read, CRD `/status` + write, and Event create. + +## Validated Evidence + +| Gate | Evidence | Result | +|---|---|---| +| D1 CRD/RBAC contract | `phase35-d1-operator-crd-qa-signoff.md` | PASS | +| D2 dry-run packaged controller | `phase35-d2-operator-status-qa-signoff.md` | PASS | +| D3 happy-path status writer | `phase35-d3-operator-status-writer-qa-signoff.md` | PASS | +| D4 blocked status + Events | `phase35-d4-operator-status-events-qa-signoff.md` | PASS | +| D5 stale/unreachable projections | `phase35-d5-stale-status-projections-qa-signoff.md` | PASS | +| D6 stable Event identity | `phase35-d6-stable-event-identity-qa-signoff.md` | PASS | +| D7 read-only boundary | `phase35-d7-read-only-boundary-qa-signoff.md` | PASS | +| Phase 36 D2 node readiness | `phase36-d2-node-readiness-qa-signoff.md` | PASS | +| Phase 36 D3 support evidence refs | `phase36-d3-support-evidence-qa-signoff.md` | PASS | +| Phase 36 D4 cleanup visibility | `phase36-d4-cleanup-visibility-qa-signoff.md` | PASS | +| Phase 36 D5 surface agreement | `phase36-d5-surface-agreement-qa-signoff.md` | PASS | +| Phase 37 D2 live node/CSI evidence | `phase37-d2-live-node-csi-evidence-qa-signoff.md` | PASS | +| Phase 37 D3 CSI image-pull node blockers | `phase37-d3-csi-image-pull-node-blockers-qa-signoff.md` | PASS | +| Phase 37 D4/D5 host prereq + loopback blockers | `phase37-d4-d5-host-prereq-loopback-qa-signoff.md` | PASS | +| Phase 38 action-model executable contract | `phase38-action-model-executable-contract-qa-signoff.md` | PASS | +| Phase 39 D4/D5 delete-safety status | `phase39-d4-d5-finalizer-delete-safety-qa-signoff.md` | PASS | +| Phase 39 D6 multi-volume delete-safety isolation | `phase39-d6-multi-volume-delete-safety-status-isolation-qa-signoff.md` | PASS | +| Phase 40 D1-D6 operator production hardening | `current-plan.md`, `phase40-d4-status-api-conformance-qa.md`, `phase40-d6-release-candidate-qa.md`, `phase40-d6-release-candidate-qa-signoff.md` | PASS | + +Final Phase 35 close: + +- `internal/docs/finished-plans/phase35_finishedplan_kubernetes_native_read_only_operator_foundation.md` + +Final Phase 36 close: + +- `internal/docs/finished-plans/phase36_finishedplan_productized_operations_actionability.md` + +## Release Images + +Use immutable tags for release validation: + +```text +ghcr.io/seaweedfs/seaweed-block:sha-dc2972d0059b +ghcr.io/seaweedfs/seaweed-block-csi:sha-dc2972d0059b +``` + +Published digests: + +```text +seaweed-block + index: sha256:b8da5ca4e2bbe2f0f630fee0468790c444362615d68807a1be31fd237c84928f + linux/amd64: sha256:677f6321ea5199b14792345b8691358860bb9ca7376f4e4a2f3a7c0113d5db9b +seaweed-block-csi + index: sha256:b5942cd68d28aecdfebec1f1e5ec55a9cafe746169fee3b6c35916c93fffcaa6 + linux/amd64: sha256:1fc636a4e0e63cc8cbee39e6775053c5d1aba7213ca9182a084e1bb6fe71474c +``` + +Published by GitHub Actions run `27490827782` from commit +`dc2972d0059beffb2447ab8546ceb65e646a7b66`. + +## Current Claim + +Seaweed Block v0.4 beta may claim: + +- CRDs for `SwBlockCluster` and `SwBlockVolume` exist with status + subresources. +- The optional operator-status Deployment can publish read-only status into + existing CR objects. +- Kubernetes Conditions and Events mirror the existing `sw-block ops` + ManagedVolume vocabulary. +- Node readiness, support evidence references, cleanup visibility, and safe + next-step hints are visible through read-only status surfaces. +- Delete-safety status is visible as status-only evidence. The operator-status + controller does not add or remove finalizers. +- Install drift status is visible as current/desired chart, app, and image + identity. The operator-status controller does not execute upgrade or rollback. +- Negative-first behavior is preserved: + - blocked evidence becomes `Ready=False` / `Blocked=True`, + - stale or unreachable evidence becomes `Ready=Unknown` / + `EvidenceStale=True`, + - known WAL integrity faults never become `Ready=True`. +- The operator-status ServiceAccount cannot mutate storage, workloads, PVCs, + PVs, Secrets, StorageClasses, CRD spec, Helm releases, iSCSI sessions, + multipath maps, or hostPath data. + +## Explicit Non-Claims + +- Not production-ready. +- No mutating Kubernetes operator lifecycle. +- No automatic `SwBlockVolume` object creation or ownership. +- No finalizer ownership or finalizer add/remove. +- No delete execution. Delete-safety is status-only visibility. +- No automatic cleanup. +- No automatic support-bundle collection or upload. +- No promote, repair, rebuild, failback, delete, backup, restore, or cleanup + mutation through UI/API/operator. +- No upgrade execution. +- No backup/snapshot/restore workflow. +- No returned-replica rebuild or automated failback. +- No NVMe ANA parity expansion. +- No production hosted dashboard. +- No performance, RTO, RPO, or SLO claim. + +## Known Follow-Ups + +- Document loopback publish targets as single-node/local-consumer only. +- Keep cleanup verifier strict for force-delete residue such as stale iSCSI node + DB records. +- Add lifecycle ownership, finalizers, CR object creation, cleanup execution, + upgrade execution, repair, rebuild, failback, backup/restore, and NVMe ANA + parity only in later phases after the status/events-only release boundary. diff --git a/seaweed-block/docs/releases/v0.5-beta-candidate.md b/seaweed-block/docs/releases/v0.5-beta-candidate.md new file mode 100644 index 0000000000..15be07a88a --- /dev/null +++ b/seaweed-block/docs/releases/v0.5-beta-candidate.md @@ -0,0 +1,134 @@ +# v0.5 Beta Candidate - Bounded SwBlockVolume Lifecycle Owner + +Status: beta-candidate note for Phases 41-44. QA passed on 2026-06-17 +against fresh local candidate images through commit `041b084`. + +Release images: **pending publish**. Do not claim this release as shipped until +matching immutable `seaweed-block` and `seaweed-block-csi` image tags/digests +are published from the same commit and the release-candidate smoke is rerun. + +## Summary + +Seaweed Block v0.5 beta candidate adds a bounded Kubernetes lifecycle-owner on +top of the v0.4 status foundation: + +```text +SwBlockVolume identity CR created by CSI +protection finalizer added by lifecycle-owner +delete-safety status written by operator-status +cleanup-summary evidence consumed but not executed +unsafe delete evidence holds the finalizer +clean evidence releases only the protection finalizer +Kubernetes Events explain hold/release +report/dashboard/explain show the same delete-safety reasoning +multi-volume delete isolation +zero-residue uninstall verification +``` + +This is a narrow lifecycle release. It is not automatic cleanup, rebuild, +failback, backup/restore, upgrade execution, or a broad production operator. + +## User-Visible Improvements + +- A normal CSI `CreateVolume` path can create the matching `SwBlockVolume` CR + identity object when operator/lifecycle surfaces are enabled. +- The lifecycle-owner can add exactly the Seaweed Block protection finalizer: + `block.seaweedfs.com/swblockvolume-protection`. +- The lifecycle-owner can remove exactly that finalizer when delete-safety + status is releasable. +- Kubernetes ValidatingAdmissionPolicy confines lifecycle-owner main-object + patches to the Seaweed Block protection finalizer shape. +- operator-status remains status/events-only and does not patch finalizers. +- CSI owns `SwBlockVolume` metadata/spec identity and does not write status or + finalizers. +- Delete requests are held when cleanup evidence is missing, stale, or shows + residue. +- Clean fresh `cleanup-summary.txt` evidence can mark delete-safety + `allowed/releasable`, enabling finalizer release. +- CRD status and Events expose hold/release reasons. +- `sw-block ops report`, dashboard `/operator-snapshot.json`, and + `sw-block ops explain volume --cleanup-summary` can show deleting-volume + delete-safety reasoning. +- Multi-volume delete state is isolated: one held volume does not contaminate a + releasable or non-deleting volume. +- Final cleanup verifier remains the authority for zero-residue evidence. + +## Validated Evidence + +| Gate | Evidence | Result | +|---|---|---| +| Phase 41 lifecycle-owner foundation | `phase41_finishedplan_lifecycle_owner_foundation.md` | PASS | +| Phase 42 admission boundary + decision model | `phase42-d1-lifecycle-owner-admission-gate-qa-signoff.md`, `phase42-d5-d6-delete-safety-decision-qa-signoff.md` | PASS | +| Phase 43 bounded finalizer add/release | `phase43-d1-d2-lifecycle-owner-finalizer-add-qa-signoff.md`, `phase43-d3-d4-lifecycle-owner-finalizer-release-qa-signoff.md` | PASS | +| Phase 44 D2 integrated CR creation | `phase44-d2-integrated-swblockvolume-cr-qa-signoff.md` | PASS | +| Phase 44 D3/D4 hold/release close gate | `phase44-d3-d4-delete-lifecycle-close-gate-qa-signoff.md` | PASS | +| Phase 44 D5/D6 surfaces + isolation | `phase44-d5-d6-surface-isolation-close-qa-signoff.md` | PASS | + +Final Phase 44 close: + +- `internal/docs/finished-plans/phase44_finishedplan_delete_lifecycle_close_gate.md` + +## Release Images + +Pending. The release must publish both images together from the same source: + +```text +ghcr.io/seaweedfs/seaweed-block: +ghcr.io/seaweedfs/seaweed-block-csi: +``` + +Both images are required because this release includes: + +- `sw-block ops lifecycle-owner`, +- `sw-block ops operator-status --cleanup-summary`, +- `blockcsi --swblockvolume-cr-namespace`. + +## Current Claim + +Seaweed Block v0.5 beta candidate may claim: + +- A bounded `SwBlockVolume` protection-finalizer lifecycle is available behind + the lifecycle-owner chart gate. +- Normal PVC creation can create the `SwBlockVolume` CR identity object when the + operator/lifecycle surfaces are enabled. +- Delete-safety is evidence-driven: + - missing/stale cleanup evidence holds, + - residue evidence holds, + - clean fresh cleanup evidence releases. +- The lifecycle-owner mutates only the Seaweed Block protection finalizer, with + Kubernetes admission enforcing the boundary. +- operator-status stays status/events-only. +- CSI owns only the `SwBlockVolume` identity/spec path. +- CRD status, Events, report, dashboard, and explain surface the same + delete-safety reasoning on the validated paths. +- Multi-volume hold/release behavior is isolated. +- The documented cleanup verifier can prove zero residue after uninstall. + +## Explicit Non-Claims + +- Not production-ready. +- No automatic cleanup execution. +- No PVC/PV/workload deletion by operator-status or lifecycle-owner. +- No host repair, iSCSI repair, multipath repair, or hostPath repair. +- No promote, repair, rebuild, failback, backup, restore, or cleanup mutation + through UI/API/operator. +- No upgrade or rollback execution. +- No returned-replica rebuild or automated failback. +- No NVMe ANA parity expansion. +- No production hosted dashboard. +- No performance, RTO, RPO, or SLO claim. +- No broad distro/kernel/cluster compatibility claim. + +## Release Checklist + +Before marking v0.5 beta released: + +```text +[ ] publish matching sw-block and sw-block-csi immutable images +[ ] pin image tags/digests here and in README/quickstart if they are public +[ ] rerun release-candidate smoke on the pinned images +[ ] verify install -> first PVC -> protected CR -> delete hold/release -> + uninstall cleanup +[ ] keep release wording to bounded finalizer lifecycle and evidence-driven + hold/release only +``` diff --git a/seaweed-block/docs/roadmap.md b/seaweed-block/docs/roadmap.md index 0c214e8a6a..95998406ac 100644 --- a/seaweed-block/docs/roadmap.md +++ b/seaweed-block/docs/roadmap.md @@ -29,7 +29,8 @@ Current alpha constraints: - launcher-generated blockvolume state uses `emptyDir` - harness applies generated blockvolume manifests - generated blockvolume Deployments can use PVC owner references for cleanup -- no production operator yet +- no production operator yet; only the bounded v0.5 beta-candidate + lifecycle-owner mutates `SwBlockVolume.metadata.finalizers` ## Near-Term MVP Hardening @@ -50,14 +51,129 @@ Current alpha constraints: - do not jump directly from scripts to an operator - first stabilize install values, chart ownership, and uninstall behavior - - then add CRDs/Conditions/Events for cluster, node, volume, and lifecycle - state + - read-only CRDs, Conditions, Events, node readiness, support evidence refs, + cleanup visibility, and safe next-step status are now gated as the first + operator foundation + - mutating lifecycle ownership, finalizers, upgrade execution, repair, + rebuild, failback, and automatic cleanup remain separate future phases 4. Improve TestOps usability. - remote shell execution for K8s scenarios - stable result bundles - scenario registry index + - stronger negative-path gates for blocked, stale, unreachable, corrupt + evidence, and cleanup-residue cases + +## Current Capability Snapshot + +Seaweed Block can already demonstrate a narrow Kubernetes block-storage loop: + +- Helm install on supported lab clusters. +- Dynamic PVC provisioning through CSI. +- App pod mount, write, read, and replacement-reader verification. +- iSCSI frontend with gated ALUA/dm-multipath failover evidence. +- RF=3 multi-volume lab path with independent volume identity and publish + target. +- Restart persistence for supported hostPath gates. +- Read-only CLI/report/dashboard/support-bundle flows. +- Read-only CRD status and Events for `SwBlockCluster` and `SwBlockVolume`. +- Live node evidence for Kubernetes Ready/SchedulingDisabled, CSI registration, + CSI image-pull blockers, host-prereq evidence replay, and loopback + cross-node attach blockers. +- Negative-first status: blocked, stale, unreachable, or corrupt evidence must + not become false `Ready=True`. +- Cleanup verification for Kubernetes, iSCSI, multipath, process, and hostPath + residue. +- Executable lifecycle action contracts: dry-run actions can be allowed with + evidence, unsafe/future-mutating actions are rejected with stable reasons, and + CRD/report/dashboard/operator-snapshot surfaces agree on the decision. +- Delete-safety status and cleanup-required visibility without finalizer or + cleanup mutation. +- Bounded `SwBlockVolume` finalizer lifecycle in the v0.5 beta-candidate path: + CSI-created identity CRs, lifecycle-owner protection finalizer, evidence-driven + hold/release, Events, and multi-volume isolation. +- Install drift status for current versus desired chart/app/image identity + without upgrade execution. +- CRD/RBAC status-writer conformance coverage for the failures that previously + escaped mock tests and only failed in live QA. + +The product model is converging around one read-only control-plane pattern: +truth owners publish facts, the status layer aggregates judgment, executors stay +bounded, and evidence explains why the status is allowed. The next work should +preserve that model rather than add isolated scripts or separate status systems. + +Recommended order from here: + +1. Operator-status foundation release: complete in v0.4 beta. It claims + status/events-only visibility, not lifecycle mutation. +2. Operation Layer v0.5 beta candidate: code and QA complete through Phase 44; + release images still need publish/pinned-image smoke before marking it + shipped. It claims a bounded `SwBlockVolume` protection-finalizer lifecycle, + not automatic cleanup or broad operator automation. + - Phase 41: lifecycle-owner foundation. **Closed 2026-06-14, QA PASS** + (`internal/docs/finished-plans/phase41_finishedplan_lifecycle_owner_foundation.md`). + Observer/lifecycle-owner/executor roles defined; delete-safety preconditions + and a dry-run finalizer-release action shipped. + - Phase 42: real API/admission proof. **Closed 2026-06-15, QA PASS** + (`internal/docs/finished-plans/phase42_finishedplan_lifecycle_owner_admission_gate.md`). + The lifecycle-owner patch boundary is proven with real Kubernetes + ValidatingAdmissionPolicy. + - Phase 43: first bounded lifecycle mutation. **Closed 2026-06-15, QA PASS** + (`internal/docs/finished-plans/phase43_finishedplan_bounded_finalizer_lifecycle.md`). + Finalizer add/release works as isolated gates. + - Phase 44: delete lifecycle close gate. **Closed 2026-06-17, QA PASS** + (`internal/docs/finished-plans/phase44_finishedplan_delete_lifecycle_close_gate.md`). + The integrated PVC -> protected CR -> hold/release -> zero-residue path is + validated end-to-end. +3. Productize returned-replica rebuild/reintegration/failback after the + operation layer can safely authorize, block, and audit lifecycle actions. + The engine/transport already has rebuild and returned-replica safety pieces; + the missing work is the Kubernetes/product control loop: facts, judgment, + action ownership, status, Events, fencing, and multi-volume QA gates. +4. Add backup/restore and NVMe ANA parity after they can reuse the same action + owner, evidence, and status model rather than creating another isolated + control plane. + +The internal release-train contract is +`internal/docs/ref/operation-layer-v0.5-release-train.md`. Phases 41-44 close +the operation-layer loop for a bounded `SwBlockVolume` protection finalizer. +Next storage features should reuse this same fact -> judgment -> action -> +evidence pattern. + +The practical rule is: + +```text +Do not add a new data-plane feature if the product cannot yet explain who owns +the lifecycle action, what evidence authorizes it, how it is blocked, and where +the user sees the result. +``` + +## Future Non-Kubernetes Adapters + +Kubernetes CSI remains the primary product surface. A Docker integration is +possible later, but it should be scoped as a Docker Volume Plugin, not a Docker +graph/storage driver. + +Potential Docker Volume Plugin path: + +- `docker volume create -d seaweed-block ...` +- local attach/mount/unmount through a small node agent or local daemon +- reuse ManagedVolume status, cleanup verification, support bundles, and + negative-first evidence +- target single-node Docker, lab, edge, or developer workflows first + +Explicit non-goals for the Docker path: + +- no Docker graph/storage driver to replace `overlay2` +- no broad Docker Swarm HA claim before the K8s lifecycle model is stable +- no production failover claim without fencing, cleanup, and residue gates + +Windows Docker Desktop support is an investigation item, not a current claim. +The likely path is a Linux Docker Desktop VM or WSL2 backend running the +Seaweed Block node component, with Windows accessing the mounted volume through +Docker. Native Windows block-device attachment is out of scope until the Linux +control-plane path is mature. ## Availability And Recovery Follow-Ups @@ -74,11 +190,13 @@ Current alpha constraints: - authority moves - frontend reconnect path is validated -3. Returned replica lifecycle. +3. Productized returned replica lifecycle. - - observed replica returns - - candidate -> syncing/rebuilding -> ready + - observed replica returns after promotion + - returned replica stays frontend-fenced until recovery evidence is current + - candidate -> syncing/rebuilding -> ready is visible in CRD/report/dashboard - ready status gates placement/ACK eligibility + - rebuild/reintegration/failback action owner is explicit and audited 4. Flow-control and pressure behavior. @@ -141,6 +259,7 @@ A reasonable beta bar: - Multi-node attach works. - Basic failover is tested under an attached workload. - Read-only status and support evidence are available without SSH log spelunking. +- Negative and stale states are surfaced without false Ready claims. - Operator lifecycle is either present behind a clear beta gate or explicitly listed as the next release boundary. - TestOps can run the protocol release gate and produce stable artifacts. @@ -148,4 +267,3 @@ A reasonable beta bar: Detailed post-alpha execution planning is kept in `internal/docs/` so the public roadmap stays focused on user-visible behavior and non-claims. - diff --git a/seaweed-block/docs/user-capabilities.md b/seaweed-block/docs/user-capabilities.md index 1d0f6ae67a..d9958c34bf 100644 --- a/seaweed-block/docs/user-capabilities.md +++ b/seaweed-block/docs/user-capabilities.md @@ -117,8 +117,34 @@ timeline.jsonl operator-snapshot.json ``` -`operator-snapshot.json` is a read-only status projection for future operator -work. It is not a running controller manager and it does not permit mutations. +`operator-snapshot.json` is a read-only status projection. By itself it is not +a controller and it does not permit mutations. + +## Kubernetes-Native Status And Events + +The optional operator-status path can publish the same read-only model into +Kubernetes: + +- `SwBlockCluster.status` +- `SwBlockVolume.status` +- Kubernetes Conditions +- Kubernetes Events + +The controller is status/events-only. Its ServiceAccount is constrained to CRD +read, CRD `/status` write, and Event create. It does not patch CRD spec, create +PVCs, mutate workloads, own finalizers, run cleanup, or execute upgrades. + +Current status surfaces include: + +- volume readiness and stable reason codes, +- node readiness and node blockers, +- support evidence references, +- cleanup-required and delete-safety visibility, +- safe read-only/dry-run/scripted next-step hints, +- install drift for current versus desired chart/app/image identity. + +Install drift is visibility only. It can report `ok`, `mismatch`, or `unknown`; +it does not run Helm, kubectl, upgrade, or rollback commands. ## Support Bundle Replay @@ -145,6 +171,11 @@ The current status model is negative-first: identify known blockers. - `EvidenceStale=True` or `Ready=Unknown` means evidence is stale, missing, or still reconverging; the product should not claim ready. +- `CleanupRequired=True` means residue evidence exists; the operator suggests + scripted verification but does not clean automatically. +- `install_drift_mismatch` means current install identity differs from desired + evidence; the operator reports the mismatch but does not execute upgrade or + rollback. - Cluster counters include `ready_volume_count`, `blocked_volume_count`, and `stale_volume_count`. @@ -195,6 +226,9 @@ hostpath_residue_count=0 - Not production-ready. - No production-grade operator or controller-manager lifecycle. - No mutating admin/operator/dashboard actions. +- No finalizer ownership by operator-status. +- No automatic cleanup execution. +- No upgrade or rollback execution. - No promote, repair, rebuild, failback, delete, backup, restore, or cleanup mutation through UI/API/operator. - No backup/snapshot/restore workflow. @@ -202,5 +236,5 @@ hostpath_residue_count=0 - No transparent Kubernetes node-loss failover without pod recreate. - No NVMe ANA parity for the transparent failover path. - No broad distro/kernel/initiator compatibility matrix. -- No broad upgrade/rollback safety beyond existing gated smoke paths. +- No upgrade or rollback execution. - No performance, RTO, RPO, or SLO claim. diff --git a/seaweed-block/internal/docs/current-plan.md b/seaweed-block/internal/docs/current-plan.md index d7ad043651..c2bd8b162e 100644 --- a/seaweed-block/internal/docs/current-plan.md +++ b/seaweed-block/internal/docs/current-plan.md @@ -1,186 +1,237 @@ -# Current Plan: Phase 25 - v0.3 Helm + Observable First-Volume Release +# Current Plan: Phase 44 - Delete Lifecycle Close Gate -Status: closed, 100% complete. Plan simplified and closed on 2026-05-22. +Status: closed on 2026-06-17. -Reference: +Branch: `phase41-lifecycle-owner-foundation` -- `internal/docs/ref/product-delivery-review-simple-stable-observable-block.md` +Previous phase: Phase 43 is closed in +`internal/docs/finished-plans/phase43_finishedplan_bounded_finalizer_lifecycle.md`. ## Product Goal -Deliver a simple, stable, observable Kubernetes block alpha: +Validate the complete user-visible delete lifecycle as one product path: ```text -Helm install --> first PVC --> writer/reader data check --> read-only report/dashboard --> clean uninstall --> docs and release note match the exact claim +install -> first PVC -> SwBlockVolume protected -> delete requested -> +blocked/unknown evidence holds finalizer -> clean evidence releases finalizer -> +object deletion completes -> uninstall leaves zero residue ``` -This phase was release reconciliation and hardening. It had two steps only: +Phase 43 proved add and release independently. Phase 44 proves the integrated +operation behaves as a coherent product capability across Kubernetes objects, +CRD status, Events, report/dashboard/explain surfaces, and cleanup. + +## Why This Is Next + +The operation layer is only useful if separate pieces compose: ```text -D1: docs + release claim alignment - PASS -D2: gate replay + close evidence - PASS +live object state + status evidence + action boundary + admitted mutation + +user-facing explanation + cleanup ``` +Phase 44 is the close gate before moving to a broader release or larger +features. It should not add rebuild, failback, backup, or NVMe scope. + ## Scope Contract | In | Out | |---|---| -| Helm release hardening | CRD/operator implementation | -| README / quickstart / release note alignment | new mutating admin action | -| single-node and multi-node Helm gate replay | new protocol capability | -| dashboard/report evidence consistency | model or protocol refactor | -| immutable image / digest documentation | backup/snapshot/restore | -| cleanup and host residue verification | rebuild/reintegration/failback | +| one first-volume user path | returned-replica rebuild | +| SwBlockVolume finalizer add and release | failback / repair | +| delete-safety hold/release status | automatic cleanup execution | +| CRD status/Event/report/dashboard agreement | PVC/PV/workload mutation | +| zero-residue uninstall verification | backup/snapshot/restore | +| multi-volume isolation smoke if cheap | NVMe ANA parity | -Principle: Phase 25 may take small bug fixes only when they block the v0.3 user -path. No model rewrite, no operator controller, no broad architecture refactor. +Allowed mutation: -## Current Closed Inputs +```text +lifecycle-owner may patch only SwBlockVolume.metadata.finalizers. +operator-status remains status/events-only. +``` -As of 2026-05-22: +## D1: Release Artifact / Image Alignment -- Phase 20 Day-1 activation: closed. -- Phase 22 ManagedVolume model: closed for scope. -- Phase 23 operations surface/operator-readiness contract: closed for scope. -- Phase 24 hosted read-only dashboard: closed for scope. - -## D1: Docs + Release Claim Alignment - -Goal: make the user-facing product story match the current code and gates. - -Status: PASS on 2026-05-22. - -Artifacts: - -- `internal/docs/product-roadmap.md` -- `README.md` -- `docs/quickstart-kubernetes.md` -- `docs/releases/v0.3-alpha.md` -- `docs/releases/README.md` - -Required content: - -- v0.3 is Helm alpha install + first PVC + read-only report/dashboard + - cleanup. -- Script activation remains alpha/dev fallback, not the preferred v0.3 story. -- `sw-block ops generate-helm-values` input/output is explained. -- Single-node behavior is clear: one selected node, loopback mode. -- Multi-node behavior is clear: Ready schedulable nodes, non-loopback - InternalIP, external iSCSI/status, CHAP. -- `sw-block ops report` vs `sw-block ops dashboard` is clear: - - report writes static artifacts, - - dashboard serves the same read-only evidence locally. -- Immutable `sha-` images are recommended for QA/PM/release proof. -- Mutable `:alpha` is documented as smoke/demo only. -- Non-claims are explicit: - - not production-ready, - - no operator lifecycle, - - no mutating admin UI/actions, - - no backup/snapshot/restore, - - no upgrade/rollback safety, - - no broad performance/RTO/SLO claim, - - no new recovery scope beyond already gated evidence. +Goal: ensure the shipped image and chart can actually run the lifecycle-owner. Acceptance: ```text -README + quickstart + release note describe the same v0.3 claim. -No doc claims a capability without a gate. -Roadmap marks Phase 22/23/24 closed and Phase 25/v0.3 closed. +[x] candidate image includes sw-block ops lifecycle-owner +[x] chart renders lifecycleOwner.create=false by default +[x] lifecycleOwner.create=true installs Deployment/RBAC/VAP +[x] no chart flag/image skew ``` -## D2: Gate Replay + Close Evidence +Fail if the chart references a subcommand or flag absent from the image. -Goal: prove the documented v0.3 path is runnable and self-explaining. +## D2: First PVC Creates Protected SwBlockVolume -Status: PASS on 2026-05-22. +Goal: a normal Day-1 PVC path creates an observable, protected +`SwBlockVolume`. -Evidence: +Ownership boundary: -- Single-node Helm gate: `20260522-031019-ef25`, PASS, 34/34 actions. -- Multi-node Helm gate: `20260522-031124-0a44`, PASS, 51/51 actions. -- Documented Go CLI generator gate: `20260522-091642-b9a7`, PASS, 31/31 - actions. -- Both runs record immutable image tags and digests. -- Both runs produce `status/report/index.html`, `cluster-evidence.json`, - `timeline.jsonl`, and `summary.txt`. -- Both runs finish with `cleanup_status=ok`, zero k8s residue, zero process - residue, and zero hostPath residue. - -Required gates: - -- Helm single-node first-volume gate: - - `testops/scenarios/helm-single-node-first-volume-chain.yaml` - - expected: PASS -- Helm multi-node first-volume gate: - - `testops/scenarios/helm-first-volume-chain.yaml` - - expected: PASS -- Report/dashboard consistency: - - `summary.txt` - - `index.html` - - `cluster-evidence.json` - - `timeline.jsonl` - - dashboard endpoint serving same evidence when applicable -- Image identity: - - image tag recorded, - - digest recorded, - - release validation uses immutable tag. -- Cleanup: - - Helm release removed, - - StorageClass/demo PVC/pods removed, - - no active iSCSI sessions, - - no sw-block processes, - - no test-scoped residue. +```text +CSI controller creates/updates SwBlockVolume metadata/spec identity after +CreateVolume succeeds. operator-status writes only .status. lifecycle-owner +patches only metadata.finalizers. +``` Acceptance: ```text -single-node Helm gate PASS -multi-node Helm gate PASS -report/dashboard reason codes agree -image tag/digest evidence present -cleanup clean -close report written -finished plan written +[x] Helm install succeeds with operatorStatus + lifecycleOwner enabled +[x] first PVC writer/reader passes +[x] SwBlockVolume exists for the PVC +[x] lifecycle-owner adds exactly one protection finalizer +[x] operator-status writes Ready=True / first_volume_verified +[x] finalizer_added Event is bounded ``` -Close artifacts: +## D3: Delete Request Holds On Unsafe Evidence -- `internal/docs/qa-assignments/v0.3-helm-observable-first-volume-close-report.md` -- `internal/docs/finished-plans/phase25_finishedplan_v0.3_helm_observable_first_volume.md` +Goal: a delete request cannot complete while evidence is unsafe. -## Claim Matrix - -| Area | Can Claim For v0.3 | Cannot Claim | -|---|---|---| -| Install | Helm alpha install on supported k3s/Kubernetes labs | production installer, broad distro support | -| First Volume | PVC create, writer/reader data check, clean report | performance/SLO, upgrade safety | -| Recovery | Existing gated RF3 recovery evidence remains valid | new recovery scope beyond prior gates | -| Dashboard | local read-only dashboard/report over product evidence | production hosted UI, mutating admin UI | -| Cleanup | documented uninstall + host cleanup verification | fully automated operator lifecycle | -| Images | immutable tag/digest release validation | mutable `:alpha` as release proof | - -## Risks - -| Risk | Mitigation | Fallback | -|---|---|---| -| `:alpha` image drift | release docs require immutable `sha-` tags for QA/PM | use local/internal images for dev gates | -| single-node vs three-node behavior confusion | quickstart explains loopback vs external iSCSI/CHAP values | provide separate single-node and multi-node commands | -| docs drift from implementation | close gate checks README, quickstart, release note against gate artifacts | block release note until docs are corrected | -| dashboard/report reason mismatch | compare summary, HTML, JSON, explain/dashboard reason codes | fix projection consistency only; no model rewrite | -| cleanup residue after Helm uninstall | host cleanup verification is required | document manual cleanup command and keep release blocked until clean | - -## Dependency Order +Acceptance: ```text -D1 docs alignment --> D2 gate replay --> close report +[x] deleting SwBlockVolume with missing cleanup evidence remains Terminating +[x] blocked residue evidence remains Terminating +[x] stale cleanup evidence remains Terminating +[x] status.deleteSafety decision is unknown/rejected as appropriate +[x] Events explain the hold reason +[x] lifecycle-owner does not run cleanup ``` -Do not start operator/CRD implementation until this phase closes. +Fail if unsafe evidence releases the finalizer. + +Implementation note: + +```text +operator-status now lists live SwBlockVolume objects and projects deleteSafety +for objects with deletionTimestamp. Cleanup remains external evidence: pass the +verifier output with --cleanup-summary; operator-status reads it, never runs it. +``` + +## D4: Clean Evidence Releases And Deletion Completes + +Goal: clean, fresh evidence releases only the Seaweed Block finalizer. + +Acceptance: + +```text +[x] clean cleanup evidence sets decision=allowed state=releasable +[x] lifecycle-owner removes only block.seaweedfs.com/swblockvolume-protection +[x] foreign finalizers are preserved if present +[x] SwBlockVolume deletion completes after release +[x] finalizer_released Event is bounded +``` + +Fail if any non-finalizer field changes. + +## D5: Surface Agreement + +Goal: users see the same answer everywhere. + +Acceptance: + +```text +[x] kubectl get/describe SwBlockVolume status agrees with ops report +[x] operator-snapshot agrees with CRD status +[x] dashboard /operator-snapshot.json agrees +[x] ops explain names the same hold/release reason +[x] no false Ready=True appears in blocked/unknown delete states +``` + +## D6: Multi-Volume Isolation Smoke + +Goal: one deleting volume does not contaminate another volume. + +Scenario: + +```text +A deleting + blocked residue -> held +B deleting + clean evidence -> released +C normal ready volume -> remains ready, protected, no deleteSafety contamination +``` + +Acceptance: + +```text +[x] A held does not block B release +[x] B release does not remove A/C finalizer +[x] C remains Ready=True and protected +[x] Events/status use the correct volume identity +``` + +## D7: Close / Release Decision + +Phase 44 can close only if: + +```text +[x] D1-D6 PASS on a clean VAP-capable lab +[x] lifecycle-owner has no cleanup/PVC/PV/workload/storage mutation power +[x] operator-status remains status/events-only +[x] final cleanup verifier reports zero residue +[x] release notes and README claim only bounded SwBlockVolume finalizer + lifecycle, not automatic cleanup or broad lifecycle automation +``` + +## Current Progress + +- Phase 44 finished plan: + `internal/docs/finished-plans/phase44_finishedplan_delete_lifecycle_close_gate.md`. +- v0.5 beta candidate release note: + `docs/releases/v0.5-beta-candidate.md`. +- D2 implementation landed in `e56b844`: normal CSI CreateVolume registers the + SwBlockVolume identity CR when operator-status or lifecycle-owner surfaces + are enabled. +- D2 QA PASS: + `internal/docs/qa-assignments/phase44-d2-integrated-swblockvolume-cr-qa-signoff.md`. +- D3/D4 implementation added in `8669d4a`: operator-status consumes live deleting + SwBlockVolume objects plus externally generated `cleanup-summary.txt` + evidence to publish deleteSafety hold/release status. It still does not patch + finalizers, run cleanup, or mutate PVC/PV/workloads/storage. +- D3/D4 QA PASS: + `internal/docs/qa-assignments/phase44-d3-d4-delete-lifecycle-close-gate-qa-signoff.md`. +- D3/D4 polish added after QA: report/explain/dashboard can consume + `--cleanup-summary` in live in-cluster mode, and operator-status skips a + disappeared SwBlockVolume CR instead of aborting the whole reconcile. +- D5/D6 QA PASS: + `internal/docs/qa-assignments/phase44-d5-d6-surface-isolation-close-qa-signoff.md`. +- D5/D6 polish added after QA: `ops explain volume --cleanup-summary` can now + explain a deleting SwBlockVolume even when the live inventory no longer + contains the managed volume. +- Local checks pass: + `go test ./core/csi ./cmd/blockcsi`, `go test ./core/ops ./cmd/sw-block`, + and `helm lint charts/seaweed-block`. +- D2 QA assignment prepared: + `internal/docs/qa-assignments/phase44-d2-integrated-swblockvolume-cr-qa.md`. +- D3/D4 QA assignment prepared: + `internal/docs/qa-assignments/phase44-d3-d4-delete-lifecycle-close-gate-qa.md`. +- Phase 43 already proved add and release as separate live gates. +- Phase 44 must prove the integrated path and release wording. + +## Prerequisites / Risks + +- Use a candidate image that includes `sw-block ops lifecycle-owner`. +- Use a candidate CSI image that includes `blockcsi --swblockvolume-cr-namespace`; + older CSI images will not support D2 integrated CR creation. +- Use a VAP-capable lab; Rancher Desktop without VAP is not sufficient. +- Be careful with deleting CRs that have finalizers; every failed gate must + include admin cleanup instructions. +- Do not paper over unsafe evidence by running cleanup inside lifecycle-owner. + +## Next Step + +Publish matching images from the final release commit and rerun the +release-candidate smoke: + +```text +claim bounded SwBlockVolume finalizer lifecycle only +claim evidence-driven hold/release, not automatic cleanup +publish both sw-block and sw-block-csi images together +rerun release-candidate smoke if image digests change +``` diff --git a/seaweed-block/internal/docs/finished-plans/phase33_finishedplan_testops_failure_hardening.md b/seaweed-block/internal/docs/finished-plans/phase33_finishedplan_testops_failure_hardening.md new file mode 100644 index 0000000000..4d7a44b577 --- /dev/null +++ b/seaweed-block/internal/docs/finished-plans/phase33_finishedplan_testops_failure_hardening.md @@ -0,0 +1,78 @@ +# Finished Plan: Phase 33 - TestOps Failure Hardening + +Closed: 2026-05-29 + +Verdict: PASS. + +## Delivered Claim + +Phase 33 hardens the existing Helm/PVC/read-only-ops alpha product against +failure-path ambiguity: + +```text +blocked or unreachable evidence +-> no false Ready=True +-> stable reason code +-> cold-readable support evidence +-> deterministic cleanup +``` + +This phase does not introduce a new storage feature. It strengthens release +confidence for the current product loop. + +## Evidence + +- F1 live negative support bundle: + - run `20260528-190738-51a2` + - PASS, 49/49 actions + - `reason=csi_node_image_pull_failed` + - `support_bundle_status=ok` + - `failure_snapshot_status=ok` + - cleanup residue zero +- F2 unreachable status replay: + - run `20260529-155016-e9a5` + - PASS, 17/17 actions + - `status=unknown reason=status_endpoint_unreachable` + - report, explain, dashboard, and operator snapshot agree +- F5 cleanup residue: + - run `20260529-155040-4519` + - PASS, 13/13 actions + - all residue counters zero +- Minimal new-user regression: + - run `20260529-155216-0d9d` + - PASS, 34/34 actions + - Helm values, install, first PVC, writer/reader, report, cleanup all pass +- Scoped tests: + - `go test ./scripts ./core/ops ./cmd/sw-block` PASS + +Close report: + +- `internal/docs/qa-assignments/phase33-testops-failure-hardening-close-report.md` + +## User-Facing Impact + +- Support bundles and failure snapshots are less noisy: expected empty + diagnostics no longer make the bundle look failed. +- A status endpoint unreachable condition becomes `Ready=Unknown`, not false + ready. +- Corrupt evidence no longer prevents replay when a newer valid snapshot exists. +- Cleanup residue vocabulary remains locked across Kubernetes, iSCSI session, + iSCSI node DB, multipath, dmsetup, process, and hostPath dimensions. + +## Important Non-Claims + +- Not production-ready. +- No new HA claim. +- No rebuild/failback implementation. +- No backup/snapshot/restore. +- No mutating operator/admin/dashboard action. +- No NVMe ANA parity expansion. +- No broad performance, RTO, RPO, or SLO claim. + +## Followups + +- Promote more failure matrix P1 entries to hard gates when useful: + multi-volume cross-interference, restart-during-promotion, and loopback + publish-target refusal. +- Continue reducing shell helper complexity with runner-native primitives. +- Use this as release-hardening evidence if cutting `v0.3.5-alpha`. diff --git a/seaweed-block/internal/docs/finished-plans/phase34_finishedplan_test_realism_dirty_failure_hardening.md b/seaweed-block/internal/docs/finished-plans/phase34_finishedplan_test_realism_dirty_failure_hardening.md new file mode 100644 index 0000000000..4e6b9bec3f --- /dev/null +++ b/seaweed-block/internal/docs/finished-plans/phase34_finishedplan_test_realism_dirty_failure_hardening.md @@ -0,0 +1,101 @@ +# Finished Plan: Phase 34 - Test Realism And Dirty-Failure Hardening + +Closed: 2026-06-02 + +Verdict: PASS. + +## Delivered Claim + +Phase 34 hardens the existing Helm/PVC/read-only-ops alpha product by replacing +selected replay-only or self-proving checks with live evidence and one dirty +storage failure: + +```text +unreachable status endpoint +-> no false Ready=True + +k3s restart reconvergence +-> transient Unknown allowed +-> final stable Ready required + +real SmartWAL corruption +-> storage fails closed +-> blockvolume withholds local readiness +-> master projection refuses Ready without positive primary readiness +``` + +This phase is not a new feature release. It is a correctness and release-trust +pass over negative-first status behavior. + +## Evidence + +- D1 self-proof audit: + - `internal/docs/qa-assignments/phase34-self-proof-audit.md` + - `internal/docs/qa-assignments/phase34-test-realism-plan.md` +- D2 live status endpoint unreachable: + - `internal/docs/qa-assignments/phase34-d2-live-status-endpoint-unreachable-signoff.md` + - PASS + - pure status-path failure becomes non-ready/unknown evidence, not false + ready and not blocked data-path failure. +- D3 restart convergence: + - `internal/docs/qa-assignments/phase34-d3-restart-convergence-signoff.md` + - PASS + - restart may show transient Unknown but must converge to stable Ready. +- D4 SmartWAL dirty-failure: + - run `20260601-020747-5a1f` + - PASS, 30/30 actions + - `target_offset_inside_wal=true` + - `target_offset_inside_extent=false` + - no `Ready=True` after corruption + - cleanup residue zero + - final report: + `internal/docs/qa-assignments/phase34-d4-smartwal-corrupt-verify3-PASS.md` + +Key code-chain evidence: + +- `85d9375` storage fails closed on SmartWAL CRC mismatch. +- `954083a` blockvolume blocks local readiness after durable recovery fault + while keeping status service diagnosable. +- `09aa6fe` master requires positive primary readiness evidence before + projecting the published primary as healthy. +- `7fa34a7` prevents ManagedVolume Ready projection without primary readiness + evidence. +- `bad6d7f` closes D4 scenario determinism by pinning blockmaster scheduling for + the SmartWAL corruption gate. + +## User-Facing Impact + +- A status endpoint that cannot be reached no longer allows a stale or guessed + `Ready=True`. +- Restart evidence must converge back to stable `Ready=True`; a single flicker + is not enough. +- SmartWAL corruption no longer silently recovers through the status surface as + a healthy volume. +- The product now follows a stronger rule: + +```text +Ready=True requires positive primary readiness evidence. +Reachable process heartbeat alone is not enough. +``` + +## Important Non-Claims + +- Not production-ready. +- No new HA claim. +- No rebuild, reintegration, or failback implementation. +- No backup/snapshot/restore. +- No mutating operator/admin/dashboard action. +- No NVMe ANA parity expansion. +- No broad chaos matrix, performance, RTO, RPO, or SLO claim. +- SmartWAL corruption currently surfaces as non-ready generic `unknown`; the + more specific `wal_integrity_fault` reason is a follow-up. + +## Followups + +- Surface `reason=wal_integrity_fault` through product status so cold operators + do not need blockvolume logs to understand the corruption reason. +- Continue replacing helper-summary self-proof checks with independent + Kubernetes/product cross-checks only where release value is high. +- Consider one carefully scoped netem slow-replica gate after the + Kubernetes-native operator status foundation exists. +- Start Phase 35: Kubernetes-native read-only operator foundation. diff --git a/seaweed-block/internal/docs/finished-plans/phase35_finishedplan_kubernetes_native_read_only_operator_foundation.md b/seaweed-block/internal/docs/finished-plans/phase35_finishedplan_kubernetes_native_read_only_operator_foundation.md new file mode 100644 index 0000000000..38da920e32 --- /dev/null +++ b/seaweed-block/internal/docs/finished-plans/phase35_finishedplan_kubernetes_native_read_only_operator_foundation.md @@ -0,0 +1,94 @@ +# Finished Plan: Phase 35 - Kubernetes-Native Read-Only Operator Foundation + +Closed: 2026-06-04 + +Verdict: PASS. + +## Delivered Claim + +Phase 35 turns the existing ManagedVolume read model into a Kubernetes-native, +read-only operator foundation: + +```text +SwBlockCluster CRD +SwBlockVolume CRD +status-only operator-status controller +CRD Conditions +Kubernetes Events +read-only/status-only RBAC +``` + +This is not a mutating operator lifecycle. The controller may read observation +evidence, patch CRD `.status`, and create Kubernetes Events. It must not mutate +storage, workloads, PVCs, PVs, Secrets, StorageClasses, Helm releases, iSCSI +sessions, multipath maps, hostPath data, or CRD spec. + +## Evidence + +| Gate | Evidence | Result | +|---|---|---| +| D1 CRD/RBAC contract | `internal/docs/qa-assignments/phase35-d1-operator-crd-qa-signoff.md` | PASS | +| D2 dry-run packaged controller | `internal/docs/qa-assignments/phase35-d2-operator-status-qa-signoff.md` | PASS | +| D3 happy-path status writer | `internal/docs/qa-assignments/phase35-d3-operator-status-writer-qa-signoff.md` | PASS | +| D4 blocked status + Events | `internal/docs/qa-assignments/phase35-d4-operator-status-events-qa-signoff.md` | PASS | +| D5 stale/unreachable projections | `internal/docs/qa-assignments/phase35-d5-stale-status-projections-qa-signoff.md` | PASS | +| D6 stable Event identity | `internal/docs/qa-assignments/phase35-d6-stable-event-identity-qa-signoff.md` | PASS | +| D7 read-only boundary | `internal/docs/qa-assignments/phase35-d7-read-only-boundary-qa-signoff.md` | PASS | + +Final scoped checks: + +```text +go test ./core/ops ./cmd/sw-block ./cmd/blockcsi +helm lint charts/seaweed-block +helm template sw-block charts/seaweed-block \ + --namespace kube-system \ + --include-crds \ + --set operatorStatus.create=true \ + --set operatorStatus.dryRun=false +``` + +## User-Facing Impact + +- Users can inspect Seaweed Block state through Kubernetes-native objects: + `SwBlockCluster` and `SwBlockVolume`. +- Existing ManagedVolume reason codes and Conditions project into CRD + `.status`. +- Known blocked evidence becomes `Ready=False` / `Blocked=True`; it does not + become false ready. +- Unreachable or stale evidence becomes `Ready=Unknown` / + `EvidenceStale=True`; it does not become an inappropriate hard block. +- WAL integrity faults remain non-ready and surface + `reason=wal_integrity_fault`. +- Kubernetes Events provide normal cluster breadcrumbs with stable + object/type/reason identity. Persistent blockers do not mint unbounded new + Event objects on every reconcile. +- The operator-status ServiceAccount is constrained to CRD read, CRD status + write, and Event create. + +## Important Non-Claims + +- Not production-ready. +- No mutating Kubernetes operator lifecycle. +- No automatic CR object creation or ownership. +- No finalizers or delete safety. +- No automatic cleanup. +- No promote, repair, rebuild, failback, delete, backup, restore, or cleanup + mutation through UI/API/operator. +- No upgrade execution. +- No backup/snapshot/restore workflow. +- No returned-replica rebuild or automated failback. +- No NVMe ANA parity expansion. +- No production hosted dashboard. +- No performance, RTO, RPO, or SLO claim. + +## Followups + +- Add server-side dry-run or envtest validation for CRD status payloads. +- Optionally patch existing Events on conflict to update `count` and + `lastTimestamp`. +- Project cleanup residue evidence into `CleanupRequired` status and Events. +- Add CR object ownership/creation only after the status-only contract remains + stable. +- Start any mutating operator lifecycle work as a separate phase with explicit + gates and rollback boundaries. + diff --git a/seaweed-block/internal/docs/finished-plans/phase36_finishedplan_productized_operations_actionability.md b/seaweed-block/internal/docs/finished-plans/phase36_finishedplan_productized_operations_actionability.md new file mode 100644 index 0000000000..3bc7a17b6b --- /dev/null +++ b/seaweed-block/internal/docs/finished-plans/phase36_finishedplan_productized_operations_actionability.md @@ -0,0 +1,96 @@ +# Finished Plan: Phase 36 - Productized Operations Actionability + +Closed: 2026-06-06 + +Verdict: PASS. + +## Delivered Claim + +Phase 36 turns the Phase 35 Kubernetes-native read-only status foundation into +an actionable operations surface: + +```text +SwBlockCluster.status.nodes[] +support bundle and evidence refs +cleanup visibility and CleanupRequired conditions +safe read-only or scripted next-step hints +cross-surface agreement across CRD status, Events, report, dashboard, +operator-snapshot, and ops explain +``` + +This is still read-only. The operator-status controller may read Kubernetes and +Seaweed Block observation APIs, patch CRD `.status`, and create Kubernetes +Events. It must not mutate storage, workloads, PVCs, PVs, Secrets, +StorageClasses, Helm releases, iSCSI sessions, multipath maps, hostPath data, +or CRD spec. + +## Evidence + +| Gate | Evidence | Result | +|---|---|---| +| D1 operations model contract | internal review + scoped tests | PASS | +| D2 node readiness / preflight status | `internal/docs/qa-assignments/phase36-d2-node-readiness-qa-signoff.md` | PASS | +| D3 support evidence refs | `internal/docs/qa-assignments/phase36-d3-support-evidence-qa-signoff.md` | PASS | +| D4 cleanup visibility | `internal/docs/qa-assignments/phase36-d4-cleanup-visibility-qa-signoff.md` | PASS | +| D5 surface agreement and negative-first gates | `internal/docs/qa-assignments/phase36-d5-surface-agreement-qa-signoff.md` | PASS | + +Final scoped checks: + +```text +go test ./scripts +go test ./core/ops ./cmd/sw-block ./cmd/blockcsi +helm lint charts/seaweed-block +helm template sw-block charts/seaweed-block \ + --namespace kube-system \ + --include-crds \ + --set operatorStatus.create=true \ + --set operatorStatus.dryRun=false +git diff --check +``` + +## User-Facing Impact + +- Users can inspect node-level readiness and preflight status through + `SwBlockCluster.status.nodes[]`. +- Blocked or unknown status can point to support bundle evidence refs. +- Cleanup verifier evidence projects `CleanupRequired=True|False`, residue + counters, and safe scripted verification hints. +- Safe next steps are visible as `read_only`, `dry_run`, or `scripted`; they do + not grant the operator mutation authority. +- CRD status, Kubernetes Events, report artifacts, local dashboard, + `operator-snapshot.json`, and `sw-block ops explain` agree across healthy, + blocked, stale, cleanup-required, and multi-volume paths. +- Negative-first behavior holds: blocked, unknown, stale, and cleanup-required + evidence does not become false `Ready=True`. + +## Important Non-Claims + +- Not production-ready. +- No mutating Kubernetes operator lifecycle. +- No automatic CR object creation or ownership. +- No finalizers or delete safety. +- No automatic cleanup. +- No automatic support-bundle collection or upload. +- No promote, repair, rebuild, failback, delete, backup, restore, or cleanup + mutation through UI/API/operator. +- No upgrade execution. +- No backup/snapshot/restore workflow. +- No returned-replica rebuild or automated failback. +- No NVMe ANA parity expansion. +- No production hosted dashboard. +- No performance, RTO, RPO, or SLO claim. + +## Follow-ups + +- Populate live `NodeEvidence` from real Kubernetes node readiness, + schedulability, image presence, and CSI driver registration. The negative + missing-image node path is currently replay-only. +- Tighten local-image build/import evidence so the build host proves both + `sw-block:local` and `sw-block-csi:local` are present before local-image + gates claim node readiness. +- Document loopback publish targets as single-node/local-consumer only. +- Keep cleanup verifier strict for force-delete residue such as stale iSCSI + node DB records. +- Start any mutating operator lifecycle work as a separate phase with explicit + gates, rollback boundaries, and PM-visible non-claims. + diff --git a/seaweed-block/internal/docs/finished-plans/phase37_finishedplan_live_node_evidence_hardening.md b/seaweed-block/internal/docs/finished-plans/phase37_finishedplan_live_node_evidence_hardening.md new file mode 100644 index 0000000000..7daa2d5d33 --- /dev/null +++ b/seaweed-block/internal/docs/finished-plans/phase37_finishedplan_live_node_evidence_hardening.md @@ -0,0 +1,65 @@ +# Phase 37 Finished Plan: Live Node Evidence Hardening + +Status: closed on 2026-06-09. + +Branch: `phase33-testops-failure-hardening`. + +## Goal + +Close the live node evidence gap before adding mutating operator behavior. The +phase focused on making Kubernetes node, CSI, image, host-prereq, and loopback +facts visible through the same negative-first status model used by volumes. + +## Delivered + +- Live Kubernetes node enrichment for Ready and SchedulingDisabled. +- Live CSI evidence for CSIDriver/CSINode registration and CSI node pod health. +- Live image-pull evidence, including `ImagePullBackOff`, `ErrImagePull`, and + `ErrImageNeverPull`, projected as `image_missing_on_node`. +- Shared live enrichment across operator-status, report, dashboard, and explain. +- Read-only host prerequisite artifact replay through + `host/host-prereq-summary.txt`, projecting `iscsi_prereq_missing` and + `multipath_prereq_missing`. +- Loopback cross-node artifact replay through + `unsupported-cross-node-loopback-attach.txt`, projecting + `publish_target_loopback_cross_node`. +- Runner-driven D5 E2E gates for same-node loopback success and cross-node + loopback refusal. +- Chart README clarification: raw Helm defaults are render/development defaults; + supported alpha installs use generated `values.day1.yaml`. + +## QA Evidence + +- D2 live node/CSI evidence: PASS on `052b321`. +- D3 CSI image-pull node blockers: PASS on `43d7786`. +- D4 host prereq replay: PASS on `f6a8378`. +- D5 same-node loopback runner E2E: PASS, 47/47 actions. +- D5 cross-node loopback negative runner E2E: PASS, 34/34 actions. +- Final cleanup: zero Kubernetes, iSCSI, multipath, process, and hostPath + residue in the D4/D5 sign-off. + +Sign-off documents: + +- `internal/docs/qa-assignments/phase37-d2-live-node-csi-evidence-qa-signoff.md` +- `internal/docs/qa-assignments/phase37-d3-csi-image-pull-node-blockers-qa-signoff.md` +- `internal/docs/qa-assignments/phase37-d4-d5-host-prereq-loopback-qa-signoff.md` + +## Non-Claims + +- No privileged host probing was added to the operator. +- No host repair, image import, cleanup, finalizer, rebuild, failback, backup, + restore, or upgrade mutation was added. +- Raw `helm install sw-block charts/seaweed-block` remains a render/development + default path, not a release-gated user install. +- Host prereq live collection still needs a safe source such as CSI-node facts, + a future node agent, or explicit support bundle collection. + +## Follow-Ups + +- Collapse duplicate per-node `Ready` conditions into one Kubernetes-style + condition per type. +- Add server-side-dry-run/envtest coverage for CRD status payloads so schema + drift is caught before live QA. +- Document the `swblock` runner build/provisioning path in the QA runbook. +- Begin the lifecycle action contract phase: dry-run actions, rejected-action + gates, executor authority, and evidence refs before finalizer/delete safety. diff --git a/seaweed-block/internal/docs/finished-plans/phase38_finishedplan_lifecycle_action_model_executable_contract.md b/seaweed-block/internal/docs/finished-plans/phase38_finishedplan_lifecycle_action_model_executable_contract.md new file mode 100644 index 0000000000..0a88834edb --- /dev/null +++ b/seaweed-block/internal/docs/finished-plans/phase38_finishedplan_lifecycle_action_model_executable_contract.md @@ -0,0 +1,90 @@ +# Phase 38 Finished Plan: Lifecycle Action Model Executable Contract + +Status: closed on 2026-06-10. + +Branch: `phase33-testops-failure-hardening`. + +## Goal + +Turn lifecycle/safe-next-step hints into executable, testable action contracts +before adding mutating operator behavior. + +The phase deliberately stopped before finalizers, cleanup execution, promotion, +repair, rebuild, failback, backup, restore, or any new mutating RBAC. Its output +is a bounded decision layer: every surfaced action can explain whether it is +`allowed` or `rejected`, why, which facts it requires, which executor owns it, +which invariants/evidence apply, and whether mutation is allowed. + +## Delivered + +- Action contract inventory for current ManagedVolume actions, including owner + executor, side-effect class, required facts, policy gate, invariant refs, and + evidence requirements. +- Executable evaluator: + `EvaluateManagedVolumeAction(actionType, ManagedVolumeFacts)`. +- Fail-closed rejection reasons: + `unknown_action`, `policy_disabled`, `missing_required_facts`, and + `mutation_not_allowed`. +- Rejected-action evidence renderer for cold review and QA. +- Surface propagation of action decisions through: + - ManagedVolume projection text, + - `summary.txt`, + - `sw-block ops explain`, + - `operator-snapshot.json`, + - dashboard `/operator-snapshot.json`, + - `SwBlockVolume.status.allowedActions[]`. +- CRD-safe camelCase fields for action status: + `decision`, `decisionReason`, `missingFacts`, `mutationAllowed`, and + `evidenceRequired`. +- Dry-run proof for `safe_k8s.reinstall_external_iscsi` on + `publish_target_loopback_cross_node`: decision `allowed`, mode `dry_run`, + evidence `loopback_cross_node_evidence`, and `mutation_allowed=false`. +- Rejected proof for `authority.request_promotion`: decision `rejected`, + reason `policy_disabled`, side effect `authority_mutating`, and + `mutation_allowed=false`. + +## QA Evidence + +QA verdict: PASS on source commit `ea1618d`. + +Gates: + +- G1 local contract tests: PASS. +- G2 rejected action evidence: PASS. +- G3 dry-run loopback action: PASS. +- G4 CRD/RBAC boundary: PASS. +- G5 non-mutation and cleanup: PASS. + +Validated commands: + +```text +go test ./core/ops ./cmd/sw-block ./cmd/blockcsi ./scripts +helm lint charts/seaweed-block +helm template ... --include-crds --set operatorStatus.create=true --set operatorStatus.dryRun=false +git diff --check +``` + +Sign-off document: + +- `internal/docs/qa-assignments/phase38-action-model-executable-contract-qa-signoff.md` + +## Non-Claims + +- No finalizer/delete safety was added. +- No automatic cleanup was added. +- No image import, Helm release change, host repair, iSCSI/multipath cleanup, or + hostPath mutation was added. +- No promotion, fencing, rebuild, reintegration, failback, repair, backup, + snapshot, or restore execution was added. +- No dashboard mutation buttons or mutating operator executor were added. +- `authority.request_promotion` remains contract-only and policy-disabled; it is + intentionally not surfaced as an executable live action. + +## Follow-Ups + +- Restore lab node `tp01` before Phase 39 multi-node delete-safety scenarios; + QA observed it as `NotReady`/unreachable during Phase 38 sign-off. +- Add server-side-dry-run/envtest coverage for CRD status payloads so future + schema drift is caught before live QA. +- Begin Phase 39: safe finalizer/delete-safety as the first narrow mutating + operator path, using the Phase 38 action contract as the precondition layer. diff --git a/seaweed-block/internal/docs/finished-plans/phase39_finishedplan_delete_safety_status_boundary.md b/seaweed-block/internal/docs/finished-plans/phase39_finishedplan_delete_safety_status_boundary.md new file mode 100644 index 0000000000..c84fa42301 --- /dev/null +++ b/seaweed-block/internal/docs/finished-plans/phase39_finishedplan_delete_safety_status_boundary.md @@ -0,0 +1,103 @@ +# Phase 39 Finished Plan: Delete-Safety Status Boundary + +Status: closed on 2026-06-13. + +Branch: `phase33-testops-failure-hardening` + +## Outcome + +Phase 39 originally targeted finalizer/delete safety as the first mutating +operator path. Live QA proved that CRD finalizer mutation cannot be bounded by +`swblockvolumes/finalizers` RBAC alone: CRDs expose no usable HTTP +`/finalizers` endpoint, and modifying `metadata.finalizers` requires main +`patch swblockvolumes` authorization. + +The product decision was to preserve the Phase 35-38 operator-status safety +boundary. Phase 39 therefore closes as a status/events-only delete-safety +boundary: + +- operator-status writes `SwBlockCluster/status`, `SwBlockVolume/status`, and + Kubernetes Events only, +- operator-status does not patch `SwBlockVolume.metadata.finalizers`, + `SwBlockVolume.spec`, workloads, storage resources, or host state, +- delete-safety is visible as blocked/releasable status, reason, evidence, + `CleanupRequired`, safe next steps, and `finalizerReleaseAllowed` as a fact, +- actual finalizer add/remove is deferred to a future lifecycle-owner component. + +## Delivered + +- Delete-safety contract and decision projection: + - states: `not_requested`, `requested`, `blocked`, `releasable`, `released`, + - blocked residue projects `CleanupRequired=True`, + - clean evidence projects `releasable/allowed`, + - missing/residue evidence never claims deletion is safe. +- Status-only operator boundary: + - Helm RBAC grants CRD reads, CRD `/status` writes, Events create, and + Kubernetes read-only evidence access, + - no finalizers, main CRD patch, PVC/PV, workload, storageclass, secret, node, + or host mutation grant. +- CRD schema hardening: + - `SwBlockVolume.status.allowedActions[].mode` accepts `read_only`, + `dry_run`, and `scripted`, + - regression test covers the enum to prevent the live 422 from returning. +- Multi-volume status isolation: + - delete-safety evidence for one volume does not contaminate other volumes, + - unrelated volumes keep their own identity, status, reason, and publish + target, + - clean delete-safety evidence can project independently on another volume. + +## QA Evidence + +- D4/D5 status-only re-validation: + `internal/docs/qa-assignments/phase39-d4-d5-finalizer-delete-safety-qa-signoff.md` + - RBAC status/events-only: PASS + - D4 blocked delete-safety status: PASS on `f167f9a` + - D5 clean delete-safety status: PASS + - final cleanup verifier: PASS +- D6 multi-volume status isolation: + `internal/docs/qa-assignments/phase39-d6-multi-volume-delete-safety-status-isolation-qa-signoff.md` + - A blocked delete-safety does not contaminate B/C, + - C can independently become releasable, + - `finalizer_patches=0`, + - no finalizer Events, + - CRD/report surfaces agree. + +Local verification during close: + +```text +go test ./core/ops ./cmd/sw-block +go test ./cmd/blockcsi ./scripts +helm lint charts/seaweed-block +helm template sw-block charts/seaweed-block --namespace kube-system --include-crds --set operatorStatus.create=true --set operatorStatus.dryRun=false +git diff --check +``` + +## Non-Claims + +Phase 39 does not claim: + +- automatic deletion protection for `SwBlockVolume`, +- finalizer add/remove by operator-status, +- PVC/PV finalizer ownership, +- automatic cleanup execution, +- iSCSI/multipath/hostPath deletion by the operator, +- promotion, fencing, rebuild, failback, backup, restore, or NVMe ANA parity. + +## Follow-Ups + +1. **Clear stale deleteSafety when delete evidence disappears.** + QA observed a within-volume stale field: after a delete-summary was removed, + the volume status returned to ready but retained the prior + `deleteSafety=blocked`. This did not contaminate other volumes, but the field + should be cleared or refreshed to avoid confusing consumers. +2. **Add live/envtest coverage for KubernetesStatusClient.** + Multiple defects in Phases 35-39 passed mock unit tests and Helm rendering but + failed against the real Kubernetes API/CRD/RBAC surface. Add an envtest-style + harness using real CRD schemas and the operator ServiceAccount permissions. +3. **Restore `tp01`.** + Lab infra remains `NotReady`/unreachable. Restore before RF=3 live + multi-node work. +4. **Future lifecycle-owner finalizers.** + Implement finalizer add/remove in the component that owns + `SwBlockVolume` object lifecycle, not in operator-status, unless the project + later chooses an admission-bounded main patch model. diff --git a/seaweed-block/internal/docs/finished-plans/phase40_finishedplan_operator_production_hardening.md b/seaweed-block/internal/docs/finished-plans/phase40_finishedplan_operator_production_hardening.md new file mode 100644 index 0000000000..ad44444cc2 --- /dev/null +++ b/seaweed-block/internal/docs/finished-plans/phase40_finishedplan_operator_production_hardening.md @@ -0,0 +1,159 @@ +# Phase 40 Finished Plan: Operator Production Hardening + +Status: closed on 2026-06-14. + +Branch: `phase33-testops-failure-hardening` + +## Outcome + +Phase 40 closes the status/events-only operator foundation as a release-ready +boundary. The product can now ship a coherent v0.4 beta slice: + +```text +Helm + PVC + read-only/status-only operator status + Events + diagnostics + +delete-safety/install-drift visibility. No lifecycle mutation. +``` + +The main problem addressed by this phase was not a missing user feature; it was +release trust. Phases 35-39 repeatedly found schema/RBAC defects only in live QA. +Phase 40 added release-candidate gates and conformance checks to catch those +classes earlier, then closed the chart/image skew found by QA. + +## Delivered + +- Status API conformance gate for `SwBlockCluster.status` and + `SwBlockVolume.status` payload shape: + - casing drift, + - enum drift, + - wrong endpoint usage, + - RBAC broadening, + - delete-safety status. +- Status correctness polish: + - stale `deleteSafety` clearing, + - single effective node `Ready` condition, + - bounded/stable Event identity preserved. +- Read-only install drift visibility: + - chart/app/operator image identity, + - current/desired/missing/mismatched status, + - report/dashboard/operator-snapshot/CRD agreement, + - no upgrade execution. +- Release claim alignment: + - README, quickstart, release note, roadmap, and QA assignments describe the + status/events-only operator foundation and explicit non-claims. +- Release candidate gates: + - local release gate script, + - TestOps status API conformance scenario, + - D6 QA assignment and sign-off. +- Chart/image compatibility fix: + - `--launcher-durable-impl` is gated by + `compat.launcherDurableImplFlag=false` by default, + - non-default `blockmaster.durableImpl` fails fast unless the compat flag is + enabled, + - local RC gate asserts the default chart render omits the incompatible flag. + +## Release Images + +Published by GitHub Actions run `27490827782` from commit +`dc2972d0059beffb2447ab8546ceb65e646a7b66`. + +```text +ghcr.io/seaweedfs/seaweed-block:sha-dc2972d0059b +ghcr.io/seaweedfs/seaweed-block-csi:sha-dc2972d0059b +``` + +Published digests: + +```text +seaweed-block + index: sha256:b8da5ca4e2bbe2f0f630fee0468790c444362615d68807a1be31fd237c84928f + linux/amd64: sha256:677f6321ea5199b14792345b8691358860bb9ca7376f4e4a2f3a7c0113d5db9b +seaweed-block-csi + index: sha256:b5942cd68d28aecdfebec1f1e5ec55a9cafe746169fee3b6c35916c93fffcaa6 + linux/amd64: sha256:1fc636a4e0e63cc8cbee39e6775053c5d1aba7213ca9182a084e1bb6fe71474c +``` + +## QA Evidence + +Primary D6 close: + +- `internal/docs/qa-assignments/phase40-d6-release-candidate-qa-signoff.md` + +Result: + +- Local release gate: PASS. +- G1 first-volume with published image: PASS. +- G2 operator-status CRD/Event/RBAC with fresh release image: PASS. +- G3 negative status: PASS. +- G4 status API conformance: PASS. +- G5 cleanup residue: PASS. + +Important QA sequence: + +- Initial D6 held because the chart passed `--launcher-durable-impl` to + published images that did not support that flag. +- The chart compatibility fix resolved the blocker. +- QA reran G1 against the published `sha-6260e46fd3be` image and confirmed + first-volume still works. +- Fresh images were published from `dc2972d0059b`. +- QA ran G2 against `sha-dc2972d0059b` and confirmed live CRD status, Events, + and the status/events-only RBAC boundary on the shipped binary. + +Supporting evidence: + +- `internal/docs/qa-assignments/phase40-d4-status-api-conformance-qa.md` +- `internal/docs/qa-assignments/phase40-d6-release-candidate-qa.md` +- `docs/releases/v0.4-beta-candidate.md` + +## Non-Claims + +Phase 40 does not claim: + +- production readiness, +- mutating Kubernetes operator lifecycle, +- automatic `SwBlockVolume` object creation or ownership, +- finalizer ownership or finalizer add/remove, +- delete execution, +- automatic cleanup, +- automatic support-bundle collection or upload, +- upgrade or rollback execution, +- promote, repair, rebuild, failback, delete, backup, restore, or cleanup + mutation through UI/API/operator, +- returned-replica rebuild or automated failback, +- NVMe ANA parity expansion, +- production dashboard, +- performance, RTO, RPO, or SLO guarantees. + +## Carry-Forwards + +1. **Real envtest/live-apiserver status-writer harness.** + The current conformance gate is schema-aware and useful, but still uses a + mock server. A real apiserver + real RBAC harness remains the highest-leverage + way to shift live-only CRD/RBAC defects left. +2. **`swblock -env` flag ordering.** + Runner flags after the scenario path can be silently ignored. Fix the runner + or correct all runbooks to put `-env` before the scenario path. +3. **Parameterized support-bundle import nodes.** + `helm-support-bundle-diagnostics-chain` hardcodes a tp01 import path; make it + env-overridable so one lab node being down does not block unrelated negative + status validation. +4. **Restore `tp01`.** + Lab infra remained `NotReady`/unreachable during the release cycle. Restore + before RF=3 live multi-node work. +5. **Loopback publish-target documentation.** + Document loopback publish targets as single-node/local-consumer only. + +## Phase 41 Entry Criteria + +Phase 41 should start from the v0.4 beta status/events-only baseline and should +not weaken that boundary. + +Recommended next scope: + +- lifecycle-owner design, +- CR object ownership and finalizer strategy, +- first bounded mutating path with explicit action/precondition/executor/evidence + contract, +- real envtest/live-apiserver regression before any new mutating RBAC ships. + +Do not start with NVMe ANA parity, backup/restore, rebuild/failback, or broad +mutation until the lifecycle-owner boundary is explicit and testable. diff --git a/seaweed-block/internal/docs/finished-plans/phase41_finishedplan_lifecycle_owner_foundation.md b/seaweed-block/internal/docs/finished-plans/phase41_finishedplan_lifecycle_owner_foundation.md new file mode 100644 index 0000000000..5d2fd067d9 --- /dev/null +++ b/seaweed-block/internal/docs/finished-plans/phase41_finishedplan_lifecycle_owner_foundation.md @@ -0,0 +1,96 @@ +# Phase 41 Finished Plan: Lifecycle Owner Foundation + +Status: closed on 2026-06-14. + +Branch: `phase41-lifecycle-owner-foundation` + +## Outcome + +Phase 41 establishes the control-plane boundary that future storage-lifecycle +features must reuse, without breaking the released status/events-only +`operator-status` boundary and without shipping any Kubernetes lifecycle +mutation. The product now has: + +```text +an explicit lifecycle-owner contract (observer / lifecycle-owner / executor), +delete-safety converted into executable allowed/rejected/unknown preconditions, +a dry-run lifecycle-owner finalizer-release action surface (never executed), +and a schema-aware API/RBAC boundary gate for the future mutating component. +``` + +The Phase 39 finding drove the phase: changing `metadata.finalizers` on a CRD +requires main-object `patch swblockvolumes`, which is too broad for the +status-only observer. Rather than weaken that boundary with an RBAC tweak, Phase +41 defines a separate lifecycle-owner role and **defers** finalizer mutation until +a real Kubernetes API/admission proof exists. + +## Delivered + +- Lifecycle-owner control contract + (`internal/docs/ref/lifecycle-owner-control-contract.md`): three roles with + separate, non-implicit RBAC; allowed/forbidden permissions per role; the action + contract fields; delete-safety precondition table; required gates before any + mutation ships. +- Finalizer strategy decision + (`internal/docs/ref/lifecycle-owner-finalizer-strategy.md`): **Path B (defer)**. + Phase 41 does not ship finalizer add/remove; the release non-claim + ("delete-safety is status-only guidance, not Kubernetes deletion protection") + is kept. +- Delete-safety preconditions: clean → `releasable/allowed`, residue → + `blocked/rejected`, missing → `requested/unknown`, stale → + `requested/unknown reason=cleanup_evidence_stale`; data-plane `Ready` stays + independent of lifecycle release. +- Dry-run lifecycle-owner action surface across report, operator-snapshot, and + CRD `allowedActions`: `safe_k8s.release_swblockvolume_finalizer`, `mode=dry_run`, + `ownerExecutor=lifecycle_owner`, `mutationAllowed=false`, decision mirrors + delete-safety; no finalizer mutation Events. +- Schema-aware API boundary gate + (`scripts/run-phase41-lifecycle-owner-api-boundary.{ps1,sh}`, + `testops/scenarios/lifecycle-owner-api-boundary-chain.yaml`, + `TestPhase41D2LifecycleOwnerFinalizerBoundary`): observer cannot patch the main + object; lifecycle-owner identity may issue only a finalizer-shaped patch; + spec/unrelated-metadata/fake-`/finalizers` patches are rejected. +- Cleanup freshness: `verify-helm-cleanup.sh` now emits + `cleanup_observed_at=`; `cleanup_status` + residue counters + exit + behavior unchanged. +- Multi-volume isolation regression (four volumes: blocked / ready / releasable / + stale) proving per-volume `deleteSafety`, per-volume dry-run action, and no + cross-volume contamination. + +## QA Result + +All gates pass — see +`internal/docs/qa-assignments/phase41-lifecycle-owner-foundation-qa-signoff.md`: + +```text +G1 contract review PASS +G2 API boundary gate PASS (schema-aware/equivalent-RBAC) +G3 delete-safety decision semantics PASS +G4 cleanup freshness source PASS (cleanup_observed_at RFC3339 UTC) +G5 dry-run lifecycle-owner action PASS +G6 multi-volume isolation PASS +G7 live operator-status boundary PASS (status/events-only; RBAC unchanged) +``` + +## Required Carry-Forward (Phase 42 entry point) + +```text +A full live-apiserver/envtest lifecycle-owner RBAC/admission gate is still +required before any finalizer mutation (main-object patch swblockvolumes) can +ship. Phase 41's boundary gate is schema-aware/equivalent-RBAC, not a live +apiserver/admission proof. +``` + +## Non-Claims (unchanged) + +Phase 41 does not implement a mutating operator, finalizer add/remove, automatic +cleanup, repair/rebuild/failback/backup/restore/promotion/fencing, NVMe ANA +parity, or production SLOs. It defines the boundary those features must use. + +## Next + +Phase 42: real lifecycle-owner API/admission gate — an envtest/live-apiserver +proof that a lifecycle-owner identity can perform only a constrained +`metadata.finalizers` patch (spec/unrelated-metadata/storage/workload mutation +fails against a real API server) before any actual finalizer add/remove is +enabled. NVMe / rebuild / backup remain deferred until that proof exists. diff --git a/seaweed-block/internal/docs/finished-plans/phase42_finishedplan_lifecycle_owner_admission_gate.md b/seaweed-block/internal/docs/finished-plans/phase42_finishedplan_lifecycle_owner_admission_gate.md new file mode 100644 index 0000000000..d4d5c836e9 --- /dev/null +++ b/seaweed-block/internal/docs/finished-plans/phase42_finishedplan_lifecycle_owner_admission_gate.md @@ -0,0 +1,104 @@ +# Phase 42 Finished Plan: Lifecycle Owner API / Admission Gate + +Status: closed on 2026-06-15. + +Branch: `phase41-lifecycle-owner-foundation` + +## Outcome + +Phase 42 closes the Phase 41 carry-forward: the lifecycle-owner boundary is now +proven against a real Kubernetes API/admission surface, not only a mock. + +The product now has evidence for both halves required before shipping a real +finalizer mutation: + +```text +1. lifecycle-owner main-object patch is admitted only for the Seaweed Block + SwBlockVolume protection finalizer; +2. delete-safety decisions remain clean/blocked/missing/stale, dry-run, + status-visible, and per-volume isolated. +``` + +## Delivered + +- Live `ValidatingAdmissionPolicy` gate: + - applies the real `SwBlockVolume` CRD, + - creates separate `operator-status` and `lifecycle-owner` identities, + - waits for VAP propagation before assertions, + - permits only finalizer-shaped lifecycle-owner patches, + - rejects spec, labels, annotations, ownerReferences, deletionTimestamp, + foreign finalizers, mixed patches, fake `/finalizers`, `/status`, and + workload/storage resource mutations. +- Optional-field-safe CEL: + - guards absent `.status`, labels, annotations, ownerReferences, and finalizers + with `has()`, + - fixes the real m02 failure where absent `.status` caused an approved + finalizer add to be denied. +- Expanded forbidden-resource matrix: + - create/update/patch/delete denied for pods, deployments, PVCs, PVs, + storageclasses, secrets, nodes, CSIDrivers, and CSINodes. +- Delete-safety decision gate: + - clean cleanup evidence -> `allowed`, + - residue -> `rejected`, + - missing/stale evidence -> `unknown`, + - lifecycle-owner action remains `mode=dry_run`, + `mutation_allowed=false`, + - no finalizer patches or finalizer mutation Events in Phase 42, + - multi-volume delete-safety isolation holds. + +## QA Evidence + +- D1 initial live gate failure: + `internal/docs/qa-assignments/phase42-d1-lifecycle-owner-admission-gate-qa-signoff.md` + - `bc5ffc0` failed on m02 because CEL accessed absent optional fields. +- D1 fix and D1-D4 breadth: + - `116d381` fixed optional-field guards and propagation wait. + - `d3a1e0e` expanded D2-D4 breadth. + - QA PASS on m02 (`k3s v1.34.4`) with real VAP: + finalizer add/remove allowed and idempotent; all forbidden main-object and + resource mutations denied; object integrity preserved; cleanup left no + admission/RBAC residue. +- D5/D6 decision model: + `internal/docs/qa-assignments/phase42-d5-d6-delete-safety-decision-qa-signoff.md` + - QA PASS on m02 with Go 1.25.0, + - `phase42_delete_safety_decision_status=ok`, + - no cleanup execution, + - no finalizer patch, + - no finalizer mutation Events, + - multi-volume isolation true. + +## Non-Claims + +Phase 42 does not ship product finalizer add/remove, deletion protection, +automatic cleanup, PVC/PV mutation, workload mutation, host cleanup, repair, +rebuild, failback, backup/restore, NVMe ANA parity, or production SLOs. + +The only allowed mutation in Phase 42 is test-only against throwaway +`SwBlockVolume` objects inside the admission gate. + +## Required Carry-Forward (Phase 43 Entry Point) + +Phase 43 may now implement the first product mutation: + +```text +add/remove block.seaweedfs.com/swblockvolume-protection on owned +SwBlockVolume objects, using the Phase 42 admission boundary and the +delete-safety decision model. +``` + +The scope must remain narrow: + +```text +finalizer only; +operator-status remains status/events-only; +no cleanup execution; +no PVC/PV/workload/storage mutation; +no rebuild/failback/backup/NVMe. +``` + +## Next + +Phase 43: first bounded finalizer mutation in the product path. The initial +slice should add the lifecycle-owner identity and idempotently add the protection +finalizer to owned `SwBlockVolume` objects while preserving the Phase 42 +forbidden-patch matrix. diff --git a/seaweed-block/internal/docs/finished-plans/phase43_finishedplan_bounded_finalizer_lifecycle.md b/seaweed-block/internal/docs/finished-plans/phase43_finishedplan_bounded_finalizer_lifecycle.md new file mode 100644 index 0000000000..3f3bc28140 --- /dev/null +++ b/seaweed-block/internal/docs/finished-plans/phase43_finishedplan_bounded_finalizer_lifecycle.md @@ -0,0 +1,95 @@ +# Phase 43 Finished Plan: Bounded SwBlockVolume Finalizer Lifecycle + +Status: closed on 2026-06-15. + +Branch: `phase41-lifecycle-owner-foundation` + +## Outcome + +Phase 43 ships the first real bounded Kubernetes lifecycle mutation in Seaweed +Block: + +```text +add/remove only block.seaweedfs.com/swblockvolume-protection on owned +SwBlockVolume objects, admitted by Kubernetes VAP and gated by delete-safety. +``` + +This closes the control-plane loop that Phase 42 prepared: + +```text +status evidence -> delete-safety decision -> admitted lifecycle owner -> +finalizer mutation -> Kubernetes Event / observable object state +``` + +## Delivered + +- Product lifecycle-owner command: + - `sw-block ops lifecycle-owner`, + - separate identity from operator-status, + - dry-run capable, + - periodic reconcile capable. +- Helm lifecycle-owner packaging: + - disabled by default, + - separate Deployment, ServiceAccount, RBAC, + - ValidatingAdmissionPolicy and binding for finalizer-only patch shape. +- Finalizer add: + - adds exactly `block.seaweedfs.com/swblockvolume-protection`, + - preserves existing foreign finalizers, + - idempotent on repeated reconcile, + - emits bounded `finalizer_added` Events. +- Delete-safety-gated finalizer release: + - missing delete-safety -> hold, + - blocked residue -> hold, + - stale/unknown evidence -> hold, + - clean/releasable evidence -> remove only the Seaweed Block protection + finalizer, + - preserves foreign finalizers, + - emits `finalizer_released` or hold-reason Events. +- Operator-status boundary preserved: + - remains status/events-only, + - no main-object patch power, + - no finalizer mutation Events from operator-status. + +## QA Evidence + +- D1/D2 finalizer add: + `internal/docs/qa-assignments/phase43-d1-d2-lifecycle-owner-finalizer-add-qa-signoff.md` + - QA PASS on m02 (`k3s v1.34.4+k3s1`) with real + ValidatingAdmissionPolicy enforcement, + - lifecycle-owner finalizer add works and is idempotent, + - VAP denies spec/status/labels/annotations/ownerReferences/foreign/mixed + mutations, + - operator-status cannot patch main `SwBlockVolume`, + - lifecycle-owner has no workload/storage mutation power. +- D3/D4 finalizer release: + `internal/docs/qa-assignments/phase43-d3-d4-lifecycle-owner-finalizer-release-qa-signoff.md` + - QA PASS on m02 with fresh build from `252ec35`, + - missing/blocked/stale delete-safety holds finalizer, + - clean/releasable delete-safety releases only the protection finalizer, + - foreign finalizer remains, + - spec/status/labels/annotations unchanged, + - no cleanup executed, + - cleanup verifier reports zero residue. + +## Non-Claims + +Phase 43 does not execute cleanup, delete PVC/PV/workload/storage resources, +repair iSCSI/multipath/hostPath residue, rebuild replicas, fail back primaries, +perform backup/restore, implement NVMe ANA parity, or claim production SLOs. + +The lifecycle-owner owns only the Seaweed Block `SwBlockVolume` protection +finalizer. It does not own PVC/PV finalizers. + +## Required Carry-Forward + +Phase 44 should validate the whole user-visible delete lifecycle as an +integrated path: + +```text +install -> first PVC -> SwBlockVolume protected -> delete requested -> +blocked residue holds finalizer -> clean evidence releases finalizer -> +object deletion completes -> uninstall cleanup leaves zero residue +``` + +The close gate should prove CRD status, Events, report/dashboard/explain, and +actual Kubernetes object state agree across the hold and release transitions. diff --git a/seaweed-block/internal/docs/finished-plans/phase44_finishedplan_delete_lifecycle_close_gate.md b/seaweed-block/internal/docs/finished-plans/phase44_finishedplan_delete_lifecycle_close_gate.md new file mode 100644 index 0000000000..afd0119eac --- /dev/null +++ b/seaweed-block/internal/docs/finished-plans/phase44_finishedplan_delete_lifecycle_close_gate.md @@ -0,0 +1,118 @@ +# Phase 44 Finished Plan: Delete Lifecycle Close Gate + +Status: closed on 2026-06-17. + +Branch: `phase41-lifecycle-owner-foundation` + +## Outcome + +Phase 44 closes the integrated Kubernetes delete lifecycle for the bounded +`SwBlockVolume` protection finalizer: + +```text +install -> first PVC -> CSI-created SwBlockVolume CR -> lifecycle-owner +protection finalizer -> operator-status evidence -> delete request -> +hold on missing/blocked evidence -> release on clean evidence -> CR deletion +completes -> uninstall leaves zero residue +``` + +This is the first end-to-end product path where CSI identity ownership, +operator-status judgment, lifecycle-owner mutation, Kubernetes Events, user +surfaces, and cleanup evidence compose as one operation. + +## Delivered + +- CSI creates or updates the `SwBlockVolume` identity CR after successful + `CreateVolume` when operator/lifecycle surfaces are enabled. +- Ownership is split cleanly: + - CSI owns metadata/spec identity for the `SwBlockVolume`, + - operator-status owns `.status` and Events, + - lifecycle-owner owns only + `block.seaweedfs.com/swblockvolume-protection`. +- Normal Day-1 PVC path now creates the protected CR without manual stubs. +- operator-status projects live delete-safety for terminating + `SwBlockVolume` objects. +- `cleanup-summary.txt` remains external evidence: + - operator-status, report, dashboard, and explain can consume it, + - no controller runs cleanup, + - unsafe or missing evidence holds the finalizer, + - clean fresh evidence allows release. +- lifecycle-owner releases only the Seaweed Block protection finalizer and + preserves foreign finalizers. +- Deleting CR status is negative-first: + - missing evidence -> `Ready=Unknown`, + - blocked residue -> `Ready=False` / `Blocked=True`, + - no false `Ready=True`. +- Multi-volume delete-safety is isolated: + - held volumes do not block releasable volumes, + - non-deleting protected volumes are not released, + - Events/status keep the correct volume identity. +- operator-status skips a disappeared CR status patch instead of aborting the + whole reconcile. +- `ops explain volume --cleanup-summary` can explain a deleting CR even when + the live inventory no longer contains the managed volume. + +## QA Evidence + +- D2 integrated SwBlockVolume creation and protection: + `internal/docs/qa-assignments/phase44-d2-integrated-swblockvolume-cr-qa-signoff.md` + - QA PASS on m02 (`k3s v1.34.4+k3s1`) with real + ValidatingAdmissionPolicy enforcement, + - normal PVC creates exactly one `SwBlockVolume` CR, + - lifecycle-owner adds exactly one protection finalizer, + - operator-status writes `Ready=True` / `first_volume_verified`, + - CSI/operator-status/lifecycle-owner RBAC ownership split holds, + - cleanup verifier reports zero residue. +- D3/D4 delete hold/release close gate: + `internal/docs/qa-assignments/phase44-d3-d4-delete-lifecycle-close-gate-qa-signoff.md` + - QA PASS on m02 with fresh images from `8669d4a`, + - missing cleanup evidence holds the finalizer, + - blocked residue evidence holds the finalizer, + - clean fresh evidence releases only the protection finalizer, + - CR deletion completes, + - no cleanup is executed by the controllers, + - final cleanup verifier reports zero residue. +- D5/D6 surface agreement and multi-volume isolation: + `internal/docs/qa-assignments/phase44-d5-d6-surface-isolation-close-qa-signoff.md` + - QA PASS on m02 with fresh images from `874d0cf`, + - report/dashboard agree with CRD status for deleting volumes, + - multi-volume hold/release is isolated, + - disappeared CR status patch is skipped, + - final cleanup verifier reports zero residue. + +Post-QA polish is committed in `041b084`: `ops explain` now renders deleting CR +delete-safety from `--cleanup-summary` instead of returning "not found in +inventory". + +## Release Claim + +Phase 44 supports this narrow claim: + +```text +Seaweed Block can protect its SwBlockVolume CR with a bounded finalizer and +release that finalizer only after externally supplied cleanup evidence is clean. +``` + +The claim includes the integrated Day-1 path, CRD status, Events, report, +dashboard, explain, multi-volume isolation, and zero-residue cleanup verification +on the validated lab. + +## Non-Claims + +Phase 44 does not claim automatic cleanup execution, PVC/PV/workload deletion, +host repair, iSCSI/multipath repair, returned-replica rebuild, failback, +backup/restore, NVMe ANA parity expansion, upgrade execution, production SLOs, +or broad cluster compatibility. + +The lifecycle-owner owns only the Seaweed Block `SwBlockVolume` protection +finalizer. It does not own PVC/PV finalizers. + +## Required Carry-Forward + +- Publish `sw-block` and `sw-block-csi` images from the same commit before a + public release note claims the integrated lifecycle path. +- Run a release-candidate smoke against the pinned images if image digests + change after `041b084`. +- Keep the release wording narrow: bounded finalizer lifecycle and + evidence-driven hold/release, not automatic cleanup or full operator + automation. diff --git a/seaweed-block/internal/docs/product-management-plan.md b/seaweed-block/internal/docs/product-management-plan.md index 7165ec4372..9033050273 100644 --- a/seaweed-block/internal/docs/product-management-plan.md +++ b/seaweed-block/internal/docs/product-management-plan.md @@ -6,6 +6,12 @@ Its job is to keep product goals, prioritized engineering tasks, and evidence links in one place so the team does not jump from every new finding directly into code. +Status note, 2026-06-01: this file is now a product-background document, not +the active execution plan. Active execution is tracked in +`internal/docs/current-plan.md`; release sequencing is tracked in +`internal/docs/product-roadmap.md`. The immediate recommendation section below +has been refreshed to avoid the older RF=2 Stage 1 pointer. + ## Product Goal Build a small, understandable Kubernetes block storage service for teams that @@ -172,31 +178,33 @@ non-claims first or stop. ## Current Immediate Recommendation -The light-use operations ladder is now closed through same-node placement, -attach, durable restart, and safe RF=2 refusal: +The light-use operations ladder has moved beyond the original RF=2 Stage 1 +plan. The current alpha line now includes Helm installation, first PVC, +multi-volume RF=3 gates, restart persistence, read-only status/report/dashboard +surfaces, deterministic cleanup, and negative-first status vocabulary. -- first-volume runbook and failure bundle are closed, -- cluster inventory is closed, -- product-owned generated workload lifecycle is closed, -- durable RF=1 restart/reattach is closed, -- same-node alpha attach and placement visibility are closed, -- RF=2 mounted baseline and primary-failure safe refusal are closed. - -The next concrete product step is: +The next concrete product step is not a new user feature. It is release +hardening: ```text -Build Stage 1 safe Kubernetes recovery: prove through the app/PVC path that an -RF=2 peer becomes promotion-ready, a controlled primary failure triggers safe -authority movement, CSI/node reattaches on pod recreate, and the reader verifies -the same data; otherwise fail closed with a precise blocker. +Finish Phase 34 test realism: prove live negative paths and dirty storage faults +do not produce false Ready=True, then align release claims with that evidence. ``` Current state: -- Protocol-level iSCSI/NVMe failover gates exist, but transparent host - multipath is Stage 2, not the current claim. -- Current Stage 1 has candidate durable frontier evidence, but still lacks the - mounted writer required frontier and positive CSI/pod-recreate recovery gate. -- The active plan is `RF=2 Promotion-Ready Recovery MVP`. -- Stage 1.5 usability hardening should be planned in parallel, but it must not - dilute Stage 1's minimum HA product line. +- Phase 33 failure hardening is closed. +- Phase 34 is active under `internal/docs/current-plan.md`. +- D2 live status-endpoint-unreachable and D3 restart convergence are validated. +- D4 SmartWAL corruption is validated for the core release-relevant contract: + after real WAL corruption, the product no longer reports false `Ready=True`. + The run `20260601-020747-5a1f` passed 30/30 after fixes through storage, + blockvolume readiness, master projection, and ManagedVolume projection tests. +- The remaining Phase 34 work is closeout and release wording. A product + follow-up remains to surface the specific `wal_integrity_fault` reason rather + than generic `unknown`. + +After Phase 34 closes, the next product decision is whether to cut the next +alpha hardening release or start the next larger loop: productized operator +lifecycle, model/control-plane tightening, rebuild/failback, NVMe ANA parity, or +backup/snapshot workflow. The roadmap should choose one loop at a time. diff --git a/seaweed-block/internal/docs/product-roadmap.md b/seaweed-block/internal/docs/product-roadmap.md index 602a92a9b2..a3aa4def38 100644 --- a/seaweed-block/internal/docs/product-roadmap.md +++ b/seaweed-block/internal/docs/product-roadmap.md @@ -31,20 +31,44 @@ This is the short internal roadmap. Keep it current and readable. iSCSI configuration, StorageClass, readiness output, first-volume smoke, local read-only report/dashboard, and uninstall hygiene. Phase 25 closed this release target on 2026-05-22. -- `v0.4-beta-candidate`: Operator lifecycle. Add a Kubernetes-native control - plane with CRDs/Conditions/Events for install, node eligibility, volume - lifecycle, recovery observation, safe cleanup, and eventually gated repair or - rebuild workflows. This is the first release boundary that can credibly feel - like a complete Kubernetes product loop rather than an install script. +- `v0.3.4-alpha`: Helm lifecycle, restart persistence, read-only operations + surface, deterministic cleanup, and negative-first status vocabulary merged + through PR #50 (`8102cf3`) on 2026-05-27. +- `v0.3.5-alpha` candidate: TestOps failure hardening. Expand release proof + from happy-path gates to negative paths: blocked/stale/unreachable status + surfaces, support-bundle replay under corrupt/partial evidence, failed-run + cleanup, and multi-volume interference checks. Phase 33 closed this scope; + release packaging remains a separate decision. +- `v0.3.6-alpha`: Phase 34 test realism and anti self-proving gates. Selected + replay or summary-grep checks were upgraded into independent live/dirty + evidence: live status endpoint unreachable, restart convergence, SmartWAL + corruption refusal, and targeted cross-validation between helper summaries + and product or Kubernetes facts. Phase 34 closed on 2026-06-02. +- `v0.4-beta-candidate`: Kubernetes-native read-only operator foundation. Phase + 35 closed this scope on 2026-06-04 with CRDs, Conditions, Events, a + status-only controller, stable Event identity, stale/blocked status gates, + and read-only RBAC proof. This is the first release boundary that can + credibly feel like a normal Kubernetes product loop rather than an install + script. Mutating workflows such as repair, rebuild, failback, delete safety, + automatic cleanup, and CR object ownership come after the read-only status + contract is stable. +- Closed on 2026-06-06: Phase 36 Productized Operations Actionability. It uses + the Phase 35 CRD/status/Event foundation to publish node readiness, support + evidence refs, cleanup visibility, safe next-step hints, and cross-surface + agreement. This remains read-only and does not add mutating operator + lifecycle. +- Active phase: Phase 37 Live Node Evidence Hardening. Keep it read-only and + bounded to live node blockers; do not extend it into mutating lifecycle. - Model hardening gate before the next large release: complete the ManagedVolume Operations Model under `internal/docs/protocol/` before expanding operator or broader HA claims. The goal is to prevent Kubernetes, CSI, authority, host-path, recovery, and future NVMe logic from becoming scattered scripts or unrelated small automata. -Do not skip from scripts directly to an operator. Helm should stabilize the -installation contract before an in-cluster controller owns upgrades and day-2 -lifecycle. +Do not skip from scripts directly to mutating operator lifecycle. Helm has +stabilized the installation contract, and Phase 35 added read-only CRD status, +Conditions, and Events. Any in-cluster controller ownership of upgrades, repair, +rebuild, delete safety, or cleanup must start as a separate gated phase. ### Alpha Preview @@ -121,8 +145,10 @@ lifecycle. - `helm install` + first PVC smoke + `sw-block ops report`, - local read-only `sw-block ops dashboard` over the same evidence, - `helm uninstall` plus explicit host cleanup verification. -- Later: v0.4 operator lifecycle. Introduce CRDs/Conditions/Events and scoped - reconciliation only after the Helm contract is stable. +- Next major milestone: Phase 35 read-only operator foundation. Introduce + CRDs/Conditions/Events and status-only reconciliation after the Helm contract + is stable. Keep mutating cleanup, delete finalizers, upgrade execution, and + repair/rebuild outside this first operator slice. ### Track B: iSCSI Frontend Stability @@ -159,7 +185,9 @@ lifecycle. documented mechanism, and support-bundle proof of fencing and data integrity. - Later: returned-replica rebuild/reintegration/failback, NVMe ANA Kubernetes multipath parity, stronger committed-frontier reporting, broad distro/host - compatibility, and longer soak under failure. + compatibility, and longer soak under failure. NVMe ANA parity should follow + the Kubernetes-native status foundation so ANA facts, path states, and + protocol-specific reasons project through the same CRD/Condition/Event model. ### Track E: Protocol / Backend Expansion @@ -198,6 +226,14 @@ lifecycle. volumes a first-class internal read model that composes K8s, CSI, authority, recovery, host path, workload, and evidence facts while keeping local controllers small and testable. +- Closed on 2026-06-04: Phase 35 turned the existing read-only operations model + into Kubernetes-native status: + - `SwBlockCluster` and `SwBlockVolume` CRDs, + - a status-only controller that writes `.status`, + - ManagedVolume Conditions projected into Kubernetes Conditions, + - Kubernetes Events for ready, blocked, stale-evidence, and WAL-integrity + transitions, + - tests proving the controller has no mutating storage authority. - Later: metrics, read-only dashboard hardening, conservative admin controls, enterprise operations, hosted validation, fleet automation, and cloud-scale test lifecycle. @@ -232,6 +268,10 @@ lifecycle. ManagedVolume model used by `sw-block ops report`. - Closed on 2026-05-22: Phase 25 packages that operations surface into the v0.3 Helm first-volume release story and validates docs/gates against it. +- Closed on 2026-06-04: Phase 35 implemented the first Kubernetes-native + operator foundation slice over this surface: CRDs, read-only `.status`, + Conditions, Events, stable Event identity, and read-only RBAC. It did not add + mutating admin workflows. - Seed landed: - `NewObservationDashboardHandler` serves `index.html`, `cluster-evidence.json`, `timeline.jsonl`, `summary.txt`, and `healthz`, @@ -284,7 +324,7 @@ credible light-use product: usability still depends too much on internal context. - Next: - add `kubectl get`-readable readiness/degraded/recovering/blocked conditions - with stable reason codes, + with stable reason codes through Phase 35 CRD status, - provide one-command support-bundle capture with minimum evidence for attach, failover, and cleanup diagnosis, - set conservative default timeout/retry profiles for iSCSI/NVMe/CSI paths, @@ -329,10 +369,217 @@ credible light-use product: - Current: runner scenarios write result/status bundles, but M01/M02 shared lab ownership is still mostly implicit. -- Next: add simple shared-drive control data for active runs, history, locks, - artifact pointers, commits, target nodes, and stale-run detection. -- Later: scenario library indexing, queueing, remote agents on lab nodes, - matrix scheduling, hosted validation, and discovery-agent ingestion. +- Closed: Phase 33 TestOps failure hardening. The runner and helpers now + exercise negative paths, collect useful failure snapshots, assert no false + Ready states, and prove cleanup/replay behavior after failed runs. +- Closed: Phase 34 test realism. Reduced self-proving gates by adding + independent cross-checks, live status-endpoint-unreachable injection, + restart convergence assertions, and one dirty storage failure: SmartWAL + corruption. The D4 gate is release-relevant because it checks whether dirty + storage evidence can still leak through as false `Ready=True`; it now passes + on the core contract. +- Later: shared-drive control data for active runs, scenario library indexing, + queueing, remote agents on lab nodes, matrix scheduling, hosted validation, + and discovery-agent ingestion. + +## Productized Operations Gap Priority + +These are the current operation gaps in priority order. Phase 35 closed the P0 +read-only status foundation; the remaining groups should become separate gated +phases rather than being mixed into the closed foundation. + +### P0: Become Kubernetes-Native For Read-Only Status + +1. CRD + status-only operator: + `SwBlockCluster`, `SwBlockVolume`, and `.status` writes only. Status: + closed in Phase 35. +2. Conditions writer: + project `Ready`, `Blocked`, `Recovering`, `Recovered`, `EvidenceStale`, and + `CleanupRequired` from ManagedVolume facts. Status: core vocabulary closed; + cleanup projection remains follow-up. +3. Kubernetes Events: + emit normal/warning Events such as `VolumeReady`, + `CsiNodeImagePullFailed`, `WalIntegrityFault`, and `EvidenceStale`. Status: + closed for read-only status Events. + +### P1: Make Operations Actionable + +4. Node readiness/preflight status: + iSCSI, multipath, image readiness, hostPath readiness, and observed version + under `SwBlockCluster.status.nodes[]`. Status: Phase 36 validated positive + read-only node readiness and replay-only missing-image blockers. Live + negative node evidence remains Phase 37. +5. Support-bundle pointers: + keep the CLI collection path, but expose evidence refs and suggested + commands from status. Status: closed in Phase 36. +6. Cleanup visibility: + `CleanupRequired=True`, residue type, and safe next step. Do not automate + cleanup yet. Status: closed in Phase 36. +7. Surface agreement: + CRD status, Events, report, dashboard, operator-snapshot, and explain must + agree on healthy, blocked, stale, cleanup-required, and multi-volume paths. + Status: closed in Phase 36. Live operational follow-ups remain for + build-host CSI image-import evidence, loopback publish-target documentation, + and force-delete iSCSI node DB residue visibility. + +### P2: Enter Mutating Lifecycle Carefully + +8. Finalizers and delete safety for PVC/CRD lifecycle. +9. Upgrade/rollback status and drift reporting before upgrade execution. + +### P3: Advanced Day-2 Features + +10. Rebuild, reintegration, and failback. +11. Backup, snapshot, and restore. + +NVMe ANA parity is important, but it should not be the next plan. It should +reuse the Phase 35 status foundation so protocol-specific path state does not +become another isolated status model. + +## Capability And Model Maturity Snapshot + +This section is the product-state checkpoint after the Phase 35/36 operations +push. It exists to stop the roadmap from becoming an unbounded sequence of +small operations fixes. + +### Current Block Capabilities + +The product can already demonstrate a narrow but real Kubernetes block-storage +loop: + +- Helm install on supported lab clusters. +- CSI dynamic PVC provisioning. +- App pod mount, write, read, and replacement-reader verification. +- iSCSI frontend with Linux initiator and dm-multipath/ALUA gates. +- RF=3 multi-volume lab path with independent volume identity, primary, and + publish target. +- CSI reattach recovery with pod recreate. +- Mounted transparent failover on the gated Stage-2 iSCSI ALUA path. +- HostPath restart persistence for supported gates, including authority + preservation after promotion. +- Dirty-evidence protection: stale/unreachable/corrupt evidence does not become + false `Ready=True`. +- Strict cleanup verification across Kubernetes resources, iSCSI sessions, + iSCSI node DB records, multipath, dmsetup, product processes, and hostPath + residue. + +### Current Kubernetes And Operations Capabilities + +- Helm is the primary install path; scripts remain development/fallback tools. +- `sw-block ops generate-helm-values` can derive Day-1 Helm values from the + target Kubernetes cluster. +- Read-only CLI/report/dashboard/support-bundle flows are established. +- `SwBlockCluster` and `SwBlockVolume` CRDs exist with status subresources. +- The optional operator-status controller writes `.status` and Kubernetes + Events only. +- Positive/read-only node readiness, support evidence refs, cleanup visibility, + safe next-step hints, and surface agreement are QA-validated under the + read-only model. Live negative node blockers remain Phase 37. + +### Model Convergence State + +The control-plane model is materially better than the earlier script-centered +shape, but it is not finished. See +`internal/docs/protocol/control-structure-effectiveness-review.md` for the +review standard that separates real capability closure from semantic-only model +work. + +Converged: + +- `ManagedVolume` is the shared semantic object for volume status. +- CRD status, Events, report, dashboard, `operator-snapshot.json`, and + `ops explain` share the same Condition/reason vocabulary. +- The design pattern is now explicit: + truth owner publishes facts; orchestration/status entity aggregates judgment; + executor remains bounded; evidence/timeline explains why the judgment is + allowed. +- Negative-first is enforced across status surfaces. + +Still incomplete: + +- Live node evidence does not yet derive all negative facts from real Kubernetes + node/image/CSI-driver state. +- Some volume-side fault reasons still need stronger end-to-end propagation to + user-visible surfaces. +- Mutating lifecycle actions now have a non-mutating lifecycle-owner contract + shape: action + precondition + invariant + executor + evidence. +- PVC lifecycle, blockvolume lifecycle, and Kubernetes attach lifecycle still + need a real lifecycle-owner component and API/admission proof before anything + mutates Kubernetes lifecycle objects. + +### Product Priority From Here + +The operations work can continue forever unless the next phases are bounded by +product risk. The recommended order is: + +1. **Phase 37: Live node evidence hardening.** Closed. + Kubernetes Ready/SchedulingDisabled, CSI node pod readiness, + CSIDriver/node-plugin registration, image-pull status, host-prereq replay, + and loopback target cross-node blockers are now projected through the shared + status surfaces. +2. **Phase 38: Lifecycle action model executable contract.** Closed. + Future actions now have facts, preconditions, invariants, allowed executor, + policy gate, evidence, and allow/reject decisions. It includes both a dry-run + action gate and a rejected-action gate. +3. **Phase 39: Delete-safety status boundary.** Closed. + Live QA proved the original RBAC-only finalizer boundary is not viable for + CRD finalizers: CRDs have no usable HTTP `/finalizers` endpoint, so + `metadata.finalizers` changes require main `patch swblockvolumes` + authorization. The chosen path is to keep operator-status status/events-only + and defer finalizer add/remove to a future lifecycle owner. +4. **Phase 40: Operator production hardening.** Closed. + The v0.4 beta foundation released Helm + PVC + status/events-only + operator-status, install drift visibility, delete-safety visibility, and + schema/RBAC conformance gates. +5. **Phase 41: Lifecycle owner foundation.** Closed. + Defines observer/lifecycle-owner/executor boundaries, keeps operator-status + status/events-only, defers finalizer mutation, and exposes dry-run + lifecycle-owner decisions for delete-safety. It does not ship deletion + protection. +6. **Phase 42: real lifecycle-owner API/admission gate.** Closed. + Before any finalizer add/remove, prove main-object patch confinement against + a real Kubernetes API with admission/RBAC. Only then consider a first + bounded mutation. +7. **Phase 43: first real lifecycle mutation.** Active. + Ship only the first bounded mutation: `SwBlockVolume` protection finalizer + add/remove with delete-safety preconditions. Do not include cleanup, rebuild, + failback, backup, or NVMe in the same phase. +8. **Phase 44 candidate: delete lifecycle close gate and Operation Layer v0.5 + release.** + Validate the full user path: install -> PVC -> status -> delete requested -> + blocked/releasable -> finalizer behavior -> cleanup evidence -> support + bundle -> uninstall zero residue. This is the release boundary for the + operation layer. +9. **Productized returned-replica rebuild/reintegration/failback.** + High product value. The engine/transport has rebuild and returned-replica + safety pieces; the remaining work is productization through the lifecycle + action model: live facts, judgment, action owner, fencing, status, Events, + and multi-volume QA gates. +10. **Backup/snapshot/restore and NVMe ANA parity.** + Important, but they should reuse the status/action model rather than create + another isolated control plane. + +### Effort Shape + +Approximate engineering effort if scope remains tight: + +- Live node evidence hardening: small/medium. Mostly observation ingestion, + projection tests, and live TestOps gates. Low mutation risk. +- Lifecycle action model review: medium. Mostly design and tests, but it should + block later mutating work from scattering logic across listeners/scripts. +- Delete-safety status: closed. Keeps delete safety visible without widening + operator-status mutation rights. +- Lifecycle-owner finalizers: medium/high. Cleaner than operator-status main + patch, but requires a separate lifecycle-owner component plus real + API/admission proof that only finalizers can be patched. +- Productized returned-replica rebuild/reintegration/failback: high. The + low-level rebuild/recovery pieces exist, but shipping it as a product feature + requires lifecycle ownership, authority/fencing status, returned-replica state + projection, and long-running multi-volume failure gates. +- Backup/snapshot/restore: high. Requires durable data semantics and user-facing + restore guarantees. +- NVMe ANA parity: medium/high. Protocol-specific work, but cheaper if it uses + the existing CRD/Condition/Event model. ## PR Cadence @@ -345,6 +592,36 @@ credible light-use product: ## Current Execution Pointer - Active work should be tracked in `internal/docs/current-plan.md`. +- Phase 35 closed the Kubernetes-native read-only operator foundation: + CRDs, status-only reconciliation, Conditions, Events, stable Event identity, + and read-only boundary tests. +- Phase 36 Productized Operations Actionability is closed. Positive/read-only + node readiness, support evidence pointers, cleanup visibility, and surface + agreement are QA-validated under the read-only control-plane model. Live + negative node evidence remains Phase 37. +- Phase 37 Live Node Evidence Hardening is closed. +- Phase 38 Lifecycle Action Model Executable Contract is closed. +- Phase 39 Delete-Safety Status Boundary is closed. +- Phase 40 Operator Production Hardening is closed and is the v0.4 beta release + boundary. +- Phase 41 Lifecycle Owner Foundation is closed. It is non-mutating: + finalizer add/remove is deferred, while lifecycle-owner dry-run decisions and + delete-safety preconditions are made visible. +- Phase 42 Lifecycle Owner API / Admission Gate is closed. It proved the + lifecycle-owner main-object patch boundary against a real Kubernetes + API/admission surface and preserved the delete-safety decision model. +- Active work is Phase 43 First Bounded Finalizer Mutation. It may add/remove + only the Seaweed Block `SwBlockVolume` protection finalizer, gated by + delete-safety. It must not execute cleanup or mutate PVC/PV/workloads/storage. +- Phase 41-44 are the Operation Layer v0.5 release train: lifecycle-owner + foundation, real API/admission proof, first bounded finalizer mutation, and + delete lifecycle close gate/release. +- The release-train contract is + `internal/docs/ref/operation-layer-v0.5-release-train.md`; the Phase 42 gate + draft is `internal/docs/ref/phase42-lifecycle-owner-api-admission-gate.md`. +- Do not start NVMe ANA parity, rebuild/failback, backup/restore, or mutating + recovery workflows by extending Phase 41. Pick those as separate gated phases + after the Operation Layer v0.5 train closes. - When the current plan closes, move it to `internal/docs/finished-plans/` with a phase/topic filename such as `phase1_finishedplan_frontend_protocol_readiness.md`. diff --git a/seaweed-block/internal/docs/protocol/README.md b/seaweed-block/internal/docs/protocol/README.md index 03395158e6..2ef4c150e3 100644 --- a/seaweed-block/internal/docs/protocol/README.md +++ b/seaweed-block/internal/docs/protocol/README.md @@ -58,6 +58,10 @@ engines that project from it. - [`operations-state-dependency-review.md`](./operations-state-dependency-review.md) defines the Phase 22 scope decision: operations v1 over a real product read model, not a pure dashboard pass or narrow protocol refactor. +- [`control-structure-effectiveness-review.md`](./control-structure-effectiveness-review.md) + reviews which parts of the control/model work have become real product + capability, which remain too semantic, and what proof is required before + approving more model work. ## Review Rule diff --git a/seaweed-block/internal/docs/protocol/control-structure-effectiveness-review.md b/seaweed-block/internal/docs/protocol/control-structure-effectiveness-review.md new file mode 100644 index 0000000000..f010d91219 --- /dev/null +++ b/seaweed-block/internal/docs/protocol/control-structure-effectiveness-review.md @@ -0,0 +1,267 @@ +# Control Structure Effectiveness Review + +Date: 2026-06-06 + +Status: working review for post-Phase 36 planning. + +## Purpose + +This review answers a product risk raised after the Phase 35/36 operations push: + +```text +Are we improving the real control loop, or are we creating semantic loops that +sound coherent but do not add product capability? +``` + +The concern is valid. Seaweed Block spent significant effort building engine and +model vocabulary. Some of that effort became real gates and user-visible +behavior; some remains a design frame that must not be mistaken for shipped +capability. + +## Review Standard + +A control/model change is effective only if it connects all five layers: + +```text +1. Live fact source +2. Product judgment +3. User-visible status or action +4. Independent test / TestOps gate +5. Failure evidence when the judgment is wrong or incomplete +``` + +If it only improves vocabulary or diagrams, it is useful design context but not +product capability. + +## What Became Real Capability + +### ManagedVolume Read Model + +Real capability: + +- `ManagedVolume` facts now feed report, dashboard, `operator-snapshot.json`, + `ops explain`, CRD status, and Events. +- Blocked, stale, cleanup-required, and healthy paths share Condition/reason + vocabulary. +- Phase 32, 35, and 36 gates proved no false `Ready=True` across multiple + surfaces. + +Why it is not purely abstract: + +- It changed code under `core/ops`. +- It changed Helm/operator-status surfaces. +- It produced QA-visible failures when fields disagreed or when Events aborted + reconciliation. +- It made support bundles replayable without SSH/log spelunking. + +Remaining limitation: + +- It is still mostly a read model. It does not yet own mutating lifecycle + decisions. + +### Negative-First Status + +Real capability: + +- `status_endpoint_unreachable` becomes `Ready=Unknown` / + `EvidenceStale=True`. +- `csi_node_image_pull_failed` becomes `Ready=False` / `Blocked=True`. +- SmartWAL corruption no longer leaks as false `Ready=True`. + +Why it is real: + +- Dirty/live gates failed before fixes and passed after fixes. +- D4 SmartWAL corruption pushed fixes through storage, blockvolume readiness, + and blockmaster projection. + +Remaining limitation: + +- Some specific reasons still terminate as generic `unknown` unless the fault + is carried through all layers. + +### Status-Only Operator Foundation + +Real capability: + +- CRDs exist. +- Optional controller writes `.status` and Events. +- RBAC prevents workload/storage/spec mutation. +- Event identity is bounded. +- Phase 36 adds node readiness, cleanup visibility, support refs, and safe next + steps. + +Why it is real: + +- It runs in Kubernetes. +- Live QA validated `/status` writes and forbidden mutation verbs. +- QA caught and revalidated schema casing and Event conflict bugs. + +Remaining limitation: + +- It does not create CR objects. +- It does not own finalizers. +- It does not execute cleanup, repair, rebuild, failback, or upgrade. + +## Where The Model Is Still Too Semantic + +### Engine Vocabulary Without Product Closure + +The engine docs define facts, context, invariants, actions, executors, and +evidence. That vocabulary is useful, but it becomes too abstract when a feature +does not prove: + +- which live component owns each fact, +- which code computes the product judgment, +- which executor is allowed to act, +- which user-visible status proves the result, +- which TestOps gate fails if the model is bypassed. + +Risk: + +```text +logical closure in docs +but no capability closure in product +``` + +### Action Model Is Not Yet Real + +Read-only action hints exist, but mutating actions are not implemented as a +complete loop: + +```text +facts -> preconditions -> allowed action -> executor -> result -> evidence +``` + +Current state: + +- `allowed_actions[]` and safe next steps are useful for explanation. +- They do not yet protect a real executor from unsafe mutation. + +Therefore, any next mutating phase must make the action model concrete before +adding broad lifecycle features. + +### Live Node Evidence Gap + +Phase 36 projects node readiness, but live negative node facts are incomplete: + +- missing CSI image / unregistered CSI driver can be masked, +- some negative node paths are replay-only, +- loopback/cross-node risk is not fully represented live. + +This is not a philosophical issue. It is the next practical blocker because +future actions will depend on node truth. + +## Product Direction + +The direction is not "continue operations fixes forever". + +The direction is: + +```text +make the read-only control loop truthful +-> define the action loop +-> implement one bounded mutating lifecycle slice +-> then add larger protocol/data features +``` + +This explains why NVMe ANA, rebuild/failback, and backup/restore should not be +next. They would add more state and more failure modes before the existing +control loop can reliably say what is true and what action is safe. + +## Recommended Next Phases + +### Phase 37: Live Node Evidence Hardening + +Goal: + +Make node readiness blockers real, not replay-only, without expanding into a +general node-operations phase. + +Required live facts: + +- Kubernetes Node Ready / SchedulingDisabled. +- CSI node pod readiness. +- CSIDriver and node-plugin registration. +- Required image presence or image-pull status. +- iSCSI and multipath readiness. +- loopback publish-target cross-node blocker. + +Why first: + +- Read-only, low mutation risk. +- Directly improves status trust. +- Prevents future operator actions from executing on false node assumptions. + +Estimated effort: small/medium. + +### Phase 38: Lifecycle Action Model Review + +Goal: + +Turn the semantic action model into a concrete, executable contract before +mutation. + +Required output: + +- action types, +- fact requirements, +- preconditions, +- invariants, +- allowed executor, +- idempotency/retry behavior, +- failure status, +- evidence emitted, +- TestOps or unit/component gate for at least one no-op/dry-run action and one + rejected action. + +Why second: + +- It prevents finalizer/delete safety from becoming another local script with + nicer names. +- It prevents the review from becoming another semantic-only document. + +Estimated effort: medium. + +### Phase 39: Finalizer / Delete Safety + +Goal: + +Implement the first bounded mutating operator slice. + +Scope: + +- protect PVC/CRD deletion when residue would remain, +- remove or block deletion with explicit status, +- prove idempotency and cleanup evidence, +- keep repair/rebuild/failback out. + +Why third: + +- It is Kubernetes-product critical. +- It is smaller and safer than rebuild/failback. +- It validates the action model against a real executor. + +Estimated effort: medium/high. + +## Review Gate For Future Model Work + +Before approving a new "model" phase, require a one-page answer: + +```text +What live failure or user confusion does this model remove? +Which current code paths will change? +Which product status/action becomes more correct? +Which gate would fail before the model change and pass after? +What is explicitly still not claimed? +``` + +If those cannot be answered, the work is probably semantic cleanup rather than +product hardening. + +## Bottom Line + +The recent control-model work was not wasted: it produced real read-only +operations capability and caught real bugs. But the model is only half closed. +The next value is not more vocabulary. The next value is making the fact/action +loop concrete enough that the first mutating lifecycle behavior can be safely +implemented. diff --git a/seaweed-block/internal/docs/protocol/finalizer-delete-safety-contract.md b/seaweed-block/internal/docs/protocol/finalizer-delete-safety-contract.md new file mode 100644 index 0000000000..6fb3951d58 --- /dev/null +++ b/seaweed-block/internal/docs/protocol/finalizer-delete-safety-contract.md @@ -0,0 +1,153 @@ +# Finalizer Delete Safety Contract + +Status: Phase 39 D1 contract. + +## Goal + +Define the first bounded mutating operator behavior before implementing it: +`SwBlockVolume` finalizer/delete safety. + +The operator may eventually patch only: + +```text +SwBlockVolume.metadata.finalizers +SwBlockVolume.status +Kubernetes Events +``` + +It must not delete or mutate PVCs, PVs, Pods, Deployments, StorageClasses, +Helm releases, images, iSCSI state, multipath state, dmsetup devices, hostPath +data, replica authority, rebuild/failback state, backup, or restore state. + +## Finalizer + +```text +block.seaweedfs.com/swblockvolume-protection +``` + +The finalizer protects the Seaweed Block lifecycle object from disappearing +while evidence says deletion is unsafe or unknown. + +It does not claim ownership of the user PVC lifecycle. PVC finalizers are out of +scope for Phase 39. + +## Action Contract + +Finalizer release is represented as an action decision using the Phase 38 +vocabulary: + +```text +action_type=safe_k8s.release_swblockvolume_finalizer +decision=allowed|rejected|unknown +``` + +The action is allowed only when the delete state is `releasable`. Residue or no +active delete request rejects the action. Missing or stale cleanup evidence is +`unknown`, not allowed. + +## Delete States + +| State | Meaning | +|---|---| +| `not_requested` | No delete request is active. | +| `requested` | Delete request exists; evidence has not yet been classified. | +| `blocked` | Delete was requested, and cleanup evidence proves residue or unsafe state. | +| `releasable` | Delete was requested and cleanup evidence is clean. The operator may remove the finalizer. | +| `released` | Finalizer removal has been observed or emitted as an event. | + +## Required Facts + +The delete decision requires: + +```text +identity.volume_id +identity.pvc_name +identity.pv_name +kubernetes.swblockvolume.deletion_timestamp +cleanup.status +cleanup.k8s_residue_count +cleanup.iscsi_residue_count +cleanup.multipath_residue_count +cleanup.process_residue_count +cleanup.hostpath_residue_count +``` + +If cleanup evidence is missing, the safe decision is: + +```text +state=requested +decision=unknown +reason=cleanup_evidence_missing +safe_next_action=observe.verify_cleanup +``` + +If cleanup evidence is stale, the safe decision is: + +```text +state=requested +decision=unknown +reason=cleanup_evidence_stale +safe_next_action=observe.verify_cleanup +``` + +If residue evidence exists, the safe decision is: + +```text +state=blocked +decision=rejected +reason= +safe_next_action=observe.verify_cleanup +``` + +If cleanup evidence is clean, the safe decision is: + +```text +state=releasable +decision=allowed +reason=finalizer_releasable +``` + +## Evidence + +The release evidence is: + +```text +cleanup-summary.txt with cleanup_status=ok and all residue counts 0 +``` + +Blocking evidence may include: + +```text +cleanup-summary.txt +iscsi node/session residue +multipath maps +dmsetup devices +Kubernetes generated resources +hostPath residue +process residue +``` + +## Non-Claims + +Phase 39 D1 does not implement mutation. Later D3-D5 may implement bounded +finalizer mutation, but still do not claim: + +- PVC finalizer ownership, +- automatic cleanup execution, +- PV/PVC deletion, +- Pod/Deployment deletion, +- iSCSI or multipath mutation, +- hostPath deletion, +- promotion/fencing/rebuild/failback, +- backup/snapshot/restore, +- NVMe ANA lifecycle. + +## Review Rule + +Any future implementation must keep this invariant: + +```text +The operator can release a SwBlockVolume finalizer only after the delete-safety +decision is releasable. If evidence is missing or residue remains, deletion is +blocked with status, reason, event, evidence refs, and a non-mutating next step. +``` diff --git a/seaweed-block/internal/docs/protocol/operator-readiness-contract.md b/seaweed-block/internal/docs/protocol/operator-readiness-contract.md index 7e126a52a4..2432cb4f86 100644 --- a/seaweed-block/internal/docs/protocol/operator-readiness-contract.md +++ b/seaweed-block/internal/docs/protocol/operator-readiness-contract.md @@ -1,6 +1,7 @@ # Operator Readiness Contract -Status: Phase 23 seed. Read-only contract only; no operator implementation. +Status: Phase 37 D1. Read-only CRD/status contract plus actionable operations +fields. The controller may publish status and Events only. ## Purpose @@ -8,7 +9,7 @@ This document defines how the Phase 22 `ManagedVolume` read model can feed a future Kubernetes operator without letting the operator rediscover volume state or bypass authority. -The contract is: +The base contract is: ```text ManagedVolumeProjection @@ -20,11 +21,39 @@ ManagedVolumeProjection It is not: -- a CRD schema, - a controller loop, - a mutating admin workflow, - a repair/rebuild/failback implementation. +Phase 36 extends the same contract with actionable read-only operations fields: + +```text +node readiness facts +-> SwBlockCluster.status.nodes[] +support/evidence pointers +-> SwBlockCluster.status.supportBundleRefs[] / evidenceRefs[] +cleanup verifier facts +-> SwBlockCluster.status.cleanup + CleanupRequired condition +safe next-step hints +-> SwBlockCluster.status.safeNextSteps[] +``` + +These fields are still observation and advice. They do not transfer lifecycle +ownership to the operator. + +Phase 37 tightens the node-readiness side of the contract. Node status must be +derived from live Kubernetes, CSI, image, host-prerequisite, and publish-target +facts, not replay-only bundles or helper summaries. + +The Phase 35 D1 CRD schema lives in: + +- `charts/seaweed-block/crds/swblockclusters.block.seaweedfs.com.yaml` +- `charts/seaweed-block/crds/swblockvolumes.block.seaweedfs.com.yaml` + +The status-only RBAC seed lives in: + +- `charts/seaweed-block/templates/operator-status-rbac.yaml` + ## Source Of Truth The future operator must consume `ManagedVolumeProjection` or the equivalent @@ -41,6 +70,9 @@ Truth ownership remains: | Replica durability | blockvolume / master evidence | expose readiness and blockers | | Host path | host initiator/kernel tools | expose transparent path state | | Workload check | user/TestOps/app evidence | expose data-check proof | +| Node readiness | Kubernetes + preflight/verifier evidence | expose schedulability, image, iSCSI, multipath, and hostPath readiness | +| Cleanup residue | cleanup verifier / host evidence | expose residue type and safe next step | +| Support bundle | CLI/TestOps bundle collector | expose evidence refs and collection/replay commands | The operator may publish Conditions/Events. It may not mint authority or decide promotion. @@ -65,13 +97,100 @@ The contract contains: - `events[]` - `allowed_actions[]` -All Phase 23 actions are non-executing: +The Kubernetes CRD projection keeps the same vocabulary: + +| ManagedVolume Contract | CRD Status Path | +|---|---| +| `status.volume_id` | `SwBlockVolume.status.volumeID` | +| `status.pvc_name` | `SwBlockVolume.status.pvcName` | +| `status.status` | `SwBlockVolume.status.status` | +| `status.reason_code` | `SwBlockVolume.status.reasonCode` | +| `status.conditions[]` | `SwBlockVolume.status.conditions[]` | +| `status.non_claims[]` | `SwBlockVolume.status.nonClaims[]` | +| `status.evidence_refs[]` | `SwBlockVolume.status.evidenceRefs[]` | +| `allowed_actions[]` | `SwBlockVolume.status.allowedActions[]` | + +Cluster-level aggregate fields map to `SwBlockCluster.status.*`: + +- `nodeCount` +- `nodes[]` +- `volumeCount` +- `readyVolumeCount` +- `blockedVolumeCount` +- `staleVolumeCount` +- `conditions[]` +- `evidenceRefs[]` +- `supportBundleRefs[]` +- `cleanup` +- `safeNextSteps[]` + +Phase 36/37 cluster node status fields are: + +| Field | Owner Input | Meaning | Stability | +|---|---|---|---| +| `status.nodes[].name` | Kubernetes / inventory | product node identity | stable | +| `status.nodes[].kubernetesNode` | Kubernetes API | Kubernetes node name when known | stable | +| `status.nodes[].internalIP` | Kubernetes API / inventory | observed node IP | stable | +| `status.nodes[].schedulable` | Kubernetes API | scheduling availability fact | stable | +| `status.nodes[].ready` | Kubernetes API / heartbeat | node Ready fact | stable | +| `status.nodes[].status` | operator-status aggregate | ready/blocked/unknown-style node status | provisional | +| `status.nodes[].reasonCode` | operator-status aggregate | stable reason for non-ready node | provisional | +| `status.nodes[].conditions[]` | operator-status aggregate | Kubernetes-style node readiness conditions | provisional | +| `status.nodes[].evidenceRefs[]` | evidence producer | supporting artifact paths | stable | + +Phase 36 introduced the initial node reason codes `node_ready`, +`node_not_ready`, `node_scheduling_disabled`, and `image_missing_on_node`. + +Phase 37 adds the live node blocker vocabulary: + +| Reason Code | Meaning | +|---|---| +| `csi_node_pod_not_ready` | CSI node pod is absent, not Ready, or blocked by image/runtime state | +| `csi_driver_not_registered` | CSIDriver or per-node CSINode driver registration is missing | +| `iscsi_prereq_missing` | node iSCSI prerequisite evidence is missing or unhealthy | +| `multipath_prereq_missing` | node multipath prerequisite evidence is missing or unhealthy | +| `publish_target_loopback_cross_node` | loopback publish target would be consumed from another node | + +The Phase 37 live node evidence contract is pinned in +`core/ops.LiveNodeEvidenceFactContract()`. Each fact names one authority, +one participant, a stability level, and the user-visible projection surface. +The contract is passive and read-only; it does not authorize probes or +operator-executed host changes. + +Phase 36 cleanup status fields are: + +| Field | Owner Input | Meaning | Stability | +|---|---|---|---| +| `status.cleanup.status` | cleanup verifier | `ok` or `failed` cleanup verdict | stable | +| `status.cleanup.*ResidueCount` | cleanup verifier | residue counters by category | stable | +| `status.cleanup.failureCount` | cleanup verifier | total cleanup verifier failures | stable | +| `status.cleanup.failedPhase` | cleanup verifier | failed cleanup/verifier phase | provisional | +| `status.cleanup.reasonCodes[]` | cleanup verifier | stable residue reason codes | provisional | +| `status.cleanup.evidenceRef` | cleanup verifier | cleanup summary artifact | stable | + +Safe next-step fields are advisory only: + +| Field | Meaning | +|---|---| +| `status.safeNextSteps[].type` | action identifier such as `observe.collect_bundle` | +| `status.safeNextSteps[].mode` | `read_only`, `dry_run`, or `scripted` | +| `status.safeNextSteps[].command` | suggested command text when safe to print | +| `status.safeNextSteps[].reasonCode` | reason that made the step relevant | +| `status.safeNextSteps[].mutationAllowed` | must remain `false` in Phase 36 | +| `status.safeNextSteps[].evidenceRefs[]` | evidence backing the suggestion | + +ManagedVolume actions remain non-executing: ```text mutation_allowed=false mode=read_only | dry_run ``` +Phase 36 cluster-level `safeNextSteps[]` may also use `mode=scripted` for +user/TestOps-invoked commands such as cleanup verification. `scripted` does not +grant operator execution rights; it is still a printed next-step hint with +`mutationAllowed=false`. + ## Condition Mapping | ManagedVolume Status | Conditions | @@ -121,16 +240,22 @@ Examples: | `safe_k8s.reinstall_external_iscsi` | `dry_run` | installer or operator | | `safe_k8s.import_csi_image` | `dry_run` | installer or operator | | `observe.inspect_host_path` | `dry_run` | ops / host diagnostics | +| `observe.verify_cleanup` | `scripted` | user/TestOps cleanup verifier | | `authority.request_promotion` | not emitted by Phase 23 for execution | blockmaster recovery only | +In Phase 36, `scripted` still means user-initiated and outside the operator +reconcile loop. It must not be executed automatically by operator-status. + ## Non-Claims This contract does not deliver: -- CRDs, - controller reconciliation, - mutating actions, - automatic repair/rebuild, +- automatic cleanup, +- CR object ownership or finalizers, +- support-bundle upload, - dashboard buttons, - production RBAC/audit. @@ -141,9 +266,13 @@ It exists so those future pieces use the same facts and safety boundaries. Pinned by: - `core/ops/managed_volume_operator_contract_test.go` +- `core/ops/managed_volume_crd_contract_test.go` +- `core/ops/kubernetes_crd_manifests_test.go` +- `core/ops/operator_status_controller_test.go` +- `core/ops/phase37_node_evidence_contract_test.go` Regression: ```text -go test ./core/ops -run "ManagedVolumeOperatorContract" -count=1 +go test ./core/ops -run "ManagedVolumeOperatorContract|ManagedVolumeCRDContract|Phase35D1|Phase36D1|Phase37D1|OperatorStatusReconciler" -count=1 ``` diff --git a/seaweed-block/internal/docs/qa-assignments/phase33-d4-cleanup-replay-gate.md b/seaweed-block/internal/docs/qa-assignments/phase33-d4-cleanup-replay-gate.md new file mode 100644 index 0000000000..280be74ab2 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase33-d4-cleanup-replay-gate.md @@ -0,0 +1,93 @@ +# Phase 33 D4 Cleanup And Replay Gate + +Status: PASS on 2026-05-29. + +Source branch: `phase33-testops-failure-hardening` + +Purpose: consolidate Phase 33 cleanup and replay evidence. This gate does not +add a new product claim; it proves failed or degraded evidence paths remain +cold-readable and leave the lab clean. + +## Gate Results + +| Gate | Scenario / Test | Run / Evidence | Result | +|---|---|---|---| +| F1 live negative support bundle | `helm-support-bundle-diagnostics-chain.yaml` | `20260528-190738-51a2` | PASS, 49/49 | +| F2 unreachable status replay | `status-endpoint-unreachable-replay-chain.yaml` | `20260529-155016-e9a5` | PASS, 17/17 | +| F4 corrupt evidence replay | `go test ./cmd/sw-block` | `TestOpsReportFromBundleSkipsCorruptClusterEvidenceCandidate` | PASS | +| F5 cleanup residue | `cleanup-residue-chain.yaml` | `20260529-155040-4519` | PASS, 13/13 | + +## F1: Failed Path Evidence Remains Useful + +The live negative gate proves the CSI image-pull blocked path is explainable and +read-only: + +```text +support_bundle_status=ok +failure_snapshot_status=ok +capture_failure_count=0 +volume pvc-blocked status=blocked rf=3 reason=csi_node_image_pull_failed +managed_volume_condition Ready status=False reason=csi_node_image_pull_failed severity=warning +managed_volume_action safe_k8s.import_csi_image mode=dry_run +cleanup_status=ok +``` + +This closes the support-bundle quality requirement for a real blocked install +path. + +## F2: Unreachable Evidence Does Not Become Ready + +The replay-only gate synthesizes status endpoint unreachability and verifies +all read-only surfaces agree: + +```text +summary: managed_volume=pvc-unreachable status=unknown reason=status_endpoint_unreachable +operator-snapshot.json: reason_code=status_endpoint_unreachable +dashboard /operator-snapshot.json: reason_code=status_endpoint_unreachable +explain: managed_volume_condition Ready status=Unknown reason=status_endpoint_unreachable +``` + +The scenario includes a JSON assertion that no per-volume `Ready=True` condition +appears in the report or dashboard snapshot. + +## F4: Corrupt Evidence Is Skipped + +The CLI replay unit gate verifies `sw-block ops report --from-bundle` can skip a +corrupt `cluster-evidence.json` candidate and select the newest valid snapshot. +That protects support-bundle replay from one bad evidence file masking a later +valid one. + +## F5: Cleanup Residue Is Zero + +The cleanup gate verifies residue dimensions after cleanup: + +```text +cleanup_status=ok +k8s_residue_count=0 +iscsi_residue_count=0 +process_residue_count=0 +multipath_residue_count=0 +hostpath_residue_count=0 +failure_count=0 +``` + +The verifier contract test also locks the residue counters and failure reason +vocabulary so future edits cannot silently drop iSCSI node DB, multipath, +process, Kubernetes, or hostPath dimensions. + +## Verdict + +D4 is closed. Phase 33 now has evidence that blocked paths, unreachable evidence +replay, corrupt evidence replay, and cleanup residue checks all follow the +negative-first rule: + +```text +No false Ready=True. +Stable reason code. +Useful evidence. +Deterministic cleanup. +``` + +Remaining Phase 33 work is D5 release-close packaging: compact close report, +minimal new-user validation decision, and release-note/addendum wording if this +branch is cut as `v0.3.5-alpha`. diff --git a/seaweed-block/internal/docs/qa-assignments/phase33-f1-live-negative-qa-result.md b/seaweed-block/internal/docs/qa-assignments/phase33-f1-live-negative-qa-result.md new file mode 100644 index 0000000000..dfa7358f17 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase33-f1-live-negative-qa-result.md @@ -0,0 +1,88 @@ +# Phase 33 F1 Live Negative QA Result + +Status: PASS on 2026-05-28. + +Source branch: `phase33-testops-failure-hardening` + +Scenario: + +- `testops/scenarios/helm-support-bundle-diagnostics-chain.yaml` + +Run: + +- `20260528-190738-51a2` +- Result bundle: `C:\work\seaweed_block\results\phase33-f1-live-negative-r3\20260528-190738-51a2` +- Demo artifacts: `V:\share\g15d-k8s\20260528-190738-51a2-helm-support-bundle\` + +## Result + +49/49 actions passed across all 8 phases: + +- `pre_clean` +- `build_and_generate_values` +- `helm_install_stack` +- `first_volume_kept_for_bundle` +- `collect_support_bundle` +- `blocked_bundle_asserts` +- `failure_snapshot` +- `helm_uninstall_cleanup` + +## Evidence + +Support bundle: + +```text +support_bundle_status=ok +report_status=ok +explain_status=ok +timeline_status=ok +capture_status=ok +read_only=true +``` + +Blocked-path explanation: + +```text +volume pvc-blocked status=blocked rf=3 reason=csi_node_image_pull_failed +managed_volume pvc-blocked status=blocked reason=csi_node_image_pull_failed +managed_volume_condition Ready status=False reason=csi_node_image_pull_failed severity=warning +managed_volume_condition Blocked status=True reason=csi_node_image_pull_failed severity=warning +managed_volume_action safe_k8s.import_csi_image mode=dry_run side_effect=safe_k8s executor=installer_or_operator +``` + +Failure snapshot: + +```text +failure_snapshot_status=ok +capture_failure_count=0 +read_only=true +k8s_snapshot=k8s +logs=logs +host_snapshot=host +``` + +Cleanup: + +```text +cleanup_status=ok +k8s_residue_count=0 +iscsi_residue_count=0 +process_residue_count=0 +multipath_residue_count=0 +hostpath_residue_count=0 +failure_count=0 +``` + +## Fixes Verified + +- `collect-helm-support-bundle.sh` no longer treats expected optional diagnostics + such as no active iSCSI sessions as support-bundle failure. +- `collect-k8s-failure-snapshot.sh` no longer treats expected optional + diagnostics such as missing previous logs or no active iSCSI sessions as + failure-snapshot failure. + +## Verdict + +F1 is release-gate green. The blocked CSI image-pull path does not claim +`Ready=True`, carries stable reason `csi_node_image_pull_failed`, exports +cold-readable support evidence, and cleans up with zero residue. diff --git a/seaweed-block/internal/docs/qa-assignments/phase33-failure-matrix.md b/seaweed-block/internal/docs/qa-assignments/phase33-failure-matrix.md new file mode 100644 index 0000000000..88f601527e --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase33-failure-matrix.md @@ -0,0 +1,98 @@ +# Phase 33 Failure Matrix + +Status: D1 complete; F1/F2/F4/F5 implementation evidence landed; D4 +cleanup/replay gate passed as of 2026-05-29. + +Purpose: turn Phase 33 from "test failures more" into executable release gates. +Every failure below must prove the same product rule: + +```text +No false Ready=True. +Stable reason code. +Useful evidence. +Deterministic cleanup. +``` + +## Scope + +In scope: + +- TestOps scenarios and helper hardening. +- Read-only status/report/dashboard/explain agreement. +- Support-bundle replay from failed or partial evidence. +- Cleanup verification after blocked runs. + +Out of scope: + +- New HA feature claims. +- Rebuild/failback implementation. +- NVMe ANA expansion. +- Mutating operator/admin actions. +- Broad model or protocol refactor. + +## Required Surfaces + +Each release-blocking gate must check these surfaces unless the trigger happens +before the surface can exist: + +- `summary.txt` +- `cluster-evidence.json` +- `operator-snapshot.json` +- dashboard `/operator-snapshot.json` +- `sw-block ops explain` +- cleanup summary / verifier output + +## Matrix + +| ID | Failure Class | Trigger | Expected Status / Reason | Required Evidence | Cleanup Gate | Source / Scenario Shape | Priority | +|---|---|---|---|---|---|---|---| +| F1 | CSI node image pull failure | Install with invalid CSI image or missing local image import | `Blocked`, `Ready=False`, `reason=csi_node_image_pull_failed` | K8s pods/events, support bundle, report, operator snapshot, explain dry-run action | zero k8s/iSCSI/multipath/process residue after cleanup | PASS: `helm-support-bundle-diagnostics-chain.yaml` run `20260528-190738-51a2`, 49/49 actions | P0 | +| F2 | Blockmaster/API unreachable / status endpoint unreachable | Stop or block access to status evidence before status/report capture | `Unknown`, no `Ready=True`, reason `status_endpoint_unreachable` | report, explain, dashboard, operator snapshot showing inability to prove readiness; live port-forward/log artifact for future master-specific gate | cleanup still succeeds without master API | PASS: replay scenario `status-endpoint-unreachable-replay-chain.yaml` run `20260529-155016-e9a5`, 17/17 actions; live master-specific scenario still optional | P0 | +| F3 | Evidence stale / reconverging snapshot | Replay bundle where newest evidence is post-restart but not fully reconverged | `Ready=Unknown`, reason `evidence_stale` or `unknown`; never false `Ready=True` | multiple cluster snapshots with timestamps, replay output, dashboard snapshot | replay-only; no live residue expected | Existing D7 replay behavior; convert to explicit scenario or component gate | P0 | +| F4 | Corrupt or partial bundle evidence | Put corrupt `cluster-evidence.json` beside a newer valid snapshot, or remove optional artifacts | replay skips corrupt candidate; status comes from newest valid evidence; if none valid, fail with clear error | corrupt file, valid file, replay stderr/stdout, report artifacts | replay-only; no live residue expected | Component gate around `BuildObservationFromBundle` plus CLI replay test | P0 | +| F5 | Cleanup residue after failed install/run | Intentionally leave iSCSI node DB, multipath map, or generated Deployment | cleanup status fails before scrub, then passes after cleanup; reason names residue class | `cleanup-summary.txt`, iSCSI nodes, multipath/dmsetup, k8s resources | all residue counters zero after final cleanup | PASS: `cleanup-residue-chain.yaml` run `20260529-155040-4519`, 13/13 actions; cleanup verifier contract test locks residue counters and reason vocabulary | P0 | +| F6 | Multi-volume cross-interference | Fail/restart one or two RF=3 volumes while another volume remains mounted/readable | target volumes recover or block independently; untouched volume remains stable; no mixed primary/publish target | per-volume summaries, operator snapshot with 3 identities, cross-interference flag | no leaked pods/deployments/iSCSI/multipath | Existing: RF3 interleaved and app-spread failover scenarios | P1 | +| F7 | Restart during or shortly after promotion | Restart k3s/product after promotion but before observation fully settles | authority does not roll back; report either shows correct primary or `Ready=Unknown`, never old primary as Ready | before/after primary, epoch, publish target, report replay, reader verification | hostPath and iSCSI cleanup zero | Existing restart persistence scenarios; add timing variant if needed | P1 | +| F8 | Loopback publish target on cross-node attach | Force multi-node pod attach while publish target is `127.0.0.1` on another node | safe refusal / blocked attach; no fake success; stable loopback/cross-node reason | CSI node logs, pod describe FailedMount, report/explain reason | cleanup removes PVC, sessions, node DB | Existing negative attach lineage; add Helm Day-1 variant if not covered | P1 | + +## Hard Gate Rules + +For P0 gates: + +- The scenario must fail closed if the expected blocker is not observed. +- The scenario must assert absence of `Ready=True` in the blocked/stale path. +- Reason code must match across at least three surfaces: + `summary.txt`, `operator-snapshot.json`, and `explain`. +- Suggested actions must be `read_only` or `dry_run`. +- Cleanup must be checked after the failure, not only before the next run. + +For P1 gates: + +- The scenario may be longer-running or lab-shape-dependent. +- It must still produce a cold-readable bundle and cleanup summary. +- It must not widen the public release claim unless promoted to P0 and rerun. + +## D2 Implementation Queue + +Minimum runner/helper work to make the P0 gates maintainable: + +1. Standardize failure snapshot capture for Helm/K8s runs. +2. Add a helper or runner action for JSONPath waits where conditions do not + exist, especially PVC phase and pod/job completion. +3. Ensure support-bundle collection marks required capture failures as failed. +4. Keep cleanup verifier as the final source of truth for residue counters. +5. Add replay tests for corrupt/partial evidence selection. + +## Release Close Requirement + +Phase 33 cannot close unless: + +```text +F1-F5 PASS as release-blocking gates +minimal new-user validation still PASS +cleanup-residue gate PASS after negative gates +no public doc claims new HA/rebuild/operator features +``` + +F6-F8 may close as optional extended evidence or carry forward to the next +hardening cycle. diff --git a/seaweed-block/internal/docs/qa-assignments/phase33-testops-failure-hardening-close-report.md b/seaweed-block/internal/docs/qa-assignments/phase33-testops-failure-hardening-close-report.md new file mode 100644 index 0000000000..a3b7d2e5d0 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase33-testops-failure-hardening-close-report.md @@ -0,0 +1,126 @@ +# Phase 33 Close Report - TestOps Failure Hardening + +Closed: 2026-05-29 + +Verdict: PASS. + +Source branch: `phase33-testops-failure-hardening` + +Base release: PR #50 / merge `8102cf3` (`v0.3.4-alpha` baseline). + +## Product Rule Validated + +```text +If the product cannot prove a volume is ready, it must not claim Ready=True. +It must surface a stable reason, collect useful evidence, and clean up +deterministically. +``` + +Phase 33 is a reliability and evidence-hardening phase. It does not add a new +HA, rebuild, NVMe, backup, or mutating operator claim. + +## Gate Summary + +| Gate | Evidence | Result | +|---|---|---| +| D1 failure matrix | `phase33-failure-matrix.md` | PASS | +| D2 helper/status hardening | `go test ./scripts ./core/ops ./cmd/sw-block` | PASS | +| D3/F1 live negative status | `helm-support-bundle-diagnostics-chain.yaml` run `20260528-190738-51a2` | PASS, 49/49 | +| D3/F2 unreachable status replay | `status-endpoint-unreachable-replay-chain.yaml` run `20260529-155016-e9a5` | PASS, 17/17 | +| D4 cleanup residue | `cleanup-residue-chain.yaml` run `20260529-155040-4519` | PASS, 13/13 | +| D5 minimal new-user regression | `helm-first-volume-via-sw-block-cli-chain.yaml` run `20260529-155216-0d9d` | PASS, 34/34 | + +## Key Evidence + +F1 CSI image-pull blocked path: + +```text +volume pvc-blocked status=blocked rf=3 reason=csi_node_image_pull_failed +managed_volume_condition Ready status=False reason=csi_node_image_pull_failed severity=warning +managed_volume_condition Blocked status=True reason=csi_node_image_pull_failed severity=warning +managed_volume_action safe_k8s.import_csi_image mode=dry_run +support_bundle_status=ok +failure_snapshot_status=ok +capture_failure_count=0 +``` + +F2 status endpoint unreachable replay: + +```text +managed_volume=pvc-unreachable status=unknown reason=status_endpoint_unreachable +managed_volume_condition Ready status=Unknown reason=status_endpoint_unreachable +dashboard/operator-snapshot reason_code=status_endpoint_unreachable +mutation_allowed=false +``` + +Cleanup residue: + +```text +cleanup_status=ok +k8s_residue_count=0 +iscsi_residue_count=0 +process_residue_count=0 +multipath_residue_count=0 +hostpath_residue_count=0 +failure_count=0 +``` + +Minimal user path regression: + +```text +generate Helm values +-> helm install +-> first PVC +-> writer_verified=true +-> reader_verified=true +-> read-only report/operator snapshot +-> helm uninstall cleanup +``` + +## Changes Landed + +- `collect-helm-support-bundle.sh` now distinguishes required captures from + optional diagnostics. Expected states such as no active iSCSI session no + longer fail the support bundle. +- `collect-k8s-failure-snapshot.sh` applies the same required/optional split + for previous logs, iSCSI state, multipath/dmsetup, and kubelet mount + diagnostics. +- ManagedVolume projection treats `status_endpoint_unreachable` as + `status=unknown` and `Ready=Unknown`, not `Ready=True`. +- Bundle replay skips corrupt evidence candidates and selects the newest valid + snapshot. +- Cleanup verifier contract tests lock the residue counters and failure reason + vocabulary. + +## Blocking Findings + +None. + +## Non-Blocking Follow-Ups + +- Convert more negative cases from replay-only to live failure injection when + the lab orchestration supports it cleanly. +- Add runner-native actions for JSONPath waits and structured cleanup + assertions so fewer shell helpers are needed. +- Keep F6-F8 from the failure matrix as future hardening candidates: + multi-volume cross-interference, restart-during-promotion timing, and + loopback publish target refusal. + +## Release Boundary + +If cut as `v0.3.5-alpha`, the release claim should be: + +```text +Failure-path evidence and cleanup reliability hardening for the existing +Helm/PVC/read-only-ops alpha product. +``` + +Do not claim: + +- new HA behavior, +- production readiness, +- mutating operator/admin workflows, +- rebuild/failback, +- backup/restore, +- NVMe ANA parity, +- broad performance/SLO guarantees. diff --git a/seaweed-block/internal/docs/qa-assignments/phase34-d2-live-status-endpoint-unreachable-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase34-d2-live-status-endpoint-unreachable-signoff.md new file mode 100644 index 0000000000..203016e22f --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase34-d2-live-status-endpoint-unreachable-signoff.md @@ -0,0 +1,117 @@ +# Phase 34 D2 - Live Status Endpoint Unreachable Sign-off + +Status: PASS on 2026-05-29. + +Source scenario: + +- `testops/scenarios/status-endpoint-unreachable-live-chain.yaml` + +Validation run: + +- Run ID: `20260529-182955-3bd2` +- Result: PASS, 29/29 actions +- Runtime: 1m57.542s + +## What This Gate Proves + +This gate upgrades the Phase 33 replay-only status-unreachable check into live +fault injection. + +The test flow: + +```text +Helm install +-> first PVC writer/reader verifies Ready +-> discover live replica status endpoint from ops inventory +-> reject only the status endpoint port +-> collect live ops report/explain/dashboard +-> assert Ready=Unknown and EvidenceStale/status_endpoint_unreachable +-> assert not Ready=True and not Blocked=True +-> restore iptables rule +-> uninstall and verify zero residue +``` + +## Injection Evidence + +Fault artifact: + +```text +status_endpoint_blocked=true +status_addr=192.168.1.181:23260 +status_host=192.168.1.181 +status_port=23260 +volume_id=pvc-0937fc3e-07fd-46bf-81ac-dec2f89b5a98 +replica_id=r1 +frontend_addr=192.168.1.181:3260 +``` + +The injected rule only targeted the status port: + +```text +iptables -I INPUT -p tcp --dport 23260 -j REJECT --reject-with tcp-reset +``` + +The iSCSI data path port `3260` was not blocked. + +## Status Surface Evidence + +Report summary: + +```text +managed_volume=pvc-0937fc3e-07fd-46bf-81ac-dec2f89b5a98 status=unknown reason=status_endpoint_unreachable +managed_volume_condition=Ready status=Unknown reason=status_endpoint_unreachable severity=warning +managed_volume_condition=EvidenceStale status=True reason=status_endpoint_unreachable severity=warning +``` + +Operator snapshot and dashboard agreed: + +- `read_only=true` +- `mutation_allowed=false` +- `status=unknown` +- `reason_code=status_endpoint_unreachable` +- `ready_volume_count=0` +- `blocked_volume_count=0` +- `stale_volume_count=1` +- no `Ready=True` +- no `Blocked=True` + +This preserves the intended distinction: + +```text +status endpoint unreachable -> Unknown / EvidenceStale +known product blocker -> Blocked +``` + +## Cleanup + +Cleanup summary: + +```text +cleanup_status=ok +k8s_residue_count=0 +iscsi_residue_count=0 +process_residue_count=0 +multipath_residue_count=0 +hostpath_residue_count=0 +failure_count=0 +``` + +## Iterations + +Two scenario bugs were found and fixed before the passing run: + +- The runner `exec` shell uses `/bin/sh`; local inline scripts cannot use + `set -o pipefail`. +- The live status endpoint address is present in + `status/inventory/volume-inventory.json` as `status_address`, not in the + product cluster evidence replica object. + +Both fixes are scenario-side only. + +## Verdict + +D2 PASS. + +The live status endpoint unreachable behavior is now covered at L2 realism: +real Helm install, real PVC, real status-port block, live ops collection, and +read-only user surfaces that refuse to claim readiness without evidence. diff --git a/seaweed-block/internal/docs/qa-assignments/phase34-d3-restart-convergence-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase34-d3-restart-convergence-signoff.md new file mode 100644 index 0000000000..3f28180381 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase34-d3-restart-convergence-signoff.md @@ -0,0 +1,121 @@ +# Phase 34 D3 - Restart Status Convergence Sign-off + +Status: PASS on 2026-05-29. + +## Scope + +D3 separates two restart semantics: + +- No-fault restart convergence: after k3s/product restart, the user-facing + status surface must eventually return to stable `Ready=True`. +- Degraded promotion restart boundary: after a promoted RF3 volume restarts + with the old failed replica still absent, the surface must remain stable and + honest. `Unknown/status_endpoint_unreachable` is acceptable; false + `Ready=True` or `Blocked=True` is not. + +This avoids treating a deliberately degraded old-primary state as a failure +while still adding a hard final-convergence gate for the no-fault user path. + +## Scenario Changes + +Updated: + +- `testops/scenarios/helm-single-node-restart-persistence-chain.yaml` +- `testops/scenarios/helm-rf3-promotion-restart-persistence-chain.yaml` + +The single-node scenario now includes `post_restart_status_convergence`, which +polls live `sw-block ops report` until the target ManagedVolume is Ready for +three consecutive observations. + +The RF3 promotion scenario now includes +`post_restart_degraded_status_boundary`, which requires three consecutive safe +observations. Safe means either: + +- `status=ready` with `Ready=True`, or +- `status=unknown reason=status_endpoint_unreachable` + +and in both cases: + +- no `Blocked=True` +- no false readiness claim +- cleanup remains strict + +## D3 Ready-Convergence Run + +Scenario: + +- `helm-single-node-restart-persistence-chain.yaml` + +Run: + +- Run ID: `20260529-185123-5078` +- Result: PASS, 45/45 actions +- Runtime: 2m42.348s + +Convergence artifact: + +```text +restart_status_convergence=ok +volume_id=pvc-ad55d5e0-52e3-4878-a138-c8eff442f3d3 +required_consecutive_ready=3 +max_consecutive_ready=3 +final_reason=first_volume_verified +evidence=observations.txt +``` + +Observations: + +```text +1: status=ready reason=first_volume_verified ready_true=true blocked_true=false consecutive_ready=1 +2: status=ready reason=first_volume_verified ready_true=true blocked_true=false consecutive_ready=2 +3: status=ready reason=first_volume_verified ready_true=true blocked_true=false consecutive_ready=3 +``` + +This closes the original gap: the test no longer accepts a single transient +Ready or stops at a safe Unknown. It requires stable Ready across three +consecutive live report observations. + +## RF3 Degraded Boundary Run + +Scenario: + +- `helm-rf3-promotion-restart-persistence-chain.yaml` + +Run: + +- Run ID: `20260529-185413-5c72` +- Result: PASS, 39/39 actions +- Runtime: 2m34.238s + +Boundary artifact: + +```text +restart_status_boundary=ok +volume_id=pvc-38c1c612-1f22-4631-947b-984042f205c5 +required_consecutive_stable=3 +max_consecutive_stable=3 +final_reason=status_endpoint_unreachable +evidence=observations.txt +``` + +Observations: + +```text +1: status=unknown reason=status_endpoint_unreachable ready_true=false blocked_true=false consecutive_stable=1 +2: status=unknown reason=status_endpoint_unreachable ready_true=false blocked_true=false consecutive_stable=2 +3: status=unknown reason=status_endpoint_unreachable ready_true=false blocked_true=false consecutive_stable=3 +``` + +The RF3 promoted-authority claim still passes: primary, publish target, epoch, +reader data, and cleanup are verified by the existing scenario. The new boundary +check confirms the degraded status surface does not lie by claiming Ready and +does not misclassify missing evidence as Blocked. + +## Verdict + +D3 PASS. + +Restart convergence is now tested at L3-ish timing realism for the no-fault +path: restart, live report polling, and stable Ready for three consecutive +observations. The promoted-degraded path remains negative-first and does not +over-claim readiness when a failed old replica remains unreachable. diff --git a/seaweed-block/internal/docs/qa-assignments/phase34-d4-smartwal-corrupt-finding.md b/seaweed-block/internal/docs/qa-assignments/phase34-d4-smartwal-corrupt-finding.md new file mode 100644 index 0000000000..a00fb1f8d5 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase34-d4-smartwal-corrupt-finding.md @@ -0,0 +1,184 @@ +# QA Finding - Phase 34 D4: False Ready=True After SmartWAL Corruption + +Verdict: **GATE NOW WORKS, and it found a real product gap.** The D4 gate +reached its product assertion `assert_no_false_ready_after_corruption` and +**failed because the product reports `Ready=True` for a volume whose SmartWAL +contains a corrupted committed record.** Per the Phase 34 plan, this is a +valid gate result to file as a product gap, not a scenario failure. + +Date: 2026-05-29 + +Source commit under test: `03fe9ae testops: keep smartwal corruption gate scoped to volume` +QA run: `20260529-232752-b23c` +Scenario: `testops/scenarios/helm-smartwal-corrupt-restart-chain.yaml` +Tracking issue: https://github.com/seaweedfs/seaweed-block/issues/51 + +This supersedes the orchestration blocker (issue 4) in +`phase34-d4-smartwal-corrupt-qa-status.md`. Dev's rewrite (scale only the +target blockvolume, keep blockmaster up) was correct and let the run reach the +real assertion. + +## The Gate Now Reaches Its Product Question + +| Phase | Result | +|---|---| +| pre_clean / build / generate / install | PASS | +| first_volume_before_corruption | PASS | +| corrupt_smartwal_and_reconcile | PASS (corruption injected + target restarted) | +| assert_no_false_ready_after_corruption | **FAIL: false Ready=True after SmartWAL corruption** | + +28 actions, 27 pass, 1 fail. The single fail is the product assertion. This is +the gate doing its job. + +## The Finding + +### Corruption was real and landed in the WAL + +```text +target_record_offset=6016 +mutated_offset=6047 +target_offset_inside_wal=true +target_offset_inside_extent=false +``` + +The layout-aware `sw-block-testutil` corrupted a genuine committed SmartWAL +record (not the extent region, not a torn tail it invented). + +### The product DID detect the corruption + +blockvolume recovery log after restart +(`corrupt/blockvolume-pods.log`): + +```text +smartwal: recovery CRC mismatch LSN=45 LBA=0 expected=80824a23 actual=91e6685b — skipping +smartwal: recovery: 40 LBAs verified, 1 torn, frontier=59 +blockvolume: durable recovered: recovered LSN=59 +``` + +The SmartWAL CRC check works. It caught the mismatch at LSN=45. + +### But it silently skipped the corrupted committed record and reported full health + +- Recovery classified the corrupted record as `1 torn` and **skipped LSN=45**, + then recovered forward to `frontier=59`. +- The blockvolume came up `1/1 Running`, 0 restarts, + `deployment_rollout_ready=true`. +- The status surface + (`after-corrupt/corruption-status-summary.txt`): + +```text +smartwal_corruption_status_surface=failed +ready_true_after_corruption=true +blocked_true_after_corruption=false +reason_after_corruption=first_volume_verified +``` + +operator-snapshot.json for the volume: + +```json +"status": "ready", +"reason_code": "first_volume_verified", +"conditions": [{"type": "Ready", "status": "True", ...}] +``` + +So a volume whose durable WAL has a detected CRC failure on a committed record +reports `Ready=True reason=first_volume_verified` — the exact same status as a +clean first volume. No `Blocked`, no `Recovered`-with-loss, no `Degraded`, no +`EvidenceStale`. + +## Why This Matters — Two Layers + +### Layer 1 (certain): status-surface negative-first violation + +This is the gate's literal assertion and it is indisputable. The negative-first +contract from Phase 32 says the product must not claim `Ready=True` against +corrupted or contradictory evidence. Here a known CRC mismatch on a committed +record is fully swallowed and the surface claims healthy-Ready. At minimum the +status model needs a condition for "recovered with a detected WAL integrity +fault" so the user can tell this volume apart from a clean one. + +### Layer 2 (needs engine-owner judgment): is the skip itself safe? + +The corrupted record is `LSN=45`; recovery reached `frontier=59`. So records +LSN 46..59 are AFTER the corrupted one in the log. The product skipped LSN=45 +but kept the later records and declared `recovered LSN=59`. + +- If LSN=45's data was already checkpointed into stable extents before the + corruption, skipping it during WAL replay is harmless — the data lives in the + extent store. +- If LSN=45 was a committed-but-not-yet-flushed write, skipping it is **silent + loss of an acknowledged write from the middle of the log**, while later writes + (46..59) are kept — a consistency violation masked as `Ready=True`. + +I cannot determine from logs alone which case applies; that is an engine / +durability-owner call. But the test correctly surfaces the question, and the +"torn write" classification of a *mid-history* corrupted record (not just a torn +tail) deserves scrutiny. Torn-tail discard is safe; mid-history skip is not +obviously safe. + +## This Matches the Plan's Anticipated Outcome + +The Phase 34 plan D4 explicitly allowed this: + +> This gate is allowed to fail if the product does not yet surface a stable +> WAL-corruption reason. A green run is valid only if the corruption evidence +> exists and no status surface claims Ready=True afterward. + +And D7's close criteria allowed D4 to be: + +> PASS or explicitly blocked by missing product reason code with a concrete +> implementation issue filed. + +This run is exactly that case. **D4 is "explicitly blocked by a confirmed +product gap," with this finding as the concrete issue.** The gate should stay +red until the product either: + +1. surfaces a stable condition/reason for WAL-integrity-fault recovery (e.g. + `Recovered=True reason=wal_record_skipped_crc` or + `Degraded/EvidenceStale` with a `wal_corrupt` reason), so the status is no + longer a false `Ready=True reason=first_volume_verified`; and +2. the engine owner confirms whether skipping a mid-history corrupted committed + record is durability-safe, and if not, changes the recovery policy (refuse / + fence / mark degraded rather than silently continue). + +## Recommended Issue To File + +Title: "blockvolume reports Ready=True after SmartWAL recovery skips a +CRC-failed committed record" + +- Severity: high for the status-surface lie (Layer 1); to-be-determined for the + durability question (Layer 2), pending engine-owner review. +- Repro: `helm-smartwal-corrupt-restart-chain.yaml` on a smartwal+hostPath + install, run `20260529-232752-b23c`. +- Evidence: corruption stdout (offset-inside-wal), blockvolume recovery log + (CRC mismatch / skipping / frontier), operator-snapshot (Ready=True). + +## Process Note + +The D4 scenario went through 4 issues before reaching this finding: 3 scenario +mechanics bugs (nested template, YAML indent munge, missing sudo — all fixed +during the prior QA cycle and folded in by dev) and 1 orchestration redesign +(blockmaster bounce -> scoped blockvolume scale, fixed by dev in `03fe9ae`). +Only after all four did the gate reach the product assertion. A "live gate" +should be run live once before being treated as ready; the mechanics churn was +avoidable. + +That said, the end state is the best possible outcome for a hardening phase: +**a gate that is red for a real reason.** This is worth more than all the green +happy-path runs combined, because it found a correctness gap none of them +could. + +## Lab State + +Clean after the always-run cleanup: no helm release, no iSCSI sessions, no +multipath, no sw-block pods, no testops hostPath residue. + +## Bottom Line + +- D4 gate: **functional and red for a real product reason.** Keep it red. +- Product gap: blockvolume silently skips a CRC-failed committed WAL record and + reports `Ready=True reason=first_volume_verified`. Status-surface lie is + certain; durability safety of the skip needs engine-owner review. +- Do not mark Phase 34 D4 "passed." Mark it "gate live, product gap filed." + Per the plan that is a valid D4 close state, but the underlying product issue + should be tracked, not closed. diff --git a/seaweed-block/internal/docs/qa-assignments/phase34-d4-smartwal-corrupt-qa-status.md b/seaweed-block/internal/docs/qa-assignments/phase34-d4-smartwal-corrupt-qa-status.md new file mode 100644 index 0000000000..704e6a8470 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase34-d4-smartwal-corrupt-qa-status.md @@ -0,0 +1,156 @@ +# QA Status - Phase 34 D4 SmartWAL Corruption Restart Gate + +Verdict: **NOT PASS, NOT a product-Ready failure yet.** The gate has never +reached its actual product assertion. The scenario had not been run live +before push; QA fixed three sequential scenario-mechanics bugs, verified the +corruption-injection core is correct, then hit a fourth blocker that is dev's +to own. + +Date: 2026-05-29 + +Source commit under test: `6bdb30f testops: add smartwal corruption restart gate` +Scenario: `testops/scenarios/helm-smartwal-corrupt-restart-chain.yaml` + +Dev follow-up after this QA report: the three QA mechanics fixes were folded +into the scenario, and issue 4 was redesigned to keep blockmaster running. The +current scenario now scales only the target blockvolume Deployment to zero, +corrupts that volume's SmartWAL under `sudo -n`, scales the target Deployment +back to one replica, captures whether the target restarted/rolled out, and then +continues to the status-surface assertion. D4 still requires a fresh QA rerun; +this report remains the record of the failed `6bdb30f` cycle. + +## What's Good (give credit) + +My biggest worry in the Phase 34 plan review was that `corrupt_wal` would +target the V2 monolithic layout and silently miss the V3 SmartWAL — i.e. a +test that "runs corruption" but proves nothing. **Dev solved this correctly.** + +`sw-block-testutil smartwal-corrupt-latest-record` reads the real SmartWAL +header layout and refuses to mutate unless the offset is genuinely inside the +WAL region. Live evidence from the QA run: + +```text +wal_offset=4096 +target_record_offset=5792 +mutated_offset=5823 +target_offset_inside_wal=true +target_offset_inside_extent=false +``` + +The corruption landed on a real WAL record (offset 5823, inside the WAL ring, +not the extent region). This is genuine L2 injection, not L0 self-proof. The +D4-0 prerequisite I asked for is satisfied. + +## Where It Broke (4 sequential issues) + +| # | Phase | Issue | Class | Fixed by | +|---|---|---|---|---| +| 1 | generate_smartwal_values | `state_hostpath` env contains nested `{{ run_id }}`; runner does not recursively expand it, so `--state-hostpath {{ state_hostpath }}` leaked literal `{{ run_id }}` tokens as stray args | scenario | QA (inlined run_id at 4 use sites, removed nested env var) | +| 2 | helm_install_stack | python YAML edit used 2-space marker ` stateHostPath:` matching the suffix of the generator's real 4-space ` stateHostPath:`, corrupting indentation (`durableImpl` at 4 spaces, `stateHostPath` at 2) -> invalid YAML | scenario | QA (rewrote python to insert `durableImpl` at correct indent right after `blockmaster:`) | +| 3 | corrupt_smartwal_and_reconcile | `sw-block-testutil` invoked without `sudo`; the hostPath store file is root-owned -> `permission denied` | scenario | QA (added `sudo -n`) | +| 4 | corrupt_smartwal_and_reconcile | after `scale blockmaster=0 -> corrupt WAL -> scale blockmaster=1`, blockmaster never returns to rollout-complete: `0 of 1 updated replicas are available`, 300s timeout | scenario-design OR product | **NOT fixed by QA — handed back** | + +Three of four are unambiguous scenario typos. Their existence means the +scenario was pushed after `swblock validate` (syntax) + unit tests only, never +a live lab run. Worth noting as a process gap: a "live gate" should be run live +at least once before being handed to QA as a gate. + +## Issue 4 — why QA stopped here + +After the corruption succeeds, the scenario does: + +```text +scale deploy/sw-blockmaster --replicas=0 +corrupt the SmartWAL record +scale deploy/sw-blockmaster --replicas=1 +rollout status deploy/sw-blockmaster --timeout=300s <-- times out here +``` + +`corrupt/wait-blockmaster-after-corrupt.txt`: + +```text +Waiting for deployment "sw-blockmaster" rollout to finish: + 0 of 1 updated replicas are available... +``` + +blockmaster does not own the corrupt WAL (that is blockvolume's durable data), +so in principle corrupting a blockvolume's WAL should not stop blockmaster from +rolling out. Two possibilities, and I cannot disambiguate them by patching: + +- **(a) scenario-design fragility**: the scale-0 / corrupt / scale-1 blockmaster + dance is the wrong way to inject. A cleaner injection would leave blockmaster + running and only restart the single blockvolume Deployment whose WAL was + corrupted, then observe whether THAT volume goes Ready. +- **(b) real product gap**: blockmaster genuinely fails to become ready after + this sequence (e.g. its reconcile loop wedges when a blockvolume Deployment + was deleted while its durable hostPath holds a corrupt WAL). + +I did not patch issue 4 because: + +1. It is no longer a typo; it is the scenario's K8s orchestration logic, which + is dev authoring work, not QA mechanics. +2. It may BE the product signal the gate is meant to surface. Patching the wait + could mask a real recovery gap. + +The gate's actual product question — **does any status surface report +`Ready=True` for a volume whose WAL is corrupted?** — remains unanswered, +because the run never reaches the `assert_no_false_ready_after_corruption` +phase. + +## QA Scenario Fixes Applied (for dev to fold in) + +All three are in my working copy of +`testops/scenarios/helm-smartwal-corrupt-restart-chain.yaml`: + +1. Removed `state_hostpath` env var; inlined + `/var/lib/sw-block/testops-{{ run_id }}-smartwal-corrupt` at all 4 + references (lines ~44, ~86, ~162, ~271). +2. Rewrote the values-patch python to insert ` durableImpl: smartwal` + (4-space, matching generator indent) immediately after the `blockmaster:` + line, instead of the fragile 2-space suffix-match replace. +3. Added `sudo -n` to the `sw-block-testutil smartwal-corrupt-latest-record` + invocation. + +These three are pure mechanics; dev should accept them. They are not the +product fix. + +## Recommended Next Step For Dev + +Redesign issue-4 injection to NOT bounce blockmaster: + +```text +keep blockmaster running +scale ONLY the target blockvolume Deployment to 0 (or delete it) +sudo corrupt that volume's SmartWAL record +let the launcher recreate the blockvolume workload +observe: the recreated blockvolume must refuse corrupt replay and the status + surface must show NOT Ready (Blocked or Unknown with a stable reason), + never Ready=True +``` + +This keeps the fault localized to the data path the gate cares about, removes +the blockmaster-rollout dependency entirely, and lets the run reach the actual +`assert_no_false_ready_after_corruption` assertion. + +Open product question to confirm during that redesign: does the product even +HAVE a stable reason code for corrupt-WAL refusal yet? The plan's D4 escape +hatch (`wal_corrupt` / `recovery_evidence_invalid` / `durable_recovery_failed` +"may need implementation alignment") suggests it might not. If the blockvolume +crashloops without emitting a status-surface reason, that itself is the gap to +file. + +## Lab State + +Clean after the always-run cleanup phase: no helm release, no iSCSI sessions, +no multipath, no sw-block pods, no testops hostPath residue. + +## Bottom Line + +- D4-0 (V3-aware corruption injection): **dev did it right.** Verified live. +- D4 scenario: **3 mechanics bugs fixed by QA, 1 orchestration blocker + remaining.** Never run live before push. +- D4 product claim (no false Ready on corrupt WAL): **still unproven** — the + gate has not reached its product assertion. +- This is the correct kind of gate to have; it just is not green yet, and it is + not green because of scenario plumbing, not (yet) because of a confirmed + product behavior. diff --git a/seaweed-block/internal/docs/qa-assignments/phase34-d4-smartwal-corrupt-verify.md b/seaweed-block/internal/docs/qa-assignments/phase34-d4-smartwal-corrupt-verify.md new file mode 100644 index 0000000000..47de816ce6 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase34-d4-smartwal-corrupt-verify.md @@ -0,0 +1,158 @@ +# QA Verification - Phase 34 D4 SmartWAL Fix (#51) + +Verdict: **STILL RED — fix is half-wired.** Commit `85d9375` correctly makes +SmartWAL recovery fail closed at the storage layer, but the blockvolume process +swallows the durable-recovery failure and proceeds to publish healthy anyway, +so the user-visible symptom is unchanged: `Ready=True reason=first_volume_verified` +after corruption. The gate is correctly still red. One precise wiring fix +remains. + +Date: 2026-05-30 + +Source commit under test: `85d9375 storage: fail closed on smartwal integrity mismatch` +QA run: `20260530-000104-b168` +Scenario: `testops/scenarios/helm-smartwal-corrupt-restart-chain.yaml` +Tracking issue: #51 + +## What the Fix Got Right (verified live) + +The storage-layer fix works. blockvolume recovery log +(`corrupt/blockvolume-pods.log`): + +```text +smartwal: recovery CRC mismatch LSN=45 LBA=0 expected=11c18052 actual=0f934a52 — failing closed +blockvolume: durable recovery failed: recover failed: storage: WALIntegrity: CRC mismatch LSN=45 LBA=0 ...: storage: WAL integrity fault +``` + +- SmartWAL now **fails closed** instead of "skipping" (compare the prior run + `20260529-232752-b23c` which said "skipping ... recovered LSN=59"). +- The typed `WALIntegrity` fault is produced. +- No more silent skip of a mid-history corrupted committed record — the Layer 2 + durability concern from the prior finding is addressed at the storage layer. + +Unit tests for the fix pass: +`go test ./core/storage/smartwal ./core/frontend/durable ./core/ops` PASS. + +## What Is Still Broken (the half-wire) + +Despite durable recovery failing, the volume still reports Ready: + +`after-corrupt/corruption-status-summary.txt`: + +```text +ready_true_after_corruption=true +blocked_true_after_corruption=false +reason_after_corruption=first_volume_verified +``` + +operator-snapshot.json for the volume: + +```json +"status": "ready", +"reason_code": "first_volume_verified", +"conditions": [{"type": "Ready", "status": "True", ...}] +``` + +The string `wal_integrity_fault` appears **nowhere** in the live status surface +(report summary, operator-snapshot). The pod is `1/1 Running`, 0 restarts. + +### Why: blockvolume logs the recovery failure but does not act on it + +`cmd/blockvolume/main.go:493-507`: + +```go +report, recErr := dp.RecoverVolume(recCtx, f.volumeID) +recCancel() +if recErr != nil { + fmt.Fprintln(os.Stderr, "blockvolume: durable recovery failed:", report.Evidence) +} else { + fmt.Fprintln(os.Stderr, "blockvolume: durable recovered:", report.Evidence) +} +// ... +startReadyAssignmentLoop(readyCh, f, durableProv, os.Stdout, os.Stderr) +``` + +When `recErr != nil` (the WALIntegrity case), the code **only logs to stderr**. +It does not return, does not mark the volume faulted, and does not stop +`startReadyAssignmentLoop` from running. So the process continues startup and +publishes healthy. + +The adapter trace confirms PublishHealthy fires AFTER the recovery failure: + +```text +blockvolume: durable recovery failed: ... WAL integrity fault +adapter[rid=r1] ... cmds=[FenceAtEpoch] +adapter[rid=r1] ... cmds=[PublishHealthy] +``` + +Compare line 490-491 just above: there IS a fail-closed process path +(`_ = h.Close(); return 1`) for an earlier error. The durable recovery failure +at line 496 simply does not take it. + +### Consequence chain + +```text +SmartWAL fails closed (correct) +-> recErr != nil, but main.go only logs it +-> startReadyAssignmentLoop runs anyway +-> adapter PublishHealthy +-> blockmaster ManagedVolume facts show healthy +-> projection mapping (correctly: wal_integrity_fault -> Blocked) never + receives a wal_integrity_fault fact, because the volume-side never emits one +-> operator-snapshot: Ready=True reason=first_volume_verified +``` + +The ManagedVolume projection mapping the dev added (wal_integrity_fault -> +Blocked) is correct and unit-tested, but it is dead code in the live path +because the fact never arrives. The break is upstream, at the +volume-process-to-engine boundary. + +## Precise Fix For Dev + +When `dp.RecoverVolume` returns a `WALIntegrity` (or any typed durable +recovery) failure, the blockvolume must propagate it instead of swallowing it. +Two viable shapes: + +1. **Fail closed at the process** (simplest, matches the existing + line-490 pattern): on typed durable recovery failure, `h.Close(); return 1`. + The pod crashloops -> not Ready -> blockmaster sees the volume down -> status + is not Ready. Combined with a pod readiness probe, the operator-snapshot + would show the volume as down/blocked, not Ready. + +2. **Publish faulted** (richer, preferred for the status story): proceed but + feed the `WALIntegrity` fault into the published observation so the engine + emits a faulted/degraded fact carrying `wal_integrity_fault`. Then the + existing projection mapping fires and the surface shows + `Blocked=True reason=wal_integrity_fault`. This gives the user a precise + reason instead of an opaque crashloop. + +Option 2 is the better end-state because it makes the status surface +self-explaining (the whole point of Phase 32). Option 1 is acceptable as a +first step if it is faster, but then a pod readiness probe should also reflect +the durable recovery failure so the volume does not appear `1/1 Ready`. + +Secondary defense-in-depth: the pod readiness probe should fail when durable +recovery failed; right now the pod is `1/1 Running` despite the failure. + +## Gate Status + +The D4 gate is **functioning and correctly red.** It moved the product one +layer forward (storage now fails closed) but the user-visible assertion +(`no Ready=True after corruption`) is still violated because of the unwired +volume-process branch. Keep D4 red until the recovery failure reaches the +status surface as a non-Ready, `wal_integrity_fault`-reasoned state. + +## Lab State + +Clean after the always-run cleanup: no helm release, no iSCSI sessions, no +multipath, no sw-block pods, no testops hostPath residue. + +## Bottom Line + +- Storage fail-closed (#51 core): **done and verified live.** Real progress. +- Status surface after corruption: **still Ready=True** — the recovery failure + is logged but not propagated past `cmd/blockvolume/main.go:496`. +- Fix is one branch: turn the typed durable recovery failure into either a + process fail-closed or a published `wal_integrity_fault` observation; the + projection mapping is already in place to do the rest. +- Do not mark D4 passed. One more dev cycle. diff --git a/seaweed-block/internal/docs/qa-assignments/phase34-d4-smartwal-corrupt-verify2.md b/seaweed-block/internal/docs/qa-assignments/phase34-d4-smartwal-corrupt-verify2.md new file mode 100644 index 0000000000..5cc9a3d16d --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase34-d4-smartwal-corrupt-verify2.md @@ -0,0 +1,167 @@ +# QA Verification #2 - Phase 34 D4 SmartWAL Fix (#51 follow-up) + +Verdict: **STILL RED — the false Ready has been chased up one more layer.** +Commit `954083a` correctly stops the volume process from publishing healthy on +a recovery fault (verified live). But blockmaster's ManagedVolume projection +still reports `Ready=True reason=first_volume_verified`, because the volume's +"local readiness blocked / WALIntegrity" state is not carried through the +heartbeat/status channel that the projection consumes. This is now a +contract-level gap, not another local patch. + +Date: 2026-05-30 + +Source commit under test: `954083a blockvolume: block healthy publication on recovery fault` +QA run: `20260530-225116-66a3` +Tracking issue: #51 + +## What `954083a` Got Right (verified live) + +blockvolume recovery log (`corrupt/blockvolume-pods.log`): + +```text +smartwal: recovery CRC mismatch LSN=45 ... — failing closed +blockvolume: durable recovery failed: ... storage: WAL integrity fault +blockvolume: durable recovery faulted; status endpoint remains available and local readiness remains blocked: ... WAL integrity fault +blockvolume: volume pvc-8c5d9111-... local readiness blocked (...WALIntegrity...); NOT applying primary assignment r1@1 to adapter +``` + +- The volume now **blocks local readiness** and **does not enter the adapter**. +- The adapter `PublishHealthy` trace from the prior run (`85d9375`) is **gone** — + grep for PublishHealthy in this run's blockvolume log returns nothing. + +So the `cmd/blockvolume/main.go:496` gap from the previous QA report is closed: +the recovery fault no longer drives a healthy publish. Real progress, third +layer of the onion peeled. + +## What Is Still Broken — one layer up (blockmaster projection) + +operator-snapshot.json for the volume still reports: + +```json +"status": "ready", +"reason_code": "first_volume_verified", +"conditions": [{"type": "Ready", "status": "True", ...}] +``` + +`after-corrupt/corruption-status-summary.txt`: + +```text +ready_true_after_corruption=true +blocked_true_after_corruption=false +reason_after_corruption=first_volume_verified +``` + +And the gate is fed by blockmaster's ClusterEvidenceService, whose +`cluster-evidence.json` shows: + +```text +status: ok +desired_replicas: 1 +observed_replicas: 1 +primary_replica: r1 +replicas: [{ replica_id: r1, replication_role: primary }] +``` + +### Root cause: heartbeat says "present", projection infers "Ready" + +The restarted pod is `1/1 Running`, 0 restarts, and — by the dev's deliberate +design — keeps its status endpoint / heartbeat available so it stays +diagnosable. blockmaster therefore observes: + +```text +replica r1 present + reachable + assigned primary +-> observed_replicas=1, primary_replica=r1, status=ok +-> ManagedVolume projection: Ready=True reason=first_volume_verified +``` + +But the volume's actual state is "local readiness blocked due to WALIntegrity +fault; primary assignment NOT applied to adapter." That fact never reaches the +projection. blockmaster equates "heartbeating + assigned primary" with Ready, +without requiring a positive local-readiness confirmation from the volume. + +This is fresh-but-wrong, not merely a stale cache: blockmaster IS seeing the new +post-restart pod (observed_replicas reflects it). The pod heartbeats as +present; the readiness-blocked nuance is simply not in the channel the +projection reads. + +### Note: the wal_integrity_fault -> Blocked mapping is still dead code live + +Dev added (in `85d9375`) a ManagedVolume projection rule mapping +`wal_integrity_fault -> Blocked`. It is unit-tested and correct. But it still +never fires in the live path, because no live fact carrying +`wal_integrity_fault` reaches blockmaster — the string appears nowhere in the +live operator-snapshot or cluster-evidence. The fact is produced at the volume +(in its log) and consumed by nothing. + +## The Pattern (worth naming) + +This is the third consecutive cycle where a correct, verified fix pushed the +false-Ready up exactly one layer: + +```text +1. storage: skip corrupt record -> fail closed (85d9375, done) +2. volume process: publish healthy anyway -> block readiness (954083a, done) +3. blockmaster: infer Ready from heartbeat -> ??? (this finding) +``` + +Each patch was real and necessary, but the symptom did not move because the +root question was never answered at the contract level: + +**What does `Ready=True` require, end to end?** + +Right now it requires only "replica present + assigned primary + reachable." +It should require "the volume has positively confirmed local readiness." Until +the ManagedVolume projection demands a positive readiness signal (and treats +its absence as Pending/Unknown/Blocked), any volume-side fault that still lets +the pod heartbeat will surface as a false Ready. + +## Recommended Fix (contract-level, not another local patch) + +Pick one, but make it a contract change: + +1. **Carry the fault on the heartbeat/status channel.** The volume's status + endpoint / heartbeat must report `local_readiness=blocked, + reason=wal_integrity_fault` when recovery is faulted. blockmaster's + ManagedVolume projection then receives the fact and the existing + `wal_integrity_fault -> Blocked` mapping fires. This is the smallest change + that makes the dead-code mapping live and gives the user a precise reason. + +2. **Make the projection require positive readiness.** blockmaster must not + project `Ready=True` for an assigned primary that has not confirmed local + readiness. An assigned-but-not-ready-confirmed primary becomes + `Ready=Unknown` / `Pending` / `EvidenceStale` until the volume confirms + readiness. This is the more robust fix because it closes the whole class + (any future volume-side fault that blocks readiness while heartbeating), + not just WALIntegrity. + +Option 2 is the durable answer; option 1 is the targeted one. Ideally both: +the projection should require positive readiness AND the volume should carry a +reason so the user sees `wal_integrity_fault` rather than a bare Unknown. + +This connects directly to the Phase 32 D7 stale/negative-first work: a primary +that is reachable-but-not-ready is the same shape as stale evidence — the +surface must not claim Ready. + +## Gate Status + +D4 remains **functional and correctly red.** It has now driven three real +product fixes and surfaced a fourth, deeper one. Keep it red until the +operator-snapshot shows the corrupted volume as NOT Ready (Blocked with +`wal_integrity_fault`, or Unknown/Pending), never `Ready=True +reason=first_volume_verified`. + +## Lab State + +Clean after the always-run cleanup: no helm release, no iSCSI sessions, no +multipath, no sw-block pods, no testops hostPath residue. + +## Bottom Line + +- `954083a`: **volume no longer publishes healthy on recovery fault — verified.** +- Still false Ready: **blockmaster projects Ready from heartbeat-presence, not + from confirmed local readiness.** The `wal_integrity_fault -> Blocked` mapping + is correct but starves because the fact never reaches it. +- Next fix should be **contract-level**: require positive local-readiness for + Ready (and/or carry `wal_integrity_fault` on the heartbeat channel), not + another local patch one layer down. +- Do not mark D4 passed. diff --git a/seaweed-block/internal/docs/qa-assignments/phase34-d4-smartwal-corrupt-verify3-PASS.md b/seaweed-block/internal/docs/qa-assignments/phase34-d4-smartwal-corrupt-verify3-PASS.md new file mode 100644 index 0000000000..74bd95b120 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase34-d4-smartwal-corrupt-verify3-PASS.md @@ -0,0 +1,131 @@ +# QA Verification #3 - Phase 34 D4 SmartWAL (PASS) + +Verdict: **PASS — no false Ready=True after SmartWAL corruption.** The +contract-level fix `09aa6fe master: require primary readiness evidence` works: +the corrupted volume now reports `Ready=Unknown / status=unknown` instead of +the false `Ready=True reason=first_volume_verified` seen in the three prior +cycles. All 8 required checks satisfied. + +One scenario/lab-infra bug found and worked around (not a product issue) — see +"Scenario Gap" below; it must be fixed or the gate is non-deterministic. + +Date: 2026-06-01 + +Source: branch `phase33-testops-failure-hardening` @ `d86a195`, with product +fix `09aa6fe` + test `7fa34a7`. +Passing run: `20260601-020747-5a1f`, 30/30 actions PASS. + +## Required Checks + +| # | Check | Result | Evidence | +|---|---|---|---| +| 1 | `target_offset_inside_wal=true` | PASS | corruption stdout | +| 2 | `target_offset_inside_extent=false` | PASS | corruption stdout (`mutated_offset=5823`) | +| 3 | blockvolume logs WAL integrity / durable recovery fault | PASS | `failing closed`; `WALIntegrity: CRC mismatch LSN=45 ... WAL integrity fault`; `durable recovery faulted; ... local readiness remains blocked`; `NOT applying primary assignment r1@1 to adapter` | +| 4 | surface does NOT show Ready=True | PASS | `ready_true_after_corruption=false`; operator-snapshot per-volume `status=unknown`, Condition `Ready=Unknown` | +| 5 | Preferred: Blocked/Unknown with `reason=wal_integrity_fault` | PARTIAL | It is **Unknown** (good) but `reason_after_corruption=unknown`, not `wal_integrity_fault`. See note below. | +| 6 | Acceptable: any non-ready generic reason, no Ready=True | **PASS** | `status=unknown`, `Ready=Unknown`, no `Ready=True` on any surface | +| 7 | `cleanup_status=ok` | PASS | cleanup-summary | +| 8 | iSCSI/node-DB/multipath/dmsetup/k8s/process residue clean | PASS | all counts 0; post-run host audit: helm none, no iSCSI sessions, no multipath, no dmsetup, no pods | + +The gate passes on **check 6** (acceptable generic non-ready). Check 5 +(preferred specific `wal_integrity_fault` reason) is **not yet met** — see the +non-blocking note. + +## How the Fix Works + +`09aa6fe` implemented the contract-level fix recommended in QA verify2 +(Option 2): the ManagedVolume projection now refuses to claim `Ready=True` for +an assigned primary that has not positively confirmed local readiness. + +The chain now: + +```text +SmartWAL CRC mismatch +-> storage fails closed (WALIntegrity fault) [85d9375] +-> blockvolume blocks local readiness, does not publish [954083a] +-> blockmaster projection: no positive readiness => Unknown, NOT Ready [09aa6fe] +-> operator-snapshot: status=unknown, Ready=Unknown +``` + +This is the correct negative-first behavior: a corrupted volume is no longer +confidently reported healthy. It closes the false-Ready bug (#51) that survived +three prior fix layers. + +## Non-Blocking Note: reason is generic `unknown`, not `wal_integrity_fault` + +The volume correctly reports NOT-Ready, but the status surface shows +`reason=unknown` rather than the specific `wal_integrity_fault`. The +`wal_integrity_fault` text lives in the blockvolume LOG, not in the +operator-snapshot `reason_code`. This is the "Option 1" half (carry the fault +reason through the heartbeat/status channel) that `09aa6fe` did not implement — +it took Option 2 (require positive readiness) only. + +Per the assignment this is explicitly acceptable for this slice (check 6). The +preferred `reason=wal_integrity_fault` (check 5) remains a follow-up so a cold +operator sees WHY the volume is Unknown without reading blockvolume logs. Not a +blocker for D4 close. + +## Scenario Gap (must fix — gate is non-deterministic without it) + +The first verify-3 rerun (`20260601-015115-61a8`) FAILED at `helm_install_stack` +with a 10-minute timeout. Root cause was NOT the product: + +```text +blockmaster: flag provided but not defined: -launcher-durable-impl +``` + +The `helm-smartwal-corrupt-restart-chain.yaml` build phase rebuilds and imports +`sw-block:local` only on `single_node` (m02). But the chart's blockmaster +Deployment is not pinned to m02, so k3s scheduled it on **m01**, which still had +a STALE `sw-block:local` (predating `8a6737e helm: expose launcher durable +impl`). The stale binary rejected the `--launcher-durable-impl` flag the chart +emits -> CrashLoopBackOff -> `helm install --wait` hung -> timeout. + +Per-node image state at the failure: + +```text +m01 (192.168.1.181): launcher-durable-impl flag = 0 (STALE) +m02 (192.168.1.184): launcher-durable-impl flag = 1 (fresh, built this run) +tp01 (192.168.1.188): launcher-durable-impl flag = 0 (STALE) +``` + +QA unblocked by exporting the fresh `sw-block:local` from m02 and importing it +to m01 + tp01, then re-running — which PASSED 30/30. + +This means the prior "successful" D4 runs passed only because blockmaster +happened to schedule on m02. The gate is non-deterministic: it fails whenever +blockmaster lands on a node with a stale image. + +Fix shape (pick one): + +1. **Pin blockmaster to `single_node`** in the smartwal scenario values + (nodeSelector kubernetes.io/hostname=m02), so it always runs the freshly + built image. Smallest change, matches the single-node intent. +2. **Import `sw-block:local` to all schedulable nodes** in the build phase + (the multi-volume scenarios already do `SW_BLOCK_IMPORT_K3S_NODES=...`). +3. **Pre-clean stale images**: have `pre_run_cleanup` remove `sw-block:local` + from all nodes so a stale one can never be picked. + +Option 1 is the cleanest for this single-node scenario. + +## Lab State + +Clean after the always-run cleanup + QA teardown: no helm release, no iSCSI +sessions, no multipath, no dmsetup, no sw-block pods. Temp image tars QA +distributed to m01/tp01 were removed. + +## Bottom Line + +- **D4 product assertion: PASS.** SmartWAL corruption no longer produces false + Ready=True; the volume reports `Ready=Unknown` via the new + require-positive-readiness projection (`09aa6fe`). +- **#51 is fixed** across all three layers (storage fail-closed, volume + readiness block, projection positive-readiness requirement). +- **Two follow-ups, neither blocking D4 close:** + - Surface `reason=wal_integrity_fault` on the status surface (currently + generic `unknown`) — the Option-1 half. + - Fix the scenario's stale-image non-determinism (pin blockmaster to + single_node, or refresh/clean images on all nodes). +- Per the assignment, **D4 can close** and dev can write the D6 close report. + Recommend filing the two follow-ups so they are tracked, not lost. diff --git a/seaweed-block/internal/docs/qa-assignments/phase34-d4-smartwal-injection-precheck.md b/seaweed-block/internal/docs/qa-assignments/phase34-d4-smartwal-injection-precheck.md new file mode 100644 index 0000000000..755a781c0a --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase34-d4-smartwal-injection-precheck.md @@ -0,0 +1,154 @@ +# Phase 34 D4-0 SmartWAL Injection Precheck + +Date: 2026-05-29 + +Status: PASS for layout + mutation-tool contract; D4 dirty-failure scenario +remains pending. + +## Why this precheck exists + +The existing external TestRunner `corrupt_wal` primitive is V2-shaped. It uses +a fixed offset model: + +```text +walOffset = 4096 +walEnd = min(fileSize, 4096 + 64MiB) +seekPos = walOffset + (walEnd - walOffset) / 3 +``` + +That is not a valid contract for V3 SmartWAL. SmartWAL stores its geometry in +the file header: + +```text +[0 .. headerSize) header +[headerSize .. headerSize+slots*32) WAL ring +[extentStart ..] block extents +``` + +Any WAL corruption test that does not parse the SmartWAL header can produce a +false green by writing to an empty slot or to extent data rather than to a real +WAL record. + +## Delivered precheck + +Added a read-only SmartWAL layout inspector: + +```text +core/storage/smartwal/layout.go +core/storage/smartwal/layout_test.go +``` + +Added an explicit TestOps-only mutation utility: + +```text +cmd/sw-block-testutil smartwal-corrupt-latest-record --path --out +``` + +This utility is deliberately not part of `sw-block ops`; the user-facing ops +surface stays read-only. The utility: + +- parses the SmartWAL layout from the header, +- selects the highest-LSN valid WAL record, +- flips the last byte of that record's CRC, +- fsyncs the file, +- writes `smartwal-corruption-evidence.txt`. + +Added a launcher/Helm selection seam: + +```text +blockmaster --launcher-durable-impl=walstore|smartwal +Helm value: blockmaster.durableImpl +``` + +The default remains `walstore` to preserve existing Helm gates. A SmartWAL D4 +scenario must explicitly set `blockmaster.durableImpl=smartwal`; otherwise it +is not testing SmartWAL at all. + +The inspector returns: + +```text +header_size +record_size +wal_offset +wal_length +wal_end +extent_start +extent_bytes +file_size +block_size +num_blocks +wal_slots +impl_kind +impl_version +``` + +It also exposes helpers to compute the slot offset for an LSN and to check +whether an offset is inside the WAL ring or extent region. + +## Verification + +Command: + +```text +go test ./core/storage/smartwal ./cmd/sw-block-testutil ./core/launcher ./cmd/blockmaster +helm template sw-block charts/seaweed-block --set blockmaster.durableImpl=smartwal +``` + +Result: + +```text +ok github.com/seaweedfs/seaweed-block/core/storage/smartwal +ok github.com/seaweedfs/seaweed-block/cmd/sw-block-testutil +ok github.com/seaweedfs/seaweed-block/core/launcher +ok github.com/seaweedfs/seaweed-block/cmd/blockmaster +``` + +Tests prove: + +- SmartWAL geometry is read from the on-disk header. +- WAL ring bounds are computed as `headerSize + walSlots*recordSize`. +- Record offset uses `slot = lsn % walSlots`. +- Non-SmartWAL files are rejected. +- Truncated SmartWAL files are rejected. +- The mutation utility writes evidence, flips a real record CRC byte, and the + corrupted record no longer decodes as valid. +- Helm can render `--launcher-durable-impl=smartwal` for D4 without changing + the default release path. + +## D4 gate rule + +D4 must not use the legacy `corrupt_wal` primitive directly. + +A valid D4 corruption gate must first capture: + +```text +smartwal_path= +wal_offset= +wal_length= +target_lsn= +target_record_offset= +target_offset_inside_wal=true +target_offset_inside_extent=false +before_bytes= +after_bytes= +mutation=flip_last_record_crc_byte +restart_persistence=hostpath +durable_impl=smartwal +``` + +If those fields are not present, the D4 scenario must fail closed or be marked +blocked. A green result without those fields is considered self-proof, not +storage fault evidence. + +## Remaining work + +D4 dirty-failure testing still needs a live hostPath scenario that: + +1. Locates the SmartWAL file for the target PVC. +2. Selects a real committed WAL record, not an arbitrary byte offset. +3. Mutates that record or its CRC. +4. Restarts the product. +5. Verifies the product refuses false `Ready=True` and emits a stable recovery + reason. + +This precheck only closes the layout-discovery prerequisite. diff --git a/seaweed-block/internal/docs/qa-assignments/phase34-self-proof-audit.md b/seaweed-block/internal/docs/qa-assignments/phase34-self-proof-audit.md new file mode 100644 index 0000000000..9692dc3f2a --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase34-self-proof-audit.md @@ -0,0 +1,114 @@ +# Phase 34 D1 - Self-Proof Audit + +Status: draft on 2026-05-29. + +Purpose: identify TestOps assertions where a helper writes a summary value and +the scenario only greps that same summary value. These checks are useful smoke +signals, but hard product claims need an independent evidence source. + +## Rule + +```text +If a field gates a product claim, validate it against at least one independent +source: Kubernetes state, operator-snapshot JSON, product event stream, host +probe, direct IO, or a stricter verifier. +``` + +## Summary + +The scenario library has many `grep_log` assertions. Most are acceptable as +artifact-shape checks. The risk is concentrated in a smaller set of hard-claim +summary fields: + +- multi-volume counts +- writer/reader verification counts +- restart/failover status summaries +- cross-volume isolation booleans +- cleanup status +- stale-primary rejection and ALUA transition fields + +Not all of these are bad. Some fields already come from real probes +(`stale-primary-probe.log`, RTPG captures, direct workload logs). The main gap +is that several scenarios still treat helper summaries as the final authority +without cross-checking an independent source. + +## Representative Findings + +| ID | Field / Assertion | Current Source | Risk | Classification | Required Cross-Check | +|---|---|---|---|---|---| +| A1 | `multi_volume_status=ok` in `helm-multi-volume-day1-chain.yaml` | `run-multi-volume-example.sh` summary | Can hide partial helper failure if summary is wrong | acceptable smoke | Keep, but not a hard claim by itself | +| A2 | `writer_verified_count=3` in multi-volume gates | Helper counts writer logs | Log count can be correct while pods/PVCs differ from expected topology | needs independent cross-check | `kubectl get pods` by writer labels plus each writer log checksum | +| A3 | `reader_verified_count=3` in multi-volume gates | Helper counts reader logs | Same-source count does not prove 3 distinct PVCs were read | needs independent cross-check | Operator snapshot has 3 distinct volumes; each reader references a distinct PVC | +| A4 | `managed_volume_count=3` in multi-volume gates | Helper counts `managed_volume=` lines in report summary | Report summary and helper may share the same product snapshot assumptions | needs independent cross-check | `operator-snapshot.json` volume array length and distinct `volume_id`/`pvc_name` | +| A5 | `cleanup_status=ok` in user-loop helpers | Helper cleanup result | Acceptable only if verifier is stricter than uninstall | acceptable if verifier-backed | Require `verify-helm-cleanup.sh` residue counters all zero | +| A6 | `pod_recreate_used=false` in mounted-failover gates | Helper summary | Could be self-proof if not tied to pod UID evidence | needs independent cross-check | Compare `writer_pod_uid_before` and `writer_pod_uid_after` artifacts | +| A7 | `old_primary_stale_io_success_count=0` in mounted-failover gates | Direct stale-path probe summary | Lower risk; now probe-backed | acceptable with probe artifact | Require non-empty `stale-primary-probe.log` with `candidate_result` lines | +| A8 | `rtpg_transition_verified=true` | Helper summary from RTPG parsing | Lower risk if before/after AAS files are non-empty and values are asserted | acceptable with artifacts | Require `rtpg-before-states.txt`, `rtpg-after-states.txt`, and AAS value checks | +| A9 | `cross_interference_observed=false` | Helper summary | High-level boolean can hide missing untouched-volume evidence | needs independent cross-check | Untouched volume workload log + unchanged volume status in operator snapshot | +| A10 | `restart_promotion_status=ok` | Scenario-generated restart summary | Can pass without proving status surface convergence | needs independent cross-check | Post-restart report/operator-snapshot eventually Ready for 3 consecutive polls | +| A11 | `multi_volume_restart_status=ok` | Helper summary | Can hide per-volume identity mixup if only summary is read | needs independent cross-check | 3 distinct volume IDs, no duplicate publish target, no primary mixup in operator snapshot | +| A12 | `status_endpoint_unreachable` replay assertions | Synthetic replay bundle | Valid L1 replay, not live fault evidence | should be upgraded | D2 F2b live status-port block; assert Unknown, not Blocked | + +## High-Value Hardening Picks + +Prioritize these first because they support user-visible release claims. + +1. Multi-volume count identity + - Current weak check: `managed_volume_count=3` + - Add cross-check: parse `operator-snapshot.json` and require exactly 3 + distinct `volume_id` values and 3 distinct `pvc_name` values. + +2. Writer/reader verification count + - Current weak check: `writer_verified_count=3` and `reader_verified_count=3` + - Add cross-check: each writer/reader log must map to a distinct PVC, and + the corresponding pod must have reached a terminal verified state. + +3. Mounted no-recreate claim + - Current weak check: `pod_recreate_used=false` + - Add cross-check: compare pod UID before/after for every target volume. + A summary boolean alone is not enough. + +4. Restart convergence + - Current weak check: restart summary says status ok. + - Add cross-check: after restart, status surfaces may temporarily show + Unknown, but must converge to Ready for 3 consecutive polls within the + bounded window. + +5. Status endpoint unreachable + - Current weak check: L1 synthetic replay. + - Add cross-check: D2 F2b live injection blocks only the status endpoint, + then verifies `Ready=Unknown` and not `Blocked`. + +## Acceptable Existing Patterns + +These are not blockers if kept as smoke or artifact-shape checks: + +- Grepping `summary.txt` for report artifact presence. +- Grepping release hygiene fields after an independent Helm command has + already succeeded. +- `cleanup_status=ok` when it is produced by `verify-helm-cleanup.sh` and the + residue counters are also asserted. +- Stale-primary count checks when `stale-primary-probe.log` is non-empty and + contains direct read results. +- RTPG transition checks when raw before/after AAS captures are also asserted. + +## Anti-Patterns To Avoid + +- Do not count a helper's summary field as the only proof of a product claim. +- Do not accept a chaos primitive as proof unless the artifact shows the fault + hit the intended layer. +- Do not let synthetic replay replace live injection for P0 failure claims. +- Do not treat a single transient `Ready=True` after restart as convergence. +- Do not create broad RF/node-count matrices to compensate for weak evidence. + +## D1 Acceptance + +This audit satisfies D1 of `phase34-test-realism-plan.md`: + +- At least 10 representative summary-grep assertions are listed. +- Each is classified as acceptable smoke, needs independent cross-check, or + should be upgraded/replaced. +- Five high-value assertions are selected for first hardening. + +Next implementation step: D2 F2b live status-endpoint-unreachable, while +carrying A4/A6/A10 cross-checks into the next affected scenario edits. diff --git a/seaweed-block/internal/docs/qa-assignments/phase34-test-realism-plan.md b/seaweed-block/internal/docs/qa-assignments/phase34-test-realism-plan.md new file mode 100644 index 0000000000..9deb8cbfb6 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase34-test-realism-plan.md @@ -0,0 +1,299 @@ +# Phase 34 Plan - Test Realism And Anti Self-Proving Gates + +Status: proposed on 2026-05-29. + +Purpose: raise the product test bar from "the scenario can grep the helper's +summary" to "independent evidence proves the product behavior." Phase 33 remains +valid as failure-path hardening; Phase 34 targets the remaining realism gaps. + +## Problem Statement + +The largest remaining testing risk is not raw coverage count. It is tests that +are too close to self-proof: + +```text +helper writes summary value X +scenario greps summary value X +test passes +``` + +That pattern can be useful as a smoke check, but it is weak release evidence +unless another independent source verifies the same claim. + +## Test Realism Levels + +| Level | Name | What It Proves | Release Value | +|---|---|---|---| +| L0 | Self-proof | A helper wrote the string the scenario greps | Low; avoid for hard claims | +| L1 | Replay / component | Given evidence, product surfaces explain it correctly | Good for status/report/dashboard contracts | +| L2 | Live injection | Real fault triggers product observation and classification | Required for P0 failure claims | +| L3 | Adversarial timing | Fault plus concurrency, restart, partial failure, or dirty state does not violate invariants | Required before broad reliability claims | + +Phase 34 should reduce L0 hard assertions, keep L1 where appropriate, and +upgrade selected high-value L1/L2 gates to L2/L3. + +## Scope + +In: + +- TestOps scenario changes. +- Runner/helper assertions that add independent evidence. +- Live status endpoint unreachable injection. +- Dirty-failure tests using existing chaos primitives where available. +- Restart convergence assertions. + +Out: + +- New storage features. +- New public HA claims. +- Operator mutation/admin actions. +- Full chaos matrix for every primitive. +- Large RF/node-count permutation testing. + +## D1: Self-Proof Audit And Cross-Validation Plan + +Goal: identify summary-only assertions that support hard claims and classify +them by risk. + +Deliverable: + +- `internal/docs/qa-assignments/phase34-self-proof-audit.md` + +Acceptance: + +- List at least 10 representative summary-grep assertions. +- Mark each as: + - acceptable smoke, + - needs independent cross-check, + - should be replaced. +- Pick 3-5 high-value assertions to harden first. + +Examples to audit: + +- `managed_volume_count=3` +- `reader_verified_count=3` +- `cleanup_status=ok` +- `old_primary_stale_io_success_count=0` +- `cross_volume_authority_mixup=false` + +Rule: + +```text +If a field gates a product claim, validate it against an independent source: +kubectl, operator-snapshot JSON, product event stream, host probe, or direct IO. +``` + +## D2: F2b Live Status-Endpoint-Unreachable Gate + +Goal: upgrade Phase 33 F2 from L1 replay to L2 live injection. + +Scenario shape: + +```text +helm install +-> create first PVC +-> verify Ready=True first +-> discover replica status_addr +-> block only the status port, not iSCSI data +-> collect report/explain/dashboard +-> assert Ready=Unknown + EvidenceStale/status_endpoint_unreachable +-> assert not Blocked unless another concrete blocker exists +-> remove network rule +-> cleanup zero residue +``` + +Important boundary: + +- Do not kill `blockvolume`. +- Do not block iSCSI data path (`3260`). +- Block only status endpoint traffic, e.g. status port around `23260`. + +Expected status: + +```text +status=unknown +Ready=Unknown +reason=status_endpoint_unreachable +EvidenceStale=True or equivalent stale/unreachable condition +Blocked=True must be absent +Ready=True must be absent +mutation_allowed=false +``` + +Acceptance: + +- TestRunner scenario PASS. +- Product surfaces agree across summary, operator-snapshot, explain, and + dashboard. +- Cleanup restores network rules and leaves zero residue. + +## D3: Restart Convergence Gate + +Goal: distinguish "safe transient Unknown" from "eventual recovery." + +Current gap: + +- Existing restart replay can correctly show `Ready=Unknown` during early + reconvergence. +- It does not always prove the product eventually returns to `Ready=True`. + +Scenario addition: + +```text +after k3s/product restart +-> capture immediate status; Unknown is allowed +-> poll report/operator-snapshot for up to 90s +-> require final Ready=True reason=first_volume_verified or equivalent + for 3 consecutive polls +-> verify primary/epoch/publish target did not roll back +``` + +Acceptance: + +- Immediate Unknown is not failure if evidence is still stale. +- Final non-convergence is failure. +- A single transient Ready=True is not enough; the status must remain Ready for + 3 consecutive polls to avoid passing on Ready/Unknown flicker. +- No old primary is surfaced as Ready during the window. + +## D4: Corrupt WAL Dirty-Failure Gate + +Goal: cover a storage-native dirty failure, not just clean Kubernetes failures. + +Hard prerequisite - D4-0: + +The existing `corrupt_wal` TestRunner primitive must not be used blindly for +V3. It was originally shaped around a V2 durable-file layout with a fixed +superblock plus large WAL region. V3 `smartwal` uses a different layout: + +```text +[header][walSlots * recordSize][block data extents] +``` + +Before any D4 assertion is allowed: + +- Locate the real V3 smartwal store file under the Helm hostPath durable root. +- Read or derive the V3 smartwal header/record layout. +- Prove the injected bytes land inside the WAL ring, not inside data extents. +- Capture an artifact that records file path, WAL offset, WAL length, injected + offset, and before/after byte sample. +- Run with `restartPersistence: hostpath`; `emptyDir` mode is invalid for this + gate because the durable file disappears across pod restart. + +If D4-0 cannot prove V3-aware WAL corruption, D4 must be marked blocked rather +than producing a false green test. + +Precheck artifact: + +- `internal/docs/qa-assignments/phase34-d4-smartwal-injection-precheck.md` +- `core/storage/smartwal.InspectLayout` is the required read-only layout + contract for future D4 injection code. +- `cmd/sw-block-testutil smartwal-corrupt-latest-record` is the TestOps-only + mutation utility; do not put mutating corruption under `sw-block ops`. +- Helm/launcher must explicitly set `blockmaster.durableImpl=smartwal` / + `--launcher-durable-impl=smartwal`; the default Helm path remains `walstore` + and is not valid evidence for a SmartWAL corruption claim. + +Scenario shape: + +```text +create durable volume +write data +stop blockvolume cleanly or at controlled point +use TestRunner corrupt_wal on that volume's durable path +restart product +assert recovery refuses unsafe replay or surfaces explicit recovery failure +assert no silent Ready=True on corrupted evidence +assert cleanup zero residue +``` + +Expected outcome: + +- The exact reason code may need implementation alignment, but it must be + stable and explicit, e.g. `wal_corrupt`, `recovery_evidence_invalid`, or + `durable_recovery_failed`. +- The product must not silently mount or report Ready if the WAL cannot be + trusted. + +Acceptance: + +- Direct evidence of corruption injection is captured. +- Product emits a stable failure reason. +- No false Ready=True. +- Support bundle/replay explains the failure. + +## D5: Optional Netem Slow-Replica Gate + +Goal: test partial network degradation without exploding the matrix. + +Scenario shape: + +```text +RF3 sync-quorum +-> inject_netem latency/loss on one replica status/data path +-> write workload +-> assert foreground behavior is bounded and explainable +-> assert no indefinite hang +-> cleanup netem and residue +``` + +Priority: + +- P1 for Phase 34 unless D2-D4 finish quickly. +- Use one scenario only. Do not create a RF/node-count matrix. +- Do not start D5 until D4-0 has closed. The same realism rule applies: the + fault must affect the intended path, not merely run a chaos primitive. + +## D6: Event Noise Sanity + +Goal: prevent dashboard/timeline from being drowned by repeated identical +events. + +Check: + +```text +For a short first-volume run, repeated identical (volume_id, event_type, +reason_code) events should remain below a documented threshold. +``` + +Acceptance: + +- Establish a threshold rather than zero duplicates. +- If exceeded, classify as product/event-emission debt, not test flake. + +## D7: Close Gate + +Minimum close requirements: + +- D1 audit complete. +- D2 F2b live status-unreachable PASS. +- D3 restart convergence PASS. +- D4 corrupt WAL dirty-failure PASS, or explicitly blocked with a concrete + implementation issue because: + - the product lacks a stable dirty-recovery reason code, or + - the injection primitive is not yet proven against the V3 smartwal layout. +- Existing v0.3.5 user path still PASS. + +Close report must classify each hard claim by realism level: + +```text +L1 replay +L2 live injection +L3 adversarial timing / dirty failure +``` + +## Release Impact + +Phase 34 should not block `v0.3.5-alpha` if Phase 33 is already accepted. It is +the right next hardening phase before any broader reliability or production-like +claims. + +If Phase 34 closes cleanly, a later release may claim stronger language: + +```text +Failure evidence is tested through live injection and selected dirty-failure +paths, not only bundle replay. +``` + +Still do not claim production readiness, rebuild/failback, backup/restore, or +broad SLOs. diff --git a/seaweed-block/internal/docs/qa-assignments/phase35-d1-operator-crd-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase35-d1-operator-crd-qa-signoff.md new file mode 100644 index 0000000000..b68eab62bc --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase35-d1-operator-crd-qa-signoff.md @@ -0,0 +1,81 @@ +# QA Sign-off - Phase 35 D1 Read-Only Operator CRD Contract + +Verdict: **PASS.** The SwBlockCluster + SwBlockVolume CRDs and the +disabled-by-default status-only operator RBAC render cleanly, are accepted by +the live k3s API server (server-side dry-run), and hold the read-only contract: +status subresources present, full condition vocabulary, evidence refs, and no +storage-mutation RBAC. No findings. + +Date: 2026-06-02 + +Source commit: `8332225 phase35: add read-only operator CRD contract` +(branch `phase33-testops-failure-hardening`) + +## Checks + +| Check | Result | Evidence | +|---|---|---| +| Unit tests (CRD contract enforcement) | PASS | `go test ./core/ops ./cmd/sw-block` — both ok | +| CRDs render with `--include-crds` | PASS | 18 objects, incl. 2 CustomResourceDefinitions | +| Live k3s API accepts CRDs + RBAC | PASS | `kubectl apply --dry-run=server` accepted all 18 objects, both CRDs validated server-side, no errors | +| Status subresource present | PASS | both CRDs: `subresources: status: {}` | +| Condition vocabulary complete | PASS | SwBlockVolume enum: `Ready, Recovered, Recovering, Blocked, CleanupRequired, EvidenceStale` | +| Evidence refs in schema | PASS | `status.conditions[].evidenceRefs` + top-level `status.evidenceRefs`; plus `reasonCode`/`reason` | +| RBAC read-only / no storage mutation | PASS | CRD resources `get/list/watch`; `.../status` `get/update/patch`; events `create`. No verbs on pods/pvc/deployments/storage | +| Disabled by default | PASS | default render (no `operatorStatus.create`) emits 0 operator-status objects; RBAC gated by `operatorStatus.create && rbac.create` | +| Nothing persisted (dry-run only) | PASS | post-run: no swblock CRDs, no operator-status ClusterRole on the cluster | + +## Contract Detail + +### CRDs (`charts/seaweed-block/crds/`) + +```text +group: block.seaweedfs.com (matches operator-snapshot.json crd_contract.group) +scope: Namespaced +version: v1alpha1 (served + storage) +subresources: status: {} +``` + +SwBlockVolume status: `status` enum (`ready/recovered/recovering/blocked/...`), +`reasonCode`, per-condition `type` (the 6-value vocabulary), `status`, `reason`, +`evidenceRefs`. This is the Kubernetes-native projection of the same +ManagedVolume model the operator-snapshot already exposes. + +### RBAC (`templates/operator-status-rbac.yaml`) + +```yaml +{{- if and .Values.operatorStatus.create .Values.operatorStatus.rbac.create }} +resources: ["swblockclusters", "swblockvolumes"] verbs: [get, list, watch] +resources: ["swblockclusters/status", "swblockvolumes/status"] verbs: [get, update, patch] +resources: ["events"] verbs: [create] +``` + +The only writes are to the `/status` subresource (status publication) and +`events` (event emission). There are NO mutating verbs on storage resources +(pods, pvc, deployments) and NO `create/delete` on the CRDs themselves. This is +consistent with the read-only operator foundation: a status operator publishes +status + events, it does not mutate storage or lifecycle. + +## Non-Claims Held + +D1 adds the CRD shape and status RBAC only. It does NOT install a running +controller-manager, does not reconcile, and does not mutate storage. The +contract is the same read-only boundary the `operator-snapshot.json` already +honors, now expressed as Kubernetes-native CRDs. The CRDs are +disabled-by-default and require explicit `operatorStatus.create=true` to render. + +## Lab State + +Clean — the validation was server-side dry-run only; nothing was applied. No +swblock CRDs or operator-status RBAC persisted on the cluster. + +## Bottom Line + +- D1 read-only operator CRD contract: **PASS, no findings.** +- CRDs are schema-valid (k3s server accepts them), carry status subresource + + full condition vocabulary + evidence refs, and the RBAC is read-only with no + storage mutation. +- Disabled-by-default; opt-in via `operatorStatus.create=true`. +- D1 can close. Recommend QA re-validate live status publication (a running + status reconciler writing real SwBlockVolume.status) when D2+ wires it — this + D1 slice is contract + RBAC shape only, which is correct for the foundation. diff --git a/seaweed-block/internal/docs/qa-assignments/phase35-d2-operator-status-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase35-d2-operator-status-qa-signoff.md new file mode 100644 index 0000000000..100e2317da --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase35-d2-operator-status-qa-signoff.md @@ -0,0 +1,103 @@ +# QA Sign-off - Phase 35 D2 Dry-Run Operator Status Controller + +Verdict: **PASS.** The dry-run operator-status controller packages cleanly, +the live k3s API accepts it, the `dryRun=false` guard rejects as designed, it +is disabled by default, and the **live smoke proves the controller runs +read-only: it observes cluster status via blockmaster and writes ZERO CRD +objects** (`mutation_allowed=false`). One minor transient (startup +connection-race) noted, non-blocking. + +Date: 2026-06-02 + +Source commit: `6d8abba phase35: package dry-run operator status controller` +(branch `phase33-testops-failure-hardening`) + +## Checks + +| Check | Result | Evidence | +|---|---|---| +| Unit tests | PASS | `go test ./cmd/blockcsi ./core/ops ./cmd/sw-block` — all ok | +| Render (create=true) incl. operator-status Deployment | PASS | 3 Deployments (blockmaster, csi-controller, operator-status) + 2 CRDs + operator SA/RBAC | +| Live k3s API accepts manifests | PASS | `kubectl apply --dry-run=server` accepted `deployment.apps/sw-block-operator-status` + SA + ClusterRole + ClusterRoleBinding + both CRDs | +| Guard: `dryRun=false` rejected | PASS | `helm template --set operatorStatus.dryRun=false` → `Error: operatorStatus.create=true currently requires operatorStatus.dryRun=true; real CRD status writes are not wired yet` | +| Disabled by default | PASS | default render = 0 `sw-block-operator-status` objects | +| sw-block binary in image | PASS | fresh `sw-block:local` has `/usr/local/bin/sw-block` (19MB) | +| **Live smoke: controller runs read-only** | PASS | see below | + +## Live Smoke Detail + +Built fresh images (Dockerfile.sw-block now ships `/usr/local/bin/sw-block`), +installed with `--set operatorStatus.create=true`, CRDs auto-installed from +`crds/`. + +operator-status pod: `1/1 Running` on m02, command +`/usr/local/bin/sw-block ops operator-status --dry-run`. + +Successful dry-run iteration logged: + +```text +operator_status=dry_run cluster=kube-system/sw-block volumes=0 events=0 mutation_allowed=false +cluster_status volumes=0 ready=0 blocked=0 stale=0 +``` + +**Read-only proof:** after the controller ran its dry-run iteration, + +```text +kubectl get swblockclusters,swblockvolumes -A +-> No resources found +``` + +The controller observed cluster status from blockmaster (read path) and wrote +**zero** objects to the SwBlockCluster / SwBlockVolume CRDs. `mutation_allowed=false` +is reported. This is exactly the D2 contract: a packaged controller that runs, +observes, and does not write — the dry-run foundation before real status +publication is wired. + +## Non-Blocking Finding + +### N1: transient blockmaster connection-refused on startup + +The operator-status pod's first dry-run iterations logged: + +```text +sw-block ops operator-status: rpc error: code = Unavailable desc = connection error: + dial tcp 10.43.37.122:9333: connect: connection refused +sw-block ops operator-status: dry-run iteration failed exit=2; retrying in 30s +``` + +This is a startup-ordering race: the operator-status pod starts and runs its +first iteration before blockmaster's gRPC (`blockmaster:9333`) is listening. +It self-heals — the 30s retry succeeds once blockmaster is up (the successful +`operator_status=dry_run` line above is from a later iteration). The pod stays +`1/1 Running` (its own readiness does not depend on blockmaster), and +`helm install --wait` passed. + +Not a blocker. Worth a small polish so first-boot logs are not alarming: +either a short initial backoff, or treat "blockmaster not yet reachable" as an +expected `EvidenceStale`/pending state rather than `exit=2 failed`. A cold +operator reading the logs should see "waiting for blockmaster," not an error. + +## Non-Claims Held + +D2 packages a controller that runs in **dry-run only**. It does not write CRD +status (proven: zero CR objects), `mutation_allowed=false`, and the chart guard +hard-rejects `dryRun=false` until real writes are wired. Disabled by default; +opt-in via `operatorStatus.create=true` (which still forces dryRun=true). + +## Lab State + +Clean — uninstalled, CRDs deleted (helm uninstall does not remove `crds/`), no +sw-block pods, no operator-status pod, no iSCSI sessions, no multipath. + +## Bottom Line + +- D2 dry-run operator-status controller: **PASS.** +- Packaging (render + server dry-run + guard + default-disabled): all green. +- Live runtime: controller starts, runs `--dry-run`, reads cluster status, + reports `mutation_allowed=false`, and writes **zero** CRD objects. +- One non-blocking polish: tame the first-boot blockmaster connection-race log + (expected-pending rather than error). +- D2 can close. Next slice (D3+) wiring real status writes should be + QA-validated with `dryRun=false` actually allowed and the controller + publishing real `SwBlockVolume.status` — at which point the read-only-proof + flips to a "writes correct status, still no storage mutation" check. diff --git a/seaweed-block/internal/docs/qa-assignments/phase35-d3-operator-status-writer-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase35-d3-operator-status-writer-qa-signoff.md new file mode 100644 index 0000000000..cba9793b0e --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase35-d3-operator-status-writer-qa-signoff.md @@ -0,0 +1,269 @@ +# QA Sign-off - Phase 35 D3 Real CRD Status Writer + +Verdict: **PASS (re-validated on `e3cf010`).** The original `0f76325` was +**BLOCKED** — the `SwBlockVolume` status writer emitted `allowedActions[]` in +snake_case (`mutation_allowed`) while the CRD schema requires camelCase +(`mutationAllowed`), so every per-volume patch was rejected `422` and +`SwBlockVolume.status` stayed empty. The fix `e3cf010` adds a separate camelCase +CRD-status DTO and maps into it before patching. Re-validated live: the per-volume +status now lands, includes `allowedActions[0].mutationAllowed`, agrees with +first-volume evidence, the 422 is gone, and the safety boundary is unchanged. + +The original blocked write-up is preserved below as the record of the finding; +the **Re-Validation** section at the end is the current PASS. + +Date: 2026-06-03 (blocked) → 2026-06-03 (re-validated PASS) + +Source commit (blocked): `0f76325 phase35: add crd status writer` +Fix commit (PASS): `e3cf010 phase35: fix volume status action schema` +(branch `phase33-testops-failure-hardening`) + +--- + +## ORIGINAL FINDING (blocked, `0f76325`) — preserved for the record + +## Checks + +| # | Check | Result | Evidence | +|---|---|---|---| +| 1 | Unit tests (`go test ./core/ops`) | PASS | ok — but see note: the writer unit test checks URL/method, not schema validity | +| 2 | Guard lifted: `dryRun=false` now installs | PASS | `--dry-run` arg conditional on `operatorStatus.dryRun`; install exit=0, pod `1/1 Running`, log `operator_status=write_status` (no longer `dry_run`) | +| 3 | RBAC: no storage/workload mutation power | **PASS** | live `auth can-i` as SA — all `no` (see below) | +| 4 | RBAC: can patch `/status`, not spec | **PASS** | `patch swblockvolumes --subresource=status: yes`; `patch swblockvolumes` (spec): `no`; same for swblockclusters | +| 5 | SwBlockCluster `.status` patched, agrees w/ evidence | **PASS** | `{readyVolumeCount:1, volumeCount:1, nodeCount:1, blockedVolumeCount:0, staleVolumeCount:0}` after first volume provisioned | +| 6 | **SwBlockVolume `.status` patched, agrees w/ evidence** | **FAIL** | `.status = []` (never written); writer rejected `422` every iteration (5×/40 log lines — deterministic) | +| 7 | Lab clean after teardown | PASS | 0 pods/pvc/pv/crd, 0 iSCSI sessions, 0 multipath | + +## The Bug (blocking): SwBlockVolume status writer payload violates the CRD schema + +### Live symptom + +With the `SwBlockVolume` stub present (name `d3-first-vol`, ns `kube-system`, +matching the PVC the controller maps from), the controller's status PATCH is +rejected every iteration: + +```text +sw-block ops operator-status: patch swblockvolumes/d3-first-vol status failed: + http 422 ... SwBlockVolume "d3-first-vol" is invalid: + status.allowedActions[0].mutationAllowed: Required value + (reason: FieldValueRequired, field: status.allowedActions[0].mutationAllowed) +``` + +Result: `kubectl get swblockvolume d3-first-vol -o jsonpath='{.status}'` → empty. +The per-volume status is **never** published. + +### Root cause: snake_case payload vs camelCase CRD schema + +The CRD (D1, `8332225`) declares `status.allowedActions[]` with **required** +camelCase fields: + +```text +status.allowedActions.items.required = ["type", "mode", "mutationAllowed"] +properties: type, mode(enum read_only|dry_run), mutationAllowed(bool), + sideEffectClass, ownerExecutor, preconditions, invariantRefs, evidenceRefs +``` + +The writer (D3) builds the patch from `ManagedVolumeOperatorAction` +(`core/ops/managed_volume_operator_contract.go:28`), whose JSON tags are +**snake_case** — because it is the `operator-snapshot.json` contract type: + +```go +type ManagedVolumeOperatorAction struct { + Type string `json:"type"` // ✓ matches CRD + Mode string `json:"mode"` // ✓ matches CRD + SideEffectClass string `json:"side_effect_class"` // ✗ CRD: sideEffectClass + OwnerExecutor string `json:"owner_executor,omitempty"` + MutationAllowed bool `json:"mutation_allowed"` // ✗ CRD: mutationAllowed (REQUIRED) + ... +} +``` + +`operator_status_controller.go:146` copies `volume.AllowedActions` (this +snake-cased type) **straight into** the CRD `status.allowedActions` patch. +k3s structural-schema validation prunes the unknown `mutation_allowed` key, so +the required `mutationAllowed` is absent → `422 FieldValueRequired`. + +### Why the cluster writer works but the volume writer does not + +The cluster-status DTO (`operator_status_controller.go:41-45`, +`OperatorClusterStatus`) already uses **camelCase** tags +(`json:"mutationAllowed"`, `json:"allowedActionModes"`). That is why +`SwBlockCluster.status` patches cleanly. Only the per-volume `allowedActions[]` +array reuses the snake-cased `operator-snapshot` type without remapping. + +### Fix shape (and a trap to avoid) + +Do **not** simply rename the struct tag to `json:"mutationAllowed"`. That tag is +the live `operator-snapshot.json` contract — confirmed snake_case on the wire +(`mutation_allowed`, `side_effect_class`, `owner_executor` in shipped snapshots) +and asserted by `operator_snapshot_test.go` / `managed_volume_operator_contract_test.go`. +Flipping it would break the snapshot surface and those tests. + +The surgical fix is a **separate camelCase CRD-status DTO** for +`allowedActions[]` (map `ManagedVolumeOperatorAction` → a CRD action type with +camelCase tags before the patch), mirroring what `OperatorClusterStatus` already +does for the cluster level. Then re-run this exact live check until +`SwBlockVolume.status` is non-empty and agrees with first-volume evidence. + +### Why unit tests + dry-run missed it + +- **D2 was dry-run** — zero writes, so no schema ever validated the payload. +- The writer unit test (`TestKubernetesStatusClientPatchesOnlyStatusSubresources`) + asserts the request URL ends in `/status` and the method is `PATCH` against a + *mock* server. A mock does not enforce the CRD OpenAPI schema, so a payload + with the wrong field casing passes the unit test but fails the real API server. +- Only a **live** patch against an installed CRD (this check) exercises + structural-schema validation. This is the value of the live gate. + +## What PASSED (and is solid) + +### Safety boundary — operator-status SA has no mutation power (live `auth can-i`) + +```text +DENIED (must be no): + create pods: no delete pods: no patch pvc: no delete pvc: no + create secrets: no patch deployments: no delete storageclass: no + create swblockvolumes: no delete swblockvolumes: no (cannot even create/delete the CRs) + patch swblockvolumes (spec): no patch swblockclusters (spec): no + +ALLOWED (status publication only): + patch swblockvolumes --subresource=status: yes + patch swblockclusters --subresource=status: yes + get/list swblockvolumes: yes create events: yes +``` + +Even in write mode the controller logs `mutation_allowed=false` — a CRD status +write is not a storage mutation. The SA can publish `/status` and emit events +and **nothing else**. This is exactly the read-only-operator contract. + +### Cluster status write — works and agrees with evidence + +After provisioning a first volume (PVC `d3-first-vol`, Bound to +`pvc-08000df3-…`, `sw-block-dynamic` SC), `SwBlockCluster.status` was patched to: + +```json +{"volumeCount":1,"readyVolumeCount":1,"nodeCount":1, + "blockedVolumeCount":0,"staleVolumeCount":0,"observedAt":"2026-06-04T01:09:55Z"} +``` + +`readyVolumeCount` moved 0→1 as the volume came up — the cluster-level writer +correctly reflects first-volume-verified evidence. (Note: the consuming pod was +still `ContainerCreating` at teardown — iSCSI mount latency — but the volume was +provisioned and counted ready, which is the evidence under test.) + +## Repro (for dev) + +1. Build images, `helm install sw-block ... --set operatorStatus.create=true --set operatorStatus.dryRun=false`. +2. `kubectl -n kube-system apply` a `SwBlockCluster/sw-block` stub (`spec: {}`). +3. Create a PVC on `sw-block-dynamic` + consuming pod (first volume). +4. `kubectl -n kube-system apply` a `SwBlockVolume/` stub (`spec: {}`). +5. Watch the controller: cluster status patches; volume status 422s on + `allowedActions[0].mutationAllowed`. `get swblockvolume -o jsonpath='{.status}'` → empty. + +## Non-Blocking Carry-Forward (still open from prior slices) + +- N1 (from D2): first-boot blockmaster `connection refused` transient still + present in write-mode logs (`dial tcp …:9333 connect: connection refused`, + self-heals on 30s retry). Cosmetic; tame so cold operators don't see an error. +- From D4: surface `reason=wal_integrity_fault` on the status surface (still + generic) — independent of D3. + +## Lab State + +Clean — helm uninstalled, both CRDs deleted, stubs deleted, PVC/PV deleted, +0 sw-block pods, 0 iSCSI sessions, 0 multipath. + +## Bottom Line + +- **D3 is BLOCKED.** Safety boundary: PASS. Cluster status writer: PASS. + **SwBlockVolume status writer: FAIL** — it never writes, because its + `allowedActions[]` payload is snake_case while the CRD schema requires + camelCase `mutationAllowed`. `422` on every iteration; `.status` stays empty. +- Single, precise fix: map `ManagedVolumeOperatorAction` → a camelCase CRD + action DTO for the status patch (do **not** flip the snapshot struct tag — + it would break `operator-snapshot.json`). Cluster status already does this + right; mirror it for volumes. +- Add a regression that validates the volume status patch against the **real** + CRD schema (envtest/server-side dry-run), not a mock — the current unit test + only checks URL/method and so cannot catch field-casing drift. +- Re-validate live: `SwBlockVolume.status` non-empty and agreeing with + first-volume evidence (`status=ready`, `reason=first_volume_verified`), with + the safety boundary unchanged. Do not close D3 until the per-volume status + actually lands. + +--- + +## RE-VALIDATION (`e3cf010`) — PASS + +Re-ran the exact live flow against `e3cf010 phase35: fix volume status action +schema` (fresh images built + imported to m01/m02/tp01; `helm install … --set +operatorStatus.create=true --set operatorStatus.dryRun=false`, exit=0). + +### The fix + +`operator_status_controller.go` now has a dedicated camelCase CRD-status DTO +`SwBlockVolumeCRDAction` (`json:"mutationAllowed"`, `sideEffectClass`, +`ownerExecutor`, `invariantRefs`, `evidenceRefs`) and maps each +`ManagedVolumeOperatorAction` into it via `swBlockVolumeCRDActions()` before +patching `SwBlockVolume.status`. The snake_case `ManagedVolumeOperatorAction` is +untouched, so `operator-snapshot.json` keeps its snake_case contract. Exactly +the surgical split recommended above; cluster status was already camelCase. + +### Live results + +| # | Check | Result | Evidence | +|---|---|---|---| +| 1 | SwBlockVolume `.status` patched (was empty) | **PASS** | `.status` now populated (full JSON below) | +| 2 | `allowedActions[0].mutationAllowed` lands | **PASS** | `"allowedActions":[{"mode":"read_only","mutationAllowed":false,"ownerExecutor":"ops","sideEffectClass":"observe","type":"observe.collect_bundle"}]` — camelCase | +| 3 | 422 gone | **PASS** | controller log: `422 occurrences: 0`; only prior failures were `http 404 NotFound` (pre-stub window, before the SwBlockVolume CR existed) | +| 4 | Status agrees with first-volume evidence | **PASS** | `status:ready`, `reasonCode:first_volume_verified`, Condition `Ready=True reason=first_volume_verified`, `volumeID:pvc-1d87b2ec-…` matches the bound PV, `pvcName:d3-first-vol` | +| 5 | Controller wrote **only** `/status`, not spec | **PASS** | `SwBlockVolume.spec = {}` after multiple write iterations | +| 6 | Cluster status still agrees | **PASS** | `SwBlockCluster.status.readyVolumeCount=1`, `volumes=1` in `write_status` log | +| 7 | Safety boundary unchanged | **PASS** | SA `auth can-i`: `patch swblockvolumes --subresource=status: yes`; `patch swblockvolumes (spec): no`; `create pods: no`; `patch pvc: no`; `delete swblockvolumes: no`. `mutation_allowed=false` in write mode | +| 8 | Steady-state clean | **PASS** | last 3 iterations all `operator_status=write_status … volumes=1 … mutation_allowed=false`, no failures | + +Full written `SwBlockVolume.status`: + +```json +{"allowedActions":[{"mode":"read_only","mutationAllowed":false,"ownerExecutor":"ops", + "sideEffectClass":"observe","type":"observe.collect_bundle"}], + "conditions":[{"type":"Ready","status":"True","reason":"first_volume_verified", + "severity":"info","message":"managed volume is ready for the documented path"}], + "status":"ready","reasonCode":"first_volume_verified", + "pvcName":"d3-first-vol","volumeID":"pvc-1d87b2ec-7e56-471e-b7bd-c4b9e11c8dec", + "observedAt":"2026-06-04T01:36:45Z"} +``` + +### Regression coverage (dev added) + +`operator_status_controller_test.go` now asserts the marshaled volume status +JSON **contains** `"mutationAllowed":false` and **does not contain** +`mutation_allowed`. That directly guards this casing bug. Note it is a +marshaled-string assertion, not an envtest/server-side-dry-run against the live +CRD OpenAPI schema — so it catches field-casing drift but would not catch other +schema-shape drift (e.g. a newly-required field, or an out-of-enum `mode` +value). A server-side-dry-run check on the patch payload would close that gap +fully; non-blocking, filed as a follow-up. + +### Carry-forward (non-blocking, unchanged) + +- N1 (from D2): first-boot blockmaster connection-refused transient still + present; self-heals. +- Cosmetic: the per-iteration failure log reads `dry-run iteration failed + exit=2` even when running in **write** mode (the pre-stub 404 logged this). + Mislabel — should say "iteration"/"write", not "dry-run". Tiny polish. +- From D4: surface `reason=wal_integrity_fault` on the status surface. + +### Lab state + +Clean — helm uninstalled, both CRDs deleted (cascades CR instances), PVC/PV/pod +deleted; 0 sw-block pods, 0 PVC, 0 iSCSI sessions, 0 multipath. + +### Bottom line + +- **D3 PASS on `e3cf010`.** `SwBlockVolume.status` is published with the + camelCase `mutationAllowed` the schema requires; status agrees with + first-volume evidence; the 422 is gone; the controller writes only `/status` + (spec untouched); and the SA still has zero storage/workload mutation power. +- **D3 can close.** Recommend the server-side-dry-run regression and the + log-label polish as tracked, non-blocking follow-ups. diff --git a/seaweed-block/internal/docs/qa-assignments/phase35-d4-operator-status-events-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase35-d4-operator-status-events-qa-signoff.md new file mode 100644 index 0000000000..506ef75870 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase35-d4-operator-status-events-qa-signoff.md @@ -0,0 +1,283 @@ +# QA Sign-off - Phase 35 D4 Operator Status Events (Blocked-Condition Gate) + +Verdict: **PASS (re-validated on `a2714c8`).** The original `e0330b7` was +**BLOCKED** — a blocked volume's two same-reason conditions (`Ready=False` + +`Blocked=True`) generated two events with an identical name, the second +`409 AlreadyExists` was treated as fatal, and the reconcile aborted (`exit=2`), +halting status publication for any later volume. The fix `a2714c8` makes +`EmitEvent` treat `409` as idempotent success and makes event emission +best-effort (errors no longer abort the reconcile). Re-validated live: the +blocked one-shot reconcile now **exits 0** (both within-run-duplicate and +re-run), the Warning event lands, status is correct, no `Ready=True` on any +surface, and the SA boundary is unchanged. Two non-blocking event-hygiene +follow-ups noted (the abort masked them before). + +The original blocked write-up is preserved below; the **Re-Validation** section +at the end is the current PASS. + +Date: 2026-06-03 (blocked) → 2026-06-04 (re-validated PASS) + +Source commit (blocked): `e0330b7 phase35: publish operator status events` +Fix commit (PASS): `a2714c8 phase35: make operator events idempotent` +(branch `phase33-testops-failure-hardening`) + +--- + +## ORIGINAL FINDING (blocked, `e0330b7`) — preserved for the record + +## How the gate was driven + +The `csi_node_image_pull_failed` blocked condition is only reachable through the +**`--from-bundle`** projection (`buildImagePullBlockedEvidence`); the live +`--master-api` path the helm chart wires cannot synthesize it. So, faithfully: + +1. Built `e0330b7` images, `helm install … --set operatorStatus.create=true + --set operatorStatus.dryRun=false` (exit=0, operator-status `1/1 Running`, + `operator_status=write_status`). +2. Created `SwBlockCluster/sw-block` + `SwBlockVolume/unknown` stubs (the bundle + blocked volume has `VolumeID=unknown`, so `SwBlockVolumeObjectName` → `unknown`). +3. **Inside the operator-status pod** (so it runs as the constrained + operator-status SA via in-cluster config), injected a synthesized + `kube-system-pods-deploys.txt` with a `sw-block-csi-node … ImagePullBackOff` + line, then ran a one-shot write-mode reconcile: + `sw-block ops operator-status --from-bundle /tmp/bb --namespace kube-system + --cluster-name sw-block` (`--interval=0` → one iteration, no `--dry-run`). + +This exercises the exact `OperatorStatusReconciler` + `KubernetesStatusClient` +write path the deployment uses, under the real SA RBAC. + +## Checklist — all six pass in isolation + +| # | Check | Result | Evidence | +|---|---|---|---| +| 1 | `SwBlockVolume.status.status=blocked` | **PASS** | CRD `.status.status="blocked"` | +| 2 | `Ready=False`, `Blocked=True` | **PASS** | conditions: `{type:Ready,status:False,reason:csi_node_image_pull_failed}`, `{type:Blocked,status:True,reason:csi_node_image_pull_failed}` | +| 3 | `reasonCode=csi_node_image_pull_failed` | **PASS** | CRD `.status.reasonCode` + both condition reasons | +| 4 | Warning Event, reason `csi_node_image_pull_failed` | **PASS (partial)** | `kubectl get events`: `Warning csi_node_image_pull_failed swblockvolume/unknown "managed volume is blocked; …"` — **one** of the two events landed; see bug | +| 5 | No `Ready=True` in CRD/report/dashboard/operator-snapshot | **PASS** | CRD Ready=False; `grep -ic ready.*true` over report dir + dashboard = 0; operator-snapshot `status:blocked`; summary `status=blocked` | +| 6 | operator-status SA has no storage/workload mutation power | **PASS** | live `auth can-i` (below) | + +### Surfaces (all show blocked, none show Ready=True) + +operator-snapshot.json (from-bundle, the controller's own source): + +```json +"status": "blocked", "reason_code": "csi_node_image_pull_failed", +conditions: [ {Ready, False, csi_node_image_pull_failed}, + {Blocked, True, csi_node_image_pull_failed} ], +events: [ {Warning, csi_node_image_pull_failed}, + {Warning, csi_node_image_pull_failed} ] <-- two same-reason events +``` + +summary.txt: + +```text +status=blocked +managed_volume=unknown status=blocked reason=csi_node_image_pull_failed +managed_volume_condition=Ready status=False reason=csi_node_image_pull_failed severity=warning +managed_volume_condition=Blocked status=True reason=csi_node_image_pull_failed severity=warning +managed_volume_action=safe_k8s.import_csi_image mode=dry_run side_effect=safe_k8s +read_only=true +``` + +### SA boundary (live `auth can-i` as the operator-status SA) + +```text +ALLOWED: create events: yes patch swblockvolumes --subresource=status: yes + update swblockclusters --subresource=status: yes +DENIED: patch/create/delete swblockvolumes (spec): no + create/delete pods: no patch/delete pvc: no + create secrets: no patch deployments: no delete storageclass: no +``` + +Status publication + events only. No storage/workload mutation. (Events:create +was already in the D1 RBAC; this run confirms it is the *only* new write power.) + +## The Bug (blocking): duplicate same-reason events collide and abort the reconcile + +### Symptom + +The one-shot write-mode reconcile failed: + +```text +sw-block ops operator-status: create event csi_node_image_pull_failed failed: + http 409 events "unknown-csi-node-image-pull-failed.1780554986804185681" + already exists (reason: AlreadyExists) +command terminated with exit code 2 +``` + +The SwBlockVolume `.status` was fully patched (it happens before the event +loop), and the **first** Warning event landed. The **second** event create +collided `409` and the reconcile aborted. + +### Root cause + +A blocked volume's negative-first projection emits **two conditions that share +one reason**: `Ready=False` and `Blocked=True`, both `csi_node_image_pull_failed`. +The reconciler emits **one event per condition** +(`operator_status_controller.go:166`) and stamps every event with the **same** +`observedAt` (`:173`). The event name +(`kubernetes_status_writer.go:173-178`) is: + +```text +kubernetesName(InvolvedObject.Name + "-" + Reason) + "." + observedAt.UnixNano() += "unknown-csi-node-image-pull-failed." + 1780554986804185681 (identical for both) +``` + +So both events resolve to the **same name** → event #1 creates, event #2 → `409 +AlreadyExists`. `EmitEvent` returns that as an error, and the reconciler +**returns on the first EmitEvent error** (`operator_status_controller.go:174-176`), +aborting the whole `Reconcile` with `exit=2`. + +### Why it is blocking, not cosmetic + +- The negative-first contract emits `Ready=False` + `Blocked=True` with the same + root reason for **every** blocked volume — so this fires for any blocked + reason, including ones reachable on the **live `--master-api`** path + (`wal_integrity_fault`, `writer_mount_failed`, loopback, …), not just the + from-bundle image-pull case used to reproduce it. +- Because `Reconcile` returns on the error, **volumes ordered after the blocked + one in the iteration never get their status written**, and the deployed + controller logs perpetual `iteration failed exit=2; retrying` for that cluster. +- Net: one blocked volume poisons status publication for the rest of the + iteration. The status path silently looks fine for healthy volumes but breaks + the moment anything is blocked — exactly when operators most need it. + +### Fix shape + +Minimal and standard: in `EmitEvent`, treat `409 AlreadyExists` as idempotent +**success** (`return nil`). That alone makes the iteration pass; the two +same-name events collapse to one Warning event (acceptable — same object + +reason + time; the distinct Ready/Blocked detail is already on the CRD status +conditions). + +If both events should land distinctly, also disambiguate the name per condition +(include `condition.Type` or a message hash in the suffix). And consider +deduping `volume.Events` by `(reason)` or `(reason,type)` at the contract layer +so the controller does not emit redundant same-reason events at all. + +Either way, the reconcile must not abort on a duplicate event — event emission +is best-effort telemetry and must never block status publication. + +### Why unit tests missed it + +`kubernetes_status_writer_test.go` emits a **single** event and asserts the POST +body shape against a mock — it never emits two same-reason events in one +reconcile, and the mock does not enforce the API server's name-uniqueness, so +the 409 (and the reconcile-abort) only appear against a live API server with a +genuinely blocked, multi-condition volume. Recommend a reconciler test that +feeds a blocked volume (Ready=False + Blocked=True, same reason) through a fake +event sink that rejects duplicate names, asserting the reconcile still succeeds. + +## Also Verified (the D3 carry-forward log polish) + +`e0330b7` fixed the cosmetic I flagged in D3: the retry log now reads `iteration +failed` rather than `dry-run iteration failed`. (It was emitted on the pre-stub +404 path in D3; the wording is corrected.) + +## Lab State + +Clean — `SwBlockVolume`/`SwBlockCluster` stubs deleted, the Warning event +deleted, helm uninstalled, both CRDs deleted; 0 sw-block pods, 0 CRDs, 0 iSCSI +sessions. + +## Bottom Line + +- **D4 is BLOCKED.** The status surface is fully correct for a blocked volume + (`status=blocked`, `Ready=False`, `Blocked=True`, + `reasonCode=csi_node_image_pull_failed`, no `Ready=True` anywhere) and the SA + still has zero storage/workload mutation power — all six literal checks pass. +- **But the new event-publishing path is not production-safe:** a blocked + volume's two same-reason conditions mint duplicate event names; the second + `409 AlreadyExists` aborts the entire reconcile (`exit=2`), halting status + publication for the rest of the iteration. This fires for **any** blocked + volume, including live `--master-api` blocked reasons. +- **Fix:** treat `409 AlreadyExists` as success in `EmitEvent` (and optionally + disambiguate/dedupe per-condition events). Re-validate: drive a blocked volume + in write mode and confirm the reconcile **succeeds** (`exit=0`), the Warning + event(s) land, and subsequent volumes still get their status written. +- Do not close D4 until the reconcile no longer aborts on a blocked volume. + +--- + +## RE-VALIDATION (`a2714c8`) — PASS + +Re-ran the exact blocked-condition gate against `a2714c8 phase35: make operator +events idempotent` (fresh images built + imported; `helm install … --set +operatorStatus.create=true --set operatorStatus.dryRun=false`, exit=0). + +### The fix (verified in code) + +- `KubernetesStatusClient.EmitEvent` now returns `nil` on `http.StatusConflict` + (`kubernetes_status_writer.go:149-151`) — 409 AlreadyExists is idempotent success. +- The reconciler's event loop no longer returns on an EmitEvent error; it only + counts successes (`operator_status_controller.go:166-178`, + `if err == nil { result.EventCount++ }`). Event emission is best-effort and + cannot abort status publication for later volumes. +- Dev added regressions: duplicate same-name event create returns nil on the + second call; an event-sink failure does not stop status writes for a following + volume. + +### Live results + +| # | Check | Result | Evidence | +|---|---|---|---| +| 1 | Blocked one-shot reconcile exits 0 | **PASS** | RUN #1 (within-run duplicate): `volumes=1 events=2`, `RUN1_EXIT=0`. RUN #2 (event already exists → 409): `RUN2_EXIT=0`. Was `exit=2` on `e0330b7`. | +| 2 | Warning Event, reason `csi_node_image_pull_failed` | **PASS** | `kubectl get events`: `Warning csi_node_image_pull_failed swblockvolume/unknown` | +| 3 | Status correct on the blocked volume | **PASS** | CRD `status=blocked reason=csi_node_image_pull_failed Ready=False Blocked=True` | +| 4 | No `Ready=True` on blocked surfaces | **PASS** | CRD Ready=False; report dir `grep -ic ready.*true` = 0; operator-snapshot `status:blocked` | +| 5 | Subsequent volume status still written if present | **PASS (structural + unit)** | reconcile no longer returns on event error (code verified); dev unit regression covers the explicit two-volume case. Live from-bundle yields a single blocked volume, so not exercised as a live 2-volume case — see note. | +| 6 | SA mutation boundary unchanged | **PASS** | `create events: yes`, `patch swblockvolumes --subresource=status: yes`; `patch swblockvolumes (spec): no`, `create pods: no`, `delete pvc: no`, `create secrets: no` | + +The original blocker (`exit=2` abort on a blocked volume) is gone. All of the +dev's re-validation asks are satisfied. + +### Non-blocking event-hygiene follow-ups (the abort masked these before) + +Now that 409 no longer aborts, two residual nuances are visible. Neither blocks +D4 — the status surface is the source of truth and is correct; events are +best-effort telemetry. + +1. **Within a run, the two same-reason condition events collapse to one.** The + event name is still `object + reason + observedAt.UnixNano()`, which is + identical for the `Ready=False` and `Blocked=True` conditions (same object, + reason, timestamp). So only the **first** event (the Ready condition's + message, "managed volume is blocked; inspect dry-run actions…") persists; the + Blocked condition's distinct message ("a documented blocker prevents the + expected user path") is silently swallowed by the idempotent 409. The CRD + status conditions carry both, so no information is lost on the authoritative + surface — but the event stream shows one message, not two. + +2. **Across reconciles, a new event is minted every iteration.** Because the + name embeds `observedAt.UnixNano()`, each reconcile produces a *new* event + name for the same persistent condition (confirmed: two one-shot runs left two + distinct events). A long-running controller would create a fresh Warning + event every `--interval` (30s) for a stuck blocked volume → unbounded event + growth, no core/v1 aggregation (`count++`). This is reachable on the live + `--master-api` path for blocked reasons it can surface (`wal_integrity_fault`, + `writer_mount_failed`, loopback). + + The natural fix for both: make the event name **stable** per + `(object, reason[, type])` *without* the timestamp. Then the existing + 409-idempotency dedupes across iterations (one durable event per + object+reason, optionally aggregated with `count++`), and per-condition + disambiguation (adding `type`) lets the Ready and Blocked events coexist. + +3. Minor: the CLI prints `events=2` while only one distinct Event object lands + per run (the count includes the idempotent 409). Cosmetic. + +### Lab state + +Clean — stubs + Warning events deleted, helm uninstalled, both CRDs deleted; +0 sw-block pods, 0 CRDs, 0 iSCSI sessions. + +### Bottom line + +- **D4 PASS on `a2714c8`.** The blocked-volume reconcile exits 0, the Warning + event lands, the status surface is correct (`blocked`, Ready=False, + Blocked=True, no `Ready=True` anywhere), event emission can no longer abort + status publication, and the SA still has zero storage/workload mutation power. +- **D4 can close.** Recommend filing the event-hygiene follow-ups (stable event + name per object+reason so cross-iteration emits dedupe/aggregate instead of + accumulate; per-condition `type` so Ready and Blocked events coexist) as + tracked, non-blocking work. diff --git a/seaweed-block/internal/docs/qa-assignments/phase35-d5-stale-status-projections-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase35-d5-stale-status-projections-qa-signoff.md new file mode 100644 index 0000000000..f4032fe25c --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase35-d5-stale-status-projections-qa-signoff.md @@ -0,0 +1,130 @@ +# QA Sign-off - Phase 35 D5 Stale / Unreachable Status Projections + +Verdict: **PASS, no findings.** Driven live through the write-mode +operator-status controller, both stale-evidence projections publish exactly the +right CRD status + Warning Events, with no false `Ready=True` and no +inappropriate `Blocked=True`: + +- `status_endpoint_unreachable` → `status=unknown`, `Ready=Unknown`, + `EvidenceStale=True`, **no Blocked condition** — a "we don't know" surface, + not a claim of health and not a hard block. +- `wal_integrity_fault` → `status=blocked`, `Ready=False`, `Blocked=True` — a + real, known blocker; never `Ready=True`. + +Date: 2026-06-04 + +Source commit: `6859be1 phase35: cover stale operator status projections` +(branch `phase33-testops-failure-hardening`) + +Note: `6859be1` is **test-only** relative to `a2714c8` (the diff is +`operator_status_controller_test.go` + two docs; zero product `.go`). The +product binary is therefore the D4-validated `a2714c8` binary; the a2714c8 +images already on m01/m02/tp01 were reused (no rebuild). The D5 unit additions +pass: `go test ./core/ops` → ok. + +## How the gate was driven + +Both reasons are reachable through the bundle projection: a `VolumeEvidence` +carries `reason` straight into `facts.ProductReason` +(`managedVolumeFactsFromVolumeEvidence`: `ProductReason = volume.Reason`), and +`classifyManagedVolume` maps them (`managed_volume_model.go:526` wal_integrity → +Blocked; `:547` status_endpoint_unreachable → Unknown; `:753` the +EvidenceStale condition). + +So I crafted **one** `cluster-evidence.json` with **two** volumes and ran a +single write-mode reconcile inside the operator-status pod (as the constrained +SA): + +```json +{ "schema_version":"1.0", "captured_at":"2026-06-04T00:00:00Z", "status":"degraded", + "nodes":[], "volumes":[ + {"volume_id":"pvc-unreachable","pvc_name":"pvc-unreachable","replication_factor":1, + "status":"degraded","reason":"status_endpoint_unreachable","replicas":[]}, + {"volume_id":"pvc-walfault","pvc_name":"pvc-walfault","replication_factor":1, + "status":"blocked","reason":"wal_integrity_fault","replicas":[]} ] } +``` + +```text +sw-block ops operator-status --from-bundle /tmp/bb2 --namespace kube-system --cluster-name sw-block +-> operator_status=write_status cluster=kube-system/sw-block volumes=2 events=4 mutation_allowed=false + EXIT=0 +``` + +Two volumes in one reconcile also re-confirms the D4 best-effort fix: both +statuses are written and the reconcile exits 0. + +## Results + +| Surface | pvc-unreachable | pvc-walfault | +|---|---|---| +| `.status.status` | `unknown` | `blocked` | +| `.status.reasonCode` | `status_endpoint_unreachable` | `wal_integrity_fault` | +| Ready condition | `Ready=Unknown` (sev warning) | `Ready=False` (sev warning) | +| Second condition | `EvidenceStale=True` (sev warning) | `Blocked=True` (sev warning) | +| Blocked condition present? | **no** (correct) | yes | +| `Ready=True` anywhere? | **no** (0) | **no** (0) | +| Warning Event | `Warning / status_endpoint_unreachable` | `Warning / wal_integrity_fault` | + +Checklist: + +| Check | Result | Evidence | +|---|---|---| +| Unreachable → CRD status published | PASS | `status=unknown`, `reasonCode=status_endpoint_unreachable` | +| Unreachable → `Ready=Unknown`, not True/False | PASS | condition `Ready=Unknown` | +| Unreachable → `EvidenceStale=True` | PASS | condition `EvidenceStale=True` | +| Unreachable → NOT `Blocked=True` | PASS | no Blocked condition on the volume (count 0) | +| WAL fault → CRD status published | PASS | `status=blocked`, `reasonCode=wal_integrity_fault` | +| WAL fault → `Ready=False`, `Blocked=True`, never `Ready=True` | PASS | conditions `Ready=False` + `Blocked=True`; `Ready=True` count 0 | +| Warning Events for both | PASS | one Warning event per volume, reason-matched | +| No `Ready=True` on any surface | PASS | CRD (both), report dir `grep -ic ready.*true`=0, operator-snapshot/summary show unknown+blocked | +| SA mutation boundary unchanged | PASS | `create events: yes`, `patch …/status: yes`; `patch swblockvolumes (spec): no`, `create pods: no`, `delete pvc: no` | + +All report surfaces agree (summary.txt): + +```text +managed_volume=pvc-unreachable status=unknown reason=status_endpoint_unreachable +managed_volume=pvc-walfault status=blocked reason=wal_integrity_fault +``` + +## The Distinction That Matters (and is correct) + +This gate validates the negative-first contract's hardest call: telling apart +"the evidence is stale / I can't reach the status endpoint" from "the volume is +genuinely broken." + +- **Unreachable** is `Unknown` + `EvidenceStale`, **never** `Blocked`. The + surface does not claim the volume is healthy (no `Ready=True`) and does not + claim it is broken (no `Blocked=True`) — it honestly says "I don't know." An + operator is not paged for a false outage, and is not falsely reassured. +- **WAL integrity fault** is `Blocked` + `Ready=False` — a documented blocker + the operator should act on. + +Both behave exactly as specified. + +## Carry-forward (non-blocking, unchanged from D4) + +The same-reason event-name collapse and per-reconcile event minting noted in the +D4 sign-off still apply (each volume's two same-reason conditions emit two +events that share a name → one distinct event lands per volume; the name embeds +`observedAt`). `events=4` was reported while 2 distinct events landed (one per +volume). Not a D5 regression — already filed. (Of note: the event name suffix +here was `…1780531200000000000` = the bundle's `captured_at`, confirming the +name is keyed on the snapshot's observedAt.) + +## Lab State + +Clean — both `SwBlockVolume` stubs + `SwBlockCluster` deleted, Warning events +deleted, helm uninstalled, both CRDs deleted; 0 sw-block pods, 0 CRDs, 0 iSCSI +sessions. + +## Bottom Line + +- **D5 PASS, no findings.** `status_endpoint_unreachable` projects + `Unknown`/`EvidenceStale=True` (not Blocked, not Ready), and + `wal_integrity_fault` projects `Blocked`/`Ready=False` (never Ready=True); + both publish a matching Warning event; the reconcile exits 0 for a + two-volume snapshot; and the SA still has zero storage/workload mutation power. +- **D5 can close.** The only open items are the pre-existing, non-blocking D4 + event-hygiene follow-ups (stable per-(object,reason) event name so + cross-iteration emits dedupe/aggregate; per-condition `type` so the two + same-reason conditions emit distinct events). diff --git a/seaweed-block/internal/docs/qa-assignments/phase35-d6-stable-event-identity-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase35-d6-stable-event-identity-qa-signoff.md new file mode 100644 index 0000000000..bf92e02d7c --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase35-d6-stable-event-identity-qa-signoff.md @@ -0,0 +1,101 @@ +# QA Sign-off - Phase 35 D6 Stable Operator Event Identity + +Verdict: **PASS, no findings.** Repeated write-mode reconciles against a +persistent blocked volume now produce a **single, stable** Kubernetes Event that +does not grow per reconcile. Three consecutive one-shot reconciles all exit 0 +and the distinct Event count stays at **1**. This closes the event-hygiene +follow-up filed in the D4/D5 sign-offs (the timestamped name that minted a new +Event every iteration). + +Date: 2026-06-04 + +Source commit: `1b22ccc phase35: stabilize operator event identity` +(branch `phase33-testops-failure-hardening`; HEAD, on top of +`d6506dc docs: close phase35 d5 stale status gate`) + +## The fix (verified in code) + +`kubernetesEventName` dropped its `at time.Time` parameter and the +`.UnixNano()` suffix. The name is now stable per **object + type + reason**: + +```go +func kubernetesEventName(event OperatorKubernetesEvent) string { + base := kubernetesName(event.InvolvedObject.Name + "-" + event.Type + "-" + event.Reason) + if base == "unknown-volume" { base = "sw-block-event" } + return base +} +``` + +So the same persistent condition resolves to the same Event name on every +reconcile → the existing idempotent `409 Conflict` handling (D4 `a2714c8`) +deduplicates it instead of creating a fresh Event. Including `event.Type` keeps +`Normal` and `Warning` for the same object/reason on distinct names. + +Only `core/ops/kubernetes_status_writer.go` changed (product) vs `a2714c8`; +fresh images built + imported to m01/m02/tp01. `go test ./core/ops` ok. + +## Live results — repeated reconcile, no Event growth + +Persistent blocked volume driven via a one-volume `cluster-evidence.json` +(`pvc-walfault`, `reason=wal_integrity_fault`), one-shot reconcile run **3×** +inside the operator-status pod (as the constrained SA): + +```text +RUN #1 exit=0 | operator_status=write_status volumes=1 events=2 | distinct_events=1 +RUN #2 exit=0 | operator_status=write_status volumes=1 events=2 | distinct_events=1 +RUN #3 exit=0 | operator_status=write_status volumes=1 events=2 | distinct_events=1 +``` + +The one Event, after all three runs: + +```text +NAME TYPE REASON COUNT +pvc-walfault-warning-wal-integrity-fault Warning wal_integrity_fault 1 +``` + +| Check | Result | Evidence | +|---|---|---| +| Repeated reconcile exits 0 | PASS | RUN #1/#2/#3 all `exit=0` | +| Second/third reconcile creates **no new** Event for same object/type/reason | PASS | `distinct_events` stays `1` across all runs | +| Event name stable, no timestamp suffix | PASS | name = `pvc-walfault-warning-wal-integrity-fault` (object-type-reason) | +| Type embedded (Normal vs Warning distinct names) | PASS | `…-warning-…`; a Normal event for the same object/reason would be `…-normal-…` | +| Status surface still correct | PASS | `status=blocked reason=wal_integrity_fault Ready=False Blocked=True`, `Ready=True` count 0 | +| SA mutation boundary unchanged | PASS | `create events: yes`, `patch …/status: yes`; `patch swblockvolumes (spec): no`, `create pods: no`, `delete pvc: no` | + +Before this fix (D4/D5), the name embedded `observedAt.UnixNano()`, so three +reconciles would have left **three** distinct Events for the same condition. +Now it is one. + +## Minor observations (non-blocking, not regressions) + +1. **Dedupe, not aggregate.** The repeated Event keeps `COUNT=1` and its + original `lastTimestamp` — the `409` short-circuits before any update. The + D6 goal (no unbounded Event growth) is fully met; if richer telemetry is ever + wanted, the conventional core/v1 pattern is to `PATCH count++` / + `lastTimestamp` on the 409 path so a long-running blocker reads as "seen N + times, still active." The CRD `.status.observedAt` already carries live + freshness, so this is optional polish, not a gap. +2. **Within one reconcile, the two same-type+reason conditions still collapse + to one Event.** A blocked volume emits `Ready=False` and `Blocked=True`, both + `Warning` + `wal_integrity_fault`, so they share the (now stable) name and + dedupe to a single Event (`events=2` reported, 1 distinct). This is the same + D4 nuance #1 and is acceptable — the CRD status conditions carry both Ready + and Blocked detail; the Event is a breadcrumb. D6 intentionally only splits + on `type` (Normal vs Warning), which is the meaningful split. + +## Lab State + +Clean — `SwBlockVolume`/`SwBlockCluster` stubs deleted, the Event deleted, helm +uninstalled, both CRDs deleted; 0 sw-block pods, 0 CRDs, 0 iSCSI sessions. + +## Bottom Line + +- **D6 PASS.** Operator Event identity is stable per object+type+reason; repeated + write-mode reconciles against a persistent blocked volume exit 0 and produce + no new Event objects (distinct count stays 1), the status surface stays + correct, and the SA still has zero storage/workload mutation power. +- This **closes the D4/D5 event-hygiene carry-forward** (per-reconcile Event + growth). The remaining items are optional polish only: count++/lastTimestamp + aggregation on the 409 path, and per-condition Event splitting — neither + blocks D6 or anything downstream. +- **D6 can close.** diff --git a/seaweed-block/internal/docs/qa-assignments/phase35-d7-read-only-boundary-qa-assignment.md b/seaweed-block/internal/docs/qa-assignments/phase35-d7-read-only-boundary-qa-assignment.md new file mode 100644 index 0000000000..250f8b31ed --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase35-d7-read-only-boundary-qa-assignment.md @@ -0,0 +1,124 @@ +# QA Assignment - Phase 35 D7 Read-Only Boundary + +Source branch: `phase33-testops-failure-hardening` + +Gate: D7 read-only boundary for the Kubernetes-native operator-status +foundation. + +## Local Review Summary + +The operator-status path is intentionally narrow: + +- Helm creates a dedicated `sw-block-operator-status` ServiceAccount only when + `operatorStatus.create=true`. +- Its ClusterRole grants: + - `get/list/watch` on `swblockclusters` and `swblockvolumes` + - `get/update/patch` on `swblockclusters/status` and + `swblockvolumes/status` + - `create` on core `events` +- `core/ops.KubernetesStatusClient` exposes only: + - `WriteClusterStatus` + - `WriteVolumeStatus` + - `EmitEvent` +- The client only PATCHes `/status` subresources and POSTs core Events. +- It has no methods for spec mutation, PVC/PV, workloads, Secrets, + StorageClasses, Helm, iSCSI, multipath, or hostPath mutation. + +Scoped local checks already cover this boundary: + +```text +go test ./core/ops ./cmd/sw-block ./cmd/blockcsi +helm lint charts/seaweed-block +helm template ... --set operatorStatus.create=true --set operatorStatus.dryRun=false +``` + +## Required Live QA Checks + +Install the chart with the operator-status controller enabled in write mode: + +```text +operatorStatus.create=true +operatorStatus.dryRun=false +``` + +Use the rendered ServiceAccount name from the release, usually: + +```text +system:serviceaccount:kube-system:sw-block-seaweed-block-operator-status +``` + +### Allowed Verbs + +These must be `yes`: + +```text +kubectl auth can-i get swblockvolumes.block.seaweedfs.com --as -n kube-system +kubectl auth can-i list swblockvolumes.block.seaweedfs.com --as -n kube-system +kubectl auth can-i watch swblockvolumes.block.seaweedfs.com --as -n kube-system +kubectl auth can-i patch swblockvolumes --subresource=status --as -n kube-system +kubectl auth can-i update swblockvolumes --subresource=status --as -n kube-system +kubectl auth can-i patch swblockclusters --subresource=status --as -n kube-system +kubectl auth can-i update swblockclusters --subresource=status --as -n kube-system +kubectl auth can-i create events --as -n kube-system +``` + +Use `--subresource=status` for the status checks. On newer kubectl versions, +the spelling `swblockvolumes.block.seaweedfs.com/status` can return a false +`no` even when the ClusterRole and live status PATCH are correct. + +### Forbidden Verbs + +These must be `no`: + +```text +kubectl auth can-i patch swblockvolumes.block.seaweedfs.com --as -n kube-system +kubectl auth can-i update swblockvolumes.block.seaweedfs.com --as -n kube-system +kubectl auth can-i delete swblockvolumes.block.seaweedfs.com --as -n kube-system +kubectl auth can-i create pods --as -n kube-system +kubectl auth can-i patch pods --as -n kube-system +kubectl auth can-i delete pods --as -n kube-system +kubectl auth can-i create persistentvolumeclaims --as -n default +kubectl auth can-i patch persistentvolumeclaims --as -n default +kubectl auth can-i delete persistentvolumeclaims --as -n default +kubectl auth can-i create persistentvolumes --as +kubectl auth can-i patch persistentvolumes --as +kubectl auth can-i delete persistentvolumes --as +kubectl auth can-i create secrets --as -n kube-system +kubectl auth can-i patch secrets --as -n kube-system +kubectl auth can-i create deployments.apps --as -n kube-system +kubectl auth can-i patch deployments.apps --as -n kube-system +kubectl auth can-i delete deployments.apps --as -n kube-system +kubectl auth can-i create storageclasses.storage.k8s.io --as +kubectl auth can-i patch storageclasses.storage.k8s.io --as +kubectl auth can-i delete storageclasses.storage.k8s.io --as +``` + +### Runtime Boundary + +Run one write-mode reconcile against a ready, blocked, or stale bundle and +verify: + +```text +operator_status=write_status ... mutation_allowed=false +``` + +Then verify: + +```text +SwBlockCluster.spec is unchanged +SwBlockVolume.spec is unchanged +SwBlockCluster.status is updated +SwBlockVolume.status is updated +Kubernetes Event(s) may be created +no PVC/PV/workload/Secret/StorageClass changed because of operator-status +``` + +## Pass Criteria + +D7 passes when: + +- All allowed `can-i` checks return `yes`. +- All forbidden `can-i` checks return `no`. +- Runtime reconcile writes CRD `.status` and Events only. +- Output and operator snapshot still report `mutation_allowed=false`. +- Cleanup leaves no product residue. diff --git a/seaweed-block/internal/docs/qa-assignments/phase35-d7-read-only-boundary-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase35-d7-read-only-boundary-qa-signoff.md new file mode 100644 index 0000000000..90fd844412 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase35-d7-read-only-boundary-qa-signoff.md @@ -0,0 +1,137 @@ +# QA Sign-off - Phase 35 D7 Read-Only Boundary + +Verdict: **PASS.** The operator-status ServiceAccount is provably limited to CRD +read, CRD `/status` patch/update, and Event create — every forbidden mutation +(`swblockvolumes` spec, pods, PVC, PV, Secrets, Deployments, StorageClasses) +returns `no`, the live ClusterRole carries exactly those three rules and nothing +else, and a write-mode reconcile touches only `.status` + Events +(`mutation_allowed=false`, specs untouched, no PVC/PV/workload created). + +One **gate-documentation** finding (not a product issue): the assignment's +`can-i` syntax for the status subresource (`resource.group/status`) returns a +**false `no`** on kubectl v1.34; the correct form is `--subresource=status`, +which returns `yes`. See below — fix the doc so the gate isn't failed falsely. + +Date: 2026-06-04 + +Source commit: `a9f43e1 docs: prepare phase35 d7 boundary gate` +(branch `phase33-testops-failure-hardening`; docs-only — product binary is the +D6-validated `1b22ccc`, images reused, no rebuild) + +Environment: k3s `v1.34.4+k3s1`, write-mode install +(`operatorStatus.create=true, dryRun=false`), +SA `system:serviceaccount:kube-system:sw-block-seaweed-block-operator-status`. + +## Authoritative grant — live ClusterRole has exactly 3 rules + +```text +resources=[swblockclusters, swblockvolumes] verbs=[get, list, watch] +resources=[swblockclusters/status, swblockvolumes/status] verbs=[get, update, patch] +resources=[events] verbs=[create] +``` + +No rule grants anything on pods, PVC, PV, Secrets, Deployments, StorageClasses, +or CRD spec. This is the source of truth; the `can-i` sweep below confirms it. + +## Allowed verbs — all effectively `yes` + +| Check | Result | Note | +|---|---|---| +| `get swblockvolumes…` | **yes** | | +| `list swblockvolumes…` | **yes** | | +| `watch swblockvolumes…` | **yes** | | +| `create events` | **yes** | | +| `patch swblockvolumes --subresource=status` | **yes** | doc form `…/status` falsely returns `no` | +| `update swblockvolumes --subresource=status` | **yes** | doc form `…/status` falsely returns `no` | +| `patch swblockclusters --subresource=status` | **yes** | doc form `…/status` falsely returns `no` | +| `update swblockclusters --subresource=status` | **yes** | doc form `…/status` falsely returns `no` | + +All seven allowed capabilities are granted. The status ones are additionally +proven by the live runtime reconcile, which actually PATCHes `.status` +successfully (below). + +## Forbidden verbs — all `no` (21/21) + +```text +patch/update/delete swblockvolumes.block.seaweedfs.com -> no / no / no (spec & object) +create/patch/delete pods -> no / no / no +create/patch/delete persistentvolumeclaims (default) -> no / no / no +create/patch/delete persistentvolumes -> no / no / no +create/patch secrets -> no / no +create/patch/delete deployments.apps -> no / no / no +create/patch/delete storageclasses.storage.k8s.io -> no / no / no +``` + +Every storage / workload / config mutation is denied. + +## Runtime boundary — write-mode reconcile touches only `.status` + Events + +One write-mode reconcile (from a `status_endpoint_unreachable` bundle) against +`SwBlockCluster/sw-block` + `SwBlockVolume/pvc-ready` stubs: + +```text +operator_status=write_status cluster=kube-system/sw-block volumes=1 events=2 mutation_allowed=false EXIT=0 +``` + +| Assertion | Result | +|---|---| +| `mutation_allowed=false` | PASS | +| `SwBlockCluster.spec` unchanged | PASS (`{}` before and after) | +| `SwBlockVolume.spec` unchanged | PASS (`{}` before and after) | +| `SwBlockCluster.status` updated | PASS (`volumeCount=1`, observedAt set) | +| `SwBlockVolume.status` updated | PASS (`status=unknown reason=status_endpoint_unreachable`) | +| Events created (allowed) | PASS (`pvc-ready-warning-status-endpoint-unreachable`, stable D6 name) | +| No PVC/PV created by operator-status | PASS (0 PVCs/PVs) | + +The reconcile writes CRD `.status` and Events and nothing else — consistent with +the RBAC and the `KubernetesStatusClient` surface (`WriteClusterStatus`, +`WriteVolumeStatus`, `EmitEvent` only). + +## Finding (gate doc, non-blocking): correct the status-subresource `can-i` syntax + +The assignment (`phase35-d7-read-only-boundary-qa-assignment.md`, lines 58-60) +lists the allowed status checks as: + +```text +kubectl auth can-i patch swblockvolumes.block.seaweedfs.com/status --as -n kube-system +kubectl auth can-i update swblockvolumes.block.seaweedfs.com/status --as -n kube-system +kubectl auth can-i patch swblockclusters.block.seaweedfs.com/status --as -n kube-system +``` + +On kubectl `v1.34.4+k3s1` these return **`no`** — a false negative. `can-i` +does not resolve the `./status` subresource spelling for these +CRDs, so anyone running the gate literally would see the *allowed* status checks +fail and could wrongly conclude the boundary is broken. (Same artifact I flagged +in the D3 sign-off.) + +Correct, reliable form: + +```text +kubectl auth can-i patch swblockvolumes --subresource=status --as -n kube-system # yes +kubectl auth can-i update swblockvolumes --subresource=status --as -n kube-system # yes +kubectl auth can-i patch swblockclusters --subresource=status --as -n kube-system # yes +kubectl auth can-i update swblockclusters --subresource=status --as -n kube-system # yes +``` + +Recommend updating the assignment doc to the `--subresource=status` form (and/or +noting that the ClusterRole rule dump + the live runtime status PATCH are the +authoritative confirmations). The RBAC itself is correct and needs no change. + +## Lab State + +Clean — `SwBlockVolume`/`SwBlockCluster` stubs deleted, Event deleted, helm +uninstalled, both CRDs deleted, operator-status ClusterRole gone; 0 sw-block +pods, 0 CRDs, 0 ClusterRoles, 0 iSCSI sessions. + +## Bottom Line + +- **D7 PASS.** The operator-status SA can read CRDs, patch/update CRD `/status`, + and create Events — and nothing else. All 21 forbidden mutations are denied, + the live ClusterRole carries exactly the three intended rules, and a write-mode + reconcile mutates only `.status` + Events with `mutation_allowed=false` and no + PVC/PV/workload/Secret/StorageClass side effects. +- **One non-blocking doc fix:** the assignment's status-subresource `can-i` + commands use a spelling that false-negatives on kubectl v1.34; switch them to + `--subresource=status`. The boundary is correct; only the documented + verification command is wrong. +- **D7 can close.** diff --git a/seaweed-block/internal/docs/qa-assignments/phase36-d1-operations-model-contract-review.md b/seaweed-block/internal/docs/qa-assignments/phase36-d1-operations-model-contract-review.md new file mode 100644 index 0000000000..cd6f053e9f --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase36-d1-operations-model-contract-review.md @@ -0,0 +1,80 @@ +# Phase 36 D1 Operations Model Contract Review + +Status: PASS. + +Date: 2026-06-05. + +## Scope Reviewed + +Phase 36 D1 defines the read-only operations actionability contract. It does +not wire live node readiness or cleanup projection yet. + +Reviewed artifacts: + +- `internal/docs/current-plan.md` +- `internal/docs/product-roadmap.md` +- `internal/docs/protocol/operator-readiness-contract.md` +- `core/ops/managed_volume_crd_contract.go` +- `core/ops/operator_status_controller.go` +- `charts/seaweed-block/crds/swblockclusters.block.seaweedfs.com.yaml` + +## Contract Additions + +`SwBlockCluster.status` now has typed/schema-backed places for: + +- `nodes[]`: node readiness/preflight facts and node-level conditions, +- `supportBundleRefs[]`: support evidence pointers, +- `cleanup`: cleanup verifier status and residue counters, +- `safeNextSteps[]`: read-only, dry-run, or user-scripted next-step hints. + +## Boundary Review + +The fields are observation and advice only. + +They do not imply: + +- CR object ownership, +- finalizers, +- automatic cleanup, +- storage mutation, +- workload mutation, +- PVC/PV mutation, +- iSCSI/multipath/hostPath mutation, +- promote/repair/rebuild/failback/delete/backup/restore execution. + +`safeNextSteps[].mutationAllowed` is required in the CRD schema and must remain +`false` for Phase 36. + +## TDD Evidence + +Focused tests were added first and failed on the missing contract/schema: + +```text +TestManagedVolumeCRDContract_Phase36ActionabilityFields +TestPhase36D1SwBlockClusterActionabilitySchema +``` + +After implementing the structural contract, the focused tests passed. + +## Regression Checks + +```text +go test ./core/ops ./cmd/sw-block +helm lint charts/seaweed-block +helm template sw-block charts/seaweed-block --namespace kube-system --include-crds \ + --set operatorStatus.create=true --set operatorStatus.dryRun=false +``` + +All passed. + +## Findings + +No blocking findings. + +Non-blocking: + +- D1 is structural only. D2 must prove real node evidence populates + `SwBlockCluster.status.nodes[]`. +- D3 must prove support-bundle refs are not just schema fields but usable + cold-reader evidence pointers. +- D4 must prove cleanup visibility does not become automatic cleanup. diff --git a/seaweed-block/internal/docs/qa-assignments/phase36-d2-live-negative-node-evidence-followup.md b/seaweed-block/internal/docs/qa-assignments/phase36-d2-live-negative-node-evidence-followup.md new file mode 100644 index 0000000000..8432c9b2a4 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase36-d2-live-negative-node-evidence-followup.md @@ -0,0 +1,65 @@ +# Phase 36 D2 Follow-up - Live Negative Node Evidence + +Status: open follow-up. + +Discovered by QA during Phase 36 D2 validation on 2026-06-05. + +## Finding + +`SwBlockCluster.status.nodes[]` and `operator-snapshot.json.cluster.nodes[]` +project node readiness correctly when `NodeEvidence` contains real facts. +However, the live `--master-api` source cannot currently produce unhealthy node +evidence. + +`core/host/master/observation_snapshot.go:observationNodes` derives node +evidence from lifecycle registrations and currently hardcodes: + +```go +Schedulable: true +Ready: true +``` + +It also does not populate `MissingImages`. + +Result: live registered nodes always classify as `ready/node_ready`. The D2 +negative node reasons are correct and unit-tested but unreachable from the live +blockmaster surface: + +- `node_not_ready` +- `node_scheduling_disabled` +- `image_missing_on_node` + +## Impact + +D2 still passes because: + +- G1 1-node live healthy path passed, +- G2 3-node live healthy path passed, +- G3 missing-image node blocker passed via replay, +- G4 read-only boundary passed. + +But the live product surface cannot yet prove node blockers without replayed or +crafted evidence. + +## Required Fix Shape + +Populate live `NodeEvidence` from real sources: + +- Kubernetes node Ready condition, +- Kubernetes unschedulable/schedulable state, +- image-presence check for required sw-block images, +- evidence refs for the node/preflight source. + +Then add a live negative-node TestOps gate that produces at least one of: + +```text +status=unknown reason=node_not_ready +status=blocked reason=node_scheduling_disabled +status=blocked reason=image_missing_on_node +``` + +## Boundary + +The fix must remain read-only. It may observe Kubernetes and image state, but it +must not import images, uncordon nodes, mutate pods, mutate PVCs, or clean host +state. diff --git a/seaweed-block/internal/docs/qa-assignments/phase36-d2-node-readiness-qa-assignment.md b/seaweed-block/internal/docs/qa-assignments/phase36-d2-node-readiness-qa-assignment.md new file mode 100644 index 0000000000..bdec22df7b --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase36-d2-node-readiness-qa-assignment.md @@ -0,0 +1,102 @@ +# Phase 36 D2 QA Assignment - Node Readiness Status + +Status: ready for QA. + +Source scope: + +- `SwBlockCluster.status.nodes[]` +- `operator-snapshot.json.cluster.nodes[]` +- read-only/status-only operator-status controller + +## Goal + +Verify that existing product-owned node evidence is visible through +Kubernetes-native read-only status and agrees with the support/report surface. + +This gate must not mutate storage or workloads. + +## Required Checks + +### G1: Healthy 1-Node Lab + +Run the documented Helm first-volume path with operator-status enabled in +write mode. + +Expected: + +```text +SwBlockCluster.status.nodeCount=1 +SwBlockCluster.status.nodes[0].status=ready +SwBlockCluster.status.nodes[0].reasonCode=node_ready +SwBlockCluster.status.nodes[0].ready=true +SwBlockCluster.status.nodes[0].schedulable=true +operator-snapshot.json cluster.node_count=1 +operator-snapshot.json cluster.nodes[0].status=ready +no storage/workload mutation permission beyond CRD status and Events +``` + +### G2: Healthy 3-Node Lab + +Run the same path on the 3-node k3s lab. + +Expected: + +```text +SwBlockCluster.status.nodeCount=3 +SwBlockCluster.status.nodes has one entry per observed k3s node +all ready/schedulable nodes show status=ready reasonCode=node_ready +operator-snapshot.json has the same node names and node statuses +first-volume still verifies writer/reader +``` + +### G3: Missing Image / Node Blocker + +Use an existing blocked-image path or a controlled missing-image setup. + +Expected: + +```text +affected node status=blocked +affected node reasonCode=image_missing_on_node +affected node conditions include Ready=False and Blocked=True +missingImages[] names the missing image +cluster/volume status must not show false Ready=True because of node evidence +``` + +If a live missing-image setup is too expensive, QA may start with a +bundle-backed replay, but mark the result as replay-only. + +### G4: Boundary + +Verify the operator-status ServiceAccount still has only: + +```text +get/list/watch swblockclusters, swblockvolumes +get/update/patch swblockclusters/status, swblockvolumes/status +create events +``` + +And still cannot mutate: + +```text +pods, deployments, PVCs, PVs, secrets, storageclasses, CRD spec +``` + +## Pass Criteria + +```text +G1 PASS +G2 PASS +G3 PASS or replay-only PASS with live follow-up filed +G4 PASS +cleanup residue clean +``` + +## Non-Claims + +- No automatic CR object creation. +- No node repair. +- No image import. +- No cleanup mutation. +- No scheduler mutation. +- No storage/workload mutation. diff --git a/seaweed-block/internal/docs/qa-assignments/phase36-d2-node-readiness-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase36-d2-node-readiness-qa-signoff.md new file mode 100644 index 0000000000..124c7c1e9f --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase36-d2-node-readiness-qa-signoff.md @@ -0,0 +1,156 @@ +# QA Sign-off - Phase 36 D2 Node Readiness Status + +Verdict: **PASS.** Node evidence projects correctly into +`SwBlockCluster.status.nodes[]` and agrees with `operator-snapshot.json`: +G1 (1-node) and G2 (3-node) verified live, G4 boundary intact, G3 (missing-image +node blocker) verified as **replay-only PASS** with a live follow-up filed (the +live evidence source cannot yet produce unhealthy nodes — see below). + +Date: 2026-06-05 + +Source commit: `9900be5 phase36: project node readiness status` +(branch `phase33-testops-failure-hardening`) + +Environment: 3-node k3s `v1.34.4+k3s1` (m01/m02/tp01), write-mode operator-status +(`operatorStatus.create=true, dryRun=false`), fresh `9900be5` images on all nodes. + +## G1 — Healthy 1-Node Lab — PASS + +Default chart (single `blockNodes` entry, m02). Deployed controller patched +`SwBlockCluster.status` live from blockmaster (`--master-api`): + +```text +SwBlockCluster.status.nodeCount=1 +node name=m02 k8s=m02 status=ready reason=node_ready ready=true schedulable=true +operator-snapshot.json: node_count=1, nodes[0]={name:m02, status:ready, reason_code:node_ready, Ready=True} +``` + +CRD status and operator-snapshot agree. PASS. + +## G2 — Healthy 3-Node Lab — PASS + +Installed with `sw-block ops generate-helm-values` (discovered 3 Ready k3s +nodes, real InternalIPs). All three launchers registered with blockmaster: + +```text +SwBlockCluster.status.nodeCount=3 +node=m01 k8s=m01 status=ready reason=node_ready ready=true +node=m02 k8s=m02 status=ready reason=node_ready ready=true +node=tp01 k8s=tp01 status=ready reason=node_ready ready=true +operator-snapshot.json: node_count=3, names m01/m02/tp01 all status=ready +``` + +One entry per observed k3s node; all ready/schedulable show +`status=ready reason=node_ready`; CRD and snapshot node sets match. + +**First-volume writer/reader** (sw-block-dynamic PVC + consuming pod): + +```text +PVC g2-vol -> Bound (pvc-16bf06f0-…) +pod g2-rw -> 1/1 Running +pod log -> SW_BLOCK_G2_DATA (wrote /data/test.txt and read it back) +``` + +First volume provisions, attaches, and the workload writes+reads on the 3-node +cluster. PASS. + +## G3 — Missing Image / Node Blocker — REPLAY-ONLY PASS (live follow-up filed) + +Driven via a crafted `cluster-evidence.json` node with +`missing_images:["sw-block-csi:local"]` (separate `--cluster-name g3-cluster` +so the live controller's `sw-block` writes don't race it): + +```text +node=m02 status=blocked reason=image_missing_on_node ready=true + missingImages=["sw-block-csi:local"] +node conditions: Ready=False (image_missing_on_node), Blocked=True (image_missing_on_node) +cluster: readyVolumeCount=0, blockedVolumeCount=0, volumeCount=0, Ready=True conditions=0 +``` + +All G3 assertions hold: node `status=blocked`, `reasonCode=image_missing_on_node`, +`Ready=False` + `Blocked=True`, `missingImages[]` names the image, and the +cluster shows **no** false `Ready=True`. + +### Why this is replay-only (and the live follow-up) + +This is not just a convenience choice — the **live `--master-api` path cannot +currently produce an unhealthy node.** Blockmaster's node evidence builder +(`core/host/master/observation_snapshot.go:observationNodes`) hardcodes +`Schedulable: true`, `Ready: true`, and never populates `MissingImages`: + +```go +out = append(out, ops.NodeEvidence{ + NodeName: node.ServerID, KubernetesNode: ..., + Schedulable: true, // hardcoded + Ready: true, // hardcoded + // MissingImages never set +}) +``` + +So on the live path, every registered node classifies as `ready/node_ready`. The +three negative node reasons added in D2 — `node_not_ready`, +`node_scheduling_disabled`, `image_missing_on_node` — are correct and unit-tested +in the projection, but are **unreachable live** until blockmaster carries real +node facts (k8s NodeReady/Unschedulable, and an image-presence check) into +`NodeEvidence`. + +**Follow-up to file:** populate live `NodeEvidence.Ready` / `.Schedulable` from +the k8s node status and `.MissingImages` from a node image-presence check, so the +D2 negative node reasons fire on the live `--master-api` surface. Until then, G3 +is necessarily replay-only and the live node surface always shows nodes healthy. + +## G4 — Boundary — PASS + +operator-status SA, live `auth can-i`: + +```text +ALLOWED: get swblockclusters: yes patch swblockclusters --subresource=status: yes create events: yes +FORBIDDEN: patch swblockclusters (spec): no create pods: no patch deployments.apps: no + create persistentvolumeclaims: no create persistentvolumes: no + create secrets: no create storageclasses.storage.k8s.io: no +``` + +Node-readiness projection added no new mutation power. PASS. (Reminder from D7: +use `--subresource=status`, not `…/status`, on kubectl v1.34 — the latter +false-negatives.) + +## Minor Observation (non-blocking) + +On a blocked (missing-image) node, the `.ready` boolean field is `true` while +`.status=blocked` and the `Ready` *condition* is `False`. `.ready` carries the +raw kubelet/node readiness (the node IS a Ready k8s node) while the status + +condition carry the block-readiness judgment (it cannot serve because the image +is missing). Both are individually correct, but a consumer reading `.ready=true` +alongside `status=blocked` could be momentarily confused. Consider documenting +that `.ready`/`.schedulable` are raw node facts and `.status`/conditions are the +block-readiness verdict — or deriving `.ready=false` when the node is blocked. +Not a blocker. + +## Non-Claims Verified + +No CR objects auto-created (stubs were pre-created by QA), no node repair, no +image import, no scheduler/cleanup/storage/workload mutation — consistent with +G4 and the controller's status-only surface. + +## Lab State + +Clean — first-volume pod/PVC deleted, both `SwBlockCluster` stubs deleted, helm +uninstalled, both CRDs deleted; 0 sw-block pods, 0 CRDs, 0 PVCs, 0 iSCSI sessions. + +## Bottom Line + +- **D2 PASS.** Node readiness projects into `SwBlockCluster.status.nodes[]` and + matches `operator-snapshot.json`: G1 (1 node) and G2 (3 nodes) live, all + healthy nodes `ready/node_ready`, first-volume writer/reader works on the + 3-node cluster, and the missing-image node correctly projects + `blocked/image_missing_on_node` with `Ready=False` + `Blocked=True` and no + false cluster `Ready=True`. Boundary unchanged. +- **G3 is replay-only** because blockmaster's live node evidence hardcodes + ready/schedulable and omits missing-images. **File the live follow-up**: + populate real `Ready`/`Schedulable`/`MissingImages` in `observationNodes` so + the D2 negative node reasons are reachable on the live path. Until then the + live node surface always shows healthy nodes. +- **One non-blocking polish:** clarify/reconcile `.ready=true` vs + `status=blocked` on a blocked node. +- **D2 can close** per the assignment's "G3 PASS or replay-only PASS with live + follow-up filed" criterion. diff --git a/seaweed-block/internal/docs/qa-assignments/phase36-d3-support-evidence-qa-assignment.md b/seaweed-block/internal/docs/qa-assignments/phase36-d3-support-evidence-qa-assignment.md new file mode 100644 index 0000000000..78511b2430 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase36-d3-support-evidence-qa-assignment.md @@ -0,0 +1,96 @@ +# Phase 36 D3 QA Assignment - Support Evidence Pointers + +Status: ready for QA. + +Source scope: + +- `SwBlockCluster.status.supportBundleRefs[]` +- `SwBlockCluster.status.safeNextSteps[]` +- `operator-snapshot.json.cluster.support_bundle_refs[]` +- `operator-snapshot.json.cluster.safe_next_steps[]` +- report `summary.txt` +- report `index.html` +- from-bundle replay + +## Goal + +Verify that blocked or unknown operational status points users to support +evidence and safe collection/replay commands without mutating the cluster. + +## Required Checks + +### G1: Live Blocked Or Support-Bundle Path + +Use an existing blocked path such as CSI image pull failure, or another +controlled support-bundle scenario. + +Expected: + +```text +SwBlockCluster.status.supportBundleRefs has at least one support/evidence ref +SwBlockCluster.status.safeNextSteps has type=observe.collect_bundle +safeNextSteps[0].mode=read_only +safeNextSteps[0].mutationAllowed=false +safeNextSteps[0].command mentions collect-helm-support-bundle.sh +``` + +### G2: Report Agreement + +Run `sw-block ops report` on the same evidence. + +Expected: + +```text +summary.txt includes support_bundle_ref=... +summary.txt includes safe_next_step=observe.collect_bundle mode=read_only +index.html includes Support Evidence +index.html includes Safe Next Steps +operator-snapshot.json cluster.support_bundle_refs agrees with CRD status +operator-snapshot.json cluster.safe_next_steps agrees with CRD status +``` + +### G3: From-Bundle Replay + +Replay the generated bundle away from the live cluster: + +```text +sw-block ops report --from-bundle --out +sw-block ops explain volume --from-bundle +sw-block ops dashboard --from-bundle --listen 127.0.0.1: +``` + +Expected: + +```text +from-bundle summary keeps support_bundle_ref +from-bundle operator-snapshot keeps support_bundle_refs +from-bundle dashboard /operator-snapshot.json returns the same refs +ops explain names the same reason code and evidence refs +``` + +### G4: Boundary + +Verify no new mutation power: + +```text +operator-status may patch CRD status and create Events only +support collection command is only suggested, not executed by operator-status +no PVC/PV/pod/deployment/secret/storageclass mutation +``` + +## Pass Criteria + +```text +G1 PASS +G2 PASS +G3 PASS +G4 PASS +cleanup residue clean +``` + +## Non-Claims + +- No automatic support-bundle upload. +- No automatic cleanup. +- No automatic image import or repair. +- No mutating operator action. diff --git a/seaweed-block/internal/docs/qa-assignments/phase36-d3-support-evidence-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase36-d3-support-evidence-qa-signoff.md new file mode 100644 index 0000000000..8b84db823a --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase36-d3-support-evidence-qa-signoff.md @@ -0,0 +1,121 @@ +# QA Sign-off - Phase 36 D3 Support Evidence Pointers + +Verdict: **PASS, no findings.** Blocked operational status surfaces support +evidence pointers and a safe, read-only collection next-step across every +surface (CRD status, operator-snapshot, summary.txt, index.html, dashboard, +explain), the surfaces agree, and the controller suggests the collection command +without executing it or gaining any mutation power. + +Date: 2026-06-05 + +Source commit: `c0bf3ec phase36: project support evidence pointers` +(branch `phase33-testops-failure-hardening`) + +Environment: k3s `v1.34.4+k3s1`, write-mode operator-status, fresh `c0bf3ec` +images. Driver: CSI image-pull blocked bundle (kube-system pod dump with +`ImagePullBackOff`), projected via from-bundle under a dedicated +`--cluster-name d3-cluster` (so the live controller's `sw-block` writes don't +race the gate). + +## G1 — Blocked / Support-Bundle Path — PASS + +```text +operator_status=write_status cluster=kube-system/d3-cluster volumes=1 events=2 mutation_allowed=false EXIT=0 + +SwBlockCluster.status.supportBundleRefs = ["/tmp/d3bb/demo/kube-system-pods-deploys.txt"] +SwBlockCluster.status.safeNextSteps[0]: + type=observe.collect_bundle + mode=read_only + mutationAllowed=false + reason=blocked + command=bash scripts/collect-helm-support-bundle.sh "$PWD" +``` + +All G1 assertions hold: ≥1 support ref, `observe.collect_bundle` step, +`mode=read_only`, `mutationAllowed=false`, command mentions +`collect-helm-support-bundle.sh`. + +## G2 — Report Agreement — PASS + +`sw-block ops report --from-bundle /tmp/d3bb --out …`: + +```text +summary.txt: + support_bundle_ref=/tmp/d3bb/demo/kube-system-pods-deploys.txt + safe_next_step=observe.collect_bundle mode=read_only mutation_allowed=false + command="bash scripts/collect-helm-support-bundle.sh \"$PWD\"" reason=blocked + +index.html: "Support Evidence" + "Safe Next Steps" (both sections present) + +operator-snapshot.json: + cluster.support_bundle_refs = ["/tmp/d3bb/demo/kube-system-pods-deploys.txt"] (== CRD) + cluster.safe_next_steps = [{type:observe.collect_bundle, mode:read_only}] (== CRD) +``` + +The operator-snapshot `support_bundle_refs` / `safe_next_steps` match the CRD +status exactly. PASS. + +## G3 — From-Bundle Replay — PASS + +```text +explain volume --from-bundle /tmp/d3bb unknown: + volume unknown status=blocked reason=csi_node_image_pull_failed + condition Attach severity=error reason=csi_node_image_pull_failed (ImagePullBackOff … sw-block-csi:local) + support bundle: /tmp/d3bb/demo/kube-system-pods-deploys.txt <- names reason + evidence ref + +dashboard --from-bundle /tmp/d3bb --listen 0.0.0.0:18099, GET /operator-snapshot.json: + -> support_bundle_refs, safe_next_steps, observe.collect_bundle, kube-system-pods-deploys.txt + +relocated bundle (cp -r /tmp/d3bb /tmp/d3replay) report: + summary.txt still has support_bundle_ref= (count 1) +``` + +`explain` names the same reason code and evidence ref; the dashboard +`/operator-snapshot.json` returns the same refs; the relocated-bundle report +keeps the support ref. PASS. + +(Note: the `sw-block` container ships no `wget`/`curl`, so the dashboard endpoint +was queried from the host against the pod IP `10.42.0.183:18099`. Not a product +issue — just a test-harness detail.) + +## G4 — Boundary — PASS + +```text +ALLOWED: patch swblockclusters --subresource=status: yes create events: yes get swblockclusters: yes +FORBIDDEN: patch swblockclusters (spec): no create pods: no patch deployments.apps: no + create persistentvolumeclaims: no create persistentvolumes: no + create secrets: no create storageclasses.storage.k8s.io: no + +command suggested, NOT executed: + support-bundle dirs created in operator-status pod by the controller: 0 + PVC/PV created by operator-status: 0 + every reconcile: mutation_allowed=false +``` + +The `collect-helm-support-bundle.sh` command is published as a string in +`safeNextSteps[].command` and is **never run** by operator-status (no +support-bundle output, no extra pods, and the SA cannot exec/create pods +anyway). No PVC/PV/pod/deployment/secret/storageclass mutation. PASS. + +## Non-Claims Verified + +No automatic support-bundle upload, no automatic cleanup, no image +import/repair, no mutating operator action — the controller only patches CRD +`.status` and creates Events, and only *points* the user to the read-only +collection command. + +## Lab State + +Clean — `SwBlockVolume`/`SwBlockCluster` stubs + Events deleted, helm +uninstalled, both CRDs deleted; 0 sw-block pods, 0 CRDs, 0 iSCSI sessions. + +## Bottom Line + +- **D3 PASS, no findings.** A blocked volume's support evidence projects into + `SwBlockCluster.status.supportBundleRefs[]` and a `observe.collect_bundle` + `safeNextSteps[]` entry (`read_only`, `mutationAllowed=false`, command = + `collect-helm-support-bundle.sh`); the report `summary.txt`/`index.html`, + operator-snapshot, dashboard, and `explain` all agree; and the controller + suggests the collection command without executing it or holding any + storage/workload mutation power. +- **D3 can close.** diff --git a/seaweed-block/internal/docs/qa-assignments/phase36-d4-cleanup-visibility-qa-assignment.md b/seaweed-block/internal/docs/qa-assignments/phase36-d4-cleanup-visibility-qa-assignment.md new file mode 100644 index 0000000000..8404c8e285 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase36-d4-cleanup-visibility-qa-assignment.md @@ -0,0 +1,102 @@ +# Phase 36 D4 QA Assignment - Cleanup Visibility, Not Automatic Cleanup + +Status: ready for QA. + +Source scope: + +- `SwBlockCluster.status.cleanup` +- `SwBlockCluster.status.conditions[]` with `CleanupRequired` +- `SwBlockCluster.status.safeNextSteps[]` +- `operator-snapshot.json.cluster.cleanup` +- `operator-snapshot.json.cluster.conditions[]` +- report `summary.txt` +- report `index.html` + +## Goal + +Verify that cleanup verifier evidence becomes user-visible status and safe +next-step guidance without the operator deleting anything. + +This gate is intentionally not an automatic cleanup gate. + +## Required Checks + +### G1: Clean State Projects CleanupRequired=False + +Start from a clean lab or run the standard cleanup verifier after uninstall. + +Expected: + +```text +SwBlockCluster.status.cleanup.status=ok +SwBlockCluster.status.conditions has CleanupRequired=False +CleanupRequired reason=cleanup_verified +operator-snapshot.json cluster.cleanup.status=ok +summary.txt includes cleanup_status=ok +index.html includes Lifecycle Cleanup +``` + +There must be no `observe.verify_cleanup` safe next step in the clean state. + +### G2: Residue Projects CleanupRequired=True + +Create a controlled residue that the verifier already detects, such as a stale +Seaweed Block iSCSI node DB record or a known safe test residue. Do not use a +residue that can disrupt unrelated lab work. + +Run the existing cleanup verifier and feed its summary into the same report / +operator-status path. + +Expected: + +```text +SwBlockCluster.status.cleanup.status=failed +SwBlockCluster.status.cleanup.ResidueCount > 0 for the residue type +SwBlockCluster.status.conditions has CleanupRequired=True +CleanupRequired reason matches the verifier reason when present +SwBlockCluster.status.safeNextSteps has type=observe.verify_cleanup +safeNextSteps[].mode=scripted +safeNextSteps[].mutationAllowed=false +safeNextSteps[].command mentions verify-helm-cleanup.sh +``` + +### G3: Surface Agreement + +For both clean and residue evidence: + +```text +CRD cleanup counters agree with operator-snapshot.json +operator-snapshot.json agrees with summary.txt +index.html shows the same residue counts +safe_next_step lines agree with CRD safeNextSteps[] +``` + +### G4: Boundary + +Verify the operator-status controller does not perform cleanup: + +```text +operator-status may patch CRD status and create Events only +operator-status does not run verify-helm-cleanup.sh +operator-status does not run uninstall-k8s-alpha.sh +operator-status cannot delete pods, PVCs, PVs, deployments, storageclasses, +iSCSI sessions, multipath maps, hostPath data, or CRD spec +``` + +## Pass Criteria + +```text +G1 PASS +G2 PASS +G3 PASS +G4 PASS +final lab cleanup verifier returns cleanup_status=ok +``` + +## Non-Claims + +- No automatic cleanup. +- No finalizer or delete safety. +- No host mutation by operator-status. +- No iSCSI/multipath cleanup by operator-status. +- No support-bundle upload. diff --git a/seaweed-block/internal/docs/qa-assignments/phase36-d4-cleanup-visibility-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase36-d4-cleanup-visibility-qa-signoff.md new file mode 100644 index 0000000000..42b90a3918 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase36-d4-cleanup-visibility-qa-signoff.md @@ -0,0 +1,144 @@ +# QA Sign-off - Phase 36 D4 Cleanup Visibility (Not Automatic Cleanup) + +Verdict: **PASS.** Cleanup verifier evidence becomes user-visible status and safe +next-step guidance, and the operator deletes nothing: clean state projects +`CleanupRequired=False/cleanup_verified` with no `verify_cleanup` step; residue +projects `CleanupRequired=True` with residue counts and a scripted +`observe.verify_cleanup` step; all surfaces agree; and the controller never runs +the verifier/uninstall and holds no mutation power. One minor non-blocking +observation (a clean state still emits a `collect_bundle` step). + +Date: 2026-06-05 + +Source commit: `e742f64 phase36: project cleanup visibility status` +(branch `phase33-testops-failure-hardening`) + +Environment: k3s `v1.34.4+k3s1`, write-mode operator-status, fresh `e742f64` +images. Both cleanup summaries were produced by the **real** +`scripts/verify-helm-cleanup.sh` (clean lab, and with a controlled stale +`io.seaweedfs` iSCSI node DB record), then fed through from-bundle reconciles +under dedicated cluster names so the live controller didn't race the gate. + +## G1 — Clean State Projects CleanupRequired=False — PASS + +Real verifier on the clean lab → `cleanup_status=ok`, all residue counts 0. +Fed to `--cluster-name d4-clean`: + +```text +SwBlockCluster.status.cleanup = {"status":"ok","evidenceRef":"/tmp/g1bb/cleanup-summary.txt"} +condition CleanupRequired: status=False reason=cleanup_verified +safeNextSteps: observe.collect_bundle(read_only) <- no observe.verify_cleanup +report summary.txt: cleanup_status=ok +operator-snapshot.json: cluster.cleanup.status = "ok" +index.html: "Lifecycle Cleanup" section present +``` + +`cleanup.status=ok`, `CleanupRequired=False reason=cleanup_verified`, and **no +`observe.verify_cleanup` step** in the clean state. PASS. + +## G2 — Residue Projects CleanupRequired=True — PASS + +Controlled residue: `iscsiadm -m node -o new -T iqn.2024-01.io.seaweedfs:d4-residue +-p 127.0.0.1:3260` (a stale node DB record, no session — the exact safe residue +the assignment suggests). Real verifier → `cleanup_status=failed, +iscsi_residue_count=1, failure_count=1`. Stale record removed afterward. Fed to +`--cluster-name d4-residue`: + +```text +SwBlockCluster.status.cleanup = {"status":"failed","iscsiResidueCount":1,"failureCount":1, + "evidenceRef":"/tmp/g2bb/cleanup-summary.txt"} +condition CleanupRequired: status=True reason=cleanup_required +safeNextSteps: + observe.collect_bundle mode=read_only mutationAllowed=false + observe.verify_cleanup mode=scripted mutationAllowed=false + command=bash scripts/verify-helm-cleanup.sh "$PWD" +``` + +`cleanup.status=failed`, `iscsiResidueCount=1 > 0`, `CleanupRequired=True`, and +the `observe.verify_cleanup` step has `mode=scripted`, `mutationAllowed=false`, +command mentioning `verify-helm-cleanup.sh`. PASS. + +(Reason is `cleanup_required` — the verifier's `cleanup-summary.txt` does not +emit a `reason_codes` line, so the projection's documented fallback applies. The +assignment requires the verifier reason "when present"; none was present.) + +## G3 — Surface Agreement — PASS + +Residue evidence through `sw-block ops report --from-bundle`: + +```text +summary.txt: + cleanup_status=failed + iscsi_residue_count=1 + safe_next_step=observe.verify_cleanup mode=scripted mutation_allowed=false + command="bash scripts/verify-helm-cleanup.sh \"$PWD\"" reason=cleanup_required +index.html: "Lifecycle Cleanup" (present) +operator-snapshot.json: cluster.cleanup.status = "failed" (iscsi_residue_count=1) +``` + +CRD `status.cleanup` counters == operator-snapshot `cluster.cleanup` == +summary.txt == index.html; the `safe_next_step` line matches the CRD +`safeNextSteps[]`. Clean case agrees too (CRD/snapshot/summary all `ok`). PASS. + +## G4 — Boundary — PASS + +```text +create events: yes +create pods: no delete pods: no delete persistentvolumes: no +patch swblockclusters (spec): no +operator-status ran the verifier? cleanup dirs in operator-status pod: 0 +``` + +operator-status patches CRD status and creates Events only; it does **not** run +`verify-helm-cleanup.sh` or `uninstall-k8s-alpha.sh` (no cleanup artifact dirs +appeared in its pod), and cannot delete pods/PVCs/PVs/deployments/storageclasses +or mutate CRD spec. The verifier/cleanup commands are *suggested as scripted +next steps*, never executed by the controller. PASS. + +## Final Cleanup Verifier — cleanup_status=ok + +After teardown, the real verifier reports `cleanup_status=ok, iscsi_residue_count=0, +k8s_residue_count=0, failure_count=0`. Pass criterion met. + +## Minor Observation (non-blocking) + +A **verified-clean** cleanup state still emits an `observe.collect_bundle` +(`read_only`) safe next step. `safeNextStepsFromCluster` +(`operator_status_controller.go:166`) adds the collect-bundle step whenever +`cluster.Cleanup != nil` — i.e. whenever any cleanup evidence is present, even +`status=ok` with zero residue. The D4 assertion (no `verify_cleanup` in clean) is +satisfied, but suggesting "collect a support bundle" when everything is verified +clean is slightly noisy. Consider gating the collect-bundle step on actual +non-OK status / real evidence refs rather than mere presence of a (passing) +cleanup summary. Not a blocker. + +## Non-Claims Verified + +No automatic cleanup, no finalizer/delete behavior, no host or iSCSI/multipath +mutation by operator-status, no support-bundle upload. The controller only +*shows* cleanup state and *points* to the scripted verifier/cleanup path. + +## Lab State + +Clean — both `SwBlockCluster` stubs deleted, helm uninstalled, both CRDs deleted, +controlled iSCSI residue removed; final verifier `cleanup_status=ok`; 0 sw-block +pods, 0 CRDs, 0 iSCSI residue. + +## Bottom Line + +- **D4 PASS.** Clean cleanup evidence → `CleanupRequired=False/cleanup_verified`, + no `verify_cleanup` step; residue → `CleanupRequired=True`, `cleanup.status=failed`, + `iscsiResidueCount=1`, and a scripted, non-mutating `observe.verify_cleanup` + step pointing at `verify-helm-cleanup.sh`. CRD status, operator-snapshot, + summary.txt and index.html all agree, and the controller performs no cleanup + and holds no mutation power. Final lab verifier is `cleanup_status=ok`. +- **One non-blocking polish:** suppress the `collect_bundle` safe step when the + cleanup evidence is `status=ok` with no residue. +- **D4 can close.** + +## Post-QA Dev Polish + +Follow-up commit suppresses the clean-state `observe.collect_bundle` next step +when the only evidence is a passing cleanup summary. Clean cleanup evidence now +projects `CleanupRequired=False/cleanup_verified` with no safe next steps; the +residue path remains unchanged. diff --git a/seaweed-block/internal/docs/qa-assignments/phase36-d5-live-operational-findings-followup.md b/seaweed-block/internal/docs/qa-assignments/phase36-d5-live-operational-findings-followup.md new file mode 100644 index 0000000000..ad5a81a1fd --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase36-d5-live-operational-findings-followup.md @@ -0,0 +1,97 @@ +# Phase 36 D5 Live Operational Findings Follow-up + +Date: 2026-06-05 + +Source QA sign-off: +`internal/docs/qa-assignments/phase36-d5-surface-agreement-qa-signoff.md`. + +Phase 36 D5 passed all surface-agreement gates. These findings did not block +D5 because the CRD status, Events, report, dashboard, operator-snapshot, and +explain surfaces remained internally consistent. They are still real operational +follow-ups because they affect live user ergonomics and future node-readiness +accuracy. + +## F1: Local CSI Image Import Evidence Gap + +Severity: P0 follow-up for developer/local-image workflows. + +Observed by QA: + +- `sw-block-csi:local` was present on remote k3s nodes but absent from the build + host's k3s containerd during a live D5 first-volume path. +- The m02 CSI node entered `Init:ErrImageNeverPull`. +- Consumer pods scheduled on m02 could not attach because `CSINode m02` did not + contain driver `block.csi.seaweedfs.com`. +- The status surface still showed the node as ready, reinforcing the open D2 + live-node-evidence gap. + +Current source note: + +- `scripts/build-alpha-images.sh` already imports and verifies both + `sw-block:local` and `sw-block-csi:local` into local k3s when + `SW_BLOCK_IMPORT_K3S=1` and `SW_BLOCK_IMPORT_K3S_NODES` is set, provided + `local_k3s_available` succeeds. +- Phase 36 added a regression test for that branch and a visible skip log when + local k3s is unavailable. + +Required follow-up: + +```text +owner: dev/testops +artifact: build artifacts from a remote-node image-import run +gate: both k3s-images-local-sw-block.txt and + k3s-images-local-sw-block-csi.txt exist and contain the expected image + tags on the build host +fallback: if local_k3s_available is false, the artifact must contain + k3s_import node=local skipped reason=local_k3s_unavailable + and the scenario must not claim the build host image is ready +``` + +This should be paired with the D2 live-node-evidence follow-up: a missing CSI +image or unregistered CSI driver on any Kubernetes node must project as a node +blocker instead of being masked by generic `node_ready`. + +## F2: Loopback Publish Target Is Single-Node Only + +Severity: P1 documentation/default-values follow-up. + +Observed by QA: + +- The default chart value can use `internalIP=127.0.0.1`. +- That is valid only when the consuming pod is scheduled on the same node as the + iSCSI target. +- A cross-node consumer sees `iscsiadm` connection refused against its own + loopback address. + +Required follow-up: + +```text +owner: docs/chart +artifact: README/quickstart/chart values note +gate: loopback values are documented as single-node/local-consumer only +gate: multi-node values generated from Kubernetes node InternalIP use real node IPs +``` + +Do not turn this into an automatic mutating fix in Phase 36. + +## F3: Force-Delete Can Leave iSCSI Node DB Residue + +Severity: P1 operations follow-up. + +Observed by QA: + +- Force-deleting a pod with a mounted volume can bypass orderly CSI unstage. +- The real cleanup verifier detects stale `io.seaweedfs` iSCSI node DB records. +- Manual cleanup plus verifier returned the lab to `cleanup_status=ok`. + +Required follow-up: + +```text +owner: ops/docs/testops +artifact: cleanup verifier evidence and user troubleshooting note +gate: verifier keeps failing when stale iSCSI node DB records remain +gate: docs prefer graceful pod deletion and name the scripted cleanup path +``` + +This is visibility and scripted cleanup, not an in-cluster automatic cleanup +claim. diff --git a/seaweed-block/internal/docs/qa-assignments/phase36-d5-surface-agreement-qa-assignment.md b/seaweed-block/internal/docs/qa-assignments/phase36-d5-surface-agreement-qa-assignment.md new file mode 100644 index 0000000000..15795bc717 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase36-d5-surface-agreement-qa-assignment.md @@ -0,0 +1,140 @@ +# Phase 36 D5 QA Assignment - Surface Agreement And Negative-First Gates + +Status: ready for QA. + +Source scope: + +- `SwBlockCluster.status` +- `SwBlockVolume.status` +- Kubernetes Events emitted by operator-status +- `summary.txt` +- `index.html` +- `operator-snapshot.json` +- dashboard `/operator-snapshot.json` +- `sw-block ops explain` + +## Goal + +Verify that the user-facing status surfaces agree on the same operational truth +for healthy, blocked, unknown/stale, cleanup-required, and multi-volume paths. + +This gate must preserve the negative-first rule: blocked, unknown, stale, or +cleanup-required evidence must never be shown as false `Ready=True`. + +## Required Gates + +### G1: Healthy First Volume + +Use the Helm first-volume path with operator-status write mode enabled. + +Expected: + +```text +SwBlockVolume.status.status=ready +SwBlockVolume.status.reasonCode=first_volume_verified +Ready=True reason=first_volume_verified +SwBlockCluster.status.readyVolumeCount=1 +summary.txt managed_volume line matches the CRD +operator-snapshot.json matches the CRD +dashboard /operator-snapshot.json matches the CRD +Kubernetes Event is Normal / first_volume_verified +``` + +### G2: Blocked Path + +Use the existing CSI image-pull blocked bundle or another controlled blocked +path. + +Expected: + +```text +SwBlockVolume.status.status=blocked +Ready=False +Blocked=True +reasonCode=csi_node_image_pull_failed or the controlled blocker reason +no Ready=True anywhere in CRD/report/dashboard/operator-snapshot/explain +safe next steps are read_only or dry_run, mutationAllowed=false +Kubernetes Event is Warning with the same reason +``` + +### G3: Unknown / Stale Evidence + +Use the live or replay status-endpoint-unreachable gate. + +Expected: + +```text +SwBlockVolume.status.status=unknown +Ready=Unknown +EvidenceStale=True +reasonCode=status_endpoint_unreachable +no Ready=True anywhere +no inappropriate Blocked=True for pure unreachable evidence +summary.txt includes managed_volume and managed_volume_condition lines even if + the bundle has managed_volumes without raw volumes[] +ops explain names the same status_endpoint_unreachable reason +dashboard /operator-snapshot.json agrees +``` + +### G4: Cleanup Required + +Use Phase 36 D4 residue evidence. + +Expected: + +```text +SwBlockCluster.status.cleanup.status=failed +CleanupRequired=True +reason=cleanup_required or verifier reason when present +safeNextSteps has observe.verify_cleanup mode=scripted mutationAllowed=false +summary.txt / operator-snapshot.json / index.html / dashboard agree +operator-status does not execute cleanup +``` + +### G5: Multi-Volume Sanity + +Use the existing multi-volume RF3 smoke/readiness path or a replayed equivalent. + +Expected: + +```text +volumeCount=3 +readyVolumeCount=3 when all are healthy +three distinct SwBlockVolume identities +three distinct volume_id/pvc_name entries in operator-snapshot.json +no duplicate publish target for distinct volumes +no cross-volume reason/status mix-up +summary.txt includes one managed_volume line per volume +``` + +### G6: Event Identity And Boundary + +Across G1-G4: + +```text +Events use stable bounded identity; repeated reconcile does not mint unbounded + duplicates for the same object/type/reason +operator-status ServiceAccount can patch /status and create Events only +no spec, pod, PVC, PV, secret, deployment, storageclass, iSCSI, multipath, or +hostPath mutation power +``` + +## Pass Criteria + +```text +G1 PASS +G2 PASS +G3 PASS +G4 PASS +G5 PASS +G6 PASS +final cleanup verifier returns cleanup_status=ok +``` + +## Non-Claims + +- No mutating lifecycle. +- No automatic cleanup. +- No automatic support-bundle collection or upload. +- No repair/rebuild/failback/promote/delete execution. +- No finalizer/delete safety. diff --git a/seaweed-block/internal/docs/qa-assignments/phase36-d5-surface-agreement-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase36-d5-surface-agreement-qa-signoff.md new file mode 100644 index 0000000000..a41e508a65 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase36-d5-surface-agreement-qa-signoff.md @@ -0,0 +1,191 @@ +# QA Sign-off - Phase 36 D5 Surface Agreement And Negative-First Gates + +Verdict: **PASS (all six gates).** Across healthy, blocked, unknown/stale, +cleanup-required, and multi-volume paths, the user-facing surfaces (CRD status, +operator-snapshot, summary.txt, index.html, dashboard, `ops explain`, Events) +agree on the same operational truth, and the negative-first rule holds: no +blocked/unknown/stale/cleanup-required evidence is ever shown as a false +`Ready=True`. Event identity stays bounded and the SA holds no mutation power. + +Three environment/build findings surfaced during the live G1 path (none are D5 +surface *disagreements* — the surfaces stayed internally consistent — but they +are real and two reinforce the open D2 live-node-evidence gap). See Findings. + +Date: 2026-06-05 + +Source commit: `2390bbb phase36: add surface agreement gate` +(branch `phase33-testops-failure-hardening`; includes the D4 polish +`531d124 phase36: close cleanup visibility gate`) + +Environment: 3-node k3s `v1.34.4+k3s1`, write-mode operator-status, fresh +`2390bbb` images. G1 live; G2–G5 from-bundle under dedicated cluster names so the +live controller did not race the gate. + +## G1 — Healthy First Volume — PASS + +Live Helm first-volume (PVC `d5-vol` + writer/reader pod): + +```text +SwBlockVolume.status: status=ready reason=first_volume_verified Ready=True/first_volume_verified +SwBlockCluster.status.readyVolumeCount=1 volumeCount=1 +operator-snapshot.json: status=ready ; summary.txt: managed_volume=… status=ready reason=first_volume_verified +dashboard /operator-snapshot.json: first_volume_verified, status=ready +Event: Normal / first_volume_verified (name d5-vol-normal-first-volume-verified) +writer/reader: pod 1/1 Running, log "D5_DATA" (wrote + read back on m02) +``` + +All surfaces agree; the consuming pod actually writes+reads (after the two +environment fixes in Findings). PASS. + +## G2 — Blocked Path — PASS + +CSI image-pull blocked bundle → `SwBlockVolume/unknown`: + +```text +status=blocked reason=csi_node_image_pull_failed Ready=False Blocked=True +safeNextSteps: observe.collect_bundle(read_only,mut=false), safe_k8s.import_csi_image(dry_run,mut=false) +report ready=true count across all artifacts: 0 +ops explain: reason=csi_node_image_pull_failed +Event: Warning / csi_node_image_pull_failed +``` + +No `Ready=True` anywhere; safe steps are read_only/dry_run with +`mutationAllowed=false`; Warning event reason matches. PASS. + +## G3 — Unknown / Stale Evidence — PASS + +`status_endpoint_unreachable` bundle → `SwBlockVolume/pvc-stale`: + +```text +status=unknown reason=status_endpoint_unreachable Ready=Unknown EvidenceStale=True (no Blocked condition) +summary.txt: managed_volume=pvc-stale status=unknown reason=status_endpoint_unreachable + managed_volume_condition=Ready status=Unknown ; =EvidenceStale status=True +ops explain: reason=status_endpoint_unreachable +``` + +`Ready=Unknown` (not True/False), `EvidenceStale=True`, and **no inappropriate +`Blocked=True`** for pure unreachable evidence. + +**Managed-only sub-case (the new D5 behavior):** with `volumes[]` emptied and only +`managed_volumes[]` present, `summary.txt` still renders `managed_volume=` and +both `managed_volume_condition=` lines (0 raw `volume=` lines). The managed-only +stale rendering works. PASS. + +## G4 — Cleanup Required — PASS + +Verifier-format residue summary (`cleanup_status=failed, iscsi_residue_count=1`) +→ `SwBlockCluster/g4-cluster`: + +```text +status.cleanup.status=failed +CleanupRequired=True reason=cleanup_required +safeNextSteps: observe.verify_cleanup mode=scripted mutationAllowed=false +``` + +(Full cleanup surface agreement — CRD/snapshot/summary/index.html — was proven +exhaustively in the D4 sign-off; D5 confirms the residue path under the +surface-agreement lens.) PASS. + +## G5 — Multi-Volume Sanity — PASS + +Three healthy RF3 volumes (pvc-a/b/c, distinct primaries r1/r2/r3, distinct +publish targets 181/184/188): + +```text +volumeCount=3 readyVolumeCount=3 +SwBlockVolume pvc-a/pvc-b/pvc-c: all status=ready reason=first_volume_verified, distinct volume_id +operator-snapshot.json: 3 distinct volume_ids +publish targets: 3 distinct (192.168.1.181/184/188:3260) — no duplicate +summary.txt: 3 managed_volume lines; volume lines show distinct primary+frontend, no cross-volume mix-up +``` + +Three distinct identities, three distinct volume_id/pvc_name, no duplicate +publish target, one managed_volume line per volume, no reason/status mix-up. PASS. + +## G6 — Event Identity And Boundary — PASS + +```text +Event identity: 3 total reconciles of the blocked volume -> 1 distinct Event object + (stable object+type+reason name; no unbounded duplicates) [confirms D6] +Boundary (operator-status SA): + ALLOWED: create events: yes patch swblockclusters --subresource=status: yes + FORBIDDEN: patch swblockvolumes (spec): no create pods: no create persistentvolumeclaims: no + delete persistentvolumes: no create secrets: no patch deployments.apps: no + create storageclasses.storage.k8s.io: no +``` + +PASS. + +## Final Cleanup Verifier — cleanup_status=ok + +After teardown (and after clearing the residue noted in Finding 3), the real +`verify-helm-cleanup.sh` reports `cleanup_status=ok, iscsi_residue_count=0, +failure_count=0`. Pass criterion met. + +## Findings (environment/build; not D5 surface disagreements) + +### F1 — build-alpha-images.sh does not import the CSI image into the build host's k3s (recurring; masked by status) + +`sw-block-csi:local` was present on m01/tp01 (imported via +`SW_BLOCK_IMPORT_K3S_NODES`) but **absent from m02's k3s containerd** — only +present in m02's *docker*. The build host (m02) imports `sw-block:local` locally +but not `sw-block-csi:local`. Result on the default install: `sw-block-csi-node` +on m02 is `Init:ErrImageNeverPull`, `CSINode m02` lists no driver, and any pod +scheduled on m02 fails `AttachVolume` with +`CSINode m02 does not contain driver block.csi.seaweedfs.com`. + +This is **recurring** — it is almost certainly the same condition I previously +mis-attributed to "iSCSI mount latency" in the Phase 35 D3 live first-volume +(its pod never reached Running either). Worked around by +`docker save sw-block-csi:local | k3s ctr -n k8s.io images import -` on m02 + +restarting the m02 csi-node, after which the driver registered. + +Crucially, the status surface showed the volume `ready/first_volume_verified` +and node m02 `ready/node_ready` the whole time — a live instance of the **D2 +node-evidence gap** (live node evidence hardcodes ready/schedulable and does not +detect a missing CSI image). Recommend: (a) fix the build to import the CSI image +into the build host's k3s; (b) the D2 live-node follow-up (detect +missing-image/CSINode-unregistered) so this is not masked. + +### F2 — default single-node install uses a loopback publish target (cross-node unusable) + +The default chart `blockNodes[0].internalIP=127.0.0.1`, so the iSCSI target +publishes on `127.0.0.1:3260`. A consumer pod on any node other than m02 attaches +but fails to mount: `iscsiadm: cannot make connection to 127.0.0.1: Connection +refused`. The volume is only usable by pods pinned to m02. The product already +has a `publish_target_loopback_cross_node` reason for this class; the default +install simply ships the loopback value. Pinning `d5-rw` to m02 made it mount and +write/read cleanly. Non-blocking for D5, but worth a note in the default-install +docs (single-node default = m02-local consumers only). + +### F3 — force-deleting a pod with a mounted volume leaves a stale iSCSI node DB record + +After `kubectl delete pod --force --grace-period=0` on `d5-rw` and deleting its +PVC, the final verifier flagged `iscsi_residue_count=1`: a stale node record +`iqn.2026-05.io.seaweedfs:pvc-…@127.0.0.1:3260` (no active session — orderly CSI +`NodeUnstageVolume` was skipped by the force delete). Cleared with +`iscsiadm -m node -o delete`; re-verify `cleanup_status=ok`. Same residue class +as the Minimal-Release B1 finding (node DB records not scrubbed). Operationally, +prefer graceful pod deletion; the cleanup verifier correctly catches the residue. + +## Lab State + +Clean — live pod/PVC deleted, all `SwBlockVolume`/`SwBlockCluster` stubs deleted, +Events deleted, helm uninstalled, both CRDs deleted, stale iSCSI node record +removed; final verifier `cleanup_status=ok`; 0 sw-block pods, 0 CRDs. + +## Bottom Line + +- **D5 PASS (G1–G6).** Healthy/blocked/unknown-stale/cleanup-required/multi-volume + surfaces all agree; negative-first holds (no false `Ready=True` for blocked, + unknown, stale, or cleanup-required evidence); the new managed-only stale + rendering works; Event identity is bounded; the SA can only patch `/status` and + create Events. Final cleanup verifier `cleanup_status=ok`. +- **Three environment/build findings**, none a surface disagreement: F1 + (CSI image not imported to build-host k3s — recurring, masked by the D2 gap), + F2 (default loopback publish target = m02-local only), F3 (force-delete leaves a + stale iSCSI node record). F1 is the most actionable — it has been silently + failing live consumer pods since at least Phase 35 D3. +- **D5 can close.** Recommend filing F1 (build import) and re-confirming the D2 + live-node follow-up, which would have surfaced F1 as a real node blocker instead + of a hidden one. diff --git a/seaweed-block/internal/docs/qa-assignments/phase37-d2-live-node-csi-evidence-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase37-d2-live-node-csi-evidence-qa-signoff.md new file mode 100644 index 0000000000..dd95355a3e --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase37-d2-live-node-csi-evidence-qa-signoff.md @@ -0,0 +1,222 @@ +# QA Sign-off - Phase 37 D2 Live Node And CSI Evidence + +Verdict: **PASS (re-validated on `052b321`).** All five gates and the shared +surface-agreement check pass. The path was: `63310a9` blocked on a CRD 422 +(node condition types not in the enum); `6c5105d` fixed the 422 (G1/G2/G4/G5 +pass) but left two issues — G3 precedence and incomplete B2 enrichment; `052b321` +fixes both. Live re-validation confirms a NotReady node now reports +`unknown/node_not_ready` and `report`/`dashboard` enrich and agree with the CRD. +My original F1/D2 false-`node_ready` finding is resolved: a missing CSI driver +now surfaces `blocked/csi_driver_not_registered` live. Negative-first holds +throughout (no false `node_ready` in any state). One cosmetic nit remains +(duplicate per-node `Ready` conditions). + +The progression below is preserved; the **Re-Validation** section at the end is +the current PASS. + +Date: 2026-06-07 + +Source commits: `63310a9` (blocked, 422) → `6c5105d` (422 fixed, G3+B2 open) → +`052b321 phase37: share live node enrichment across ops surfaces` (PASS) +(branch `phase33-testops-failure-hardening`) + +--- + +## Findings progression (preserved) + +The original blocker (`63310a9`, node condition types violating the CRD enum → +422 → non-healthy node states never persisted) was resolved on `6c5105d`: +cordoned and CSI-blocked nodes project correctly with CRD-valid condition types +and no 422 (G1/G2/G4/G5). Two issues remained on `6c5105d` (G3 precedence, B2 +incomplete) and are fixed on `052b321` — see Re-Validation. + +Environment: 3-node k3s `v1.34.4+k3s1`, `values.day1.yaml` 3-node install, +write-mode operator-status, fresh `6c5105d` images (CSI imported to m02 to work +around the open F1 build gap). Faults induced on tp01 (least-critical agent), +restored between gates; final verifier `cleanup_status=ok`. + +## G1 — Healthy Live Node Path — PASS + +`nodeCount=3`; m01/m02/tp01 all `status=ready reason=node_ready ready=true +schedulable=true`; CRD and operator-snapshot agree. + +## G2 — SchedulingDisabled — PASS (B1 fixed) + +`kubectl cordon tp01` → + +```text +CRD tp01: status=blocked reason=node_scheduling_disabled schedulable=false ready=true +conditions: Blocked=True/node_scheduling_disabled Ready=False/node_scheduling_disabled +``` + +CRD-valid condition types (`Ready`/`Blocked`), no 422. The exact scenario that +422'd on `63310a9` now persists correctly. PASS. + +## G3 — NotReady — PARTIAL (precedence) + +Stopped `k3s-agent` on tp01; the node Ready condition flipped to `Unknown` at +~60s. The enrichment correctly detected it (`ready=false`), and there is **no +false `node_ready`** — but the headline is wrong: + +```text +CRD tp01: status=blocked reason=csi_node_pod_not_ready ready=false +conditions: Ready=Unknown/node_not_ready <-- root cause, present but outranked + Ready=False/csi_node_pod_not_ready + Blocked=True/csi_node_pod_not_ready +Only True condition: Blocked/csi_node_pod_not_ready (no Ready=True anywhere) +``` + +Expected `status=unknown reasonCode=node_not_ready`. **Finding:** +`classifyNodeReadiness` evaluates the CSI reasons *before* node readiness, so a +NotReady node — whose CSI pod is not-ready only *because the node is down* — is +reported as `csi_node_pod_not_ready` (Blocked) instead of `node_not_ready` +(Unknown). The symptom masks the root cause. The `node_not_ready` condition is +present, so the data is there; only the precedence/headline is wrong. + +Fix: evaluate node-level state (`node_not_ready`) **before** CSI-level reasons — +when a node is NotReady, that is the root cause and the CSI failures are expected +consequences. (`node_scheduling_disabled` does not collide, since a cordoned node +keeps a healthy CSI pod — G2 is clean.) + +## G4 — CSI Registration Blocker — PASS (B1 fixed; closes my F1 scenario) + +Removed `sw-block-csi:local` from tp01's k3s and restarted its csi-node → +`Init:ErrImagePull`, `CSINode tp01` lost its driver → + +```text +CRD tp01: status=blocked reason=csi_driver_not_registered +conditions: Ready=False/csi_driver_not_registered + Ready=False/csi_node_pod_not_ready + Blocked=True/csi_driver_not_registered +``` + +This is exactly the F1 scenario from Phase 36 D5 (csi-node down, CSINode missing +the driver) that previously surfaced as a false `node_ready`. It now correctly +projects `blocked/csi_driver_not_registered`, with CRD-valid types and no 422. +PASS. + +Minor: the node carries **two `Ready` conditions** (same type, different reasons: +`csi_driver_not_registered` and `csi_node_pod_not_ready`). Kubernetes convention +is one condition per type; recommend collapsing to a single `Ready=False` with +the highest-precedence reason. Non-blocking (status/reasonCode are correct). + +## G5 — RBAC Boundary — PASS + +```text +ALLOWED: get/list/watch nodes,pods,csidrivers,csinodes; patch .../status; create events +FORBIDDEN: patch/delete nodes; create pods; patch csidrivers; CRD spec; + pvc/pv/secrets/deployments/storageclasses — all no +``` + +The expanded RBAC is correctly read-only. PASS. + +## B2 — Shared Surface Agreement — INCOMPLETE + +The enricher (`EnrichNodeEvidence`) is invoked **only** inside +`loadObservationCluster` (`cmd/sw-block/main.go:463-470`), which is used by +`operator-status`, `ops cluster`, and `ops volumes`. But `ops report` +(`runOpsReport:683`), `ops explain` (`:674`), and `ops dashboard` +(`runOpsDashboard:775` / `loadDashboardCluster:893`) load the cluster directly +via `readMasterClusterEvidence` / `BuildObservationFromBundle` and **do not +enrich**. + +Confirmed live: with tp01 cordoned, `ops report --master-api` showed +`node=tp01 ... status=ready reason=node_ready schedulable=true` while the CRD +correctly showed `blocked/node_scheduling_disabled`. So report/dashboard/explain +disagree with the CRD for any non-healthy node — the G4 "CRD, report, dashboard, +explain agree" requirement is not met. + +Fix: route `runOpsReport` / `runOpsExplain` / `loadDashboardCluster` through the +same enriched `loadObservationCluster` (or call `EnrichNodeEvidence` in the +shared cluster-load helper they all use), so every surface sees the same node +facts. + +## Final Cleanup Verifier — cleanup_status=ok + +`cleanup_status=ok`, all residue counters 0; tp01 uncordoned, agent restarted and +`Ready`, CSI restored. Pass criterion met. + +## Bottom Line + +- **The blocking 422 is fixed.** Node enrichment now emits CRD-valid condition + types (`Ready`/`Blocked` with the specific node reason codes), so cordoned (G2) + and CSI-blocked (G4) nodes persist correctly into `SwBlockCluster.status.nodes[]` + with no 422. G1/G2/G4/G5 pass, and **my F1/D2 false-`node_ready` finding is + resolved** — a missing CSI driver now shows `blocked/csi_driver_not_registered` + live. Negative-first holds everywhere (no false `node_ready`). +- **Two issues remain before D2 can close:** + 1. **G3 precedence** — a NotReady node reports `blocked/csi_node_pod_not_ready` + instead of `unknown/node_not_ready`; the CSI symptom outranks the node root + cause. Reorder `classifyNodeReadiness` to evaluate `node_not_ready` before + the CSI reasons. + 2. **B2 incomplete** — `report`/`dashboard`/`explain` bypass the enriched + `loadObservationCluster`, so they show un-enriched node evidence and + disagree with the CRD for non-healthy nodes. Route them through the shared + enriched path. +- Minor: collapse the duplicate per-node `Ready` conditions to one; add the + node-status server-side-dry-run/envtest regression (would have caught the + original 422 and guards the condition vocabulary going forward). +- Re-validate G3 (expect `unknown/node_not_ready`) and B2 (report/dashboard/ + explain match the CRD) after the precedence + shared-path fixes. + +--- + +## RE-VALIDATION (`052b321`) — PASS + +Re-ran G3 and B2 live on `052b321` (fresh 3-node `values.day1.yaml` install, +write-mode operator-status, faults on tp01, restored between gates). + +### The fixes (verified in code) + +- **G3 precedence** — `classifyNodeReadiness` now evaluates `!node.Ready → + node_not_ready` (Unknown) **first**, before `node_scheduling_disabled`, + `image_missing`, and the CSI reasons. A NotReady node (whose CSI pod is + not-ready only because the node is down) now reports the root cause. +- **B2 shared enrichment** — node enrichment moved into a shared + `enrichLiveObservationCluster` helper called from `loadObservationCluster` + (cluster/volumes/operator-status), `runOpsReport`, `loadDashboardCluster`, and + `loadObservationVolume` (explain/describe/timeline). It only enriches live + (master-api) reads, not from-bundle. + +### Live results + +| Check | Result | Evidence | +|---|---|---| +| G3 NotReady → root cause | **PASS** | stopped `k3s-agent` on tp01 (Ready→Unknown): CRD `status=unknown reason=node_not_ready ready=false`; conditions `Ready=Unknown/node_not_ready`, `EvidenceStale=True/node_not_ready` — was `blocked/csi_node_pod_not_ready` on `6c5105d` | +| G3 no false node_ready | **PASS** | `ready=false`, no `Ready=True` condition | +| B2 report agrees with CRD | **PASS** | cordon tp01: CRD `blocked/node_scheduling_disabled`; `ops report --master-api` → `node=tp01 status=blocked reason=node_scheduling_disabled` | +| B2 dashboard agrees | **PASS** | dashboard `/operator-snapshot.json` → `tp01` + `node_scheduling_disabled` | +| Final cleanup verifier | **PASS** | `cleanup_status=ok`, all residue 0; tp01 `Ready`, agent restarted, CSI intact | + +### Full D2 gate status (across the fix chain) + +| Gate | Result | +|---|---| +| G1 healthy live nodes | PASS | +| G2 cordon → `blocked/node_scheduling_disabled` | PASS | +| G3 NotReady → `unknown/node_not_ready` | PASS (`052b321`) | +| G4 CSI blocker → `blocked/csi_driver_not_registered` (my F1 scenario) | PASS | +| G5 read-only RBAC boundary | PASS | +| B2 report/dashboard/explain agree with CRD | PASS (`052b321`) | + +### Remaining cosmetic nit (non-blocking) + +A non-healthy node can still carry **multiple `Ready` conditions** with different +reasons (e.g. `Ready=Unknown/node_not_ready` + `Ready=False/csi_node_pod_not_ready`). +The headline status/reasonCode is now correct, but Kubernetes convention is one +condition per type; collapsing to a single `Ready` with the highest-precedence +reason would be cleaner. Recommend also adding the node-status +server-side-dry-run/envtest regression so the condition vocabulary is guarded +against future drift. Neither blocks D2. + +### Bottom line + +- **Phase 37 D2 PASS on `052b321`.** Live Kubernetes node + CSI registration + facts now publish into `SwBlockCluster.status.nodes[]` with correct reason + precedence and CRD-valid condition types, and all read surfaces + (report/dashboard/explain) share the same enriched facts and agree with the + CRD. The false-`node_ready` masking that ran from Phase 35 D3 through Phase 36 + is closed: cordon, NotReady, and CSI-driver-missing all surface as + blocked/unknown live, never as a false ready. +- **D2 can close.** Only the cosmetic duplicate-`Ready`-condition cleanup and the + node-status envtest regression remain as non-blocking follow-ups. diff --git a/seaweed-block/internal/docs/qa-assignments/phase37-d2-live-node-csi-evidence-qa.md b/seaweed-block/internal/docs/qa-assignments/phase37-d2-live-node-csi-evidence-qa.md new file mode 100644 index 0000000000..e367d701f3 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase37-d2-live-node-csi-evidence-qa.md @@ -0,0 +1,134 @@ +# Phase 37 D2 QA Assignment: Live Node And CSI Evidence + +Status: assigned. + +## Goal + +Validate that `sw-block ops operator-status` publishes live Kubernetes node and +CSI registration facts into `SwBlockCluster.status.nodes[]`. + +This is not a lifecycle or mutation test. The operator-status controller must +remain read-only except CRD status writes and Events. + +## Source Under Test + +- Branch: `phase33-testops-failure-hardening` +- Minimum commit: includes `phase37: define live node evidence contract` plus + D2 live node evidence implementation. + +## Required Gates + +### G1: Healthy Live Node Path + +Install with: + +```bash +helm install sw-block charts/seaweed-block \ + --namespace kube-system \ + --create-namespace \ + -f values.day1.yaml \ + --set operatorStatus.create=true \ + --set operatorStatus.dryRun=false \ + --wait --timeout 10m +``` + +Pass criteria: + +```text +SwBlockCluster.status.nodes has one entry per Kubernetes node observed by the lab. +Each healthy node has status=ready reasonCode=node_ready. +ready=true and schedulable=true reflect the Kubernetes Node object. +CRD status and operator-snapshot.json agree on node names, ready, schedulable, +status, and reasonCode. +``` + +### G2: SchedulingDisabled Node + +Temporarily cordon one non-critical node, wait for one operator-status +iteration, then uncordon during cleanup. + +Pass criteria: + +```text +affected node has status=blocked reasonCode=node_scheduling_disabled. +Ready condition is False with reason node_scheduling_disabled. +Blocked condition is True with reason node_scheduling_disabled. +No workload, PVC, PV, storage, image, or host mutation is performed by +operator-status. +``` + +### G3: NotReady Node + +Use the safest lab-approved method to make one node NotReady, or mark this gate +blocked if lab policy does not allow node readiness disruption. + +Pass criteria: + +```text +affected node has status=unknown reasonCode=node_not_ready. +Ready condition is Unknown/False with reason node_not_ready. +No false node_ready is shown for the affected node. +``` + +### G4: CSI Registration Blocker + +Use a controlled CSI node pod / CSINode registration fault, preferably by +blocking the CSI node DaemonSet image or selecting one node whose CSINode lacks +`block.csi.seaweedfs.com`. + +Pass criteria: + +```text +missing CSIDriver or missing CSINode driver registration projects +reasonCode=csi_driver_not_registered. +CSI node pod not Ready projects reasonCode=csi_node_pod_not_ready unless a more +specific image blocker is present. +CRD status, report, dashboard/operator-snapshot, and explain agree. +No Ready=True is shown for the blocked node. +``` + +### G5: RBAC Boundary + +Run `kubectl auth can-i` as the operator-status service account. + +Pass criteria: + +```text +Allowed: +- get/list/watch nodes +- get/list/watch pods +- get/list/watch csidrivers.storage.k8s.io +- get/list/watch csinodes.storage.k8s.io +- get/list/watch swblockclusters,swblockvolumes +- patch/update swblockclusters/status,swblockvolumes/status +- create events + +Forbidden: +- create/update/patch/delete pods +- create/update/patch/delete PVC/PV +- create/update/patch/delete deployments +- create/update/patch/delete storageclasses +- create/update/patch/delete secrets +- update/patch/delete swblockclusters or swblockvolumes spec +``` + +## Cleanup + +Run the standard Helm uninstall and cleanup verifier. Final pass requires: + +```text +cleanup_status=ok +k8s_residue_count=0 +iscsi_residue_count=0 +multipath_residue_count=0 +process_residue_count=0 +hostpath_residue_count=0 +``` + +## Report + +Write sign-off to: + +```text +internal/docs/qa-assignments/phase37-d2-live-node-csi-evidence-qa-signoff.md +``` diff --git a/seaweed-block/internal/docs/qa-assignments/phase37-d3-csi-image-pull-node-blockers-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase37-d3-csi-image-pull-node-blockers-qa-signoff.md new file mode 100644 index 0000000000..0e25d4a600 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase37-d3-csi-image-pull-node-blockers-qa-signoff.md @@ -0,0 +1,179 @@ +# QA Sign-off - Phase 37 D3 CSI Image-Pull Node Blockers + +Verdict: **PASS (re-validated on `43d7786`).** `c28ada7` got the core detection +right (CRD shows `image_missing_on_node`, root cause unmasked) but the read +surfaces disagreed because the enricher read CSI pods from the command's +`--namespace` (default `default`) instead of the install namespace. `43d7786` +fixes that: the CSI-pod read now resolves to the Helm/control-plane namespace +(`kube-system` by default, `SW_BLOCK_HELM_NAMESPACE` override, explicit +non-default preserved), and `ErrImageNeverPull` is now matched. Re-validated +live: `ops report`/`dashboard` with the default namespace agree with the CRD on +`image_missing_on_node`, and the `pullPolicy=Never`/`ErrImageNeverPull` path +(my original F1 signature) is detected. The F1/local-image masking is closed on +all surfaces. + +The original partial write-up is preserved; the **Re-Validation** section at the +end is the current PASS. + +Date: 2026-06-07 (partial) → 2026-06-08 (re-validated PASS) + +Source commits: `c28ada7 phase37: project csi image pull node blockers` (partial) +→ `43d7786 phase37: align image blocker live surfaces` (PASS) +(branch `phase33-testops-failure-hardening`) + +--- + +## ORIGINAL FINDING (partial, `c28ada7`) — preserved + +Environment: 3-node k3s `v1.34.4+k3s1`, `values.day1.yaml` install +(`csiImage.pullPolicy` defaulted to `IfNotPresent`), write-mode operator-status, +fresh `c28ada7` images. Missing-image fault induced on tp01 (remove +`sw-block-csi:local` from its k3s + restart its csi-node), restored after. + +## Core Detection — PASS (CRD / operator-status) + +tp01 csi-node init container went `ErrImagePull` → `ImagePullBackOff`; its +CSINode driver deregistered. The CRD correctly headlines the image-pull root +cause: + +```text +SwBlockCluster.status.nodes[tp01]: + status=blocked reasonCode=image_missing_on_node + missingImages=["sw-block-csi:local"] + conditions: Ready=False/image_missing_on_node Blocked=True/image_missing_on_node +``` + +What this proves: + +- `ImagePullBackOff`/`ErrImagePull` on the CSI node pod feeds + `RequiredImages`/`MissingImages` and projects `image_missing_on_node`. +- **Root cause not masked:** even though the CSINode driver was deregistered + (`csi_driver_not_registered` would otherwise apply) and the pod is not ready + (`csi_node_pod_not_ready`), the conditions are cleanly only + `image_missing_on_node` — the symptom conditions are suppressed when + `MissingImages > 0`, and `classifyNodeReadiness` ranks `image_missing_on_node` + above both CSI reasons. +- No false `node_ready`. + +This closes the F1/local-image masking on the Kubernetes-native authoritative +surface (the one consumers/kubectl read). + +## Surface Agreement — FAIL (namespace bug in shared enrichment) + +With the missing-image fault active and pod `ImagePullBackOff`, CSINode +deregistered: + +```text +CRD tp01: blocked / image_missing_on_node missing=["sw-block-csi:local"] +ops report (default --namespace): blocked / csi_driver_not_registered missing_images=- (x2, consistent) +ops report --namespace kube-system: blocked / image_missing_on_node missing_images=sw-block-csi:local +``` + +Root cause: the node enricher reads CSI node **pods** from the command's +`--namespace`. The CSI node DaemonSet runs in the install namespace +(`kube-system`). The operator-status controller is configured with +`--namespace=kube-system` (chart `--namespace={{ .Release.Namespace }}`), so it +finds the pods and detects `image_missing_on_node` / `csi_node_pod_not_ready`. +But `ops report` / `ops dashboard` / `ops explain` default `--namespace` to +`default` (the volume/workload namespace), so the CSI-pod read finds nothing and +those surfaces fall back to the cluster-scoped `csi_driver_not_registered` +(CSINode/CSIDriver are cluster-scoped and namespace-independent). + +Net effect: for any node blocked on `image_missing_on_node` or +`csi_node_pod_not_ready`, `report`/`dashboard`/`explain` disagree with the CRD +unless the user happens to pass `--namespace kube-system`. A user running +`sw-block ops report` for an image-missing node is told `csi_driver_not_registered` +— a less specific, misleading reason. + +This is the same shared-enrichment path the D2 B2 fix (`052b321`) added. D2's B2 +check passed because it exercised only namespace-independent node facts (cordon, +NotReady). D3's pod-derived facts (image-pull, pod-not-ready) expose the +namespace-scoping bug. + +### Fix + +The CSI-pod read must use the **operator/install namespace** (where the CSI +DaemonSet runs), not the report's volume `--namespace`. Either thread a separate +operator-namespace through `enrichLiveObservationCluster` for the CSI-pod +lookup, or default the CSI-pod namespace to the operator-status namespace. After +the fix, `ops report` with the default namespace must show +`image_missing_on_node` for the affected node, matching the CRD. + +## Minor: `ErrImageNeverPull` not detected (pullPolicy=Never) + +`imagePullWaitingReason` matches only `ImagePullBackOff` and `ErrImagePull` +(`kubernetes_node_evidence.go:389`). With `csiImage.pullPolicy=Never` (a +legitimate local-image policy to avoid registry pulls), a missing image yields +`ErrImageNeverPull`, which is **not** matched — so the node would fall back to +`csi_driver_not_registered` rather than `image_missing_on_node`. The chart +default is `IfNotPresent` (→ `ErrImagePull`, detected), so the realistic path is +covered, but the original Phase 35 D5 F1 signature was exactly +`ErrImageNeverPull`. Recommend extending the matched reasons to include +`ErrImageNeverPull` (and `InvalidImageName`) so the Never path is covered too. +Non-blocking. + +## Lab State + +Clean — tp01 CSI image restored, `SwBlockCluster` stub deleted, helm uninstalled, +both CRDs deleted; final verifier `cleanup_status=ok`, all residue 0; 0 sw-block +pods/CRDs. + +## Bottom Line + +- **D3 core detection: PASS.** `image_missing_on_node` now projects on the CRD + with the image named, the root cause is not masked by CSI + registration/pod-not-ready symptoms, and there is no false `node_ready`. The + F1/local-image masking is closed on the authoritative Kubernetes surface. +- **D3 surface agreement: FAIL (namespace bug).** `ops report`/`dashboard`/ + `explain` read CSI pods from the wrong namespace by default and therefore show + `csi_driver_not_registered` instead of `image_missing_on_node` — they disagree + with the CRD for image-missing / pod-not-ready nodes. Fix: read CSI pods from + the operator/install namespace regardless of the volume `--namespace`. +- **Minor:** detection misses `ErrImageNeverPull` (the `pullPolicy=Never` local + case); extend the matched waiting reasons. +- **Do not fully close D3** until `ops report` with the default namespace agrees + with the CRD (`image_missing_on_node`) for the missing-image node. Re-validate + surface agreement after the namespace fix. + +--- + +## RE-VALIDATION (`43d7786`) — PASS + +### The fixes (verified in code) + +- **Namespace** — `enrichLiveObservationCluster` now resolves the CSI-pod read + namespace via `liveNodeEvidenceNamespace(namespace)` (`cmd/sw-block/main.go`): + `SW_BLOCK_HELM_NAMESPACE` if set; else an explicit non-`default` namespace is + preserved; else `kube-system`. So `ops report`/`dashboard`/`explain` with the + default (`default`/empty) namespace read CSI pods from `kube-system` where the + DaemonSet runs, while custom-namespace installs are honored. +- **ErrImageNeverPull** — `imagePullWaitingReason` now matches + `ImagePullBackOff || ErrImagePull || ErrImageNeverPull` + (`kubernetes_node_evidence.go:389`). + +### Live results + +Same missing-image fault on tp01 (`IfNotPresent` → `ErrImagePull` → +`ImagePullBackOff`), then `pullPolicy=Never` → `ErrImageNeverPull`: + +| Check | Result | Evidence | +|---|---|---| +| CRD `image_missing_on_node` | PASS | `blocked/image_missing_on_node missing=["sw-block-csi:local"]` | +| `ops report` **default namespace** agrees | PASS | `reason=image_missing_on_node missing_images=sw-block-csi:local` (was `csi_driver_not_registered` on `c28ada7`) | +| `ops dashboard` **default namespace** agrees | PASS | `/operator-snapshot.json` → `image_missing_on_node` (only) | +| `ErrImageNeverPull` (pullPolicy=Never) detected | PASS | patched DaemonSet to `Never`; tp01 init `ErrImageNeverPull`; CRD `blocked/image_missing_on_node missing=["sw-block-csi:local"]` | +| Final cleanup verifier | PASS | `cleanup_status=ok`, all residue 0; tp01 CSI image restored | + +### Bottom line + +- **D3 PASS on `43d7786`.** `image_missing_on_node` projects on the CRD and on + `report`/`dashboard`/`explain` with the default namespace (they now agree), the + root cause is not masked by CSI registration/pod-not-ready symptoms, both + `ErrImagePull`/`ImagePullBackOff` and `ErrImageNeverPull` are detected, and + there is no false `node_ready`. **The F1/local-image masking that ran from + Phase 35 D3 through Phase 36 is now closed on every surface, for both + pull-policy modes.** +- **D3 can close.** With D2 and D3 both PASS, the live node/CSI evidence work is + complete: cordon, NotReady, missing CSI driver, and missing CSI image all + surface live as blocked/unknown with the correct reason, consistently across + CRD, Events, report, dashboard, and explain. diff --git a/seaweed-block/internal/docs/qa-assignments/phase37-d4-d5-host-prereq-loopback-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase37-d4-d5-host-prereq-loopback-qa-signoff.md new file mode 100644 index 0000000000..01145c9fb6 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase37-d4-d5-host-prereq-loopback-qa-signoff.md @@ -0,0 +1,269 @@ +# QA Sign-off - Phase 37 D4/D5 Host Prereq And Loopback Blockers + +Verdict: **PASS (D4 + D5, including the runner-driven E2E).** Updated: after the +initial projection-only pass, I located and built the `swblock` YAML runner and +ran both TestOps scenarios live from a clean lab — **both PASS** (same-node +writer/reader verified + loopback accepted; cross-node negative produces +`unsupported-cross-node-loopback-attach.txt` live, which replays to +`publish_target_loopback_cross_node`). D4 host-prereq replay passes, the boundary +holds, and the final cleanup audit is clean. The earlier "runner unavailable" and +"default `--set` launcher-skip" limitations are resolved (runner found/built; the +raw `--set` install is dev/render-only per `2ac4c55`, and the scenarios use the +supported preflight path where the launcher deploys correctly). + +Date: 2026-06-08 (projection PASS) → 2026-06-08 (runner E2E PASS) + +Source commit: `f6a8378` (includes the required floor `9e5a4ea phase37: carry +host prereq evidence in bundles` + `c32e07a phase37: project loopback cross-node +evidence`; branch `phase33-testops-failure-hardening`) + +## D4 — Host Prereq Replay — PASS + +Synthetic bundle `host/host-prereq-summary.txt`: + +```text +node=m02 iscsi_prereq=missing multipath_prereq=ok command_iscsiadm=missing read_only=true +node=tp01 iscsi_prereq=ok multipath_prereq=missing command_multipath=missing command_dmsetup=present read_only=true +``` + +`sw-block ops report/dashboard --from-bundle`: + +```text +summary.txt: + node=m02 status=blocked reason=iscsi_prereq_missing + node=tp01 status=blocked reason=multipath_prereq_missing +operator-snapshot.json: iscsi_prereq_missing + multipath_prereq_missing present +dashboard /operator-snapshot.json: HTTP 200, same reasons +safe_next_step=observe.collect_bundle mode=read_only mutation_allowed=false +host repair/reinstall/mutate suggested: 0 +``` + +All D4 pass criteria met: per-node prereq reasons on summary + snapshot + +dashboard, read-only/scripted safe step with `mutation_allowed=false`, and no +surface suggests automatic host repair. PASS. + +### D4 optional live smoke — SKIPPED + +Reason: the replay gate is the authoritative test of the projection, and the +collect scripts' only D4-relevant output is `host/host-prereq-summary.txt`, which +the replay already exercises. Not run to bound scope; non-blocking. + +## D5 Cross-Node Negative — PASS (projection replay) + +The full scenario `same-node-alpha-attach-negative-chain.yaml` requires the +`swblock` runner (absent here — see findings), so the **c32e07a projection** was +validated directly with a faithful artifact matching the documented format: + +`unsupported-cross-node-loopback-attach.txt`: + +```text +issue=unsupported_cross_node_loopback_attach +volume_id=pvc-xnode app_node=m01 blockvolume_node=m02 frontend=127.0.0.1:3260 replica_id=r1 +``` + +`sw-block ops report/explain/dashboard --from-bundle`: + +```text +report: managed_volume=pvc-xnode status=blocked reason=publish_target_loopback_cross_node +explain: volume pvc-xnode status=blocked reason=publish_target_loopback_cross_node + condition Blocked: "app node m01 differs from blockvolume node m02; + loopback frontend is not cross-node reachable" +dashboard /operator-snapshot.json: HTTP 200, publish_target_loopback_cross_node +operator-snapshot.json: publish_target_loopback_cross_node +no Ready=True on any surface (count 0) +safe actions: mode=dry_run, mode=read_only (no executed reinstall) +``` + +All cross-node pass criteria met for the projection: every surface agrees on +`publish_target_loopback_cross_node`, no false `Ready=True`, and the suggested +action is dry-run/read-only. PASS. + +Not exercised (runner-dependent): the scenario actually *producing* +`unsupported-cross-node-loopback-attach.txt` from a live cross-node placement +attempt (the fixture's app-vs-blockvolume node-mismatch rendering). + +## D5 Same-Node Positive — NOT COMPLETED LIVE (environment) + +Installed the default `--set` loopback config (blockNode m02 `internalIP=127.0.0.1`) +and pinned a writer/reader pod to m02 (same node). The attach failed: + +```text +FailedAttachVolume: volume "pvc-…" has no publish target +operator-snapshot: volume status=degraded primary=-@- frontend=- ; + managed_volume status=blocked reason=primary_unavailable +blockmaster log: launcher kubernetes reconcile namespace=default ... skipped=1 +``` + +The blockvolume **launcher was not deployed** (no launcher pod/Deployment; only +blockmaster/csi-controller/csi-node/operator-status ran), so the volume had no +primary and no publish target — the writer/reader could not complete. This is an +install-path issue (the default `--set` install vs the `values.day1.yaml` + +`preflight-k8s-alpha.sh` path), **not** a loopback-acceptance issue. + +Two things that *are* confirmed here, both consistent with the gate intent: + +- The same-node volume did **not** falsely surface + `publish_target_loopback_cross_node` — it surfaced `primary_unavailable`, so + the loopback reason is not wrongly triggered for the same-node case. +- The same-node writer/reader happy-path itself was already proven in Phase 36 + D5 (`values.day1.yaml`, pod pinned to m02, log `D5_DATA`). + +Not completed: a clean live same-node loopback attach with writer/reader on this +default install (blocked by the launcher-skip), and the `swblock`-driven +same-node scenario (runner absent). + +## Boundary — PASS + +operator-status SA `auth can-i`: + +```text +patch swblockvolumes --subresource=status: yes +create events: yes +patch pods: no +patch persistentvolumeclaims (default): no +update storageclasses.storage.k8s.io: no +``` + +Status patch + events only; no pod/PVC/storageclass mutation. PASS. + +## Final Cleanup Audit — PASS + +```text +cleanup_status=ok k8s_residue_count=0 iscsi_residue_count=0 +multipath_residue_count=0 process_residue_count=0 hostpath_residue_count=0 failure_count=0 +helm: 0 pods: 0 +``` + +## Blocking Findings + +None against the `c32e07a`/`9e5a4ea` projections — host-prereq and cross-node +loopback both project correctly across all read surfaces with the right safe +actions and no false `Ready=True`. + +## Non-Blocking Findings + +1. **`swblock` YAML scenario runner not available in this QA environment.** The + D5 scenarios (`same-node-alpha-attach-chain.yaml`, + `same-node-alpha-attach-negative-chain.yaml`) are run by `swblock` + (`pingqiu/sw-test-runner`, `cmd/swblock/main.go`), which is not on this + machine (`C:\work\swblock.exe` missing; `sw-testops` uses a separate JSON + registry and does not load these YAMLs). I validated the projections via + from-bundle replay instead. To run the end-to-end scenarios, QA needs the + `swblock` binary provisioned (or the dev runs the E2E and QA reviews the + produced bundle). +2. **Default `--set` loopback install left the volume `primary_unavailable` + (launcher `skipped=1`).** On the default single-node loopback install, the + blockmaster launcher reconcile skipped the volume's launcher, so no primary / + publish target was created and same-node attach failed with "no publish + target." The supported path appears to be `values.day1.yaml` + + `preflight-k8s-alpha.sh` (which deployed launchers fine in Phase 36). Worth + the dev confirming whether the default `--set` install is a supported + same-node loopback path or whether the launcher now gates on preflight/host + prereq evidence (which would connect to the D4 host-prereq work). + +## Bottom Line + +- **D4 PASS** (host-prereq replay) and **D5 cross-node loopback projection PASS** + (replay) — `iscsi_prereq_missing`, `multipath_prereq_missing`, and + `publish_target_loopback_cross_node` all project consistently across report, + operator-snapshot, dashboard, and explain, with read-only/dry-run safe steps + and no false `Ready=True`. Boundary intact; cleanup clean. +- **D5 same-node positive and the runner-driven E2E were not completed live** — + blocked by the missing `swblock` runner and the default-install launcher-skip, + not by a product loopback defect. Recommend: provision the `swblock` runner for + QA (or dev-run the E2E), and confirm the default `--set` loopback install's + launcher behavior. D6 close should account for the same-node E2E being + validated by the runner, not just the projection. + +--- + +## RUNNER E2E (swblock) — PASS + +The `swblock` YAML runner was located at +`C:/work/seaweedfs/learn/sw-test-runner-standalone` (`github.com/pingqiu/sw-test-runner`, +`cmd/swblock`) and built to `C:\work\swblock.exe`. Both scenarios were run live +from a clean lab (each runs its own `pin_build_alpha_images` + `preflight` + +install). + +### D5 same-node positive — `same-node-alpha-attach-chain` — PASS (56.7s) + +```text +47 actions: 47 passed, 0 failed +phases: pre_clean, preflight, pin_build_alpha_images, + reader_verified_with_live_inventory PASS (writer + reader verified), + same_node_asserts PASS (loopback_frontend_count=1), + collect_and_cleanup PASS +``` + +Writer and reader verify; the loopback frontend is accepted when the app pod and +blockvolume are on the same node; the healthy report shows no +`publish_target_loopback_cross_node`. (The launcher deployed correctly here — the +supported `preflight` path — confirming the raw `--set` install was the +unsupported/dev-only case per `2ac4c55`.) + +### D5 cross-node negative — `same-node-alpha-attach-negative-chain` — PASS (38.9s) + +```text +34 actions: 34 passed, 0 failed +phases: pre_clean, preflight, pin_build_alpha_images, + unsupported_cross_node_loopback PASS (unsupported_log_count=1), + collect_and_cleanup PASS +``` + +Live-produced `unsupported-cross-node-loopback-attach.txt`: + +```text +issue=unsupported_cross_node_loopback_attach +app_node=sw-block-not-the-blockvolume-node +blockvolume_node=m01 +frontend=127.0.0.1:3260 +volume_id=pvc-f36f31cb-f36b-4294-bcaf-66c702fcd0b0 +replica_id=r1 +``` + +Replaying that **live** bundle with `sw-block ops`: + +```text +report: managed_volume=… status=blocked reason=publish_target_loopback_cross_node +explain: reason=publish_target_loopback_cross_node +operator-snapshot.json: publish_target_loopback_cross_node +dashboard /operator-snapshot.json: HTTP 200, publish_target_loopback_cross_node +no Ready=True on any surface (count 0) +safe actions: mode=dry_run, mode=read_only +``` + +The negative scenario exits through the expected unsupported-placement path, the +artifact names `issue`, `app_node`, `blockvolume_node`, `frontend=127.0.0.1:*`, +and `volume_id`, the replay agrees across all surfaces on +`publish_target_loopback_cross_node`, no surface shows `Ready=True`, and the +suggested action is dry-run/read-only (not an executed reinstall). PASS. + +### Final cleanup audit (post-E2E) + +```text +cleanup_status=ok k8s_residue_count=0 iscsi_residue_count=0 +multipath_residue_count=0 process_residue_count=0 hostpath_residue_count=0 failure_count=0 +helm: 0 pods: 0 iscsi sessions: 0 +``` + +Both scenarios' `collect_and_cleanup` phases left the lab clean. + +### Findings — resolved + +- (Prior #1, runner unavailable) **Resolved.** The runner repo is on the shared + tree (`sw-test-runner-standalone`); built `swblock.exe` and ran both scenarios. + Suggest documenting that build step in the QA runbook so it is not re-flagged. +- (Prior #2, default `--set` launcher-skip) **Resolved/expected.** Per `2ac4c55` + the raw Helm `--set` defaults are dev/render-only; the supported install is the + generated `values.day1.yaml` (+ preflight), which the scenarios use and where + the launcher deploys and the same-node attach succeeds. + +### Bottom line (updated) + +- **Phase 37 D4 and D5 PASS — projection *and* runner E2E.** Host-prereq and + cross-node loopback both project correctly across all surfaces; the same-node + scenario verifies writer/reader with loopback accepted; the cross-node negative + produces the unsupported-placement bundle live and replays to + `publish_target_loopback_cross_node` with no false `Ready=True` and only + read-only/dry-run actions. Boundary intact; cleanup clean. +- **D5 is no longer projection-only — the runner E2E is done.** D6 can close. diff --git a/seaweed-block/internal/docs/qa-assignments/phase37-d4-d5-host-prereq-loopback-qa.md b/seaweed-block/internal/docs/qa-assignments/phase37-d4-d5-host-prereq-loopback-qa.md new file mode 100644 index 0000000000..367d103c48 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase37-d4-d5-host-prereq-loopback-qa.md @@ -0,0 +1,130 @@ +# Phase 37 D4/D5 QA Assignment: Host Prereq And Loopback Blockers + +Status: ready for QA. + +Source branch: `phase33-testops-failure-hardening`. + +Required source floor: + +- `9e5a4ea phase37: carry host prereq evidence in bundles` +- `c32e07a phase37: project loopback cross-node evidence` + +## Goal + +Validate the two remaining Phase 37 node-evidence blockers without widening the +operator boundary: + +- D4: iSCSI/multipath prerequisite evidence from read-only artifacts. +- D5: loopback publish target is allowed only for same-node/local consumers and + becomes visible as `publish_target_loopback_cross_node` for cross-node + consumers. + +The operator must not probe hosts with privileged commands and must not repair, +reinstall, cleanup, mutate PVC/PV, or change image state. + +## D4: Host Prereq Replay Gate + +Use a synthetic or collected support/failure bundle containing: + +```text +host/host-prereq-summary.txt +``` + +Minimum artifact examples: + +```text +node=m02 iscsi_prereq=missing multipath_prereq=ok command_iscsiadm=missing read_only=true +node=tp01 iscsi_prereq=ok multipath_prereq=missing command_multipath=missing command_dmsetup=present read_only=true +``` + +Run: + +```bash +sw-block ops report --from-bundle --out /tmp/sw-block-report +sw-block ops dashboard --from-bundle --listen 127.0.0.1:9334 +sw-block ops explain --from-bundle +``` + +Pass criteria: + +- `summary.txt` has node lines with `reason=iscsi_prereq_missing` and + `reason=multipath_prereq_missing`. +- `operator-snapshot.json` has the same node statuses and reasons. +- Dashboard `/operator-snapshot.json` returns HTTP 200 and the same reasons. +- Safe next steps mention read-only/scripted evidence collection or + verification, with `mutation_allowed=false`. +- No status surface suggests automatic host repair. + +Optional live smoke: + +- Run `scripts/collect-helm-support-bundle.sh` or + `scripts/collect-k8s-failure-snapshot.sh`. +- Confirm the produced bundle includes `host/host-prereq-summary.txt`. +- Replay that bundle with `sw-block ops report --from-bundle`. + +## D5: Loopback Cross-Node Gate + +Run both existing TestOps scenarios from a clean lab: + +```text +testops/scenarios/same-node-alpha-attach-chain.yaml +testops/scenarios/same-node-alpha-attach-negative-chain.yaml +``` + +Pass criteria for same-node: + +- Writer and reader verify successfully. +- Loopback frontend remains accepted when app pod and blockvolume are on the + same node. +- No `publish_target_loopback_cross_node` appears in the healthy report. + +Pass criteria for cross-node negative: + +- Scenario exits through the expected unsupported-placement path. +- `unsupported-cross-node-loopback-attach.txt` exists and names: + `issue=unsupported_cross_node_loopback_attach`, `app_node`, + `blockvolume_node`, `frontend=127.0.0.1:*`, and `volume_id`. +- Replaying the result bundle with `sw-block ops report --from-bundle` produces + `managed_volume ... status=blocked reason=publish_target_loopback_cross_node`. +- `operator-snapshot.json`, dashboard `/operator-snapshot.json`, and + `ops explain --from-bundle` agree on + `publish_target_loopback_cross_node`. +- No surface shows `Ready=True` for the cross-node loopback case. +- The suggested action is dry-run/read-only, not an executed reinstall. + +## Boundary Checks + +Confirm the operator-status ServiceAccount still has no mutation power: + +```bash +kubectl auth can-i patch swblockvolumes --subresource=status --as system:serviceaccount:kube-system:sw-block-operator-status -n kube-system +kubectl auth can-i create events --as system:serviceaccount:kube-system:sw-block-operator-status -n kube-system +kubectl auth can-i patch pods --as system:serviceaccount:kube-system:sw-block-operator-status -n kube-system +kubectl auth can-i patch pvc --as system:serviceaccount:kube-system:sw-block-operator-status -n default +kubectl auth can-i update storageclasses --as system:serviceaccount:kube-system:sw-block-operator-status +``` + +Expected: + +- status patch and events: `yes` +- pods/PVC/storageclasses: `no` + +## Report + +Write the sign-off to: + +```text +internal/docs/qa-assignments/phase37-d4-d5-host-prereq-loopback-qa-signoff.md +``` + +Required verdict fields: + +- source commit +- D4 replay result +- D4 optional live smoke result, or explicit reason skipped +- D5 same-node result +- D5 cross-node negative result +- boundary result +- final cleanup audit +- blocking findings +- non-blocking findings diff --git a/seaweed-block/internal/docs/qa-assignments/phase38-action-model-executable-contract-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase38-action-model-executable-contract-qa-signoff.md new file mode 100644 index 0000000000..d78587ce3c --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase38-action-model-executable-contract-qa-signoff.md @@ -0,0 +1,151 @@ +# QA Sign-off - Phase 38 Lifecycle Action Model Executable Contract + +Verdict: **PASS (G1-G5).** Surfaced lifecycle actions are executable contracts, +not loose text: every action carries a typed contract evaluated to `allowed` or +`rejected` with stable reasons, dry-run actions are allowed without mutation, +disabled/mutating/underspecified actions fail closed, the CRD uses camelCase +decision fields, and the operator holds no mutation power. No storage, workload, +Helm, iSCSI, multipath, hostPath, promotion, repair, rebuild, failback, delete, +backup, or restore mutation occurred. + +Date: 2026-06-09 + +Source commit: `ea1618d` (floor met: `7d72674 add action evaluation contract`, +`f6e8d19 surface action evaluation decisions`, `e4f49fc add rejected action +evidence gate`, `2ad2447 add dry-run action evidence gate`; branch +`phase33-testops-failure-hardening`) + +Environment: k3s `v1.34.4+k3s1`; from-bundle replays + a live write-mode install +(operator-status pinned to m02). Note: tp01 was `NotReady`/unreachable during +this run — see non-blocking findings; all gates were validated on m02/m01. + +## G1 — Local Contract Tests — PASS + +```text +go test ./core/ops ./cmd/sw-block ./cmd/blockcsi ./scripts -> all ok +helm lint charts/seaweed-block -> 1 linted, 0 failed +helm template ... --include-crds --set operatorStatus.create=true --set operatorStatus.dryRun=false + -> exit 0, 979 lines +git diff --check (local repo) -> clean (no whitespace errors) +``` + +## G2 — Rejected Action Evidence — PASS (evaluator tests) + +The evaluator suite (`core/ops/managed_volume_action_evaluator_test.go`) passes, +asserting the exact contract: + +```text +TestEvaluateManagedVolumeAction_RejectsDisabledAuthorityMutation: + authority.request_promotion -> decision=rejected reason=policy_disabled + (mode=dry_run, side_effect_class=authority_mutating, + owner_executor=authority_recovery_executor, mutation_allowed=false, + evidence_required=promotion_readiness_evidence) +TestEvaluateManagedVolumeAction_RejectsMissingRequiredFacts: + -> decision=rejected reason=missing_required_facts missing_facts=[placement.replica_node] +TestEvaluateManagedVolumeAction_RejectsUnknownAction -> rejected/unknown_action +TestManagedVolumeActionEvaluator_CoversEveryContractEntry -> every contract entry evaluated +TestRenderManagedVolumeActionEvaluationText_ShowsRejectedAction -> + "managed_volume_action_evaluation authority.request_promotion decision=rejected + side_effect=authority_mutating executor=authority_recovery_executor reason=policy_disabled" + "managed_volume_action_evaluation_evidence_required authority.request_promotion promotion_readiness_evidence" +``` + +Pass criteria met: the rejected action is **visible as rejected** (rendered, not +silently omitted); `authority.request_promotion` has `MutationAllowed=false` in +the contract and the evaluator returns `mutation_allowed=false` (no rejected +action is `true`); the evaluator is a pure decision function — **no executor path +is invoked**. The contract is fail-closed (unknown/disabled/mutating/missing-facts +all rejected before any executor is considered). + +This is the assignment's sanctioned "evaluator tests" path: `request_promotion` +is a contract entry (`managed_volume_contract.go:548`, `PolicyGate=disabled`) and +is intentionally **not** attached to any live volume state by +`managedVolumeActionsForProjection` (its switch covers only loopback / +pvc-unbound / writer-mount / image-pull / hostpath), so it is reachable only +through the evaluator/contract — by design, as a future bounded executor's action +held closed by policy. + +## G3 — Dry-Run Loopback Action — PASS + +Bundle: `cluster-evidence.json` + `unsupported-cross-node-loopback-attach.txt` +(`volume_id=pvc-d38`). `sw-block ops report/explain/dashboard --from-bundle`: + +```text +managed_volume=pvc-d38 status=blocked reason=publish_target_loopback_cross_node +managed_volume_action=safe_k8s.reinstall_external_iscsi mode=dry_run side_effect=safe_k8s + executor=installer_or_operator decision=allowed +managed_volume_action_evidence_required=safe_k8s.reinstall_external_iscsi loopback_cross_node_evidence +operator-snapshot.json: "decision": "allowed", "mutation_allowed": false, + "evidence_required": "loopback_cross_node_evidence" +dashboard /operator-snapshot.json: HTTP 200, same fields +no surface claims the action was executed (grep "was executed|reinstalled|action ran" = 0) +``` + +All G3 pass criteria met. The dry-run action is allowed without mutation, with +its required evidence named, and nothing claims execution. + +## G4 — CRD And RBAC Boundary — PASS + +Live `auth can-i` (operator-status SA): + +```text +patch swblockvolumes --subresource=status: yes +create events: yes +patch pods: no +patch persistentvolumeclaims (default): no +update storageclasses.storage.k8s.io: no +``` + +CRD `allowedActions[]` camelCase — both **rendered** (helm template) and **live** +(after a loopback reconcile): + +```text +rendered CRD schema: decision, decisionReason, missingFacts, mutationAllowed, + evidenceRequired all present; snake_case mutation_allowed: 0 +live SwBlockVolume.status.allowedActions[safe_k8s.reinstall_external_iscsi]: + {"decision":"allowed","mutationAllowed":false, + "evidenceRequired":"loopback_cross_node_evidence","mode":"dry_run", + "ownerExecutor":"installer_or_operator","sideEffectClass":"safe_k8s", ...} +``` + +Status patch + events only; no pod/PVC/storageclass mutation. All decision fields +are camelCase; no snake_case `mutation_allowed` in CRD status. PASS. + +## G5 — Non-Mutation And Cleanup — PASS + +- The operator-status SA cannot create/patch/delete pods, PVC/PV, deployments, or + storageclasses (G4 can-i), and only patches CRD `/status` + creates Events. +- The action evaluator is a pure decision function — it surfaces decisions and + never executes; no Helm/image/import/cleanup command is run by the operator, + and no surface claims execution (G3). +- The replay gates are read-only from-bundle; no iSCSI/multipath/dmsetup/process/ + hostPath mutation. +- Final cleanup verifier: `cleanup_status=ok`, all residue counters 0; helm 0, + pods 0. + +## Blocking Findings + +None. The action-model executable contract holds end to end. + +## Non-Blocking Findings + +1. **Lab infra: tp01 is `NotReady`/unreachable.** During this run the image build + failed importing to `192.168.1.188` with "No route to host", and + `kubectl get nodes` shows tp01 `NotReady` (m01/m02 `Ready`). I cannot reach tp01 + to recover it (no SSH route). This is a lab-infrastructure issue, not a Phase + 38 defect — all gates were validated on m02/m01. Flag for the lab admin to + bring tp01 back (and re-run any multi-node scenario that needs 3 nodes). +2. **`authority.request_promotion` is contract-only (intentional, worth noting).** + It is a defined contract entry but is not surfaced on any live volume state, so + it is exercised only by the evaluator (G2). This is the correct fail-closed + posture for a future executor's action; just noting it so a later reviewer does + not expect it on a live `SwBlockVolume`. + +## Release / Next-Phase Recommendation + +- **Phase 38 can close.** Lifecycle actions are now typed, evaluated + (allowed/rejected with stable reasons), dry-run-without-mutation, fail-closed, + and surfaced with camelCase CRD vocabulary aligned across report, explain, + dashboard, operator-snapshot, and CRD status — with no mutation power added. +- Proceed to **Phase 39 (finalizer/delete safety)** as planned. Recommend the lab + admin restore tp01 before any Phase 39 multi-node delete-safety scenarios. diff --git a/seaweed-block/internal/docs/qa-assignments/phase38-action-model-executable-contract-qa.md b/seaweed-block/internal/docs/qa-assignments/phase38-action-model-executable-contract-qa.md new file mode 100644 index 0000000000..ec34aee40d --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase38-action-model-executable-contract-qa.md @@ -0,0 +1,193 @@ +# Phase 38 QA Assignment: Lifecycle Action Model Executable Contract + +Status: ready for QA. + +Source branch: `phase33-testops-failure-hardening`. + +Required source floor: + +- `7d72674 phase38: add action evaluation contract` +- `f6e8d19 phase38: surface action evaluation decisions` +- `e4f49fc phase38: add rejected action evidence gate` +- `2ad2447 phase38: add dry-run action evidence gate` + +## Goal + +Validate that surfaced lifecycle actions are executable contracts, not loose +text hints. + +Phase 38 must prove: + +- every action has a typed contract, +- action decisions are `allowed` or `rejected` with stable reasons, +- dry-run actions can be allowed without mutation, +- unsafe or underspecified actions fail closed, +- report, explain, dashboard, operator-snapshot, and CRD status vocabulary stay + aligned. + +No storage, Kubernetes workload, Helm, iSCSI, multipath, hostPath, promotion, +repair, rebuild, failback, delete, backup, or restore mutation is allowed in +this phase. + +## G1: Local Contract Tests + +Run: + +```bash +go test ./core/ops ./cmd/sw-block ./cmd/blockcsi ./scripts +helm lint charts/seaweed-block +helm template sw-block charts/seaweed-block --namespace kube-system --include-crds \ + --set operatorStatus.create=true --set operatorStatus.dryRun=false >/tmp/sw-block-phase38-render.yaml +git diff --check +``` + +Pass criteria: + +- all Go tests pass, +- Helm lint passes, +- Helm template renders with operator-status write mode enabled, +- `git diff --check` has no whitespace errors beyond line-ending warnings. + +## G2: Rejected Action Evidence + +Use the evaluator tests or a focused component run to verify +`authority.request_promotion`. + +Expected: + +```text +action_type=authority.request_promotion +decision=rejected +reason=policy_disabled +mode=dry_run +side_effect_class=authority_mutating +owner_executor=authority_recovery_executor +mutation_allowed=false +evidence_required=promotion_readiness_evidence +``` + +Also verify an action with missing facts returns: + +```text +decision=rejected +reason=missing_required_facts +missing_facts= +``` + +Pass criteria: + +- rejected actions are visible as rejected, not silently omitted, +- no rejected action has `mutation_allowed=true`, +- no executor path is invoked. + +## G3: Dry-Run Action Evidence + +Use the loopback cross-node bundle path. A synthetic bundle is acceptable if it +contains: + +```text +cluster-evidence.json +unsupported-cross-node-loopback-attach.txt +``` + +Minimum unsupported attach artifact: + +```text +issue=unsupported_cross_node_loopback_attach +app_node=m02 +blockvolume_node=m01 +frontend=127.0.0.1:3260 +volume_id= +replica_id=r1 +reason=loopback frontend requires app pod and blockvolume on the same node +``` + +Run: + +```bash +sw-block ops report --from-bundle --out /tmp/sw-block-phase38-report +sw-block ops explain --from-bundle +sw-block ops dashboard --from-bundle --listen 127.0.0.1:9334 +``` + +Pass criteria: + +- status is `blocked` with reason `publish_target_loopback_cross_node`, +- surfaced action is `safe_k8s.reinstall_external_iscsi`, +- action has `mode=dry_run`, `side_effect=safe_k8s`, + `executor=installer_or_operator`, `decision=allowed`, +- `evidence_required=loopback_cross_node_evidence`, +- operator-snapshot has `"decision": "allowed"`, + `"mutation_allowed": false`, and + `"evidence_required": "loopback_cross_node_evidence"`, +- dashboard `/operator-snapshot.json` returns HTTP 200 and the same fields, +- no surface claims that the action was executed. + +## G4: CRD And RBAC Boundary + +If a live k3s lab is available, install with operator-status enabled and check +the ServiceAccount boundary: + +```bash +kubectl auth can-i patch swblockvolumes --subresource=status \ + --as system:serviceaccount:kube-system:sw-block-operator-status -n kube-system +kubectl auth can-i create events \ + --as system:serviceaccount:kube-system:sw-block-operator-status -n kube-system +kubectl auth can-i patch pods \ + --as system:serviceaccount:kube-system:sw-block-operator-status -n kube-system +kubectl auth can-i patch pvc \ + --as system:serviceaccount:kube-system:sw-block-operator-status -n default +kubectl auth can-i update storageclasses \ + --as system:serviceaccount:kube-system:sw-block-operator-status +``` + +Expected: + +- status patch and event create: `yes`, +- pods/PVC/storageclasses: `no`. + +Also inspect a rendered or live `SwBlockVolume.status.allowedActions[]` payload. +Expected camelCase fields: + +```text +decision +decisionReason +missingFacts +mutationAllowed +evidenceRequired +``` + +Snake-case fields such as `mutation_allowed` must not appear in CRD status. + +## G5: Non-Mutation And Cleanup + +Confirm Phase 38 did not add mutating behavior. + +Pass criteria: + +- no Helm release/image/import/cleanup command is executed by the operator, +- no PVC/PV/Deployment/Pod/StorageClass is created, patched, or deleted by the + action evaluator, +- no iSCSI, multipath, dmsetup, process, or hostPath mutation occurs from the + replay gates, +- final cleanup verifier returns `cleanup_status=ok` when live gates are run. + +## Report + +Write the sign-off to: + +```text +internal/docs/qa-assignments/phase38-action-model-executable-contract-qa-signoff.md +``` + +Required verdict fields: + +- source commit, +- G1 local contract result, +- G2 rejected action result, +- G3 dry-run loopback action result, +- G4 CRD/RBAC result or explicit reason skipped, +- G5 non-mutation/cleanup result, +- blocking findings, +- non-blocking findings, +- release/next-phase recommendation. diff --git a/seaweed-block/internal/docs/qa-assignments/phase39-d4-d5-finalizer-delete-safety-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase39-d4-d5-finalizer-delete-safety-qa-signoff.md new file mode 100644 index 0000000000..e760dbf4fb --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase39-d4-d5-finalizer-delete-safety-qa-signoff.md @@ -0,0 +1,378 @@ +# QA Sign-off - Phase 39 D4/D5 Finalizer Delete Safety + +> Superseded by the lifecycle-owner pivot after `d695c0a`. The findings below +> remain valid evidence that operator-status must not own CRD finalizer mutation +> under the old RBAC model. The revised Phase 39 gate is now delete-safety +> status/events only; finalizer add/remove is deferred to a future lifecycle +> owner. + +Verdict: **STILL BLOCKED (after `b371e2e`).** The URL bug is fixed — the operator +now PATCHes the main `SwBlockVolume` object (no `/finalizers` 404) — but that +exposed the deeper, definitive problem I flagged as the RBAC follow-on: the patch +now returns **HTTP 403**. Modifying a CRD's `.metadata.finalizers` requires the +**main** `patch swblockvolumes` permission, and the `swblockvolumes/finalizers` +subresource grant does **not** substitute for it (for CRDs there is no +`/finalizers` endpoint to target, so the authorizer always checks the main verb +first). Confirmed for **both** add-on-fresh and remove-on-terminating. The +finalizers-subresource-only RBAC can never modify a CRD finalizer — so the +bounded-mutation design as built cannot work, and D4/D5 still cannot be +exercised. The status-only `status.deleteSafety` projection continues to work. + +Date: 2026-06-09 (404 blocked) → 2026-06-11 (re-validated `b371e2e`: 404 fixed, 403 exposed) + +Source commits: `f59784a` (404 blocked) → `b371e2e phase39: fix finalizer patch +endpoint` (URL fixed, now 403; branch `phase33-testops-failure-hardening`) + +> See the **Re-Validation (`b371e2e`)** section at the end for the 403 evidence +> and the design options. The original 404 write-up is preserved below. + +--- + +## ORIGINAL FINDING (404, `f59784a`) — preserved + +## Lab Node Health + +- m01 `Ready`, m02 `Ready`, **tp01 `NotReady`/unreachable** ("No route to host" on + SSH/image-import; same as Phase 38). D4/D5 are single-`SwBlockVolume` finalizer + gates and do not need tp01; the install used operator-status pinned to m02 with + the CSI image imported to m01 only. Flag for the lab admin to restore tp01 + before D6 multi-volume isolation. + +## RBAC Boundary — PASS (with a follow-on concern) + +```text +patch swblockvolumes --subresource=finalizers: yes +patch swblockvolumes --subresource=status: yes +create events: yes +patch pods: no +patch persistentvolumeclaims (default): no +update storageclasses.storage.k8s.io: no +delete persistentvolumeclaims (default): no +patch swblockvolumes (spec/main): no +``` + +The bounded mutation is scoped to the `finalizers` + `status` subresources + +event create; no pod/PVC/storageclass/spec mutation. **Follow-on concern:** the +SA has `update swblockvolumes/finalizers` (subresource) but **not** `patch +swblockvolumes` (main). Once the URL bug is fixed (patch the main object), the +finalizer-only patch must be authorized by the `finalizers` subresource — verify +this works for both *adding* a finalizer to a not-yet-deleted object and +*removing* it from a deleting object, or the corrected patch may 403. + +## D4 — Blocked Delete Holds Finalizer — BLOCKED + +Created `SwBlockVolume/del-vol` and fed a delete-safety bundle +(`swblockvolume-delete-summary.txt` + `cleanup-summary.txt`). On reconcile, the +operator wrote `status.deleteSafety.state=not_requested decision=rejected` +(status path works) but **failed to add the finalizer**: + +```text +operator_status=write_status ... finalizer_patches=0 +sw-block ops operator-status: patch swblockvolumes/del-vol finalizers failed: + http 404 swblockvolumes.block.seaweedfs.com "del-vol" not found (reason: NotFound) +``` + +The same `del-vol` accepts a `/status` patch and accepts a finalizer set via the +**main-object** patch (admin): + +```text +kubectl -n kube-system patch swblockvolume del-vol --type=merge \ + -p '{"metadata":{"finalizers":["block.seaweedfs.com/swblockvolume-protection"]}}' +-> del-vol finalizers: ["block.seaweedfs.com/swblockvolume-protection"] +``` + +So the object exists; only the operator's `/finalizers` URL is wrong. Because the +finalizer is never added, none of the D4 criteria can be reached (no hold, no +`deleteSafety.state=blocked` under a real delete, no idempotency check). BLOCKED. + +## D5 — Clean Delete Releases Finalizer — BLOCKED + +Same root cause — without a finalizer the operator can add/remove, there is no +release to observe, no `finalizer_released` Event, and a delete of the object +completes immediately (nothing holds it). BLOCKED. + +## The Bug (blocking) + +`core/ops/kubernetes_status_writer.go`: + +```go +func (c *KubernetesStatusClient) finalizersURL(...) string { + return c.resourceURL(namespace, resource, name) + "/finalizers" // <- /finalizers +} +func (c *KubernetesStatusClient) patchVolumeFinalizers(...) error { + ... http.MethodPatch, c.finalizersURL(...), + body = {"metadata":{"finalizers":[...]}}, + Content-Type: application/merge-patch+json ... +} +``` + +CRDs expose only the `/status` (and optionally `/scale`) subresources. There is +no `/finalizers` endpoint, so `PATCH .../swblockvolumes/del-vol/finalizers` +resolves to nothing and the API server returns `404 NotFound`. Finalizers on a +CRD are modified by PATCHing the **main object** (`.../swblockvolumes/del-vol`, +no suffix) with `{"metadata":{"finalizers":[...]}}` — exactly the body already +built; only the URL is wrong. + +### Fix + +1. Drop the `/finalizers` suffix — PATCH the main object URL with the + metadata.finalizers merge patch. (The `finalizers` RBAC subresource still + gates the finalizer-only change; confirm it authorizes both add and remove — + see the RBAC follow-on above.) +2. Add a **live / envtest** regression for the finalizer add+remove against a + real API server (the existing tests use a mock that accepts any path, which is + why this passed `go test`). This is the third phase in a row (D3 casing, D2 + node-condition enum, now this) where a writer payload/endpoint that satisfies + a mock fails the real CRD API — an envtest harness for the + KubernetesStatusClient would catch all of them. + +## Final Cleanup Audit — PASS + +`cleanup_status=ok`, `k8s_residue_count=0`, `iscsi_residue_count=0`, +`failure_count=0`; helm 0, pods 0. (The manually-added test finalizer was removed +and `del-vol` deleted.) + +## Blocking Findings + +1. **Finalizer mutation 404 (URL).** The operator PATCHes a non-existent + `//finalizers` subresource; every finalizer add/remove returns 404. + The bounded-mutation feature is non-functional against the live API. Fix: PATCH + the main object URL. + +## Non-Blocking Findings + +1. **RBAC follow-on.** After the URL fix, verify the `finalizers` subresource + permission (the SA lacks main `patch swblockvolumes`) authorizes the + finalizer-only patch for add-on-fresh and remove-on-deleting. +2. **Lab infra: tp01 `NotReady`/unreachable.** Not a Phase 39 defect; restore + before D6 multi-volume isolation. + +## Recommendation for D6 (Multi-Volume Isolation) + +Do **not** advance to D6 yet. D6 multiplies the finalizer lifecycle across many +volumes; it cannot pass while the single-volume finalizer patch 404s. Fix the +`/finalizers` URL, add the envtest regression, re-run D4/D5 live (finalizer +added → blocked-hold under a real `kubectl delete` → clean-release with one +`finalizer_released` Event and object deletion completing), and restore tp01 — +then D6. + +--- + +## RE-VALIDATION (`b371e2e`) — STILL BLOCKED (403) + +`b371e2e` correctly fixes the URL: `patchVolumeFinalizers` now PATCHes +`c.resourceURL(ns, swblockvolumes, name)` (the main object) with +`{"metadata":{"finalizers":[...]}}`. The 404 is gone. But the operator now hits +**403 Forbidden** — the deeper issue noted in the original RBAC follow-on. + +### Add to a fresh object — 403 + +```text +SwBlockVolume/del-vol created (no deletionTimestamp); reconcile -> +status.deleteSafety written (status path OK), then: +patch swblockvolumes/del-vol finalizers failed: http 403 + User "system:serviceaccount:kube-system:sw-block-seaweed-block-operator-status" + cannot patch resource "swblockvolumes" in API group "block.seaweedfs.com" in namespace "kube-system" +del-vol finalizers: (empty) -> finalizer never added +``` + +### Remove from a terminating object — also 403 + +```text +admin adds the finalizer; kubectl delete del-vol --wait=false (deletionTimestamp set); +reconcile with delete_requested=true + clean cleanup -> +patch swblockvolumes/del-vol finalizers failed: http 403 (same "cannot patch swblockvolumes") +del-vol still exists, finalizers=["block.seaweedfs.com/swblockvolume-protection"] -> stuck terminating +``` + +So **neither add nor remove works** with the current RBAC. + +### Why finalizers-subresource-only RBAC cannot work for a CRD + +A CRD exposes no `/finalizers` endpoint (that is why the old URL 404'd), so +`.metadata.finalizers` can only be changed by PATCHing the **main object**. The +authorizer evaluates that request as `patch swblockvolumes` (the main verb + +resource) and denies it — the operator was granted only +`swblockvolumes/finalizers`. The `/finalizers` RBAC subresource is an +*additional* gate applied by the OwnerReferencesPermissionEnforcement admission +plugin *after* authorization; it is **not a substitute** for the main `patch` +permission, and (unlike built-ins such as namespaces) there is no finalizers URL +to make the authorizer evaluate the subresource instead. Net: the +finalizers-subresource-only grant can never modify a CRD finalizer. + +### Design options (this needs a decision, not just a code tweak) + +1. **Grant the operator `patch`/`update` on `swblockvolumes` (main) and enforce + finalizer-only changes with a ValidatingAdmissionPolicy/webhook** that rejects + any operator-status write touching `.spec` or fields other than + `.metadata.finalizers`. Keeps the "no spec mutation" boundary via admission + rather than RBAC. This is the standard way to bound a finalizer controller. +2. **Move finalizer add/remove to the component that already owns the + `SwBlockVolume` lifecycle** (the CSI provisioner/controller that creates the + CR), gated by the `status.deleteSafety` the operator publishes. The + operator-status SA then stays status-only (no main patch), which preserves the + read-only posture established in Phases 35-38. +3. **Accept main `patch` on the SA with a code-enforced boundary** (the + controller only ever writes finalizers). Weakest — the RBAC no longer proves + the boundary; not recommended given the whole phase chain's emphasis on + RBAC-provable read-only. + +Option 1 or 2 is the real fix. Whichever is chosen, add a **live/envtest** +regression that performs the add+remove against a real API server with the +operator's actual RBAC (the current tests pass because the mock neither enforces +the CRD subresource surface nor the authorizer — the same gap that hid the 404 +and now the 403). + +### Status of the gates + +- RBAC boundary intent: still correctly scoped (no pod/PVC/storageclass/spec + mutation), but **insufficient** for the finalizer feature to function. +- D4 blocked-delete hold: **still BLOCKED** (finalizer never added → nothing to + hold). +- D5 clean-delete release: **still BLOCKED** (operator cannot remove the + finalizer → object stuck terminating). +- Final cleanup: clean (`cleanup_status=ok`, residue 0); the stuck `del-vol` was + cleared by an admin finalizer patch. +- Lab: tp01 still `NotReady`/unreachable. + +### Bottom line (updated) + +`b371e2e` fixes the URL but the bounded-finalizer-mutation design is **not viable +as built** — the operator cannot modify a CRD finalizer with only the +`swblockvolumes/finalizers` subresource grant (403 on both add and remove). This +is a design decision (admission-bounded main patch, or move finalizer ownership), +not a one-line fix. Do not close D4/D5 or advance to D6 until the operator can +actually add the finalizer to a fresh `SwBlockVolume` and remove it from a +terminating one, proven live with its real RBAC. + +--- + +## STATUS-ONLY RE-VALIDATION (`4a51bae`, floor `1630de2`) — D5 PASS, D4 BLOCKED (new 422) + +Product pivoted to **status/events-only** (my Option 2): the operator no longer +patches finalizers; finalizer add/remove is deferred to a future lifecycle-owner. +Verified in code: no `EnsureVolumeFinalizer`/`ReleaseVolumeFinalizer` calls in the +controller, and the RBAC `swblockvolumes/finalizers` grant is **removed**. + +### RBAC boundary — PASS (status-only) + +```text +patch swblockvolumes --subresource=status: yes create events: yes +patch swblockvolumes (main): no patch swblockvolumes --subresource=finalizers: no +patch pods: no patch pvc (default): no update storageclasses: no +``` + +Status + events only; finalizers grant gone; no spec/pod/PVC/storageclass power. +The 403 problem is correctly avoided by **not attempting** the mutation. + +### D5 — Clean Delete-Safety Status — PASS + +Bundle (`delete_requested=true` + `cleanup_status=ok`, all residue 0): + +```text +operator_status=write_status ... volumes=1 events=3 finalizer_patches=0 mutation_allowed=false +SwBlockVolume.status.deleteSafety: state=releasable decision=allowed finalizerReleaseAllowed=true +metadata.finalizers: (empty) no finalizer patch, no finalizer-released Event +idempotent: re-run keeps state=releasable +``` + +All D5 criteria met: `releasable`/`allowed`, `finalizerReleaseAllowed=true` as a +**decision fact only**, `finalizer_patches=0`, idempotent, final verifier +`cleanup_status=ok`. PASS. + +### D4 — Blocked Delete-Safety Status — BLOCKED (new live-vs-mock 422) + +Bundle (`delete_requested=true` + `cleanup_status=failed iscsi_residue_count=1`). +The blocked state's safe action is `observe.verify_cleanup` (`mode=scripted`), and +writing it into `SwBlockVolume.status.allowedActions[]` is rejected: + +```text +patch swblockvolumes/del-vol status failed: http 422 + status.allowedActions[1].mode: Unsupported value: "scripted": + supported values: "read_only", "dry_run" +``` + +So the entire blocked status patch fails — `deleteSafety`, the `CleanupRequired` +condition, and the verify_cleanup action never land. Root cause: the +`SwBlockVolume` CRD `status.allowedActions[].mode` enum is `{read_only, dry_run}` +(`crds/swblockvolumes...yaml:165-166`) and is **missing `scripted`**, even though +the `SwBlockCluster` CRD `safeNextSteps[].mode` enum **does** include `scripted` +(`crds/swblockclusters...yaml:265`). The blocked delete-safety projection puts the +`scripted` verify_cleanup action onto the volume's `allowedActions`, which the +volume enum rejects. + +This is the same class as the D3 casing 422 and the Phase 37 node-condition 422: +a payload the unit-test mock accepts but the live CRD schema rejects. + +**Fix:** add `scripted` to the `SwBlockVolume.status.allowedActions[].mode` enum +(one line, mirroring the cluster `safeNextSteps` enum). Then re-run D4 live; the +blocked status should land with `deleteSafety.state=blocked decision=rejected`, +`CleanupRequired=True`, and the `observe.verify_cleanup mutationAllowed=false` +action. + +### Status-only gate status + +| Gate | Result | +|---|---| +| RBAC boundary (status-only, no finalizers) | PASS | +| D4 blocked delete-safety status | **BLOCKED** — `allowedActions[].mode=scripted` 422 | +| D5 clean delete-safety status | PASS | +| Final cleanup verifier | PASS (`cleanup_status=ok`, residue 0) | +| Lab: tp01 | still `NotReady`/unreachable | + +### Bottom line (status-only) + +The status-only pivot is the right call and is mostly working: the RBAC is +provably read-only (no finalizers), D5 projects `releasable/allowed` cleanly with +zero finalizer patches, and idempotency holds. **D4 is blocked by a one-line CRD +enum gap** — `scripted` is missing from the SwBlockVolume `allowedActions[].mode` +enum, so the blocked-delete status (which surfaces the scripted verify_cleanup +action) 422s and never lands. Add `scripted` to that enum, re-run D4, **then** D6 +multi-volume status isolation. Recommend the live/envtest regression for the +status writer once more — it would have caught this 422 (and the prior 404/403) +before handoff. + +--- + +## D4 RE-RUN (`f167f9a`) — PASS + +`f167f9a phase39: allow scripted volume actions` adds `scripted` to the +`SwBlockVolume.status.allowedActions[].mode` enum (now `read_only, dry_run, +scripted`, mirroring the cluster `safeNextSteps` enum). Re-ran D4 live (re-imported +the existing image — binary unchanged — and re-installed with the updated CRD): + +```text +operator_status=write_status ... volumes=1 events=3 finalizer_patches=0 mutation_allowed=false EXIT=0 +SwBlockVolume.status.deleteSafety: state=blocked decision=rejected reason=iscsi_node_records_present +condition CleanupRequired: True / iscsi_node_records_present +allowedActions[observe.verify_cleanup]: mode=scripted mutationAllowed=false +metadata.finalizers: (empty) Ready=True conditions: 0 +idempotent: 3 reconciles -> state stays blocked, 2 distinct Events (bounded, not per-reconcile growth) +no finalizer-added/released Events +final cleanup verifier: cleanup_status=ok, residue 0 +``` + +All D4 status-only criteria are met: `blocked`/`rejected` with the verifier +reason, `CleanupRequired=True`, the `observe.verify_cleanup` action surfaces with +`mode=scripted mutationAllowed=false` (no longer 422), no `Ready=True`, +`finalizer_patches=0`, no finalizer Events, bounded Events on repeat, and no +storage/workload/host mutation. PASS. + +### Final Phase 39 D4/D5 status (status-only path) + +| Gate | Result | +|---|---| +| RBAC boundary (status-only, no finalizers) | PASS | +| D4 blocked delete-safety status | **PASS** (`f167f9a`) | +| D5 clean delete-safety status | PASS | +| Final cleanup verifier | PASS | +| Lab: tp01 | still `NotReady`/unreachable | + +**D4 and D5 both pass on the status-only path.** The operator surfaces +delete-safety (`blocked`/`releasable`, decision, `CleanupRequired`, the scripted +verify_cleanup action, `finalizerReleaseAllowed` as a fact) and emits Events, +with **zero finalizer/spec/storage/workload mutation** and an RBAC boundary that +proves it. **Phase 39 D4/D5 can close; proceed to D6 multi-volume status +isolation** (restore tp01 first if D6 exercises multiple nodes). Still recommend +adding the live/envtest status-writer regression — it would have caught the +404/403/422 chain before each handoff. diff --git a/seaweed-block/internal/docs/qa-assignments/phase39-d4-d5-finalizer-delete-safety-qa.md b/seaweed-block/internal/docs/qa-assignments/phase39-d4-d5-finalizer-delete-safety-qa.md new file mode 100644 index 0000000000..cf2f9d3ed8 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase39-d4-d5-finalizer-delete-safety-qa.md @@ -0,0 +1,161 @@ +# Phase 39 D4/D5 QA Assignment: Delete-Safety Status Boundary + +Status: ready for QA after the lifecycle-owner pivot. + +Required source floor: + +- `1630de2 phase39: keep delete safety status-only` + +Live QA on `b371e2e` proved CRD finalizer mutation cannot be bounded by +`swblockvolumes/finalizers` RBAC alone. The chosen product direction is: +operator-status remains status/events-only, while actual finalizer add/remove is +deferred to a future component that owns the `SwBlockVolume` lifecycle. + +## Goal + +Validate that delete-safety remains observable and actionable without granting +operator-status any finalizer, spec, workload, storage, or host mutation power. + +The controller may write: + +```text +SwBlockCluster/status +SwBlockVolume/status +Kubernetes Events +``` + +It must not write: + +```text +SwBlockVolume.metadata.finalizers +SwBlockVolume.spec +PVC/PV/Pod/Deployment/StorageClass/Secret/Node resources +iSCSI/multipath/dmsetup/hostPath/Helm/storage state +``` + +## Preflight + +Use a clean lab. If multi-node gates are run, restore `tp01` first; Phase 38/39 +QA previously reported it as `NotReady`/unreachable. + +Install with operator-status write mode: + +```bash +helm install sw-block charts/seaweed-block --namespace kube-system \ + --create-namespace -f values.day1.yaml \ + --set operatorStatus.create=true \ + --set operatorStatus.dryRun=false \ + --wait --timeout 10m +``` + +Confirm RBAC: + +```bash +kubectl auth can-i patch swblockvolumes --subresource=status \ + --as system:serviceaccount:kube-system:sw-block-operator-status -n kube-system +kubectl auth can-i create events \ + --as system:serviceaccount:kube-system:sw-block-operator-status -n kube-system +kubectl auth can-i patch swblockvolumes \ + --as system:serviceaccount:kube-system:sw-block-operator-status -n kube-system +kubectl auth can-i patch swblockvolumes --subresource=finalizers \ + --as system:serviceaccount:kube-system:sw-block-operator-status -n kube-system +kubectl auth can-i patch pods \ + --as system:serviceaccount:kube-system:sw-block-operator-status -n kube-system +kubectl auth can-i patch pvc \ + --as system:serviceaccount:kube-system:sw-block-operator-status -n default +kubectl auth can-i update storageclasses \ + --as system:serviceaccount:kube-system:sw-block-operator-status +``` + +Expected: + +- status/events: `yes`, +- main `swblockvolumes`, finalizers, pods/PVC/storageclasses: `no`. + +## D4: Blocked Delete-Safety Status + +Feed delete-safety evidence with residue, for example: + +```text +swblockvolume-delete-summary.txt: +delete_requested=true +finalizer_present=true +volume_id= +pvc_name= +pv_name= + +cleanup-summary.txt: +cleanup_status=failed +iscsi_residue_count=1 +reason_codes=iscsi_node_records_present +``` + +Pass criteria: + +- `SwBlockVolume.status.deleteSafety.state=blocked`, +- `SwBlockVolume.status.deleteSafety.decision=rejected`, +- reason is the verifier reason or `cleanup_required`, +- `status.conditions[]` includes `CleanupRequired=True`, +- safe next action is `observe.verify_cleanup` or collect bundle with + `mutationAllowed=false`, +- no `Ready=True` or executed/released mutation claim appears, +- `operator_status=... finalizer_patches=0`, +- no finalizer-added or finalizer-released Events appear, +- repeated reconcile does not mint unbounded Events, +- no PVC/PV/Pod/Deployment/StorageClass/iSCSI/multipath/dmsetup/hostPath + mutation is performed by operator-status. + +## D5: Clean Delete-Safety Status + +Feed clean cleanup evidence: + +```text +delete_requested=true +finalizer_present=true +volume_id= +pvc_name= +pv_name= +cleanup_status=ok +k8s_residue_count=0 +iscsi_residue_count=0 +multipath_residue_count=0 +process_residue_count=0 +hostpath_residue_count=0 +failure_count=0 +``` + +Pass criteria: + +- `SwBlockVolume.status.deleteSafety.state=releasable`, +- `SwBlockVolume.status.deleteSafety.decision=allowed`, +- `finalizerReleaseAllowed=true` is visible as a decision fact only, +- no finalizer patch is attempted and no finalizer-released Event is emitted, +- `operator_status=... finalizer_patches=0`, +- repeated reconcile is idempotent, +- final cleanup verifier returns `cleanup_status=ok`, +- all residue counters are zero. + +## D6 Preview: Multi-Volume Status Isolation + +Do not test finalizer add/remove. Test that delete-safety evidence for volume A +does not change volume B/C status, identity, publish target, or Events. + +## Report + +Write or update the sign-off at: + +```text +internal/docs/qa-assignments/phase39-d4-d5-finalizer-delete-safety-qa-signoff.md +``` + +Required verdict fields: + +- source commit, +- lab node health, especially `tp01`, +- RBAC boundary result, +- D4 blocked delete-safety status result, +- D5 clean delete-safety status result, +- final cleanup audit, +- blocking findings, +- non-blocking findings, +- recommendation for D6 multi-volume status isolation. diff --git a/seaweed-block/internal/docs/qa-assignments/phase39-d6-multi-volume-delete-safety-status-isolation-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase39-d6-multi-volume-delete-safety-status-isolation-qa-signoff.md new file mode 100644 index 0000000000..10b1bc615f --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase39-d6-multi-volume-delete-safety-status-isolation-qa-signoff.md @@ -0,0 +1,141 @@ +# QA Sign-off - Phase 39 D6 Multi-Volume Delete-Safety Status Isolation + +Verdict: **PASS.** Delete-safety evidence for one volume does not contaminate the +others. With three managed volumes, volume A's blocked delete-safety +(`iscsi_node_records_present`) leaves volumes B and C `ready/first_volume_verified` +with their own identities, and volume C can independently show `releasable` +without changing A/B. No finalizer patch is attempted (`finalizer_patches=0`), no +finalizer Events appear, the operator mutates only CRD status + Events, and the +cluster counts and all read surfaces agree. One minor non-blocking staleness +observation (a removed delete-summary leaves a stale `deleteSafety` on that same +volume — not cross-volume). + +Date: 2026-06-13 + +Source commit: `afd98f5 phase39: guard delete safety status isolation` (test-only +on the validated floor `f167f9a phase39: allow scripted volume actions`; branch +`phase33-testops-failure-hardening`) + +## Lab Node Health + +- m01 `Ready`, m02 `Ready`, **tp01 `NotReady`/unreachable** (unchanged since + Phase 38; "No route to host"). D6 is a status/events-only gate on three + from-bundle volumes; it does not require a healthy 3-node RF=3 cluster. Install + used operator-status pinned to m02 with the image re-imported from docker + (binary unchanged from `f167f9a`; `afd98f5` is test/docs-only). Restore tp01 + before any RF=3 live multi-node work. + +## Evidence Shape + +A single from-bundle `cluster-evidence.json` with three healthy volumes +(distinct `volume_id`/`pvc_name`/primary/publish_target), plus a per-reconcile +`swblockvolume-delete-summary.txt` + `cleanup-summary.txt`: + +```text +pvc-a primary=r1 frontend=192.168.1.181:3260 +pvc-b primary=r2 frontend=192.168.1.184:3260 +pvc-c primary=r3 frontend=192.168.1.188:3260 +Reconcile 1 (blocked-isolation): delete-summary=pvc-a, cleanup_status=failed iscsi_residue_count=1 +Reconcile 2 (releasable-isolation): delete-summary=pvc-c, cleanup_status=ok all residue 0 +``` + +(Note: the bundle carries one `swblockvolume-delete-summary.txt` + one +cluster-level `cleanup-summary.txt` per reconcile, so A-blocked and C-releasable +are shown in separate reconciles rather than one snapshot. The isolation property +is demonstrated in each.) + +## Per-Volume CRD Status + +### Reconcile 1 — A blocked, B/C healthy + +```text +operator_status=write_status ... volumes=3 events=4 finalizer_patches=0 mutation_allowed=false +pvc-a: status=blocked reason=iscsi_node_records_present deleteSafety.state=blocked decision=rejected +pvc-b: status=ready reason=first_volume_verified deleteSafety=(none) +pvc-c: status=ready reason=first_volume_verified deleteSafety=(none) +SwBlockCluster.status: volumeCount=3 readyVolumeCount=2 blockedVolumeCount=1 +``` + +A's residue reason on B or C: **0**. A's blocked delete-safety did **not** block +B/C status publication (both published `ready`). Counts match the evidence. + +### Reconcile 2 — C releasable, A/B independent + +```text +pvc-a: status=ready reason=first_volume_verified deleteSafety.state=blocked (stale — see findings) +pvc-b: status=ready reason=first_volume_verified deleteSafety=(none) +pvc-c: status=ready reason=first_volume_verified deleteSafety.state=releasable decision=allowed +finalizer_patches=0 +``` + +C independently became `releasable/allowed` without making A or B releasable or +blocked. (B unchanged; A's *status* is its healthy base — see the staleness note.) + +## Cross-Surface Agreement Matrix + +| Surface | pvc-a | pvc-b | pvc-c | A reason on B/C? | +|---|---|---|---|---| +| CRD `SwBlockVolume.status` | blocked / iscsi_node_records_present | ready / first_volume_verified | ready / first_volume_verified | no | +| report `summary.txt` (managed_volume) | blocked / iscsi_node_records_present | ready / first_volume_verified | ready / first_volume_verified | no (grep count 0) | +| report `volume=` identity | r1 @ 192.168.1.181:3260 | r2 @ 192.168.1.184:3260 | r3 @ 192.168.1.188:3260 | distinct | + +Distinct `volumeID`, `pvcName`, primary replica, and publish target per volume; +no cross-volume reason-code mix-up; report agrees with CRD. (operator-snapshot is +the same artifact the report writes; dashboard serves it — consistent with the +prior phases' surface-agreement checks.) + +## RBAC Boundary — PASS (status-only) + +Same status-only chart/install validated in the Phase 39 D4/D5 status-only +sign-off: + +```text +patch swblockclusters/status: yes patch swblockvolumes/status: yes create events: yes +patch swblockvolumes (main): no patch swblockvolumes --subresource=finalizers: no +patch pods / pvc / update storageclasses: no +``` + +`finalizer_patches=0` on every reconcile; no finalizer-added/released Events; the +operator writes only CRD status + Events. + +## Final Cleanup Audit — PASS + +`cleanup_status=ok`, `iscsi_residue_count=0`, `failure_count=0`; helm 0, pods 0. + +## Blocking Findings + +None. All D6 pass criteria are met: per-volume isolation, distinct identities, +cluster counts match, no cross-volume reason mix-up, `finalizer_patches=0`, no +finalizer Events, no storage/workload/host mutation, no surface claiming a +completed deletion. + +## Non-Blocking Findings + +1. **Stale `deleteSafety` when a volume's delete evidence disappears.** In + reconcile 2, pvc-a no longer had a `swblockvolume-delete-summary.txt`, so the + operator did not update its `deleteSafety` — pvc-a kept the prior reconcile's + `deleteSafety.state=blocked` while its `status` was the healthy `ready`. This + is a *within-volume* staleness (the field is not reset to `not_requested`/ + cleared when delete evidence is withdrawn), **not** cross-volume contamination + — B/C stayed clean throughout. It is partly a test-construction artifact (a + real volume's delete-summary would not vanish arbitrarily), but consider + clearing/refreshing `deleteSafety` for managed volumes that have no current + delete evidence so a consumer never sees `status=ready` with + `deleteSafety=blocked`. +2. **Lab: tp01 `NotReady`/unreachable.** Lab infra; restore before RF=3 live work. +3. **(Carried) live/envtest status-writer regression.** Six live-vs-mock CRD + schema defects across this phase chain (D3 casing, D2/D37 condition enum, + finalizer URL 404 → RBAC 403, scripted-mode 422) all passed `go test`/`helm + template` and failed only against the live API. An envtest harness for + `KubernetesStatusClient` (real CRD schema + the operator's real RBAC) would + have caught each before handoff. + +## Recommendation for Phase 39 Close + +**Phase 39 D4/D5/D6 all pass on the status-only path.** Delete-safety is +observable and isolated per volume (blocked/releasable/decision/CleanupRequired/ +the scripted verify_cleanup action/`finalizerReleaseAllowed` as a fact), with +RBAC-provable zero finalizer/spec/storage/workload mutation. **Phase 39 can +close.** Track the stale-`deleteSafety` polish and the envtest-regression +follow-up, and restore tp01 — these do not block close. Actual finalizer +add/remove remains correctly deferred to the future lifecycle-owner component. diff --git a/seaweed-block/internal/docs/qa-assignments/phase39-d6-multi-volume-delete-safety-status-isolation-qa.md b/seaweed-block/internal/docs/qa-assignments/phase39-d6-multi-volume-delete-safety-status-isolation-qa.md new file mode 100644 index 0000000000..5466d620ab --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase39-d6-multi-volume-delete-safety-status-isolation-qa.md @@ -0,0 +1,99 @@ +# Phase 39 D6 QA Assignment: Multi-Volume Delete-Safety Status Isolation + +Status: ready for QA. D4/D5 status-boundary validation passed on `f167f9a`. + +Required source floor: + +- `f167f9a phase39: allow scripted volume actions` + +## Goal + +Validate that delete-safety evidence for one volume does not contaminate other +volumes. This is a status/events-only gate. Do not test finalizer add/remove. + +The operator-status controller may write only: + +```text +SwBlockCluster/status +SwBlockVolume/status +Kubernetes Events +``` + +It must not patch `SwBlockVolume.metadata.finalizers`, `SwBlockVolume.spec`, +PVCs, PVs, Pods, Deployments, StorageClasses, Secrets, Nodes, iSCSI, multipath, +dmsetup, hostPath data, or Helm resources. + +## Preflight + +- Use a clean lab. +- Restore `tp01` first if running on the 3-node RF=3 lab. +- Install with `operatorStatus.create=true` and `operatorStatus.dryRun=false`. +- Confirm RBAC: + - `patch swblockclusters/status`: yes + - `patch swblockvolumes/status`: yes + - `create events`: yes + - main `patch swblockvolumes`: no + - `patch swblockvolumes --subresource=finalizers`: no + - pod/PVC/PV/deployment/storageclass mutations: no + +## Scenario Shape + +Create or replay evidence for three managed volumes: + +- Volume A: delete requested + cleanup residue. +- Volume B: healthy and not deleting. +- Volume C: clean delete-safety evidence or healthy, depending on available + fixture. + +Minimum expected status: + +```text +volume A: deleteSafety.state=blocked, decision=rejected +volume B: status=ready, reasonCode=first_volume_verified +volume C: status remains independent; if clean-delete evidence is used, + deleteSafety.state=releasable, decision=allowed +``` + +## Pass Criteria + +- Volume A has `deleteSafety.state=blocked` and a stable residue reason. +- Volume B keeps its original `volumeID`, `pvcName`, status, reason, and publish + target identity. +- Volume C keeps independent status; if it has clean delete-safety evidence, it + becomes `releasable` without changing A/B. +- `SwBlockCluster.status.volumeCount` and ready/blocked/stale counts match the + three-volume evidence. +- No cross-volume reason-code mix-up appears in CRD status, report, + operator-snapshot, dashboard, or explain output. +- Events, if emitted, reference the correct `SwBlockVolume` object only. +- `operator_status=... finalizer_patches=0`. +- No finalizer-added or finalizer-released Events appear. +- Cleanup verifier ends with `cleanup_status=ok` and all residue counters zero. + +## Failure Conditions + +- Any volume other than A shows A's residue reason. +- A blocked delete-safety decision prevents B/C status publication. +- Any finalizer patch is attempted. +- Any workload/storage/host mutation occurs from operator-status. +- Any surface claims object deletion completed because of operator-status. + +## Report + +Write the sign-off to: + +```text +internal/docs/qa-assignments/phase39-d6-multi-volume-delete-safety-status-isolation-qa-signoff.md +``` + +Include: + +- source commit, +- lab node health, +- evidence shape used, +- per-volume CRD status, +- cross-surface agreement matrix, +- RBAC boundary result, +- final cleanup audit, +- blocking/non-blocking findings, +- recommendation for Phase 39 close. diff --git a/seaweed-block/internal/docs/qa-assignments/phase40-d4-status-api-conformance-qa.md b/seaweed-block/internal/docs/qa-assignments/phase40-d4-status-api-conformance-qa.md new file mode 100644 index 0000000000..eb4744b8a4 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase40-d4-status-api-conformance-qa.md @@ -0,0 +1,121 @@ +# Phase 40 D4 QA: Operator-Status API Conformance Gate + +## Goal + +Validate that operator-status payloads fail fast against the real CRD schema and +the status/events-only RBAC boundary before live release QA. + +This is a regression gate for the live-only defects found in Phases 35-39: + +- snake_case payload drift, +- unsupported condition/action enum values, +- wrong CRD endpoint usage, +- RBAC boundary broadening, +- delete-safety status regressions. + +## Scope + +In: + +- local scripted gate, +- TestOps runner gate, +- CRD schema and RBAC-equivalent validation, +- Helm render validation for operator-status write mode. + +Out: + +- live Helm install, +- CRD finalizer mutation, +- storage/workload/host mutation, +- automatic cleanup, +- upgrade execution. + +## Minimal Local Gate + +From the product repo: + +```powershell +powershell -NoProfile -ExecutionPolicy Bypass -File scripts/run-phase40-status-api-conformance.ps1 +``` + +Expected artifact: + +```text +results/phase40-status-api-conformance-*/phase40-status-api-conformance-summary.txt +``` + +Required summary lines: + +```text +phase40_status_api_conformance_status=ok +casing_drift_gate=ok +enum_drift_gate=ok +wrong_endpoint_gate=ok +rbac_boundary_gate=ok +delete_safety_status_gate=ok +operator_status_mutation_scope=status_events_only +finalizer_mutation_allowed=false +``` + +## TestOps Gate + +Run on the lab with the runner: + +```text +swblock run testops/scenarios/operator-status-api-conformance-chain.yaml +``` + +If the product repo is not at `/tmp/seaweed_block` on `m02`, pass: + +```text +-env product_root=/path/to/seaweed_block +``` + +Expected remote artifact: + +```text +/mnt/smb/work/share/g15d-k8s/-operator-status-api-conformance/phase40-status-api-conformance-summary.txt +``` + +## Failure Criteria + +Fail D4 if any of the following happens: + +- status payload casing drift is accepted, +- unsupported condition/action enum drift is accepted, +- main-object or `/finalizers` endpoint mutation is accepted, +- operator-status gains main resource, storage, workload, or host mutation + authority, +- blocked/releasable delete-safety status tests fail, +- Helm cannot render operator-status with `operatorStatus.dryRun=false`. + +## Close Report Template + +```text +Phase 40 D4 Operator-Status API Conformance QA — PASS/FAIL + +Source commit: +Runner: +Run ID: + +Local/scripted gate: +- phase40_status_api_conformance_status: +- casing_drift_gate: +- enum_drift_gate: +- wrong_endpoint_gate: +- rbac_boundary_gate: +- delete_safety_status_gate: +- finalizer_mutation_allowed: + +TestOps gate: +- scenario: +- actions: +- result: +- artifact path: + +Blocking findings: +- ... + +Non-blocking findings: +- ... +``` diff --git a/seaweed-block/internal/docs/qa-assignments/phase40-d6-release-candidate-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase40-d6-release-candidate-qa-signoff.md new file mode 100644 index 0000000000..15aa5c5f20 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase40-d6-release-candidate-qa-signoff.md @@ -0,0 +1,371 @@ +# QA Sign-off — Phase 40 D6 Release Candidate Gate + +Verdict: **PASS — release-clear from the QA gate.** First filed HOLD on `9a8df78` +(chart-ahead-of-image flag skew); chart-flag gate verified on `5f0566e` with G1 +against published images; and the final blocker — G2 operator-status live +CRD/Event/RBAC on the **shipped release image `sha-dc2972d0059b`** — now passes +(see "G2 on the fresh release image" below). All D6 gates (Local, G1–G5) pass on +the shipped release artifacts; no QA release blocker remains. + +## Re-validation — 2026-06-13, commit `5f0566e phase40: gate durable impl chart flag` + +The dev gated `--launcher-durable-impl` behind `compat.launcherDurableImplFlag` +(default `false`): + +- Default `helm template` now renders blockmaster with **only** + `--launcher-durable-root` (the flag every published image already has); + `--launcher-durable-impl` is omitted. `--set compat.launcherDurableImplFlag=true` + re-adds it. A `fail` guards `blockmaster.durableImpl != walstore` while the + compat flag is off (no silent drop). Omitting the flag is behavior-neutral for + the default — the blockmaster binary's own `--launcher-durable-impl` default is + already `walstore`. + +**G1 re-run against the PUBLISHED image** (lab tree synced to `5f0566e`; scenario +default image, no local override): + +```text +swblock run testops/scenarios/helm-first-volume-via-sw-block-cli-chain.yaml +day1.yaml image = ghcr.io/seaweedfs/seaweed-block:sha-6260e46fd3be (published) +=== helm-first-volume-via-sw-block-cli-chain === PASS (52.9s) — 34/34 actions + helm_install_stack PASS (blockmaster starts; no CrashLoopBackOff) + first_volume_user_loop PASS writer_verified=1 reader_verified=1 + first_volume_asserts PASS first_volume_ok=1 + helm_uninstall_cleanup PASS cleanup_ok=1 +bundle results/20260613-203738-8794 +``` + +The blocking finding (chart-ahead-of-image flag skew) is **resolved**: the +documented Helm + first-PVC + writer/reader path now works end-to-end with the +currently-published images. Lab left clean (helm 0, pods 0). + +**Residual confirmation (not a regression, a scope note).** `sha-6260e46fd3be` +(and `:alpha`) are old published images used here only to prove the chart is +backward-compatible. Their **operator-status binary predates the Phases 35–39 +fixes**, so the G2 operator-status live-CRD/Event claim was validated on the +*from-source* build, not on these digests. Before a full release PASS, re-run G2 +against the **actual release image** (a fresh publish from the release commit) to +confirm live status/events publication and the RBAC boundary hold on the shipped +binary. The chart-flag gate does not change any binary; it only makes the chart +installable on older images. + +## Fresh Release Image For G2 + +GitHub Actions run `27490827782` published commit `dc2972d0059b` from branch +`phase33-testops-failure-hardening`. + +Use these images for the remaining G2 operator-status live CRD/Event/RBAC check: + +```text +ghcr.io/seaweedfs/seaweed-block:sha-dc2972d0059b +ghcr.io/seaweedfs/seaweed-block-csi:sha-dc2972d0059b +``` + +Published digests: + +```text +seaweed-block: + sha256:b8da5ca4e2bbe2f0f630fee0468790c444362615d68807a1be31fd237c84928f +seaweed-block-csi: + sha256:b5942cd68d28aecdfebec1f1e5ec55a9cafe746169fee3b6c35916c93fffcaa6 +``` + +### G2 on the fresh release image — PASS (2026-06-14) + +Ran the operator-status live write-mode path against the shipped release images +(`sha-dc2972d0059b`, pulled into m01+m02 k3s) on the gated chart (`5f0566e`, lab +tree; chart unchanged through `340e05f`). Image preflight: the shipped blockmaster +binary defines **both** `--launcher-durable-root` and `--launcher-durable-impl` +(fully current), and `sw-block ops` exposes `operator-status`. + +```text +install: helm install ... -f day1.yaml(image=sha-dc2972d0059b) + --set operatorStatus.create=true --set operatorStatus.dryRun=false + --set operatorStatus.interval=15s --wait +blockmaster: 1/1 Running (no CrashLoopBackOff on the gated chart) +first volume: first_volume_status=ok writer_verified=true reader_verified=true + (pvc sw-block-example-pvc / volume pvc-3344346b-...) + +live CRD status (patched by the shipped operator-status loop): + SwBlockCluster sw-block: readyVolumeCount=1 volumeCount=1 blocked=0 + SwBlockVolume sw-block-example-pvc: status=ready Ready=True reason=first_volume_verified +Event: Normal first_volume_verified swblockvolume/sw-block-example-pvc + "managed volume is ready for the documented path" + +RBAC (can-i as system:serviceaccount:kube-system:sw-block-seaweed-block-operator-status): + patch swblockvolumes --subresource=status => yes + patch swblockclusters --subresource=status => yes + create events => yes + patch swblockvolumes (main object) => no + patch swblockvolumes --subresource=finalizers => no + patch pods => no + patch persistentvolumeclaims => no + update storageclasses => no + delete swblockvolumes => no +``` + +The shipped release binary publishes live CRD status + the ready Event with the +exact status/events-only RBAC boundary — no schema/casing/enum/endpoint defects, +no spec/finalizer/storage/workload/delete mutation power. The Phases 35–39 +operator-status fixes are present in the published image. Cleanup verified: +`cleanup_status=ok`, helm 0 / pods 0. + +**Final verdict: all D6 gates pass on the shipped release artifacts.** The chart +(`5f0566e`) installs and runs the documented first-volume path on the published +images (G1), and the operator-status read-only/status-only CRD + Event claim holds +on the shipped binary (G2). No release blocker remains from the QA gate. + +--- + +## Original finding (commit `9a8df78`, superseded by the Re-validation above) + +Verdict at filing: **HOLD (do not release the published images as-is).** + +The product **code** at `9a8df78` is good: with an image built from that source, +the full documented path passes — fresh Helm install, first PVC bind, +writer/reader verify, live read-only/status-only operator-status CRD + Events +publication with a provable status/events-only RBAC boundary, correct +negative-status reporting, and zero-residue cleanup (G1/G2/G3/G4/G5 all pass). + +But the release candidate ships a **chart that no published image satisfies**. +The `9a8df78` chart's blockmaster Deployment passes `--launcher-durable-impl`, +and **neither** published image referenced by the release defines that flag: + +- `ghcr.io/seaweedfs/seaweed-block:alpha` (the chart's *default* `image.tag` and + `generate-helm-values`' default `--image`): has `--launcher-durable-root`, + **missing `--launcher-durable-impl`**. +- `ghcr.io/seaweedfs/seaweed-block:sha-6260e46fd3be` (the pinned digest in the G1 + scenario, the helm-lifecycle scenario, and the status-endpoint scenarios): + **missing `--launcher-durable-impl`** (older still). + +So **any install that uses a published image** — i.e. the default documented user +path — gets `blockmaster: flag provided but not defined: -launcher-durable-impl` +→ blockmaster `CrashLoopBackOff` → `helm install --wait` 10m timeout → no first +volume. This meets the assignment's own blocking criterion ("first-volume +writer/reader fails") for the as-published artifacts. + +Date: 2026-06-13 + +Source commit: `9a8df78 phase40: update beta candidate evidence` (branch +`feature/sw-block` working tree, synced to `/tmp/seaweed_block` on m02) + +Image(s): +- **Tested-good:** fresh local build from `9a8df78` → `sw-block:local` / + `sw-block-csi:local` (has both launcher flags). G1/G2 pass with these. +- **Tested-bad (published):** `ghcr.io/seaweedfs/seaweed-block:alpha` and + `:sha-6260e46fd3be` — both lack `--launcher-durable-impl`; blockmaster crashes. + +Runner: `swblock` from `sw-test-runner-standalone` `d45c60c` (built to +`C:\work\swblock.exe`; runs from Windows, SSHes to m02). + +## Lab Node Health + +- m01 `Ready`, m02 `Ready`, **tp01 `NotReady`/unreachable** (Connection timed + out; unchanged since Phase 37). Generated day1 values correctly exclude tp01 + (m01+m02 only), and the csi-node DaemonSet's desired count is 2 (tp01 excluded) + — so the 2-node install does not wait on tp01. Restore tp01 before any RF=3 + live multi-node gate. +- Two lab-infra issues were hit and resolved during this run (neither is a + product defect; both are recorded under Non-Blocking): + 1. **m02 disk pressure** (88% > k3s 85% image-GC-high-threshold) caused k3s to + continuously GC the unused `:local` images, so installs raced GC → + `ErrImageNeverPull`. Reclaimed 54 GB of dangling docker layers (no project + data touched) → 63%; GC stopped; installs stable. + 2. **`build-alpha-images.sh` remote import** did not refresh m01's containerd + tag; pushed the fresh tar to m01 explicitly. (F1-class image-distribution + friction.) + +## Local Gate — PASS + +`scripts/run-phase40-release-candidate-local.ps1`: + +```text +phase40_release_candidate_local_status=ok +go_test_release_scope=ok +helm_lint=ok +helm_operator_status_template=ok +status_api_conformance_gate=ok +git_diff_check=ok +``` + +The local gate does not exercise the live Kubernetes path; it passed even though +the published-image install is broken (the skew is only visible when a real +blockmaster pod starts). + +## G1 — Minimal New-User Helm Path + +- Run (fresh local image, correct flag order): + `swblock run -env sw_block_image=sw-block:local -env + sw_block_csi_image=sw-block-csi:local + testops/scenarios/helm-first-volume-via-sw-block-cli-chain.yaml` +- Result: **PASS — 34/34 actions** (bundle `results/20260613-193258-4963`). + - `helm_install_stack` PASS, `first_volume_user_loop` PASS, + `first_volume_ok=1`, `writer_verified=1`, `reader_verified=1`, + `report_html=1` (index.html/operator-snapshot present), + `helm_cleanup_ok=1`. +- Result with **published image** (scenario default `sha-6260e46fd3be`): + **FAIL** — `helm_install_stack` 10m timeout; blockmaster `CrashLoopBackOff` + (`flag provided but not defined: -launcher-durable-impl`). This is the blocking + finding below. + +## G2 — Operator-Status CRD And Event Path — PASS + +Live write-mode install (`operatorStatus.create=true`, +`operatorStatus.dryRun=false`, `interval=15s`, fresh local image) + first volume; +CR stubs created per the assignment (the controller patches existing CRs, it does +not create them): + +```text +SwBlockCluster sw-block: status.readyVolumeCount=1 volumeCount=1 blocked=0 +SwBlockVolume sw-block-example-pvc: status=ready Ready=True reason=first_volume_verified +Event: Normal first_volume_verified swblockvolume/sw-block-example-pvc + "managed volume is ready for the documented path" +``` + +The operator-status loop reached the blockmaster gRPC +(`blockmaster.kube-system.svc.cluster.local:9333`), observed the ready volume, +and patched live. RBAC boundary (`kubectl auth can-i` as +`system:serviceaccount:kube-system:sw-block-seaweed-block-operator-status`): + +```text +patch swblockvolumes --subresource=status => yes +patch swblockclusters --subresource=status => yes +create events => yes +patch swblockvolumes (main object) => no +patch pods => no +patch persistentvolumeclaims => no +update storageclasses => no +``` + +Status/events-only, exactly as claimed; no storage/workload/spec/finalizer +mutation power. Note: the controller keys `SwBlockVolume` by **PVC name** +(`sw-block-example-pvc`), not by `volume_id`. + +## G3 — Negative Status — PASS (substance), full-install path blocked by tp01 + +The negative-status substance was validated on `9a8df78` via the scenario's own +cold synthetic-bundle + `sw-block ops explain`/`report` path (deterministic; no +live cluster needed): + +```text +volume pvc-blocked status=blocked reason=csi_node_image_pull_failed +condition Attach ... pod sw-block-csi-node waiting=ImagePullBackOff on node m02 +managed_volume_condition Ready status=False reason=csi_node_image_pull_failed +managed_volume_condition Blocked status=True reason=csi_node_image_pull_failed +safe action: import_csi_image mode=dry_run side_effect=safe_k8s decision=rejected +report: read_only=true mutation_allowed=false (summary.txt + operator-snapshot.json) +index.html: Ready=False, Blocked=True (no false Ready=True anywhere) +``` + +Pass criteria met: stable blocked reason, no false `Ready=True` on any surface +(explain / report index.html / operator-snapshot), safe actions only +(`read_only`/`dry_run`, `mutation_allowed=false`). + +The full `helm-support-bundle-diagnostics-chain` live-install path was **not** +run end-to-end because its `build_and_generate_values` phase hardcodes +`SW_BLOCK_IMPORT_K3S_NODES='192.168.1.181,192.168.1.188'` under `set -euo +pipefail`, and the `.188` (tp01) import aborts the step. Lab-infra block (tp01 +down), not a product defect — see Non-Blocking. + +## G4 — Status API Conformance TestOps Gate — PASS (with a fidelity caveat) + +`swblock run testops/scenarios/operator-status-api-conformance-chain.yaml` → +**PASS, 15/15**: + +```text +phase40_status_api_conformance_status=ok +casing_drift_gate=ok enum_drift_gate=ok wrong_endpoint_gate=ok +rbac_boundary_gate=ok delete_safety_status_gate=ok finalizer_mutation_allowed=false +``` + +Caveat (so the green is not over-read): `scripts/run-phase40-status-api-conformance.sh` +runs `go test ./core/ops` (5 named tests) + `helm template`, then **derives all +six sub-gate lines from a single `$status`** — they are not independent live +assertions. The underlying test (`kubernetes_status_conformance_test.go`) does +load the **real chart CRD OpenAPI schema** from +`charts/seaweed-block/crds/*.yaml` (so casing/enum drift is genuinely checked +against the real schema — real value), but it validates against an +`httptest.Server` **mock**, not a live apiserver or envtest. The live-only +behaviors that bit Phases 35–39 (subresource 404, RBAC 403 on a finalizers +patch) are simulated, not exercised. This gate is a real improvement for +schema/enum drift; it does **not** close the live-RBAC/subresource gap. The +standing recommendation (a real envtest harness — real apiserver + the operator's +real RBAC for `KubernetesStatusClient`) still stands. + +## G5 — Final Cleanup — PASS + +`swblock run testops/scenarios/cleanup-residue-chain.yaml` → **PASS, 13/13**: +`host_protocol_residue` (no iSCSI sessions, no NVMe subsys, no product +processes), `kubernetes_residue` (no sw-block/seaweed-block/CSI-driver +resources), `hostpath_residue` (no `/var/lib/sw-block` testops residue), +`collect_and_cleanup` final sweep. Lab left clean. + +## Blocking Findings + +1. **Chart-ahead-of-image skew — the documented Helm install is broken with every + published image.** `9a8df78`'s `charts/seaweed-block/templates/blockmaster.yaml` + passes `--launcher-durable-impl`, but `ghcr.io/seaweedfs/seaweed-block:alpha` + (chart default + `generate-helm-values` default) and `:sha-6260e46fd3be` + (pinned in `testops/scenarios/helm-first-volume-via-sw-block-cli-chain.yaml:23-24`, + `helm-lifecycle-upgrade-rollback-chain.yaml`, `status-endpoint-*-chain.yaml`) + both lack that flag → blockmaster `CrashLoopBackOff` → install timeout → no + first volume. **Fix:** publish an image built from the release commit (with + `--launcher-durable-impl`), retag `:alpha`, and bump every `sha-6260e46fd3be` + reference (scenarios + any docs/release notes) to it; then re-run G1 **with the + published image** (not a local override) to confirm. Until then, only + build-from-source installs work. + +## Non-Blocking Findings + +1. **Documented `swblock` `-env` override is silently dropped when flags follow + the scenario path.** The runner (`cli/cli.go`, Go stdlib `flag`) stops parsing + at the first non-flag arg, so `swblock run -env K=V` (the ordering + shown in this assignment's G1 example) ignores the overrides and the scenario + falls back to its pinned image. Overrides only take effect as + `swblock run -env K=V ... `. Recommend fixing the runner to accept + interspersed flags (or correcting every doc/runbook). (Windows note: `/tmp/...` + values passed via `-env` are MSYS path-mangled to `C:/work/tmp/gotmp/...`; + leave `product_root` to the scenario default or set `MSYS_NO_PATHCONV=1`.) +2. **G4 conformance is a schema-aware mock, not live/envtest** (see G4 caveat). + The six sub-gates derive from one status; the envtest harness for + `KubernetesStatusClient` (real apiserver + real RBAC) remains the gap-closer + for the live-only RBAC/subresource class. +3. **`helm-support-bundle-diagnostics-chain` hardcodes tp01 in the build import + list** (`SW_BLOCK_IMPORT_K3S_NODES='192.168.1.181,192.168.1.188'`, fail-fast), + so it cannot run while tp01 is down. Recommend parameterizing the import node + list (env-overridable) so single-node-down labs can still run it. +4. **tp01 `NotReady`/unreachable** — lab infra; restore before RF=3 live work. +5. **m02 local-image GC under disk pressure** — `:local` images get pruned when + m02 disk > 85%; keep m02 below the GC threshold (it was at 88%; 54 GB of + dangling docker layers reclaimed this run → 63%) or use a registry image so + `helm install --wait` does not race containerd GC. + +## Release Recommendation + +**HOLD.** The product code, chart logic, live operator-status read-only/status-only +publication, RBAC boundary, negative-status reporting, and cleanup are all good on +`9a8df78` (proven with a from-source image). The release is gated solely on +release-engineering: **publish a matching image (chart default `:alpha` and any +pinned digest must contain `--launcher-durable-impl`) and bump all references**, +then re-run **G1 against the published image** to flip this to PASS. Do not ship +the chart at `9a8df78` against the current `:alpha`/`sha-6260e46fd3be` images — +the documented first-volume path fails on a clean cluster. The flag-ordering and +envtest items above are follow-ups, not release blockers. + +## Developer Follow-Up After HOLD + +The selected unblock path is a chart compatibility fix rather than relying only +on immediate image republish: + +- `--launcher-durable-impl` is now gated behind + `compat.launcherDurableImplFlag`. +- The default remains `false`, matching the existing compatibility pattern for + newer blockmaster launcher flags. +- Default `walstore` behavior is preserved because `walstore` is the + blockmaster binary default when the flag is omitted. +- Setting `blockmaster.durableImpl` to a non-default value now requires + `compat.launcherDurableImplFlag=true`, so Helm fails fast instead of silently + ignoring the requested implementation. + +Release is still held until QA reruns the published-image first-volume path and +confirms the chart no longer crashes blockmaster with the current published +images. diff --git a/seaweed-block/internal/docs/qa-assignments/phase40-d6-release-candidate-qa.md b/seaweed-block/internal/docs/qa-assignments/phase40-d6-release-candidate-qa.md new file mode 100644 index 0000000000..9119d4c0b8 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase40-d6-release-candidate-qa.md @@ -0,0 +1,231 @@ +# Phase 40 D6 QA: Release Candidate Gate + +## Goal + +Prove the Phase 40 release candidate from both a local build perspective and a +user/lab perspective. + +The release claim is narrow: + +```text +Helm + PVC + read-only/status-only operator status + Events + diagnostics + +delete-safety/install-drift visibility. No lifecycle mutation. +``` + +## Local Gate + +Run from the product repo: + +```powershell +powershell -NoProfile -ExecutionPolicy Bypass -File scripts/run-phase40-release-candidate-local.ps1 +``` + +Required summary: + +```text +phase40_release_candidate_local_status=ok +go_test_release_scope=ok +helm_lint=ok +helm_operator_status_template=ok +helm_published_image_compat_template=ok +status_api_conformance_gate=ok +git_diff_check=ok +``` + +The local gate does **not** prove the Kubernetes user path. It only proves the +release-candidate code, chart render, and CRD/RBAC conformance checks. + +## Required Lab Gates + +Use the release image digest if available. If no digest is published yet, use a +fresh local build and state that clearly in the report. + +### G1 — Minimal New-User Helm Path + +Run the documented CLI values path: + +```text +swblock run testops/scenarios/helm-first-volume-via-sw-block-cli-chain.yaml \ + -env product_root=/path/to/seaweed_block \ + -env sw_block_image= \ + -env sw_block_csi_image= +``` + +Pass criteria: + +- Helm install succeeds. +- First PVC binds. +- Writer verifies data. +- Replacement reader verifies data. +- Report has `index.html`, `summary.txt`, `cluster-evidence.json`, + `timeline.jsonl`, and `operator-snapshot.json`. +- Cleanup summary is `cleanup_status=ok`. + +### G2 — Operator-Status CRD And Event Path + +Install with operator-status write mode enabled: + +```text +helm install sw-block charts/seaweed-block \ + --namespace kube-system \ + --create-namespace \ + -f values.day1.yaml \ + --set operatorStatus.create=true \ + --set operatorStatus.dryRun=false \ + --wait --timeout 10m +``` + +Create the minimal CR stubs if the chart/user path did not create them: + +```yaml +apiVersion: block.seaweedfs.com/v1alpha1 +kind: SwBlockCluster +metadata: + name: sw-block + namespace: kube-system +spec: {} +--- +apiVersion: block.seaweedfs.com/v1alpha1 +kind: SwBlockVolume +metadata: + name: + namespace: kube-system +spec: {} +``` + +Pass criteria: + +- `SwBlockCluster.status.readyVolumeCount >= 1`. +- At least one `SwBlockVolume.status.status=ready`. +- Ready condition has `reasonCode=first_volume_verified`. +- Kubernetes Events exist for the ready volume. +- `kubectl auth can-i` confirms status/events only: + - `patch swblockvolumes --subresource=status`: yes + - `create events`: yes + - `patch swblockvolumes`: no + - `patch pods`: no + - `patch pvc`: no + - `update storageclasses`: no + +### G3 — Negative Status + +Run a blocked-path validation. Preferred path: + +```text +swblock run testops/scenarios/helm-support-bundle-diagnostics-chain.yaml \ + -env product_root=/path/to/seaweed_block \ + -env sw_block_image= \ + -env sw_block_csi_image= +``` + +Pass criteria: + +- Blocked evidence shows `reason=csi_node_image_pull_failed` or another stable + blocked reason intentionally induced by the scenario. +- No CRD/report/dashboard/operator-snapshot surface shows false `Ready=True`. +- Suggested actions are `read_only`, `dry_run`, or `scripted` with + `mutationAllowed=false`. + +### G4 — Status API Conformance TestOps Gate + +Run: + +```text +swblock run testops/scenarios/operator-status-api-conformance-chain.yaml \ + -env product_root=/path/to/seaweed_block +``` + +Pass criteria: + +```text +phase40_status_api_conformance_status=ok +casing_drift_gate=ok +enum_drift_gate=ok +wrong_endpoint_gate=ok +rbac_boundary_gate=ok +delete_safety_status_gate=ok +finalizer_mutation_allowed=false +``` + +### G5 — Final Cleanup + +Run: + +```text +swblock run testops/scenarios/cleanup-residue-chain.yaml \ + -env product_root=/path/to/seaweed_block +``` + +Pass criteria: + +- no Helm release, +- no Seaweed Block pods/deployments/CRDs left unless intentionally kept for + follow-up inspection, +- no iSCSI sessions, +- no Seaweed Block iSCSI node DB records, +- no multipath/dmsetup residue, +- no product processes, +- no test hostPath residue. + +## Optional Extended Gates + +Run only if lab time is available: + +- RF=3 multi-volume smoke, +- restart persistence, +- WAL corruption no-false-ready gate, +- loopback cross-node negative gate. + +## Blocking Criteria + +Block D6 if any of these happen: + +- first-volume writer/reader fails, +- operator-status cannot publish CRD status, +- operator-status gains any storage/workload/spec/finalizer mutation power, +- blocked/stale/corrupt evidence becomes false `Ready=True`, +- cleanup leaves residue, +- docs/release note claim a capability not covered by the tested image. + +## Close Report Template + +```text +Phase 40 D6 Release Candidate QA — PASS/FAIL + +Source commit: +Image(s): +Runner: + +Local gate: +- run/artifact: +- result: + +G1 first-volume: +- run: +- result: + +G2 operator-status CRD/Event: +- evidence: +- result: + +G3 negative status: +- run: +- result: + +G4 status API conformance: +- run: +- result: + +G5 cleanup: +- run: +- result: + +Blocking findings: +- ... + +Non-blocking findings: +- ... + +Release recommendation: +- release / hold +``` diff --git a/seaweed-block/internal/docs/qa-assignments/phase41-lifecycle-owner-foundation-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase41-lifecycle-owner-foundation-qa-signoff.md new file mode 100644 index 0000000000..1fcdc0cdc1 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase41-lifecycle-owner-foundation-qa-signoff.md @@ -0,0 +1,167 @@ +# QA Sign-off — Phase 41 Lifecycle Owner Foundation + +Verdict: **PASS (non-mutating slice).** Phase 41 establishes the lifecycle-owner +control boundary, converts delete-safety into executable preconditions, and ships +a dry-run lifecycle-owner action surface — **without** turning `operator-status` +into a mutating controller and **without** any finalizer add/remove. G1–G7 pass. + +**Required carry-forward (recorded per the assignment):** + +```text +A full live-apiserver/envtest lifecycle-owner RBAC/admission gate is still +required before any finalizer mutation (main-object patch swblockvolumes) can +ship. Phase 41's API boundary gate (G2) is schema-aware/equivalent-RBAC, not a +live apiserver/admission proof. +``` + +Date: 2026-06-14 +Source: branch `phase41-lifecycle-owner-foundation` @ `43c7a87 phase41: prepare +qa close handoff` (commits `d0ba1fb`..`b414a9f` + close handoff) +Runner/env: local `go test` + PowerShell boundary gate on the branch tree; live +`kubectl auth can-i` + `verify-helm-cleanup.sh` on the m02 k3s lab (clean). + +## Lab Node Health + +m01 `Ready`, m02 `Ready`, **tp01 `NotReady`/unreachable** (unchanged). Phase 41 +is non-mutating status/dry-run work; no multi-node RF=3 gate is required. Restore +tp01 before any future live finalizer-mutation gate. + +## G1 — Contract Review — PASS + +Reviewed `lifecycle-owner-control-contract.md`, +`lifecycle-owner-finalizer-strategy.md`, `current-plan.md`, `docs/roadmap.md`. + +- Three roles are explicit and separately permissioned: **observer/status + writer** (`operator-status`; CRD `/status` + Events only), **lifecycle owner** + (separate; owns lifecycle metadata, may patch finalizers *only if a future + phase proves the boundary*), **executor** (separate; not introduced here). +- Finalizer mutation is explicitly **deferred** (strategy doc "Decision": "Phase + 41 does **not** ship `SwBlockVolume` finalizer add/remove"). +- Delete-safety is framed as **status guidance, not deletion protection** + ("Delete-safety is status-only guidance, not Kubernetes deletion protection"). +- Non-claims list excludes mutating operator, finalizer add/remove, automatic + cleanup, rebuild, backup, NVMe — consistent across roadmap and current-plan. + +No doc implies operator-status owns finalizers or that cleanup/deletion-protection/ +rebuild/backup/NVMe is delivered. Pass criteria met; no fail conditions present. + +## G2 — API Boundary Gate — PASS (schema-aware; carry-forward applies) + +`scripts/run-phase41-lifecycle-owner-api-boundary.ps1` +(`results/phase41-api-boundary-qa/...-summary.txt`): + +```text +phase41_lifecycle_owner_api_boundary_status=ok +go_test_core_ops=ok +operator_status_main_patch_allowed=false +lifecycle_owner_finalizer_patch_allowed=true +lifecycle_owner_spec_patch_allowed=false +lifecycle_owner_unrelated_metadata_patch_allowed=false +finalizers_endpoint_allowed=false +``` + +As the assignment notes, this is schema-aware/equivalent-RBAC (CRD schema + token +RBAC equivalence), **not** a live-apiserver/admission envtest. Called out as the +open carry-forward, not a product failure. + +## G3 — Delete-Safety Decision Semantics — PASS + +`go test ./core/ops -run +'TestEvaluateSwBlockVolumeDeleteSafety|TestObservationBundle_DeleteSafety'` → `ok`. +All decision behaviors green (both the evaluator and the observation-bundle +projection): + +```text +clean evidence -> state=releasable decision=allowed release_allowed=true +residue -> state=blocked decision=rejected release_allowed=false +missing evidence -> state=requested decision=unknown release_allowed=false +stale evidence -> state=requested decision=unknown reason=cleanup_evidence_stale +not requested -> no premature decision +``` + +Missing/stale never becomes `allowed`; missing is not reported as confirmed +residue; data-plane `Ready` is not used to imply finalizer release is safe. + +## G4 — Cleanup Freshness Source — PASS + +`scripts/verify-helm-cleanup.sh` on the clean m02 lab: + +```text +cleanup_status=ok +k8s_residue_count=0 iscsi_residue_count=0 process_residue_count=0 +multipath_residue_count=0 hostpath_residue_count=0 +cleanup_observed_at=2026-06-14T17:56:28Z +``` + +`cleanup_observed_at` is present and RFC3339 UTC (`date -u +%Y-%m-%dT%H:%M:%SZ`, +script line 237); `cleanup_status` and all residue counters are preserved; exit +behavior unchanged (`exit 1` on failure, line 242). The verifier does not hide +residue. + +## G5 — Dry-Run Lifecycle-Owner Action Surface — PASS + +`go test ./core/ops -run +'TestOperatorStatusReconcilerProjectsDeleteSafetyWithoutFinalizerMutation|TestOperatorStatusReconcilerDeleteSafetyDoesNotContaminateOtherVolumes'` +→ `ok`. The reconciler projects, for each delete-safety volume, an `allowedActions` +entry `safe_k8s.release_swblockvolume_finalizer` with `Mode=dry_run`, +`OwnerExecutor=lifecycle_owner`, `MutationAllowed=false`, and `Decision` equal to +the volume's `deleteSafety` decision. `FinalizerPatchCount==0` and no +`finalizer_added`/`finalizer_released` Events are emitted. + +## G6 — Multi-Volume Isolation — PASS + +The isolation test drives four volumes in one reconcile and asserts per-volume +isolation: + +```text +A delete-a (blocked, iscsi_node_records_present) -> deleteSafety blocked / decision rejected +B healthy-b (ready, first_volume_verified) -> NO deleteSafety (uncontaminated) +C clean-c (clean evidence) -> deleteSafety releasable / decision allowed +D stale-d (stale evidence) -> deleteSafety requested / decision unknown / cleanup_evidence_stale +``` + +A does not contaminate B/C/D; C does not release A/B/D; D stays unknown only for +D; each volume carries its own `deleteSafety` + dry-run lifecycle-owner action; +`FinalizerPatchCount==0` (no finalizer mutation attempted). + +## G7 — Live Boundary / Non-Mutation — PASS + +Phase 41 makes **no change** to `operator-status` RBAC (git-confirmed: no Phase 41 +commit touches `templates/operator-status-rbac.yaml`; the only chart change is +2 +lines of SwBlockVolume CRD status schema). Fresh live `kubectl auth can-i` against +the applied Phase 41 operator-status RBAC on the m02 apiserver: + +```text +patch swblockvolumes.block.seaweedfs.com => no +patch swblockvolumes.block.seaweedfs.com --subresource=status => yes +create events => yes +patch pods => no +patch persistentvolumeclaims => no +update storageclasses.storage.k8s.io => no +``` + +`operator-status` remains status/events-only on the live apiserver. (RBAC was +applied for the check and removed; lab left clean.) + +## Blocking Findings + +None. Phase 41 is a non-mutating boundary + dry-run/status slice; it neither +broadens `operator-status` nor executes any lifecycle mutation. + +## Non-Blocking Findings / Carry-Forwards + +1. **Live-apiserver/envtest lifecycle-owner RBAC/admission gate is still required + before any finalizer mutation ships** (the explicit carry-forward above). G2 is + schema-aware/equivalent-RBAC; it does not exercise a real apiserver admission + path. This is the natural Phase 42 entry point. +2. **tp01 `NotReady`** — lab infra; restore before any live finalizer-mutation or + RF=3 gate. + +## Recommendation + +**Phase 41 can close** as the lifecycle-owner boundary + delete-safety +preconditions + dry-run lifecycle-owner action surface, with `operator-status` +provably still status/events-only. The next phase must build the real +live-apiserver/admission proof for a constrained main-object finalizer patch +before any actual finalizer add/remove is enabled. NVMe / rebuild / backup should +remain deferred until that control-plane proof exists. diff --git a/seaweed-block/internal/docs/qa-assignments/phase41-lifecycle-owner-foundation-qa.md b/seaweed-block/internal/docs/qa-assignments/phase41-lifecycle-owner-foundation-qa.md new file mode 100644 index 0000000000..297384ff91 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase41-lifecycle-owner-foundation-qa.md @@ -0,0 +1,233 @@ +# QA Assignment - Phase 41 Lifecycle Owner Foundation + +## Goal + +Validate that Phase 41 improves the lifecycle-owner control boundary without +quietly turning `operator-status` into a mutating controller. + +The expected product result is: + +```text +operator-status remains status/events-only; +finalizer add/remove is deferred; +delete-safety decisions are allowed/rejected/unknown with stable evidence; +dry-run lifecycle-owner actions are visible but never executed. +``` + +## Source Under Test + +Branch: + +```text +phase41-lifecycle-owner-foundation +``` + +Relevant commits: + +```text +d0ba1fb phase41: define lifecycle owner contract +a362c28 phase41: add lifecycle owner api boundary gate +cabe790 phase41: tighten delete safety preconditions +ab004fc phase41: gate stale cleanup evidence +1f4f769 phase41: choose finalizer strategy and dry-run action +c80fdfc phase41: prove lifecycle action isolation +b414a9f phase41: add lifecycle owner qa gate +plus the latest Phase 41 branch HEAD docs close handoff +``` + +## G1 - Contract Review + +Review: + +```text +internal/docs/ref/lifecycle-owner-control-contract.md +internal/docs/ref/lifecycle-owner-finalizer-strategy.md +internal/docs/current-plan.md +docs/roadmap.md +``` + +Pass criteria: + +```text +operator-status role = observer/status writer only +lifecycle-owner role is separate from operator-status +executor role is separate from both +finalizer mutation is explicitly deferred in Phase 41 +non-claim says delete-safety is status guidance, not deletion protection +``` + +Fail if: + +```text +docs imply operator-status owns finalizers +docs imply automatic cleanup, deletion protection, rebuild, backup, or NVMe work +``` + +## G2 - API Boundary Gate + +Run either: + +```powershell +powershell -NoProfile -ExecutionPolicy Bypass ` + -File scripts/run-phase41-lifecycle-owner-api-boundary.ps1 ` + -ProductRoot C:\work\seaweed_block ` + -ArtifactDir C:\work\seaweed_block\results\phase41-api-boundary-qa +``` + +or the TestOps scenario: + +```bash +swblock run testops/scenarios/lifecycle-owner-api-boundary-chain.yaml +``` + +Pass criteria in +`phase41-lifecycle-owner-api-boundary-summary.txt`: + +```text +phase41_lifecycle_owner_api_boundary_status=ok +operator_status_main_patch_allowed=false +lifecycle_owner_finalizer_patch_allowed=true +lifecycle_owner_spec_patch_allowed=false +lifecycle_owner_unrelated_metadata_patch_allowed=false +finalizers_endpoint_allowed=false +``` + +Note: + +This is schema-aware/equivalent-RBAC, not yet a full live-apiserver envtest. +QA should call that out as an open carry-forward, not as a product failure. + +## G3 - Delete-Safety Decision Semantics + +Run: + +```bash +go test ./core/ops -count=1 -run 'TestEvaluateSwBlockVolumeDeleteSafety|TestObservationBundle_DeleteSafety' +``` + +Pass criteria: + +```text +clean cleanup evidence -> state=releasable decision=allowed release_allowed=true +residue evidence -> state=blocked decision=rejected release_allowed=false +missing cleanup evidence -> state=requested decision=unknown release_allowed=false +stale cleanup evidence -> state=requested decision=unknown reason=cleanup_evidence_stale +data-plane Ready is not falsified by missing/stale lifecycle evidence +``` + +Fail if: + +```text +missing/stale evidence becomes allowed +missing evidence is reported as confirmed residue +Ready=True is used to imply finalizer release is safe +``` + +## G4 - Cleanup Freshness Source + +Run a cleanup verifier in any clean lab or inspect the generated summary from an +existing cleanup gate: + +```bash +bash scripts/verify-helm-cleanup.sh "$PWD" +``` + +Pass criteria: + +```text +cleanup-summary.txt includes cleanup_observed_at= +cleanup_status remains ok/failed as before +existing residue counters remain present +``` + +Fail if: + +```text +cleanup_observed_at is missing from new verifier output +the timestamp is local time or not RFC3339 parseable +the verifier hides residue or changes its exit behavior +``` + +## G5 - Dry-Run Lifecycle-Owner Action Surface + +Run: + +```bash +go test ./core/ops -count=1 -run 'TestOperatorStatusReconcilerProjectsDeleteSafetyWithoutFinalizerMutation|TestOperatorStatusReconcilerDeleteSafetyDoesNotContaminateOtherVolumes' +``` + +Pass criteria: + +```text +SwBlockVolume.status.deleteSafety is populated +allowedActions includes safe_k8s.release_swblockvolume_finalizer +mode=dry_run +ownerExecutor=lifecycle_owner +mutationAllowed=false +decision matches deleteSafety decision +no finalizer_added or finalizer_released Events are emitted +``` + +Fail if: + +```text +operator-status emits finalizer mutation Events +allowedActions claims mutationAllowed=true +release action is missing from CRD status for delete-safety volumes +``` + +## G6 - Multi-Volume Isolation + +Use the same D5 test or a live/from-bundle equivalent with at least four +volumes: + +```text +A: blocked residue -> rejected +B: normal ready volume -> no deleteSafety +C: clean delete evidence -> allowed +D: stale cleanup evidence -> unknown +``` + +Pass criteria: + +```text +A does not contaminate B/C/D +C does not release A/B/D +D stays unknown only for D +each volume has its own deleteSafety and lifecycle-owner dry-run action +no finalizer mutation is attempted +``` + +## G7 - Boundary / Non-Mutation + +If running a live operator-status install, verify: + +```bash +kubectl auth can-i patch swblockvolumes --as -n kube-system +kubectl auth can-i patch swblockvolumes --subresource=status --as -n kube-system +kubectl auth can-i create events --as -n kube-system +kubectl auth can-i patch pods --as -n kube-system +kubectl auth can-i patch persistentvolumeclaims --as -n kube-system +``` + +Pass criteria: + +```text +patch swblockvolumes main: no +patch swblockvolumes/status: yes +create events: yes +pods/PVC/PV/StorageClass mutation: no +``` + +## Final Verdict + +PASS only if G1-G6 pass and any live boundary check in G7 preserves +status/events-only. + +Do not mark Phase 41 fully closed unless the report explicitly records the open +carry-forward: + +```text +full live-apiserver/envtest lifecycle-owner RBAC/admission gate is still needed +before any finalizer mutation can ship +``` diff --git a/seaweed-block/internal/docs/qa-assignments/phase42-d1-lifecycle-owner-admission-gate-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase42-d1-lifecycle-owner-admission-gate-qa-signoff.md new file mode 100644 index 0000000000..75f1abff29 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase42-d1-lifecycle-owner-admission-gate-qa-signoff.md @@ -0,0 +1,207 @@ +# QA Sign-off — Phase 42 D1 Lifecycle Owner Admission Gate + +Verdict: **PASS.** First filed FAIL on `bc5ffc0` (VAP CEL errored on absent +optional fields); fixed in `116d381` (G1–G4 green); breadth-expanded to D1–D4 in +`d3a1e0e` and re-validated green on a real VAP-capable cluster. See the +Re-validation sections below; the original FAIL analysis is kept at the bottom. + +## Re-validation — 2026-06-15, commit `d3a1e0e phase42: expand lifecycle owner admission checks` (D1–D4 breadth) + +The dev widened the same live VAP gate to cover D2–D4: finalizer add/remove +idempotency; annotation / ownerReferences / deletionTimestamp / mixed-metadata +rejects; `/status` subresource denied and main-object status proven unmutated; +object integrity preserved after rejected patches; and create/update/patch/delete +denied for all forbidden resources. + +Re-ran on m02 (k3s v1.34.4): `GATE_EXIT=0`. Every criterion in the expanded +assignment holds: + +```text +status=ok harness=live VAP admission_policy_propagated=true object_integrity_preserved=true +operator_status_main_patch_allowed=false +finalizer_add_allowed=true finalizer_add_idempotent=true +finalizer_remove_allowed=true finalizer_remove_idempotent=true +spec/label/annotation/ownerreferences/deletiontimestamp/foreign_finalizer/ + mixed/mixed_metadata patch_allowed = false +main_status_mutated=false status_subresource_patch_allowed=false finalizers_endpoint_allowed=false +forbidden resources {pods,deployments,pvc,pv,storageclasses,secrets,nodes, + csidrivers,csinodes} × {create,update,patch,delete} = false (36/36) +G3 final object: spec.pvcName=phase42-a, labels.keep=true, annotations.keep=true, no foreign finalizer +G4 cleanup: ns NotFound, VAP/VAPBinding/ClusterRole/Binding all 0 +``` + +Note: `lifecycle_owner_main_status_patch_request_denied=false` is expected and +safe — a CRD with a status subresource silently strips `.status` from a +main-object patch rather than rejecting the request, and the gate independently +proves `main_status_mutated=false` (the status is not changed). The lifecycle-owner +main-object patch is now comprehensively confined to the +`block.seaweedfs.com/swblockvolume-protection` finalizer against a real Kubernetes +admission server. **Phase 42 D1–D4 pass**; lab left clean. + +## Re-validation — 2026-06-15, commit `116d381 phase42: fix lifecycle owner admission gate` + +The fix: (a) the VAP CEL now `has()`-guards the optional fields (status, labels, +annotations, ownerReferences, finalizers) so absent-key eval errors no longer +deny legitimate patches; (b) a probe object drives an admission-propagation wait +before the real assertions, with `admission_policy_propagated=true` added to the +pass criteria. + +Re-ran `bash scripts/run-phase42-lifecycle-owner-admission-gate.sh` on m02 +(k3s v1.34.4, VAP-capable), artifacts `/tmp/p42d1c`. `GATE_EXIT=0`, full summary: + +```text +phase42_lifecycle_owner_admission_status=ok +harness=live_kubernetes_validating_admission_policy +admission_policy_propagated=true +operator_status_main_patch_allowed=false +lifecycle_owner_finalizer_add_allowed=true +lifecycle_owner_finalizer_remove_allowed=true +lifecycle_owner_spec_patch_allowed=false +lifecycle_owner_label_patch_allowed=false +lifecycle_owner_foreign_finalizer_allowed=false +lifecycle_owner_mixed_patch_allowed=false +finalizers_endpoint_allowed=false +lifecycle_owner_{pods,deployments,persistentvolumeclaims,persistentvolumes, + storageclasses,secrets,nodes,csidrivers,csinodes}_patch_allowed=false +``` + +- **G1** PASS — `status=ok`, `admission_policy_propagated=true`, legitimate + finalizer add/remove allowed, all forbidden main-object patches (spec, label, + foreign finalizer, mixed, `/finalizers` subresource) denied; operator-status + main patch denied (RBAC). +- **G2** PASS — all nine forbidden resource mutations (pods, deployments, pvc, + pv, storageclasses, secrets, nodes, csidrivers, csinodes) `=false`. +- **G3** PASS — final object integrity: `spec.pvcName=phase42-a`, + `metadata.labels.keep=true`, `metadata.annotations.keep=true`, no foreign + finalizer remains (the allowed finalizer add/remove changed nothing else). +- **G4** PASS — `sw-block-phase42-gate` namespace NotFound; no leftover + `sw-block-phase42-*` VAP / VAPBinding / ClusterRole / ClusterRoleBinding. + +The lifecycle-owner main-object patch is now provably confined to the +`block.seaweedfs.com/swblockvolume-protection` finalizer against a real +Kubernetes admission server. **Phase 42 D1 passes**; lab left clean. + +--- + +## Original finding (commit `bc5ffc0`, superseded by the Re-validation above) + +Verdict at filing: **FAIL (blocking product defect in the VAP policy).** On a real +VAP-capable cluster the admission gate denies the **legitimate** lifecycle-owner +finalizer add — the policy CEL errors on absent optional fields. This is a +live-only defect: it is invisible to the Phase 41 schema-aware mock and to the +dev's VAP-less rancher-desktop, and is exactly the class Phase 42 exists to catch. + +Date: 2026-06-14 +Source: branch `phase41-lifecycle-owner-foundation` @ `bc5ffc0 phase42: add live +lifecycle owner admission gate` +Environment: m02 k3s **v1.34.4+k3s1** — `admissionregistration.k8s.io/v1` +`ValidatingAdmissionPolicy` + `ValidatingAdmissionPolicyBinding` served and +enforced (this is **not** the env-blocked case; the gate's environment +requirement is met). + +## How It Was Run + +`bash scripts/run-phase42-lifecycle-owner-admission-gate.sh /tmp/seaweed_block` +on m02 (`KUBECONFIG=/etc/rancher/k3s/k3s.yaml`), artifacts in `/tmp/p42d1`. A +second diagnostic run injected a 25 s VAP-propagation wait after the policy apply +to separate the propagation race from the policy logic. + +## Result + +`GATE_EXIT=1`; summary stops at `status=running` (incomplete): + +```text +phase42_lifecycle_owner_admission_status=running +harness=live_kubernetes_validating_admission_policy +operator_status_main_patch_allowed=false +lifecycle_owner_finalizer_add_allowed=true <- first run only (VAP not yet active) +lifecycle_owner_finalizer_remove_allowed=true <- first run only (VAP not yet active) +``` + +- **Run 1 (no wait):** the VAP had not propagated, so the lifecycle-owner + finalizer add/remove succeeded and the **spec-patch deny-check** (the first + negative case) was *not* denied — the patch went through. Gate aborted at + `lifecycle-owner-spec-patch`. +- **Run 2 (25 s wait, VAP active):** the gate aborted *earlier*, at the + **legitimate** `lifecycle-owner-add-finalizer` — the active VAP denied it: + +```text +ValidatingAdmissionPolicy 'sw-block-phase42-finalizer-only' ... denied request: +expression '... object.status == oldObject.status ...' resulted in error: +no such key: status +``` + +## Root Cause + +The VAP CEL (script lines 165–178) compares optional object fields directly: + +```text +object.spec == oldObject.spec && +object.status == oldObject.status && <-- errors when .status absent +object.metadata.labels == oldObject.metadata.labels && +object.metadata.annotations == oldObject.metadata.annotations && +object.metadata.ownerReferences == oldObject.metadata.ownerReferences && <-- also absent on the test object +... +``` + +The test object `phase42-a` is created with only `metadata` (labels/annotations) +and `spec` — **no `.status`, no `.ownerReferences`**. In Kubernetes VAP CEL, +reading an absent key (`object.status`) raises `no such key: status`. With +`validationActions: [Deny]` and the default `failurePolicy: Fail`, a CEL +**evaluation error is treated as DENY**. So the active policy denies the very +finalizer add it is meant to allow. (Once `status` is guarded, the next absent +field — `ownerReferences` — would error the same way.) + +So there are two defects, in priority order: + +1. **(Blocking, product) VAP CEL does not handle absent optional fields.** + `object.status`, `object.metadata.ownerReferences` (and any optional + metadata) must be `has()`-guarded, e.g. per field: + `(has(object.X) == has(oldObject.X)) && (!has(object.X) || object.X == oldObject.X)` + (or CEL optional access `object.?X.orValue(null) == oldObject.?X.orValue(null)`). + Until this is fixed, the gate cannot pass: a real apiserver denies the + approved finalizer mutation. +2. **(Gate robustness) No wait for VAP propagation before the deny-checks.** + The script runs the patch checks immediately after `kubectl apply` of the + policy/binding (line 194 → 215). VAP enforcement is not synchronous, so the + negative checks are non-deterministic and, in run 1, raced an inactive policy + (which masked defect #1 by letting the spec patch through). Add a readiness + wait — poll until a known-bad patch is actually denied, or `kubectl wait` / + bounded sleep — before any check. + +## Gate Coverage Reached + +```text +G1 run the gate FAIL (policy denies legitimate finalizer add; spec deny-check raced in run 1) +G2 forbidden resource mutations NOT REACHED (gate aborts at G1) +G3 object integrity NOT REACHED +G4 cleanup PASS (ns/VAP/VAPBinding/ClusterRole/Binding all removed on failure exit; + verified 0 leftovers after both runs) +``` + +`operator_status_main_patch_allowed=false` is correct (RBAC-enforced; the +operator-status SA has no main-object patch). The harness is genuinely live VAP — +it *did* enforce in run 2; it enforced the wrong outcome. + +## Blocking Findings + +1. VAP CEL errors on absent optional fields (`no such key: status`) → + `failurePolicy:Fail` → the approved lifecycle-owner finalizer add/remove is + denied on a real API server. Fix the CEL to `has()`-guard optional-field + immutability comparisons, then re-run. + +## Non-Blocking Findings + +1. Gate has no VAP-propagation wait; the negative checks are order/timing + dependent. Add a readiness gate so a fixed policy is deterministically + enforced before the checks. (Surface this even after #1 is fixed.) +2. tp01 `NotReady` — unrelated to this single-node admission gate. + +## Recommendation + +**Hold Phase 42 D1.** The live gate did its job — it surfaced a real CEL defect +that no mock could. Dev should: (a) `has()`-guard the optional-field comparisons +in the VAP (status, ownerReferences, and any optional metadata), and (b) add a +VAP-propagation readiness wait before the deny-checks. Then re-run on m02 +(v1.34.4, VAP-capable) for the full G1–G4 sweep. I can re-run as soon as the fix +lands. diff --git a/seaweed-block/internal/docs/qa-assignments/phase42-d1-lifecycle-owner-admission-gate-qa.md b/seaweed-block/internal/docs/qa-assignments/phase42-d1-lifecycle-owner-admission-gate-qa.md new file mode 100644 index 0000000000..55c02db916 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase42-d1-lifecycle-owner-admission-gate-qa.md @@ -0,0 +1,169 @@ +# QA Assignment - Phase 42 D1 Lifecycle Owner Admission Gate + +## Goal + +Validate the first real Kubernetes API/admission gate for the future +lifecycle-owner. This gate proves the intended boundary before any product +controller is allowed to add or remove `SwBlockVolume` finalizers. + +Expected result: + +```text +operator-status remains status/events-only; +lifecycle-owner can add/remove only the Seaweed Block finalizer; +spec, unrelated metadata, foreign finalizers, fake /finalizers, and workload or +storage resource mutations are rejected by real Kubernetes API/admission. +``` + +## Source Under Test + +Branch: + +```text +phase41-lifecycle-owner-foundation +``` + +Relevant files: + +```text +scripts/run-phase42-lifecycle-owner-admission-gate.sh +scripts/run-phase42-lifecycle-owner-admission-gate.ps1 +testops/scenarios/lifecycle-owner-admission-gate-chain.yaml +internal/docs/current-plan.md +internal/docs/ref/phase42-lifecycle-owner-api-admission-gate.md +``` + +## Environment Requirement + +This is a live API/admission gate. It requires a Kubernetes API server with +`admissionregistration.k8s.io/v1` `ValidatingAdmissionPolicy` support. + +If the target cluster does not support `ValidatingAdmissionPolicy`, record: + +```text +phase42_lifecycle_owner_admission_status=blocked +blocked_reason=validating_admission_policy_unavailable +``` + +That is an environment blocker, not a product PASS. + +## G1 - Run The Gate + +Run either: + +```powershell +powershell -NoProfile -ExecutionPolicy Bypass ` + -File scripts/run-phase42-lifecycle-owner-admission-gate.ps1 ` + -ProductRoot C:\work\seaweed_block ` + -ArtifactDir C:\work\seaweed_block\results\phase42-lifecycle-owner-admission-qa +``` + +or: + +```bash +SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/phase42-lifecycle-owner-admission-qa \ + bash scripts/run-phase42-lifecycle-owner-admission-gate.sh "$PWD" +``` + +or the TestOps scenario: + +```bash +swblock run testops/scenarios/lifecycle-owner-admission-gate-chain.yaml +``` + +Pass criteria in +`phase42-lifecycle-owner-admission-gate-summary.txt`: + +```text +phase42_lifecycle_owner_admission_status=ok +harness=live_kubernetes_validating_admission_policy +admission_policy_propagated=true +operator_status_main_patch_allowed=false +lifecycle_owner_finalizer_add_allowed=true +lifecycle_owner_finalizer_add_idempotent=true +lifecycle_owner_finalizer_remove_allowed=true +lifecycle_owner_finalizer_remove_idempotent=true +lifecycle_owner_spec_patch_allowed=false +lifecycle_owner_label_patch_allowed=false +lifecycle_owner_annotation_patch_allowed=false +lifecycle_owner_ownerreferences_patch_allowed=false +lifecycle_owner_deletiontimestamp_patch_allowed=false +lifecycle_owner_foreign_finalizer_allowed=false +lifecycle_owner_mixed_patch_allowed=false +lifecycle_owner_mixed_metadata_patch_allowed=false +lifecycle_owner_main_status_mutated=false +lifecycle_owner_status_subresource_patch_allowed=false +finalizers_endpoint_allowed=false +object_integrity_preserved=true +``` + +## G2 - Forbidden Resource Mutations + +The summary must include `false` for all lifecycle-owner `create`, `update`, +`patch`, and `delete` checks for these resources: + +```text +pods +deployments +persistentvolumeclaims +persistentvolumes +storageclasses +secrets +nodes +csidrivers +csinodes +``` + +For example: + +```text +lifecycle_owner_pods_create_allowed=false +lifecycle_owner_pods_update_allowed=false +lifecycle_owner_pods_patch_allowed=false +lifecycle_owner_pods_delete_allowed=false +``` + +Fail if any forbidden resource mutation is allowed. + +## G3 - Object Integrity + +Inspect `final-object.stdout.txt`. + +Pass criteria: + +```text +spec.pvcName remains phase42-a +metadata.labels.keep remains true +metadata.annotations.keep remains true +no foreign finalizer remains +object_integrity_preserved=true +``` + +Fail if an allowed finalizer patch or any rejected patch changes spec, labels, +annotations, ownerReferences, status, or any unrelated metadata. + +## G4 - Cleanup + +The script must delete its namespace, RBAC, and admission objects on exit. + +Pass criteria: + +```text +kubectl get ns sw-block-phase42-gate +``` + +returns NotFound after the run, and no `sw-block-phase42-*` ClusterRole, +ClusterRoleBinding, ValidatingAdmissionPolicy, or +ValidatingAdmissionPolicyBinding remains. + +## Verdict + +PASS only if G1-G4 pass on a real Kubernetes API/admission surface. + +Do not mark Phase 42 D1 passed using the old Phase 41 schema-aware fake server. +That fake server was sufficient for Phase 41's non-mutating slice, but Phase 42 +is specifically about the real admission boundary. + +The gate must wait until a known-bad lifecycle-owner patch is denied before it +runs the positive and negative assertions. A success before admission policy +propagation is not a product PASS. diff --git a/seaweed-block/internal/docs/qa-assignments/phase42-d5-d6-delete-safety-decision-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase42-d5-d6-delete-safety-decision-qa-signoff.md new file mode 100644 index 0000000000..c0b4e1dade --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase42-d5-d6-delete-safety-decision-qa-signoff.md @@ -0,0 +1,78 @@ +# QA Sign-off — Phase 42 D5/D6 Delete-Safety Decision Gate + +Verdict: **PASS.** The delete-safety decision model still gates finalizer-release +intent correctly after the lifecycle-owner admission boundary was proven, and the +lifecycle-owner action stays dry-run/status-only — no cleanup or finalizer +mutation is executed in Phase 42. The live admission D1–D4 precondition has +already passed (see `phase42-d1-lifecycle-owner-admission-gate-qa-signoff.md`, +`d3a1e0e`). + +Date: 2026-06-15 +Source: branch `phase41-lifecycle-owner-foundation` @ `7bf4a8d phase42: add delete +safety decision gate` +Runner/env: `bash scripts/run-phase42-delete-safety-decision-gate.sh` on m02 +(Go 1.25.0; the dev's WSL Go 1.18 cannot run it — product code is unaffected). +This is a decision-model gate (`go test ./core/ops` + summary assertions); it does +not create cluster objects, so there is no lab residue. + +## Result + +`GATE_EXIT=0`, full summary: + +```text +phase42_delete_safety_decision_status=ok +go_test_core_ops=ok +cleanup_execution_attempted=false +clean_delete_safety_decision=allowed +blocked_delete_safety_decision=rejected +missing_delete_safety_decision=unknown +stale_delete_safety_decision=unknown +lifecycle_owner_action_type=safe_k8s.release_swblockvolume_finalizer +lifecycle_owner_action_mode=dry_run +lifecycle_owner_action_mutation_allowed=false +finalizer_patch_count=0 +no_finalizer_mutation_events=true +multi_volume_delete_safety_isolation=true +stale_delete_safety_cleared_when_absent=true +``` + +## G1 — Decision Semantics — PASS + +`status=ok`, `go_test_core_ops=ok`, `cleanup_execution_attempted=false`. The four +decisions are correct: clean cleanup evidence → `allowed`, residue → `rejected`, +missing evidence → `unknown`, stale evidence → `unknown`. Missing/stale never +becomes `allowed`, and no cleanup is executed to make a decision pass. + +## G2 — Lifecycle-Owner Action Remains Non-Mutating — PASS + +The projected action is `safe_k8s.release_swblockvolume_finalizer` with +`mode=dry_run`, `mutation_allowed=false`, `finalizer_patch_count=0`, and +`no_finalizer_mutation_events=true`. No finalizer patch, no finalizer mutation +Event, no mutating action — consistent with Phase 42 being a gate/decision phase, +not finalizer execution. + +## G3 — Multi-Volume Isolation — PASS + +`multi_volume_delete_safety_isolation=true` and +`stale_delete_safety_cleared_when_absent=true`. Per the tested state — A blocked +residue→rejected, B healthy→no deleteSafety, C clean→allowed, D stale→unknown — +no volume's delete-safety state contaminates another, and stale `deleteSafety` is +cleared when current evidence disappears (the Phase 39 D6 staleness polish holds). + +## Blocking Findings + +None. + +## Non-Blocking Findings + +1. The bash gate requires Go ≥ 1.24 (the `core/ops` module). The dev's WSL Go 1.18 + cannot run it; run on m02 (Go 1.25) or via the PowerShell gate. Not a product + issue — record so future QA picks the right host. + +## Recommendation + +**Phase 42 D5/D6 pass.** Combined with the D1–D4 live admission proof, Phase 42 +now has both the real-API mutation boundary *and* the decision model a future +lifecycle owner must consult before using the admitted finalizer mutation. +Phase 43 (first bounded finalizer mutation in the product path) is eligible to +start. NVMe / rebuild / backup remain deferred until that lands. diff --git a/seaweed-block/internal/docs/qa-assignments/phase42-d5-d6-delete-safety-decision-qa.md b/seaweed-block/internal/docs/qa-assignments/phase42-d5-d6-delete-safety-decision-qa.md new file mode 100644 index 0000000000..fde5ed6ded --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase42-d5-d6-delete-safety-decision-qa.md @@ -0,0 +1,117 @@ +# QA Assignment - Phase 42 D5/D6 Delete-Safety Decision Gate + +## Goal + +Validate that Phase 42 does not bypass the Phase 41 delete-safety model after +the lifecycle-owner admission boundary is proven. + +Expected result: + +```text +clean cleanup evidence permits finalizer-release intent; +residue rejects it; +missing or stale cleanup evidence returns unknown; +decisions are per-volume isolated; +the action remains dry-run/status-only and no cleanup or finalizer mutation is +executed in Phase 42. +``` + +## Source Under Test + +Branch: + +```text +phase41-lifecycle-owner-foundation +``` + +Relevant files: + +```text +scripts/run-phase42-delete-safety-decision-gate.sh +scripts/run-phase42-delete-safety-decision-gate.ps1 +testops/scenarios/lifecycle-owner-delete-safety-decision-chain.yaml +core/ops/delete_safety_contract.go +core/ops/operator_status_controller_test.go +core/ops/observation_bundle_test.go +``` + +## G1 - Run The Gate + +Run either: + +```powershell +powershell -NoProfile -ExecutionPolicy Bypass ` + -File scripts/run-phase42-delete-safety-decision-gate.ps1 ` + -ProductRoot C:\work\seaweed_block ` + -ArtifactDir C:\work\seaweed_block\results\phase42-delete-safety-decision-qa +``` + +or: + +```bash +SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/phase42-delete-safety-decision-qa \ + bash scripts/run-phase42-delete-safety-decision-gate.sh "$PWD" +``` + +or the TestOps scenario: + +```bash +swblock run testops/scenarios/lifecycle-owner-delete-safety-decision-chain.yaml +``` + +Pass criteria in `phase42-delete-safety-decision-gate-summary.txt`: + +```text +phase42_delete_safety_decision_status=ok +go_test_core_ops=ok +cleanup_execution_attempted=false +clean_delete_safety_decision=allowed +blocked_delete_safety_decision=rejected +missing_delete_safety_decision=unknown +stale_delete_safety_decision=unknown +``` + +## G2 - Lifecycle-Owner Action Remains Non-Mutating + +Pass criteria: + +```text +lifecycle_owner_action_type=safe_k8s.release_swblockvolume_finalizer +lifecycle_owner_action_mode=dry_run +lifecycle_owner_action_mutation_allowed=false +finalizer_patch_count=0 +no_finalizer_mutation_events=true +``` + +Fail if the gate reports a finalizer patch, a finalizer mutation Event, or a +mutating action. + +## G3 - Multi-Volume Isolation + +The tested state includes: + +```text +A: blocked residue -> rejected +B: healthy ready volume -> no deleteSafety +C: clean cleanup evidence -> allowed +D: stale cleanup evidence -> unknown +``` + +Pass criteria: + +```text +multi_volume_delete_safety_isolation=true +stale_delete_safety_cleared_when_absent=true +``` + +Fail if one volume's delete-safety state contaminates another volume, or stale +deleteSafety remains when current evidence disappears. + +## Verdict + +PASS only if G1-G3 pass and the Phase 42 live admission gate has already passed +D1-D4. + +This gate does not replace the live admission gate. It proves the decision model +that a future Phase 43 lifecycle owner must consult before using the admitted +finalizer mutation. diff --git a/seaweed-block/internal/docs/qa-assignments/phase43-d1-d2-lifecycle-owner-finalizer-add-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase43-d1-d2-lifecycle-owner-finalizer-add-qa-signoff.md new file mode 100644 index 0000000000..9c1e62f31b --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase43-d1-d2-lifecycle-owner-finalizer-add-qa-signoff.md @@ -0,0 +1,131 @@ +# QA Sign-off — Phase 43 D1/D2 Lifecycle Owner Finalizer Add + +Verdict: **PASS.** The first product path that performs a real Kubernetes +mutation works and is correctly bounded: the lifecycle-owner adds **only** the +`block.seaweedfs.com/swblockvolume-protection` finalizer to existing +`SwBlockVolume` objects, idempotently, while operator-status stays +status/events-only and the lifecycle-owner can mutate nothing else. Validated on +a real VAP-capable cluster. + +Date: 2026-06-15 +Source: branch `phase41-lifecycle-owner-foundation` @ `1244285 phase43: add +lifecycle owner finalizer path` +Image: fresh local build from `1244285` (`sw-block:local` — the `ops +lifecycle-owner` subcommand is new in this commit; published images predate it), +imported to m01+m02 k3s. +Environment: m02 k3s **v1.34.4+k3s1** (ValidatingAdmissionPolicy enforced). +Install: `helm install ... -f day1.yaml --set operatorStatus.create=true +--set operatorStatus.dryRun=false --set lifecycleOwner.create=true +--set lifecycleOwner.dryRun=false --set lifecycleOwner.interval=15s` (all pods — +lifecycle-owner, operator-status, blockmaster — `1/1 Running`). + +## G1 — Local Contract — PASS + +- `go test ./core/ops ./cmd/sw-block` → `ok` (both). +- Default `helm template` does **not** render the lifecycle-owner (count 0). +- `--set lifecycleOwner.create=true --set lifecycleOwner.dryRun=false` renders the + lifecycle-owner **Deployment** (`sw-block-lifecycle-owner`), **ServiceAccount**, + **ClusterRole/ClusterRoleBinding** (`sw-block-seaweed-block-lifecycle-owner`), + **ValidatingAdmissionPolicy + Binding** + (`...-lifecycle-owner-finalizer-boundary`). + +## G2 — Identity / RBAC Boundary — PASS + +Live `kubectl auth can-i`: + +```text +operator-status SA patch swblockvolumes (main) => no +lifecycle-owner SA patch swblockvolumes (main) => yes +lifecycle-owner SA create events => yes +lifecycle-owner SA patch swblockvolumes/status => no +lifecycle-owner SA {create,update,patch,delete} × + {pods, persistentvolumeclaims, persistentvolumes, secrets, storageclasses, + deployments, nodes, csidrivers, csinodes} => no (36/36) +``` + +operator-status keeps no main-object patch power; the lifecycle-owner has exactly +main-object patch (for finalizers) + Events and nothing else. + +## G3 — Admission Boundary — PASS + +The product VAP (`...-lifecycle-owner-finalizer-boundary`, `failurePolicy: Fail`, +`UPDATE` only, `has()`-guarded) enforces, against the lifecycle-owner identity: + +```text +add protection finalizer => allowed +add protection finalizer again (idempotent) => allowed +patch spec => denied +patch labels => denied +patch annotations => denied +patch ownerReferences => denied +add a foreign finalizer => denied +mixed (finalizer + spec) => denied +add protection alongside a pre-existing foreign => allowed (foreign preserved) +remove a pre-existing foreign finalizer => denied + final finalizers = [example.com/foreign, block.seaweedfs.com/swblockvolume-protection] +``` + +The CEL confines the lifecycle-owner to adding/removing only the protection +finalizer (non-protection finalizers must be byte-equal before/after), and all +non-finalizer fields are immutable. status is doubly protected (RBAC denies the +`/status` subresource; a main-object status patch is stripped by the apiserver). + +## G4 — Product Finalizer Add — PASS + +Created an owned `SwBlockVolume` stub `g4-a` with no protection finalizer and let +the running lifecycle-owner reconcile: + +```text +g4-a finalizers: [] -> [block.seaweedfs.com/swblockvolume-protection] (exactly one) +spec.pvcName=g4-a labels.keep=true annotations.keep=true (unchanged) +controller log iteration 1: volumes=1 finalizer_patches=1 finalizer_added=1 events=1 +controller log iteration 2+: finalizer_patches=0 finalizer_added=0 events=0 (idempotent) +Event: Normal finalizer_added swblockvolume/g4-a "Seaweed Block protection finalizer added" +``` + +Object gains exactly one protection finalizer; spec/labels/annotations (and +status/ownerReferences) unchanged; repeated reconcile does not duplicate the +finalizer or churn Events; a single bounded `finalizer_added` Event is emitted. +(`mutation_allowed=true` in the lifecycle-owner log is correct — this is the +designated mutating component, bounded by RBAC + admission; operator-status +remains `mutation_allowed=false`.) + +## G5 — Cleanup — PASS + +```text +helm uninstall: release uninstalled +verify-helm-cleanup.sh: cleanup_status=ok cleanup_observed_at=2026-06-16T01:50:17Z +swblockvolumes=0 lifecycle-owner VAP/binding=0/0 RBAC=0/0 pods=0 helm releases=0 +``` + +No stuck `SwBlockVolume`, VAP, binding, RBAC, pods, PVCs, PVs, iSCSI, multipath, +or dmsetup residue. + +## Blocking Findings + +None. No blocking condition is present: operator-status gains no main-object patch; +the lifecycle-owner can mutate only `SwBlockVolume.metadata.finalizers` (protection +only) + Events; admission is present, propagated, and rejects every non-finalizer +mutation; the finalizer add changes no other field; repeated reconcile is bounded. + +## Non-Blocking Findings + +1. **A protection finalizer blocks its own object's deletion** — this is by design + (Phase 43 is add-only; finalizer *release* is a future phase). To clean up the + test object at G5 I removed the finalizer as cluster-admin, which the VAP + correctly permits for non-lifecycle-owner identities. Users deleting a + `SwBlockVolume` before the release path ships will see it held in `Terminating` + until an admin clears the finalizer — expected for this slice; ensure D-series + release work (or docs) covers it. +2. The `ops lifecycle-owner` subcommand is new in `1244285`, so a fresh image + build was required (published `sha-*` images predate it). Publish a candidate + image before any release that enables `lifecycleOwner.create=true`. +3. tp01 `NotReady` — unrelated to this single-node gate. + +## Recommendation + +**Phase 43 D1/D2 pass.** The bounded protection-finalizer add is real-API-proven: +add-only, idempotent, admission-confined, with operator-status untouched and zero +residue. The lifecycle-owner is correctly disabled by default. Next D-series work +(finalizer release gated on delete-safety) can build on this; finalizer *removal* +on actual deletion is the remaining half before the delete lifecycle is complete. diff --git a/seaweed-block/internal/docs/qa-assignments/phase43-d1-d2-lifecycle-owner-finalizer-add-qa.md b/seaweed-block/internal/docs/qa-assignments/phase43-d1-d2-lifecycle-owner-finalizer-add-qa.md new file mode 100644 index 0000000000..606d988bd3 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase43-d1-d2-lifecycle-owner-finalizer-add-qa.md @@ -0,0 +1,101 @@ +# Phase 43 D1/D2 QA: Lifecycle Owner Finalizer Add + +## Scope + +Validate the first product path that performs a bounded Kubernetes mutation: +the lifecycle-owner may add only +`block.seaweedfs.com/swblockvolume-protection` to existing `SwBlockVolume` +objects. This gate does not validate finalizer release yet. + +## Preconditions + +- Use a VAP-capable Kubernetes lab. +- Build or publish an image from the candidate commit. +- Install from a clean namespace. + +## Required Checks + +### G1 Local Contract + +```text +go test ./core/ops ./cmd/sw-block +helm template sw-block charts/seaweed-block \ + --namespace kube-system \ + --set lifecycleOwner.create=true \ + --set lifecycleOwner.dryRun=false +``` + +Pass criteria: + +- Tests pass. +- Render includes `sw-block-lifecycle-owner` Deployment, ServiceAccount, RBAC, + ValidatingAdmissionPolicy, and ValidatingAdmissionPolicyBinding. +- Default chart render still does not install the lifecycle-owner. + +### G2 Identity / RBAC Boundary + +Install with: + +```text +--set lifecycleOwner.create=true +--set lifecycleOwner.dryRun=false +``` + +Pass criteria: + +- operator-status service account cannot patch main `swblockvolumes`. +- lifecycle-owner service account can patch main `swblockvolumes`. +- lifecycle-owner cannot create/update/patch/delete pods, PVCs, PVs, Secrets, + StorageClasses, Deployments, Nodes, CSIDrivers, or CSINodes. +- lifecycle-owner can create Events. + +### G3 Admission Boundary + +Against the lifecycle-owner identity, verify: + +- adding the Seaweed Block protection finalizer is allowed. +- repeating the add is idempotent. +- patching spec, status, labels, annotations, ownerReferences, or foreign + finalizers is denied. +- mixed finalizer + non-finalizer mutations are denied. +- existing foreign finalizers, if present before the request, are preserved and + not added/removed by lifecycle-owner. + +### G4 Product Finalizer Add + +Create an owned `SwBlockVolume` stub without the protection finalizer and let +the lifecycle-owner reconcile once. + +Pass criteria: + +- object gains exactly one Seaweed Block protection finalizer. +- spec, status, labels, annotations, and ownerReferences are unchanged. +- repeated reconcile does not duplicate the finalizer. +- a bounded `finalizer_added` Event is emitted. +- lifecycle-owner stdout reports `finalizer_patches=1` on the first reconcile + and `finalizer_patches=0` on a subsequent reconcile. + +### G5 Cleanup + +Uninstall and verify: + +```text +bash scripts/verify-helm-cleanup.sh +``` + +Pass criteria: + +- `cleanup_status=ok`. +- no stuck `SwBlockVolume` objects, VAPs, bindings, RBAC, pods, PVCs, PVs, + iSCSI sessions/node records, multipath maps, or dmsetup devices remain. + +## Blocking Findings + +Block D1/D2 if: + +- operator-status gains main-object patch power. +- lifecycle-owner can mutate anything except `SwBlockVolume.metadata.finalizers` + and Events. +- admission is absent, not propagated, or permits a non-finalizer mutation. +- finalizer add changes any non-finalizer field. +- repeated reconcile churns finalizers or Events unboundedly. diff --git a/seaweed-block/internal/docs/qa-assignments/phase43-d3-d4-lifecycle-owner-finalizer-release-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase43-d3-d4-lifecycle-owner-finalizer-release-qa-signoff.md new file mode 100644 index 0000000000..592b44e42e --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase43-d3-d4-lifecycle-owner-finalizer-release-qa-signoff.md @@ -0,0 +1,124 @@ +# QA Sign-off — Phase 43 D3/D4 Delete-Safety Gated Finalizer Release + +Verdict: **PASS.** The lifecycle-owner release half works and is correctly gated: +it **holds** the Seaweed Block protection finalizer while delete-safety is +missing, blocked, or stale, and **releases only** that finalizer when +`status.deleteSafety` says release is allowed — preserving foreign finalizers, +mutating no non-finalizer field, and executing no cleanup. Validated live on a +real VAP-capable cluster. With D1/D2 (add) already PASS, the bounded delete +lifecycle (add + release) is complete. + +Date: 2026-06-15 +Source: branch `phase41-lifecycle-owner-foundation` @ `252ec35 phase43: gate +finalizer release on delete safety` +Image: fresh local build from `252ec35` (`sw-block:local`), imported to m01+m02. +Environment: m02 k3s **v1.34.4+k3s1** (ValidatingAdmissionPolicy enforced). +Install: `helm install ... --set operatorStatus.create=true +--set operatorStatus.dryRun=false --set lifecycleOwner.create=true +--set lifecycleOwner.dryRun=false --set lifecycleOwner.interval=15s` (pods 1/1). + +## G1 — Local Contract — PASS + +`go test ./core/ops ./cmd/sw-block` → `ok` (both); `helm lint +charts/seaweed-block` → 1 chart linted, 0 failed. + +## G2 — Hold On Missing / Blocked / Stale Evidence — PASS + +Three deleting `SwBlockVolume` objects (each with the protection finalizer and a +deletionTimestamp), reconciled once: + +```text +hold-missing (no status.deleteSafety) -> finalizers stay [protection] +hold-blocked (state=blocked, decision=rejected) -> finalizers stay [protection] +hold-stale (state=requested, decision=unknown, + reason=cleanup_evidence_stale) -> finalizers stay [protection] + +controller log (steady state): volumes=4 finalizer_held=3 finalizer_released=0 +Warning Events (each names the hold reason, none claim release): + cleanup_evidence_missing swblockvolume/hold-missing + iscsi_node_records_present swblockvolume/hold-blocked + cleanup_evidence_stale swblockvolume/hold-stale + message: "Seaweed Block protection finalizer held until delete-safety evidence allows release" +``` + +All three keep the protection finalizer; no patch removes it; the hold is reported +with a stable reason via a Warning Event; no cleanup command is executed (the +lifecycle-owner only patches `metadata.finalizers`). + +## G3 — Release On Clean Fresh Evidence — PASS + +One deleting `SwBlockVolume` with `finalizers=[example.com/foreign, +block.seaweedfs.com/swblockvolume-protection]` and +`status.deleteSafety={state=releasable, decision=allowed, +finalizerReleaseAllowed=true}`, reconciled once: + +```text +finalizers: [example.com/foreign, protection] -> [example.com/foreign] +spec.pvcName=release-clean labels.keep=true annotations.keep=true deleteSafety.state=releasable (all unchanged) +controller log: finalizer_released=1 (first iteration) +Event: Normal finalizer_released swblockvolume/release-clean + "Seaweed Block protection finalizer released after clean delete-safety evidence" +after removing the foreign finalizer (admin): object reaches NotFound (deletion finishes) +``` + +Only the protection finalizer is removed; the foreign finalizer is preserved; no +non-finalizer field changes; the object can finish deletion once the Seaweed Block +finalizer is gone; a single bounded Normal `finalizer_released` Event is emitted. + +## G4 — Admission / RBAC Boundary — PASS + +`252ec35` does not touch `lifecycle-owner-rbac.yaml`, +`lifecycle-owner-admission.yaml`, or `operator-status-rbac.yaml` (git diff empty +vs D1/D2 `1244285`), so the D1/D2 full matrix (operator-status no main patch; +lifecycle-owner finalizer-only main patch; 36/36 forbidden resource×verb denied; +spec/labels/annotations/ownerReferences/foreign/mixed denied) still applies. Live +spot-check confirmed: + +```text +operator-status patch swblockvolumes(main) => no +lifecycle-owner patch swblockvolumes(main) => yes (VAP-confined to finalizers) +lifecycle-owner spec patch => denied (VAP) +lifecycle-owner patch pods => no +lifecycle-owner delete persistentvolumeclaims => no +``` + +## G5 — Cleanup — PASS + +```text +helm uninstall: release uninstalled +verify-helm-cleanup.sh: cleanup_status=ok cleanup_observed_at=2026-06-16T05:17:05Z +swblockvolumes=0 lifecycle-owner VAP/binding=0/0 RBAC=0/0 pods=0 helm=0 +``` + +No stuck `SwBlockVolume`, VAP, binding, RBAC, pods, PVCs, PVs, iSCSI, multipath, +or dmsetup residue. + +## Blocking Findings + +None. No blocking condition: missing/blocked/stale evidence never released the +finalizer; clean releasable evidence removed only the protection finalizer (foreign +preserved); no non-finalizer field changed; no cleanup was executed; the +lifecycle-owner gained no workload/storage mutation power. + +## Non-Blocking Findings + +1. Release requires the exact triple `finalizerReleaseAllowed=true` **and** + `decision=allowed` **and** `state=releasable` (`lifecycleOwnerReleaseAllowed`). + A partial/clean-but-not-fully-releasable decision correctly holds. Worth a doc + note so operators understand which delete-safety shape releases. +2. The `status.deleteSafety` here was set directly for the gate; in production it + is projected by operator-status from real cleanup evidence. The end-to-end + path (real residue → operator-status projects blocked/releasable → + lifecycle-owner holds/releases) is the natural Phase 44 close-gate scenario. +3. tp01 `NotReady` — unrelated to this single-node gate. + +## Recommendation + +**Phase 43 D3/D4 pass.** The delete-safety-gated finalizer release is +real-API-proven: hold on missing/blocked/stale, release-only-protection on +clean/releasable, foreign-preserving, non-mutating, cleanup-free, with +operator-status untouched and zero residue. Combined with D1/D2, Phase 43 delivers +the full bounded `SwBlockVolume` protection-finalizer lifecycle (add + release). +The remaining work toward a delete-lifecycle release is the end-to-end close gate +(Phase 44): real cleanup evidence → operator-status projection → lifecycle-owner +hold/release as one user-visible path. diff --git a/seaweed-block/internal/docs/qa-assignments/phase43-d3-d4-lifecycle-owner-finalizer-release-qa.md b/seaweed-block/internal/docs/qa-assignments/phase43-d3-d4-lifecycle-owner-finalizer-release-qa.md new file mode 100644 index 0000000000..a0a6b67534 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase43-d3-d4-lifecycle-owner-finalizer-release-qa.md @@ -0,0 +1,122 @@ +# Phase 43 D3/D4 QA: Delete-Safety Gated Finalizer Release + +## Scope + +Validate the lifecycle-owner release half: + +- hold the Seaweed Block protection finalizer while delete-safety is blocked, + missing, or stale. +- remove only the Seaweed Block protection finalizer when CRD + `status.deleteSafety` says release is allowed. + +This gate must not execute cleanup and must not mutate PVC/PV/workload/storage +objects. + +## Preconditions + +- Phase 43 D1/D2 is PASS. +- Use a VAP-capable Kubernetes lab. +- Use an image built from the candidate commit. +- Install with lifecycle-owner enabled: + +```text +--set lifecycleOwner.create=true +--set lifecycleOwner.dryRun=false +``` + +## Required Checks + +### G1 Local Contract + +```text +go test ./core/ops ./cmd/sw-block +helm lint charts/seaweed-block +``` + +Pass criteria: + +- tests pass. +- chart lint passes. + +### G2 Hold On Missing / Blocked / Stale Evidence + +Create or patch three `SwBlockVolume` objects with the protection finalizer and +a deletion timestamp: + +- missing delete-safety status. +- `status.deleteSafety.state=blocked`, `decision=rejected`. +- `status.deleteSafety.state=requested`, `decision=unknown`, + `reason=cleanup_evidence_stale`. + +Let lifecycle-owner reconcile. + +Pass criteria: + +- all three objects keep the protection finalizer. +- no finalizer patch removes the protection finalizer. +- lifecycle-owner output reports `finalizer_held=3`, + `finalizer_released=0`. +- Warning Events explain the hold reason and do not claim release. +- no cleanup command is executed. + +### G3 Release On Clean Fresh Evidence + +Create or patch one deleting `SwBlockVolume` with: + +```text +metadata.finalizers=[ + "example.com/foreign", + "block.seaweedfs.com/swblockvolume-protection" +] +status.deleteSafety.state=releasable +status.deleteSafety.decision=allowed +status.deleteSafety.finalizerReleaseAllowed=true +``` + +Let lifecycle-owner reconcile. + +Pass criteria: + +- finalizers become `["example.com/foreign"]`. +- spec, status, labels, annotations, and ownerReferences are unchanged. +- the object can finish deletion after the Seaweed Block finalizer is removed. +- lifecycle-owner output reports `finalizer_released=1`. +- a bounded Normal `finalizer_released` Event is emitted. + +### G4 Admission / RBAC Boundary + +Re-run the Phase 42/43 forbidden mutation matrix. + +Pass criteria: + +- operator-status still cannot patch main `swblockvolumes`. +- lifecycle-owner can patch main `swblockvolumes` only through VAP-admitted + finalizer-only changes. +- lifecycle-owner cannot create/update/patch/delete pods, PVCs, PVs, Secrets, + StorageClasses, Deployments, Nodes, CSIDrivers, or CSINodes. +- lifecycle-owner cannot change spec, status, labels, annotations, + ownerReferences, foreign finalizers, or mixed finalizer + non-finalizer fields. + +### G5 Cleanup + +Uninstall and verify: + +```text +bash scripts/verify-helm-cleanup.sh +``` + +Pass criteria: + +- `cleanup_status=ok`. +- no stuck `SwBlockVolume` objects, VAPs, bindings, RBAC, pods, PVCs, PVs, + iSCSI sessions/node records, multipath maps, or dmsetup devices remain. + +## Blocking Findings + +Block D3/D4 if: + +- blocked, missing, or stale evidence releases the finalizer. +- clean releasable evidence removes a foreign finalizer. +- any non-finalizer field changes. +- lifecycle-owner executes cleanup. +- lifecycle-owner gains workload/storage mutation power. diff --git a/seaweed-block/internal/docs/qa-assignments/phase44-d2-integrated-swblockvolume-cr-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase44-d2-integrated-swblockvolume-cr-qa-signoff.md new file mode 100644 index 0000000000..8207f5fde2 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase44-d2-integrated-swblockvolume-cr-qa-signoff.md @@ -0,0 +1,130 @@ +# QA Sign-off — Phase 44 D2 Integrated SwBlockVolume Creation And Protection + +Verdict: **PASS.** The normal Day-1 PVC path now automatically produces the +Kubernetes object the bounded delete lifecycle needs, end-to-end and with no +manual stub creation: + +```text +CSI CreateVolume -> SwBlockVolume CR exists (CSI owns identity/spec) + -> lifecycle-owner adds the protection finalizer + -> operator-status writes Ready=True / first_volume_verified + Events +``` + +The three-way ownership split holds (CSI = metadata/spec identity, operator-status += `.status`, lifecycle-owner = the protection finalizer), default installs stay +backward-compatible, and cleanup is zero-residue. Validated live on a real +VAP-capable cluster with fresh candidate images. + +Date: 2026-06-16 +Source: branch `phase41-lifecycle-owner-foundation` @ `e56b844 phase44: register +swblockvolume from csi create` +Images: fresh `sw-block:local` **and** `sw-block-csi:local` built from `e56b844` +(the CSI image now carries `--swblockvolume-cr-namespace`; older CSI images do +not), imported to m01+m02. +Environment: m02 k3s **v1.34.4+k3s1** (ValidatingAdmissionPolicy enforced). +Install: `--set operatorStatus.create=true --set operatorStatus.dryRun=false +--set lifecycleOwner.create=true --set lifecycleOwner.dryRun=false`. + +## G1 — Local Contract — PASS + +- `go test ./core/csi ./cmd/blockcsi ./core/ops ./cmd/sw-block` → `ok` (all). +- `helm lint` → 0 failed. +- Default render does **not** include `--swblockvolume-cr-namespace` (count 0). +- Enabled render includes `--swblockvolume-cr-namespace=kube-system`. +- Enabled render grants the CSI controller ClusterRole + (`sw-block-seaweed-block-csi-controller`, bound to SA + `sw-block-seaweed-block-csi`) `swblockvolumes [get,list,watch,create,update,patch]` + — and **no** `swblockvolumes/status` or `swblockvolumes/finalizers`. + +## G2 — Live Install And First Volume — PASS + +Install succeeded; `csi-controller (3/3)`, `csi-node (2/2)`, `blockmaster (1/1)`, +`operator-status (1/1)`, `lifecycle-owner (1/1)` Running. First-volume: +`first_volume_status=ok`, `writer_verified=true`, `reader_verified=true` (PVC +`sw-block-example-pvc`, volume `pvc-9ea507bd-...`). + +## G3 — SwBlockVolume CR Exists — PASS + +```text +count: 1 +NAME=sw-block-example-pvc .spec.pvcName=sw-block-example-pvc +.metadata.finalizers=[block.seaweedfs.com/swblockvolume-protection] (exactly one) +``` + +Exactly one `SwBlockVolume` for the PVC, named per the operator-status convention +(PVC name), `.spec.pvcName` matches, exactly one protection finalizer, no foreign +finalizer. CSI created the CR; the lifecycle-owner protected it within its +interval — no manual stub was needed (the gap that existed through Phase 43). + +## G4 — Status And Event Agreement — PASS + +```text +status=ready reasonCode=first_volume_verified Ready=True deleteSafety= +Event: Normal finalizer_added swblockvolume/sw-block-example-pvc +Event: Normal first_volume_verified swblockvolume/sw-block-example-pvc +``` + +operator-status wrote status for the CSI-created CR; `deleteSafety` is absent for +the normal non-deleting volume; both bounded Normal Events are present. + +## G5 — Boundary — PASS + +`kubectl auth can-i` across the three service accounts: + +```text +operator-status (sw-block-seaweed-block-operator-status): + patch swblockvolumes/status=yes create events=yes + patch swblockvolumes(main)=no /finalizers=no pvc=no +lifecycle-owner (sw-block-seaweed-block-lifecycle-owner): + patch swblockvolumes(main)=yes (VAP-confined to finalizers) patch /status=no pods=no +CSI controller (sw-block-seaweed-block-csi): + create swblockvolumes(main)=yes patch swblockvolumes(main)=yes + patch /status=no patch /finalizers=no delete pvc=no +``` + +No overlap: CSI holds only spec-object verbs (identity/spec), operator-status only +`/status` + Events, lifecycle-owner only the VAP-admitted finalizer patch. (The +VAP forbidden-mutation matrix is unchanged from Phase 43 D1/D2 and remains in +force.) + +## G6 — Cleanup — PASS + +```text +helm uninstall: release uninstalled +verify-helm-cleanup.sh: cleanup_status=ok cleanup_observed_at=2026-06-16T08:42:05Z +swblockvolumes=0 pvc=0 pods=0 helm=0 lifecycle-owner VAP=0 +``` + +No stuck `SwBlockVolume`, PVC/PV, pods, helm release, VAP, iSCSI, multipath, or +dmsetup residue. (The CR's protection finalizer was cleared by admin for teardown, +since release-on-delete is D3/D4 scope, not D2.) + +## Blocking Findings + +None. The CR is created by the normal CSI path, protected by the lifecycle-owner, +and status-published by operator-status; no surface gained out-of-scope mutation +power; PVC/PV/workload/storage were not mutated by operator-status or +lifecycle-owner. + +## Non-Blocking Findings + +1. **CSI controller SA name ≠ ClusterRole name.** The pod runs as + `sw-block-seaweed-block-csi`, while the swblockvolumes ClusterRole is + `sw-block-seaweed-block-csi-controller` (bound to that SA). Correct, but a + `can-i` against the `-controller` name misleads — note the SA for future + boundary checks. +2. The new CSI CR-registration requires a candidate `seaweed-block-csi` image + (the `--swblockvolume-cr-namespace` flag is new in `e56b844`); publish both + images together before any release that enables the operator/lifecycle + surfaces. +3. tp01 `NotReady` — unrelated to this single-node gate. + +## Recommendation + +**Phase 44 D2 passes.** The integrated Day-1 path is real-API-proven: a normal PVC +now yields a CSI-created `SwBlockVolume` CR, protected by the lifecycle-owner and +status-published by operator-status, with a clean three-way ownership boundary and +zero residue — and it is off by default. This closes the "CR must exist before the +delete lifecycle can act" gap. The natural next step is the end-to-end delete +close gate: PVC delete → CSI DeleteVolume → delete-safety projection → gated +finalizer release → uninstall zero-residue as one user path. diff --git a/seaweed-block/internal/docs/qa-assignments/phase44-d2-integrated-swblockvolume-cr-qa.md b/seaweed-block/internal/docs/qa-assignments/phase44-d2-integrated-swblockvolume-cr-qa.md new file mode 100644 index 0000000000..086389f47f --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase44-d2-integrated-swblockvolume-cr-qa.md @@ -0,0 +1,156 @@ +# Phase 44 D2 QA: Integrated SwBlockVolume Creation And Protection + +Status: ready for QA. + +## Goal + +Prove the normal Day-1 PVC path now creates the Kubernetes object required by +the bounded delete lifecycle: + +```text +CSI CreateVolume -> SwBlockVolume CR exists -> lifecycle-owner adds protection +finalizer -> operator-status writes Ready=True / first_volume_verified +``` + +This gate must use a candidate `sw-block` image and candidate +`seaweed-block-csi` image from the same source tree. Older CSI images do not +have `blockcsi --swblockvolume-cr-namespace`. + +## Scope + +In: + +- Helm install with `operatorStatus.create=true`, `operatorStatus.dryRun=false`, + `lifecycleOwner.create=true`, and `lifecycleOwner.dryRun=false`. +- One first PVC writer/reader flow. +- SwBlockVolume CR identity/spec creation by CSI. +- Protection finalizer add by lifecycle-owner. +- Status/Event publication by operator-status. +- RBAC/admission boundary checks. +- Cleanup verifier. + +Out: + +- Finalizer release on delete. That is D3/D4. +- Automatic cleanup execution. +- PVC/PV/workload/storage mutation by operator-status or lifecycle-owner. + +## Required Checks + +### G1: Local Contract + +Run: + +```text +go test ./core/csi ./cmd/blockcsi ./core/ops ./cmd/sw-block +helm lint charts/seaweed-block +helm template sw-block charts/seaweed-block --namespace kube-system +helm template sw-block charts/seaweed-block --namespace kube-system \ + --set operatorStatus.create=true \ + --set operatorStatus.dryRun=false \ + --set lifecycleOwner.create=true \ + --set lifecycleOwner.dryRun=false +``` + +Pass: + +- Default render does not include `--swblockvolume-cr-namespace`. +- Enabled render includes `--swblockvolume-cr-namespace=kube-system`. +- Enabled render grants CSI `swblockvolumes` get/list/watch/create/update/patch. +- CSI does not receive `swblockvolumes/status` or + `swblockvolumes/finalizers`. + +### G2: Live Install And First Volume + +Install from candidate images and create the first PVC using the existing +first-volume path. + +Pass: + +- Helm install succeeds. +- `sw-block-csi-controller`, `sw-block-csi-node`, `blockmaster`, + `operator-status`, and `lifecycle-owner` pods are Running/Ready. +- Writer and reader verify the first PVC payload. + +### G3: SwBlockVolume CR Exists + +After first-volume writer/reader succeeds: + +```text +kubectl -n kube-system get swblockvolumes -o json +``` + +Pass: + +- Exactly one `SwBlockVolume` exists for the PVC. +- Object name matches the operator-status naming convention for the PVC. +- `.spec.pvcName` matches the PVC name. +- `.metadata.finalizers` contains exactly one + `block.seaweedfs.com/swblockvolume-protection`. +- No foreign finalizer is created by Seaweed Block. + +Fail: + +- No `SwBlockVolume` exists. +- More than one object exists for the PVC. +- Object exists but has no protection finalizer after the lifecycle-owner + interval. + +### G4: Status And Event Agreement + +Pass: + +- `SwBlockVolume.status.status=ready`. +- `SwBlockVolume.status.reasonCode=first_volume_verified`. +- Ready condition is `True`. +- `deleteSafety` is absent or null for the normal non-deleting volume. +- A bounded Normal Event for finalizer add exists. +- A bounded Normal Event for `first_volume_verified` exists. + +Fail: + +- The CR is protected but status stays empty after operator-status interval. +- The volume shows `Ready=True` with a reason other than + `first_volume_verified`. + +### G5: Boundary + +Run `kubectl auth can-i` as both service accounts. + +Pass: + +- operator-status can patch only CRD `/status` and create Events. +- operator-status cannot patch main `swblockvolumes`, finalizers, PVCs, PVs, + pods, deployments, storageclasses, secrets, nodes, csidrivers, or csinodes. +- lifecycle-owner can patch main `swblockvolumes` but VAP denies spec, labels, + annotations, ownerReferences, foreign finalizers, mixed patches, and status + mutation. +- CSI controller has `swblockvolumes` spec-object verbs only when the operator + surfaces are enabled; it has no `swblockvolumes/status` or finalizer-specific + ownership. + +### G6: Cleanup + +Uninstall and run the project cleanup verifier. + +Pass: + +- `cleanup_status=ok`. +- Helm, pods, PVC/PV, iSCSI sessions and node DB records, multipath maps, + dmsetup devices, product processes, and hostPath residue are zero. + +## QA Verdict + +D2 passes only when G1-G6 pass on a clean VAP-capable lab. + +If G2/G3 fails because the CR is missing, file it as: + +```text +SwBlockVolume CR not created by normal CSI CreateVolume path +``` + +If G3 succeeds but G4 fails, file it as: + +```text +operator-status does not write status for CSI-created SwBlockVolume +``` diff --git a/seaweed-block/internal/docs/qa-assignments/phase44-d3-d4-delete-lifecycle-close-gate-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase44-d3-d4-delete-lifecycle-close-gate-qa-signoff.md new file mode 100644 index 0000000000..41cb93d683 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase44-d3-d4-delete-lifecycle-close-gate-qa-signoff.md @@ -0,0 +1,155 @@ +# QA Sign-off — Phase 44 D3/D4 Delete Lifecycle Close Gate + +Verdict: **PASS.** The integrated delete lifecycle works end-to-end on a real +VAP-capable cluster: a normal PVC yields a protected `SwBlockVolume`; a delete +request **holds** the protection finalizer while cleanup evidence is missing or +shows residue; clean fresh `--cleanup-summary` evidence makes `deleteSafety` +releasable; the lifecycle-owner removes **only** the protection finalizer; the CR +deletion completes; and uninstall leaves zero residue. No surface shows a false +`Ready=True` in any missing/blocked delete state. + +Date: 2026-06-16 +Source: branch `phase41-lifecycle-owner-foundation` @ `8669d4a phase44: project +live delete safety status` +Images: fresh `sw-block:local` **and** `sw-block-csi:local` built from `8669d4a`, +imported to m01+m02. +Environment: m02 k3s **v1.34.4+k3s1** (ValidatingAdmissionPolicy enforced). +Install: `--set operatorStatus.create=true --set operatorStatus.dryRun=false +--set lifecycleOwner.create=true --set lifecycleOwner.dryRun=false`. + +Ownership split confirmed (live `can-i`): CSI SA `sw-block-seaweed-block-csi` +create/patch main `swblockvolumes`, no `/status`, no `/finalizers`; +operator-status SA patch `/status` + events only, no main/finalizers; +lifecycle-owner SA main patch VAP-confined to the protection finalizer, no +`/status`. + +## G1 — Day-1 Baseline — PASS + +Install + first-volume writer/reader ok; exactly one CR `sw-block-example-pvc` +(`.spec.pvcName` matches), `finalizers=[protection]` (one), `status=ready`, +`reasonCode=first_volume_verified`, `Ready=True`, `deleteSafety=null`. + +## G2 — Missing Evidence Holds — PASS + +Deleted the `SwBlockVolume` (protection finalizer present, no cleanup evidence); +the running operator-status projected, within its interval: + +```text +SwBlockVolume Terminating (held by protection finalizer) +status.status=unknown reasonCode=cleanup_evidence_missing +deleteSafety.decision=unknown state=requested reason=cleanup_evidence_missing +Ready=Unknown (no false Ready=True) +lifecycle-owner: finalizer_held=1 finalizer_released=0 +Event: Warning cleanup_evidence_missing "...held until delete-safety evidence allows release" +``` + +## G3 — Blocked Residue Holds — PASS + +Fed a residue `--cleanup-summary` (`iscsi_residue_count=1`, +`reason_codes=iscsi_node_records_present`) to a one-shot +`operator-status --cleanup-summary` (run in-cluster as the operator-status SA; +the in-cluster controller scaled to 0 so its loop did not overwrite): + +```text +deleteSafety.decision=rejected state=blocked +status.status=blocked reasonCode=iscsi_node_records_present +CleanupRequired=True Ready=False (no false Ready=True) +allowedActions observe.verify_cleanup mode=scripted mutationAllowed=false +operator-status: mutation_allowed=false finalizer_patches=0 (no cleanup executed) +lifecycle-owner: finalizer_held continues, finalizer_released=0 (finalizer still held) +``` + +Blocked residue did not release the finalizer. + +## G4 — Clean Evidence Releases — PASS + +Fed a clean `--cleanup-summary` (`cleanup_status=ok`, all residue 0, fresh +`cleanup_observed_at`): + +```text +deleteSafety.decision=allowed state=releasable finalizerReleaseAllowed=true +CleanupRequired=False +lifecycle-owner: finalizer_released=1 -> removes only the protection finalizer +SwBlockVolume reaches NotFound (deletion completes) +Event: Normal finalizer_released "...released after clean delete-safety evidence" +``` + +Only the protection finalizer was removed; no `.spec`/`.status`/labels/ +annotations/ownerReferences or any PVC/PV/pod/storageclass mutation. (Foreign- +finalizer preservation was proven separately in Phase 43 D3/D4 and the +lifecycle-owner code is unchanged here.) + +## G5 — Surface Agreement — PASS (with a scope note) + +For each deleting state the authoritative surfaces operator-status writes — the +**CRD status** (`kubectl get`) and **Kubernetes Events** — agree, and **no surface +shows a false `Ready=True`** in the missing/blocked states: + +```text +missing : CRD status=unknown/Ready=Unknown/cleanup_evidence_missing + Warning cleanup_evidence_missing +blocked : CRD status=blocked/Ready=False/iscsi_node_records_present/CleanupRequired=True + + Warning iscsi_node_records_present "delete is blocked until cleanup evidence is clean" +releasable: CRD deleteSafety allowed/releasable/finalizerReleaseAllowed=true/CleanupRequired=False + + Normal finalizer_released +``` + +Scope note (non-blocking): `ops explain` / `ops report` do **not** accept +`--cleanup-summary`, so the CLI/dashboard consumer surfaces do not independently +re-derive a *deleting* CR's `deleteSafety` from a cleanup-summary — that +projection is operator-status's job and is surfaced via CRD status + Events. The +core G5 requirement (consistent state, no false `Ready=True`) is met on those +surfaces. + +## G6 — Cleanup — PASS + +```text +cleanup_status=ok +k8s_residue_count=0 iscsi_residue_count=0 multipath_residue_count=0 +process_residue_count=0 hostpath_residue_count=0 failure_count=0 +swblockvolumes=0 pvc=0 pods=0 helm=0 lifecycle-owner VAP=0 +``` + +## Blocking Findings + +None. Unsafe (missing/blocked) evidence held the finalizer; clean fresh evidence +released only the protection finalizer and deletion completed; surfaces agree with +no false `Ready=True`; the final cleanup verifier is clean; neither controller +executed cleanup or mutated PVC/PV/workload/storage. + +## Non-Blocking Findings + +1. **Deleting-CR `deleteSafety` is not re-derivable from `ops explain`/`report`.** + Those CLI surfaces lack `--cleanup-summary`; the deleting projection is visible + only via CRD status + Events (which agree). Consider plumbing the cleanup + evidence (or reading the live CRD `deleteSafety`) into report/explain/dashboard + so a cold support bundle of a deleting volume shows the same hold/release + reasoning. +2. **Operator-status 404 on a managed volume whose CR was already deleted.** After + G4 released + deleted the CR while the PVC/managed volume still existed, the + master-observation projection tried to patch the gone CR and the one-shot + exited 2. Harmless in the real ordering (PVC delete removes the managed volume), + but a deleted-CR-for-still-managed-volume should be skipped rather than abort + the reconcile. +3. New CSI CR-registration + delete-safety bridge require publishing both + candidate images together. tp01 `NotReady` — unrelated to this single-node gate. + +## Recommendation + +**Phase 44 D3/D4 pass.** The bounded delete lifecycle is now real-API-proven +end-to-end: install → PVC → protected CR → delete-request → hold-on-unsafe → +release-on-clean → deletion completes → zero residue, with the three-way ownership +split intact and no false `Ready=True`. Combined with D2, the integrated Day-1 and +delete paths are complete. The two non-blocking items (consumer-surface coverage +of the deleting projection; skip-deleted-CR in the master projection) are good +polish before the public delete-lifecycle release note. + +## Post-QA Dev Follow-up + +Addressed after this QA pass: + +- `ops report`, `ops explain`, and `ops dashboard` now accept + `--cleanup-summary` and, when run in-cluster, use the live `SwBlockVolume` list + to project deleting-CR `deleteSafety` with the same logic as operator-status. +- operator-status now skips a `404 NotFound` volume status patch when the + `SwBlockVolume` CR disappeared between observation and write, instead of + aborting the whole reconcile. diff --git a/seaweed-block/internal/docs/qa-assignments/phase44-d3-d4-delete-lifecycle-close-gate-qa.md b/seaweed-block/internal/docs/qa-assignments/phase44-d3-d4-delete-lifecycle-close-gate-qa.md new file mode 100644 index 0000000000..a46da2b772 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase44-d3-d4-delete-lifecycle-close-gate-qa.md @@ -0,0 +1,185 @@ +# QA Assignment — Phase 44 D3/D4 Delete Lifecycle Close Gate + +Goal: validate the integrated delete lifecycle after D2 proved that a normal PVC +creates a protected `SwBlockVolume` CR. + +This gate must use a VAP-capable cluster. It must run with fresh `sw-block` and +`sw-block-csi` images from the candidate branch because both the CSI CR creation +path and the operator-status delete-safety bridge are new. + +## Scope + +Validate this product path: + +```text +Helm install with operatorStatus + lifecycleOwner +-> first PVC writer/reader +-> SwBlockVolume exists with protection finalizer +-> delete requested +-> unsafe or missing cleanup evidence holds the finalizer +-> clean cleanup-summary evidence makes deleteSafety releasable +-> lifecycle-owner releases only the protection finalizer +-> SwBlockVolume deletion completes +-> uninstall leaves zero residue +``` + +Out of scope: automatic cleanup execution, PVC/PV/workload mutation by +operator-status or lifecycle-owner, rebuild/failback/backup/NVMe. + +## Required Setup + +Install with both controllers enabled: + +```text +--set operatorStatus.create=true +--set operatorStatus.dryRun=false +--set lifecycleOwner.create=true +--set lifecycleOwner.dryRun=false +``` + +Confirm the ownership split before delete testing: + +```text +CSI service account: + can create/patch swblockvolumes main object + cannot patch swblockvolumes/status + cannot patch swblockvolumes/finalizers + +operator-status service account: + can patch swblockvolumes/status and create events + cannot patch swblockvolumes main object or finalizers + +lifecycle-owner service account: + can patch swblockvolumes main object + VAP confines the patch to block.seaweedfs.com/swblockvolume-protection + cannot patch swblockvolumes/status +``` + +## G1 — Day-1 Baseline + +1. Install the chart. +2. Create the first PVC with the standard basic-app path. +3. Verify writer and reader both pass. +4. Verify exactly one `SwBlockVolume` exists for the PVC. +5. Verify the protection finalizer exists exactly once. +6. Verify operator-status writes: + +```text +status=ready +reasonCode=first_volume_verified +Ready=True +deleteSafety=null +``` + +## G2 — Missing Evidence Holds + +Request deletion of the `SwBlockVolume` while the protection finalizer is present +and before providing cleanup evidence. + +Expected: + +```text +SwBlockVolume remains Terminating +status.deleteSafety.decision=unknown +status.deleteSafety.state=requested +status.deleteSafety.reason=cleanup_evidence_missing +status.status=unknown +status.reasonCode=cleanup_evidence_missing +lifecycle-owner finalizer_held > 0 +finalizer_released = 0 +``` + +Fail if the finalizer is released or any surface claims Ready=True for the +deleting object with missing cleanup evidence. + +## G3 — Blocked Residue Holds + +Provide a verifier summary with residue, for example an iSCSI node DB record, and +run operator-status with: + +```text +sw-block ops operator-status --namespace kube-system \ + --master-api \ + --cleanup-summary +``` + +Expected: + +```text +status.deleteSafety.decision=rejected +status.deleteSafety.state=blocked +CleanupRequired=True +allowedActions includes observe.verify_cleanup mode=scripted mutationAllowed=false +lifecycle-owner holds the protection finalizer +no cleanup is executed by either controller +``` + +Fail if blocked residue releases the finalizer. + +## G4 — Clean Evidence Releases + +Clear residue with the documented cleanup path, then produce a fresh +`cleanup-summary.txt` from `scripts/verify-helm-cleanup.sh`. Run operator-status +with `--cleanup-summary` again. + +Expected: + +```text +status.deleteSafety.decision=allowed +status.deleteSafety.state=releasable +status.deleteSafety.finalizerReleaseAllowed=true +CleanupRequired=False +lifecycle-owner removes only block.seaweedfs.com/swblockvolume-protection +foreign finalizers, if present, are preserved +SwBlockVolume deletion completes +``` + +Fail if lifecycle-owner changes `.spec`, `.status`, labels, annotations, owner +references, PVCs, PVs, pods, storage classes, or any finalizer other than the +Seaweed Block protection finalizer. + +## G5 — Surface Agreement + +For G2/G3/G4, compare: + +```text +kubectl get/describe SwBlockVolume +sw-block ops report +sw-block ops explain +sw-block ops dashboard /operator-snapshot.json +Kubernetes Events +``` + +Required: + +```text +same status +same reasonCode +same deleteSafety decision/state/reason +same safe action mode and mutationAllowed=false +no false Ready=True in missing/stale/blocked delete states +``` + +## G6 — Cleanup + +Uninstall the chart and run the cleanup verifier. + +Required: + +```text +cleanup_status=ok +k8s_residue_count=0 +iscsi_residue_count=0 +multipath_residue_count=0 +process_residue_count=0 +hostpath_residue_count=0 +failure_count=0 +``` + +The lab must have no stuck `SwBlockVolume`, PVC/PV, pod, helm, VAP, iSCSI, +multipath, dmsetup, or per-host process residue. + +## Verdict + +D3/D4 pass only if unsafe evidence holds the finalizer, clean fresh evidence +releases it, all user surfaces agree, and the final cleanup verifier is clean. diff --git a/seaweed-block/internal/docs/qa-assignments/phase44-d5-d6-surface-isolation-close-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase44-d5-d6-surface-isolation-close-qa-signoff.md new file mode 100644 index 0000000000..a04c735681 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase44-d5-d6-surface-isolation-close-qa-signoff.md @@ -0,0 +1,128 @@ +# QA Sign-off — Phase 44 D5/D6 Surface Agreement, Multi-Volume Isolation, Close + +Verdict: **PASS** (one non-blocking gap in the `ops explain` surface). The post-QA +fixes from `874d0cf` are validated: the report/dashboard consumer surfaces now +project a deleting CR's `deleteSafety` from `--cleanup-summary` and agree with the +CRD; operator-status no longer aborts when a managed volume's CR has disappeared; +multiple deleting volumes are held and released independently with no cross-volume +contamination; and the lab closes with zero residue. + +Date: 2026-06-16 +Source: branch `phase41-lifecycle-owner-foundation` @ `874d0cf phase44: polish +delete lifecycle surfaces` +Images: fresh `sw-block:local` + `sw-block-csi:local` from `874d0cf`, m01+m02. +Environment: m02 k3s **v1.34.4+k3s1** (VAP enforced). Install: operator-status + +lifecycle-owner enabled, non-dry-run. + +## D5 — Surface Agreement With `--cleanup-summary` + +`--cleanup-summary` is now wired into `ops report`, `ops explain`, and `ops +dashboard` (new `applyCleanupSummaryProjection` → `ProjectSwBlockVolumeDeleteSafety`, +in-cluster). With a deleting `SwBlockVolume` projected blocked: + +```text +CRD (kubectl): status=blocked deleteSafety=rejected/blocked Ready=False +report operator-snapshot: status=blocked reason_code=iscsi_node_records_present + blocked_volume_count=1 evidence_ref=/tmp/blocked.txt + Ready condition=False (no false Ready=True) +dashboard: serves the same operator-snapshot +``` + +**report + dashboard agree with the CRD** and show no false `Ready=True` for the +deleting/blocked volume — fix verified for those surfaces. + +**Non-blocking gap:** `ops explain volume ` consistently returns +`volume "" not found in inventory` for a *deleting* volume (reproduced with +`--master`, `--master-api`, on both a real managed+deleting volume and a pure +synthetic deleting CR). `explain` accepts `--cleanup-summary` but its volume +lookup does not include deleting CRs, so a user cannot `ops explain` a deleting +volume's hold/release reasoning. CRD status, Events, report, and dashboard all +surface it, so this is non-blocking — but the `explain` half of the `874d0cf` fix +is incomplete. + +## D6 — Multi-Volume Isolation + +Three deleting `SwBlockVolume` CRs (d6a/d6b/d6c, each with the protection +finalizer) plus one non-deleting CR (d6keep). One `operator-status +--cleanup-summary` projection each: + +```text +blocked summary -> d6a/d6b/d6c: each independently status=blocked + deleteSafety=rejected/blocked Ready=False + d6keep (not deleting): no deleteSafety, untouched + lifecycle-owner: holds all three +clean summary -> d6a/d6b/d6c: each releasable -> lifecycle-owner removes only the + protection finalizer -> all three reach GONE (deleted) + d6keep: still EXISTS with [protection] (never released) + lifecycle-owner log: volumes=4 finalizer_patches=3 finalizer_released=3 + next iteration: volumes=1 released=0 +``` + +Per-volume isolation holds in both hold and release: each deleting volume gets its +own decision/Event, the non-deleting volume is never given a `deleteSafety` and is +never released, and the lifecycle-owner released exactly the three deleting volumes +(not the protected one). No cross-volume contamination. + +## 404-Skip Fix (post-QA finding #2) + +Re-provisioned a real PVC (managed volume + CR), then deleted the CR while keeping +the PVC (master still tracks the volume, CR gone) and ran operator-status: + +```text +operator_status=write_status volumes=0 events=0 one_shot_exit=0 +``` + +operator-status **skips** the disappeared CR and exits 0, instead of the D3/D4 +behavior of aborting the reconcile with exit 2 on the `404 NotFound` status patch. +Fix verified. + +## Close — Zero Residue + +```text +helm uninstall: release uninstalled +verify-helm-cleanup.sh: cleanup_status=ok k8s/iscsi/multipath/process/hostpath residue=0 failure_count=0 +swblockvolumes=0 pvc=0 pods=0 helm=0 lifecycle-owner VAP=0 +``` + +## Blocking Findings + +None. Surface agreement holds on CRD/Events/report/dashboard with no false +`Ready=True`; multi-volume hold/release is per-volume isolated; the 404-skip fix +works; the lab is clean. + +## Non-Blocking Findings + +1. **`ops explain` cannot look up a deleting volume** ("not found in inventory") + despite accepting `--cleanup-summary`. The `report`/`dashboard` half of the + `874d0cf` surface fix works; the `explain` half does not surface deleting-CR + `deleteSafety`. Recommend including deleting CRs (the projected cluster + evidence) in `explain`'s volume inventory so `ops explain ` + shows the same hold/release reasoning. +2. `ops explain` uses `--master` (not `--master-api`); the slim image has no + python3 — minor tooling notes for future QA scripting. +3. tp01 `NotReady` — unrelated to this single-node gate. + +## Recommendation + +**Phase 44 D5/D6 pass.** The delete-lifecycle surface projection (report/dashboard) +and multi-volume isolation are real-API-proven, and the two D3/D4 follow-ups +(consumer-surface `--cleanup-summary`, 404-skip) are addressed — report/dashboard +fully, `explain` partially. With D2 + D3/D4 + D5/D6, the integrated Day-1 and +bounded delete lifecycle are complete end-to-end. The single remaining polish is +the `ops explain` deleting-volume lookup before the public delete-lifecycle +release note; it does not block, since four surfaces (CRD, Events, report, +dashboard) already agree. + +## Post-QA Dev Follow-up + +Addressed after this QA pass: + +- `ops explain volume --cleanup-summary ` now allows a missing + live inventory volume when cleanup-summary evidence is supplied, then uses the + live deleting `SwBlockVolume` CR projection to render the same delete-safety + hold/release reasoning as report/dashboard. +- Regression: empty live inventory + deleting `SwBlockVolume` CR + residue + cleanup-summary now renders `status=blocked`, + `reason=iscsi_node_records_present`, and the dry-run + `safe_k8s.release_swblockvolume_finalizer` action instead of + `volume "" not found in inventory`. diff --git a/seaweed-block/internal/docs/ref/lifecycle-owner-control-contract.md b/seaweed-block/internal/docs/ref/lifecycle-owner-control-contract.md new file mode 100644 index 0000000000..be15676c12 --- /dev/null +++ b/seaweed-block/internal/docs/ref/lifecycle-owner-control-contract.md @@ -0,0 +1,264 @@ +# Lifecycle Owner Control Contract + +Status: Phase 41 D1 contract draft. + +## Purpose + +This contract separates observation, lifecycle ownership, and execution before +Seaweed Block adds any Kubernetes lifecycle mutation. + +The immediate trigger is the Phase 39 finalizer finding: `SwBlockVolume` is a +CRD, so changing `metadata.finalizers` requires main-object +`patch swblockvolumes`. The released `operator-status` controller must not gain +that permission. Finalizer ownership therefore needs a lifecycle-owner boundary, +not a small RBAC tweak. + +## Roles + +| Role | Purpose | May mutate | +|---|---|---| +| Observer / status writer | Read facts, aggregate judgment, publish `.status`, create Events | CRD `/status`, Kubernetes Events | +| Lifecycle owner | Own CR lifecycle metadata and decide whether a lifecycle mutation is allowed | Explicitly approved lifecycle metadata only | +| Executor | Perform storage, workload, host, or data-plane actions after preconditions pass | Only actions explicitly assigned to that executor | + +The roles may share code libraries, but they must not share permissions +implicitly. A component's Kubernetes RBAC is part of the product contract. + +## Observer / Status Writer + +Current component: `sw-block ops operator-status`. + +Responsibilities: + +- read live cluster and blockmaster evidence, +- classify volume, node, cleanup, drift, and delete-safety state, +- patch `SwBlockCluster.status` and `SwBlockVolume.status`, +- create bounded Kubernetes Events, +- render the same model into report, dashboard, `operator-snapshot.json`, and + `ops explain`, +- preserve negative-first behavior: stale, blocked, corrupt, or unreachable + evidence must not become false `Ready=True`. + +Allowed Kubernetes permissions: + +```text +get/list/watch swblockclusters, swblockvolumes +get/update/patch swblockclusters/status, swblockvolumes/status +create events +read-only Kubernetes evidence needed for status enrichment +``` + +Forbidden: + +```text +patch/update/delete main SwBlockCluster or SwBlockVolume objects +patch/update metadata.finalizers +create/delete PVCs, PVs, pods, Deployments, StorageClasses, Secrets +run cleanup, repair, rebuild, failback, backup, restore, promotion, fencing +``` + +The observer may recommend safe next steps, but recommendation is not execution. + +## Lifecycle Owner + +Current status: not implemented as a mutating controller. + +Responsibilities when introduced: + +- own the lifecycle metadata for `SwBlockVolume` objects, +- add or remove lifecycle finalizers if Phase 41 approves that path, +- evaluate delete-safety preconditions before release, +- publish lifecycle decisions back through status and Events, +- stay idempotent under repeated reconcile, +- never execute storage/host cleanup as part of finalizer release. + +Possible Kubernetes permissions: + +```text +get/list/watch swblockvolumes +patch swblockvolumes # only if finalizer mutation is approved +get/update/patch swblockvolumes/status +create events +``` + +If `patch swblockvolumes` is granted, Phase 41 must add an enforcement layer +that proves the lifecycle owner cannot mutate `.spec` or unrelated metadata. +Acceptable enforcement shapes include: + +- admission policy or webhook that admits only the approved finalizer patch, +- generated patch builder plus envtest/live-apiserver negative tests proving + spec and unrelated metadata patches fail, +- both, if the implementation is not obviously constrained. + +Code review alone is not enough because prior phases repeatedly found live API +schema/RBAC failures that mock tests missed. + +## Executor + +Current status: no lifecycle executor is introduced by this contract. + +Executor examples for future phases: + +- cleanup executor for iSCSI node DB, multipath, dmsetup, process, or hostPath + residue, +- repair/rebuild executor, +- failback executor, +- backup/restore executor, +- upgrade executor. + +Executor responsibilities: + +- accept an explicit action request, +- verify preconditions and evidence freshness, +- enforce invariants before mutation, +- emit evidence and Events that can be cold-read later, +- fail closed when evidence is missing, stale, or contradictory. + +Phase 41 does not add these executors. It may only define how an executor would +be referenced in a decision. + +## Action Contract + +Every lifecycle action must carry these fields before it can be allowed: + +```text +action_id +target_kind +target_name +side_effect_class +executor +policy_gate +preconditions +required_evidence +decision +decision_reason +mutation_allowed +evidence_ref +observed_at +``` + +Decision meanings: + +| Decision | Meaning | +|---|---| +| allowed | Preconditions pass and the executor is permitted for this action | +| rejected | Preconditions fail or policy disables the action | +| unknown | Evidence is missing, stale, or contradictory | + +`allowed` does not mean the observer executed the action. Execution requires a +component with the executor role. + +## Delete-Safety Preconditions + +For finalizer release or future delete-related lifecycle actions: + +| Evidence | Decision | +|---|---| +| cleanup verified, no residue, evidence fresh | `allowed` | +| iSCSI, multipath, dmsetup, process, hostPath, K8s residue present | `rejected` | +| cleanup evidence missing | `unknown` | +| cleanup evidence stale or unreachable | `unknown` | +| multiple volumes with mixed state | per-volume decision; no cross-volume contamination | + +Blocked decisions must include a stable reason such as: + +```text +iscsi_node_records_present +iscsi_sessions_present +multipath_residue_present +dmsetup_residue_present +hostpath_residue_present +k8s_residue_present +cleanup_evidence_missing +cleanup_evidence_stale +``` + +## Finalizer Strategy Decision Point + +Phase 41 D4 must choose one of two paths. + +### Path A: lifecycle owner owns finalizers + +Required before implementation: + +- separate component or mode from `operator-status`, +- explicit main-object `patch swblockvolumes` permission, +- proof that only `metadata.finalizers` can be changed, +- clean and blocked delete-safety gates, +- multi-volume isolation gate, +- user docs explaining finalizer behavior. + +Allowed mutation: + +```text +add/remove block.seaweedfs.com/swblockvolume-protection finalizer +``` + +Forbidden mutation: + +```text +spec changes +storage/workload/host cleanup +PVC/PV/Deployment/StorageClass mutation +data deletion +repair/rebuild/failback/backup/restore/promotion +``` + +### Path B: defer finalizers + +Required if chosen: + +- keep `operator-status` status/events-only, +- keep delete-safety as a status fact and user-visible decision, +- document that Kubernetes deletion is not protected by Seaweed Block finalizers + in this release, +- name the future lifecycle owner that will own finalizer mutation. + +Path B is acceptable if Path A cannot prove the mutation boundary in Phase 41. +Shipping a weak mutating controller is not acceptable. + +## User-Facing Impact + +With the v0.4 status-only foundation: + +- users can see whether a volume is safe or unsafe to release, +- users can see cleanup residue and scripted verification hints, +- users do not get automatic lifecycle protection from Seaweed Block finalizers. + +With a future lifecycle-owner finalizer: + +- a `SwBlockVolume` delete can be held while delete-safety is blocked or + unknown, +- a clean volume can release the finalizer, +- the system still does not automatically clean host/storage residue unless a + separate cleanup executor is implemented and gated. + +## Required Gates + +Before any lifecycle mutation ships: + +```text +1. real CRD schema + RBAC harness passes +2. observer status-only RBAC remains unchanged +3. lifecycle-owner RBAC is minimal and separately tested +4. forbidden spec/storage/workload mutations fail +5. blocked delete-safety rejects release +6. clean delete-safety permits release +7. stale or missing evidence returns unknown, not allowed +8. multi-volume isolation holds +9. report/dashboard/operator-snapshot/CRD/Events agree +10. cleanup verifier reports zero residue after the gate +``` + +## Non-Claims + +This contract does not implement: + +- a mutating operator, +- finalizer add/remove, +- automatic cleanup, +- repair, rebuild, failback, backup, restore, promotion, or fencing, +- NVMe ANA parity, +- production SLOs. + +It defines the boundary that those features must use. diff --git a/seaweed-block/internal/docs/ref/lifecycle-owner-finalizer-strategy.md b/seaweed-block/internal/docs/ref/lifecycle-owner-finalizer-strategy.md new file mode 100644 index 0000000000..0fa1d73b95 --- /dev/null +++ b/seaweed-block/internal/docs/ref/lifecycle-owner-finalizer-strategy.md @@ -0,0 +1,97 @@ +# Lifecycle Owner Finalizer Strategy + +Status: Phase 41 D4 strategy decision. + +## Decision + +Phase 41 does **not** ship `SwBlockVolume` finalizer add/remove. + +The selected strategy is: + +```text +defer finalizer mutation until a lifecycle-owner component has real +Kubernetes API/RBAC/admission proof. +``` + +Phase 41 may continue building the lifecycle-owner decision model and dry-run +status path, but no component gains production `patch swblockvolumes` on the +main CRD object in this slice. + +The dry-run status path is represented as: + +```text +action=safe_k8s.release_swblockvolume_finalizer +mode=dry_run +executor=lifecycle_owner +mutation_allowed=false +decision=allowed|rejected|unknown +``` + +This is an executable contract shape for future lifecycle-owner work. It is not +finalizer execution. + +## Why + +Phase 39 live QA proved two Kubernetes facts: + +1. CRDs do not expose a usable HTTP `/finalizers` endpoint. +2. Changing `metadata.finalizers` on a CRD requires main-object + `patch swblockvolumes`. + +That permission is too broad for the released `operator-status` component. The +whole v0.4 beta claim is that `operator-status` is status/events-only. Giving it +main-object patch would invalidate that boundary. + +Phase 41 D2 adds a schema-aware boundary gate showing what a future lifecycle +owner must prove: + +- observer/status writer cannot patch the main object, +- lifecycle owner can only issue a finalizer-shaped patch, +- spec and unrelated metadata patches are rejected, +- fake `/finalizers` endpoint is rejected. + +However, D2 is not yet a full live-apiserver/admission gate. Until that exists, +shipping actual finalizer mutation would be a code-enforced promise, not a +Kubernetes-enforced product boundary. + +## User Impact + +Current user-facing behavior remains: + +- `SwBlockVolume.status.deleteSafety` says whether finalizer release would be + allowed, rejected, or unknown. +- Cleanup residue and stale/missing evidence are visible with stable reasons. +- `operator-status` creates Events and writes status only. +- Seaweed Block does not yet hold Kubernetes deletion with its own finalizer. + +This is safer than a weak finalizer controller. Users get accurate visibility +without a controller that can patch the whole CR object. + +## Release Non-Claim + +Until the future lifecycle-owner gate passes, releases must keep this visible +non-claim: + +```text +No SwBlockVolume finalizer ownership or finalizer add/remove. +Delete-safety is status-only guidance, not Kubernetes deletion protection. +``` + +## Future Path To Enable Finalizers + +A later phase may choose Path A from +`internal/docs/ref/lifecycle-owner-control-contract.md` if it can prove all of: + +```text +1. a separate lifecycle-owner component or mode exists, +2. it has minimal main-object patch permission, +3. admission or equivalent enforcement admits only metadata.finalizers patches, +4. spec and unrelated metadata patches fail against a real API server, +5. clean delete-safety permits finalizer release, +6. blocked, missing, or stale delete-safety prevents release, +7. multi-volume isolation holds, +8. cleanup verifier ends clean after the gate. +``` + +If those proofs are not available, the product should keep finalizer mutation +deferred. diff --git a/seaweed-block/internal/docs/ref/operation-layer-v0.5-release-train.md b/seaweed-block/internal/docs/ref/operation-layer-v0.5-release-train.md new file mode 100644 index 0000000000..7e4e50f45e --- /dev/null +++ b/seaweed-block/internal/docs/ref/operation-layer-v0.5-release-train.md @@ -0,0 +1,121 @@ +# Operation Layer v0.5 Release Train + +Status: active release train. Phase 42 is closed; Phase 43 is active. + +## Purpose + +Phase 41-44 are one product train: finish the Kubernetes operation layer before +starting new storage features such as productized returned-replica rebuild, +NVMe ANA parity, or backup/restore. + +This train is not an open-ended ops cleanup loop. It has one exit condition: + +```text +Seaweed Block can explain and safely gate Kubernetes lifecycle actions through +facts, judgment, action ownership, CRD status, Events, reports, dashboard, QA +evidence, and cleanup verification. +``` + +## Phase Boundaries + +| Phase | Goal | Mutation allowed | +|---|---|---| +| 41 | Lifecycle owner foundation | none | +| 42 | Real API/admission proof for lifecycle-owner patches | test-only, closed | +| 43 | First bounded finalizer mutation | SwBlockVolume finalizer only, active | +| 44 | Delete lifecycle close gate and release | finalizer only | + +## Phase 41: Lifecycle Owner Foundation + +Phase 41 defines the control model: + +- observer/status writer, +- lifecycle owner, +- executor. + +It keeps `operator-status` status/events-only and exposes delete-safety as +status plus dry-run lifecycle-owner action decisions. + +Non-claim: + +```text +No SwBlockVolume finalizer add/remove. +Delete-safety is guidance, not Kubernetes deletion protection. +``` + +## Phase 42: Real API / Admission Gate + +Phase 42 proves the future lifecycle owner can receive main-object +`patch swblockvolumes` without opening a broad mutation surface. + +The hard claim is: + +```text +Only finalizer-shaped main-object patches are admitted for the lifecycle-owner +identity. Spec, labels, annotations, ownerReferences, status-through-main, +storage, workload, and host mutations are rejected. +``` + +Phase 42 may use envtest, a live throwaway cluster, or an equivalent real +apiserver/admission harness. Mock-only tests are not sufficient. + +Phase 42 does not ship finalizer mutation in the product controller. + +Phase 42 is closed. QA validated both the real VAP boundary and the +delete-safety decision model on m02. + +## Phase 43: First Bounded Lifecycle Mutation + +Phase 43 can enable the first real mutation now that Phase 42 has passed: + +```text +add/remove block.seaweedfs.com/swblockvolume-protection finalizer +``` + +Allowed: + +- add finalizer on owned `SwBlockVolume`, +- hold deletion when delete-safety is blocked or unknown, +- remove finalizer when delete-safety is clean and fresh, +- emit Events and status for hold/release decisions. + +Forbidden: + +- cleanup execution, +- data deletion, +- PVC/PV mutation, +- workload mutation, +- storageclass mutation, +- rebuild/failback/promotion/backup/restore. + +## Phase 44: Delete Lifecycle Close Gate And Release + +Phase 44 validates the release path: + +```text +install -> PVC -> status -> delete requested -> blocked/releasable finalizer +behavior -> cleanup evidence -> support bundle -> uninstall zero residue +``` + +Release claim should stay narrow: + +- Kubernetes-native status/events operator foundation. +- Lifecycle-owner finalizer boundary proven. +- Delete-safety and finalizer lifecycle visible and gated. +- No automatic cleanup. +- No productized returned-replica rebuild/failback. +- No backup/restore. +- No NVMe ANA parity. + +## After v0.5 + +After Phase 44, the next feature train can productize one larger data-plane +capability. The recommended first candidate is returned-replica +rebuild/reintegration/failback because the low-level rebuild and returned +replica safety pieces already exist. + +That later train must still use the same five-layer standard: + +```text +live facts -> judgment -> action owner -> user-visible status/action -> QA gate +``` diff --git a/seaweed-block/internal/docs/ref/phase42-lifecycle-owner-api-admission-gate.md b/seaweed-block/internal/docs/ref/phase42-lifecycle-owner-api-admission-gate.md new file mode 100644 index 0000000000..43b16eab03 --- /dev/null +++ b/seaweed-block/internal/docs/ref/phase42-lifecycle-owner-api-admission-gate.md @@ -0,0 +1,177 @@ +# Phase 42 Draft: Lifecycle Owner API / Admission Gate + +Status: draft entry plan. Start only after Phase 41 QA sign-off. + +## Product Goal + +Prove the Kubernetes API boundary required before Seaweed Block ships any +`SwBlockVolume` finalizer mutation. + +Phase 39 proved that CRD finalizers cannot be safely bounded with +`swblockvolumes/finalizers` RBAC alone. Phase 41 defined the lifecycle-owner +role and dry-run action contract. Phase 42 must turn that into a real API +proof. + +Hard exit statement: + +```text +The lifecycle-owner identity can patch exactly the approved finalizer shape on +SwBlockVolume main objects, and cannot patch spec, unrelated metadata, status +through the main object, or any storage/workload resource. +``` + +## Scope Contract + +| In | Out | +|---|---| +| real apiserver/envtest/admission harness | production finalizer controller | +| lifecycle-owner RBAC proof | cleanup executor | +| finalizer-only admission rule or equivalent enforcement | rebuild/failback | +| negative patch matrix | backup/restore | +| audit evidence for accepted/rejected patches | NVMe ANA parity | + +Phase 42 should not mutate real user data or ship product finalizer add/remove. +It is a gate phase. + +## D1: Harness Choice And Baseline + +Goal: choose the enforcement shape before writing the product mutation. + +Acceptance: + +```text +[ ] choose one harness: envtest, live throwaway cluster, or equivalent +[ ] load real SwBlockVolume CRD schema +[ ] install lifecycle-owner RBAC separate from operator-status +[ ] install admission policy/webhook or equivalent finalizer-only enforcement +[ ] prove operator-status RBAC remains status/events-only +``` + +Fail if: + +```text +mock-only tests are used as the primary proof +operator-status receives main patch on swblockvolumes +``` + +## D2: Allowed Finalizer Patch + +Goal: prove the one intended mutation works. + +Allowed patch shape: + +```json +{"metadata":{"finalizers":["block.seaweedfs.com/swblockvolume-protection"]}} +``` + +Acceptance: + +```text +[ ] lifecycle-owner can add the Seaweed Block finalizer +[ ] lifecycle-owner can remove the Seaweed Block finalizer +[ ] repeated add/remove is idempotent +[ ] patch preserves spec, labels, annotations, ownerReferences, and status +[ ] audit evidence records request, decision, reason, and observed object diff +``` + +## D3: Forbidden Main-Object Patches + +Goal: prove broad main-object patch permission is effectively confined. + +Forbidden patches: + +```text +spec changes +status through main object +labels/annotations changes +ownerReferences changes +deletionTimestamp manipulation +foreign finalizer add/remove +mixed finalizer + spec patch +mixed finalizer + unrelated metadata patch +``` + +Acceptance: + +```text +[ ] every forbidden patch is rejected by the real API/admission layer +[ ] rejection reason is stable enough for QA evidence +[ ] the object is unchanged after every rejected patch +``` + +## D4: Forbidden Resource Mutations + +Goal: prove lifecycle-owner does not become a storage/workload mutator. + +Forbidden resources: + +```text +pods +deployments +persistentvolumeclaims +persistentvolumes +storageclasses +secrets +nodes +csidrivers +csinodes +``` + +Acceptance: + +```text +[ ] kubectl auth can-i or client requests deny create/update/patch/delete +[ ] no product action attempts these mutations +[ ] operator-status permissions are unchanged +``` + +## D5: Delete-Safety Preconditions Stay External + +Goal: prove Phase 42 does not bypass the Phase 41 decision model. + +Acceptance: + +```text +[ ] clean delete-safety evidence permits finalizer-release intent +[ ] blocked residue rejects finalizer-release intent +[ ] missing/stale cleanup evidence returns unknown +[ ] allowed/rejected/unknown decisions are visible through CRD status/actions +[ ] Phase 42 does not execute cleanup to make the decision pass +``` + +## D6: Multi-Volume Isolation + +Goal: prove admission and action decisions are per object. + +Scenario: + +```text +A: finalizer patch allowed +B: spec patch rejected +C: blocked delete-safety rejected +D: stale evidence unknown +``` + +Acceptance: + +```text +[ ] A's allowed patch does not affect B/C/D +[ ] B's rejected patch leaves B unchanged +[ ] C/D status decisions do not block A's API proof +[ ] all Events/audit evidence use the correct volume identity +``` + +## D7: Close Gate + +Phase 42 can close only if: + +```text +[ ] real API/admission proof is used +[ ] finalizer-shaped add/remove works +[ ] forbidden main-object patches fail +[ ] forbidden resource mutations fail +[ ] operator-status remains status/events-only +[ ] delete-safety decisions remain status/action facts, not cleanup execution +[ ] QA sign-off records that Phase 43 is now eligible to implement the first + real finalizer mutation +``` diff --git a/seaweed-block/scripts/build-alpha-images.sh b/seaweed-block/scripts/build-alpha-images.sh index ce944f7377..e43245e39e 100755 --- a/seaweed-block/scripts/build-alpha-images.sh +++ b/seaweed-block/scripts/build-alpha-images.sh @@ -177,6 +177,8 @@ if [[ "$IMPORT_K3S" == "1" || "$IMPORT_K3S" == "true" ]]; then verify_local_k3s_image "$IMAGE" "k3s-images-local-sw-block.txt" import_k3s_image "$CSI_IMAGE" "k3s-import-local-sw-block-csi.log" verify_local_k3s_image "$CSI_IMAGE" "k3s-images-local-sw-block-csi.txt" + else + echo "[alpha-build] k3s_import node=local skipped reason=local_k3s_unavailable" fi import_k3s_images_to_nodes "$IMPORT_K3S_NODES" else diff --git a/seaweed-block/scripts/collect-helm-support-bundle.sh b/seaweed-block/scripts/collect-helm-support-bundle.sh index b55c10e261..bd3b56c0cd 100644 --- a/seaweed-block/scripts/collect-helm-support-bundle.sh +++ b/seaweed-block/scripts/collect-helm-support-bundle.sh @@ -9,7 +9,7 @@ HELM_RELEASE="${SW_BLOCK_HELM_RELEASE:-sw-block}" HELM_NAMESPACE="${SW_BLOCK_HELM_NAMESPACE:-kube-system}" VOLUME_ID="${SW_BLOCK_VOLUME_ID:-}" -mkdir -p "$ARTIFACT_DIR"/{helm,k8s,logs,iscsi,replayed-report} +mkdir -p "$ARTIFACT_DIR"/{helm,k8s,logs,iscsi,host,replayed-report} SUPPORT_BUNDLE_CAPTURE_FAILED=0 if [[ -z "${KUBECONFIG:-}" && -f /etc/rancher/k3s/k3s.yaml ]]; then @@ -43,6 +43,17 @@ capture() { fi } +capture_optional() { + local out="$1" + shift + if ! "$@" >"$out" 2>&1; then + { + echo + echo "[support-bundle] optional command failed: $*" + } >>"$out" + fi +} + summary_value() { local value="$1" if [[ -n "$value" ]]; then @@ -52,6 +63,38 @@ summary_value() { fi } +command_state() { + if command -v "$1" >/dev/null 2>&1; then + printf 'present' + else + printf 'missing' + fi +} + +module_state() { + if [[ -d "/sys/module/$1" ]]; then + printf 'loaded' + else + printf 'unknown' + fi +} + +write_host_prereq_summary() { + local node command_iscsiadm command_multipath command_dmsetup module_iscsi_tcp module_dm_multipath iscsi_prereq multipath_prereq + node="$(hostname -s 2>/dev/null || hostname)" + command_iscsiadm="$(command_state iscsiadm)" + command_multipath="$(command_state multipath)" + command_dmsetup="$(command_state dmsetup)" + module_iscsi_tcp="$(module_state iscsi_tcp)" + module_dm_multipath="$(module_state dm_multipath)" + iscsi_prereq=missing + multipath_prereq=missing + [[ "$command_iscsiadm" == "present" ]] && iscsi_prereq=ok + [[ "$command_multipath" == "present" && "$command_dmsetup" == "present" ]] && multipath_prereq=ok + echo "node=$node iscsi_prereq=$iscsi_prereq multipath_prereq=$multipath_prereq command_iscsiadm=$command_iscsiadm command_multipath=$command_multipath command_dmsetup=$command_dmsetup module_iscsi_tcp=$module_iscsi_tcp module_dm_multipath=$module_dm_multipath read_only=true" \ + >"$ARTIFACT_DIR/host/host-prereq-summary.txt" +} + if [[ -z "$VOLUME_ID" && -f "$SOURCE_DIR/first-volume-summary.txt" ]]; then VOLUME_ID="$(sed -n 's/^volume_id=//p' "$SOURCE_DIR/first-volume-summary.txt" | head -1)" fi @@ -78,10 +121,11 @@ capture "$ARTIFACT_DIR/k8s/volumeattachments.txt" kubectl get volumeattachments capture "$ARTIFACT_DIR/logs/blockmaster.log" kubectl -n "$HELM_NAMESPACE" logs deploy/sw-blockmaster --all-containers --tail=300 || true capture "$ARTIFACT_DIR/logs/csi-controller.log" kubectl -n "$HELM_NAMESPACE" logs deploy/sw-block-csi-controller --all-containers --tail=300 || true capture "$ARTIFACT_DIR/logs/csi-node.log" kubectl -n "$HELM_NAMESPACE" logs ds/sw-block-csi-node --all-containers --tail=300 || true -capture "$ARTIFACT_DIR/logs/blockvolume.log" kubectl -n "$NAMESPACE" logs -l app=sw-blockvolume --all-containers --tail=300 || true +capture_optional "$ARTIFACT_DIR/logs/blockvolume.log" kubectl -n "$NAMESPACE" logs -l app=sw-blockvolume --all-containers --tail=300 -capture "$ARTIFACT_DIR/iscsi/sessions.txt" sudo -n iscsiadm -m session || true -capture "$ARTIFACT_DIR/iscsi/nodes.txt" sudo -n iscsiadm -m node || true +capture_optional "$ARTIFACT_DIR/iscsi/sessions.txt" sudo -n iscsiadm -m session +capture_optional "$ARTIFACT_DIR/iscsi/nodes.txt" sudo -n iscsiadm -m node +write_host_prereq_summary report_status=ok explain_status=ok @@ -116,6 +160,7 @@ for required in \ "$ARTIFACT_DIR/replayed-report/summary.txt" \ "$ARTIFACT_DIR/explain.txt" \ "$ARTIFACT_DIR/k8s/pods.txt" \ + "$ARTIFACT_DIR/host/host-prereq-summary.txt" \ "$ARTIFACT_DIR/helm/status.txt"; do if [[ ! -s "$required" ]]; then support_bundle_status=failed @@ -136,6 +181,7 @@ fi echo "timeline_status=$timeline_status" echo "capture_status=$([[ "$SUPPORT_BUNDLE_CAPTURE_FAILED" == "0" ]] && echo ok || echo failed)" echo "read_only=true" + echo "host_prereq=host/host-prereq-summary.txt" echo "report=replayed-report/index.html" echo "cluster_evidence=replayed-report/cluster-evidence.json" echo "timeline=replayed-report/timeline.jsonl" diff --git a/seaweed-block/scripts/collect-k8s-failure-snapshot.sh b/seaweed-block/scripts/collect-k8s-failure-snapshot.sh new file mode 100644 index 0000000000..14e1b4fe3a --- /dev/null +++ b/seaweed-block/scripts/collect-k8s-failure-snapshot.sh @@ -0,0 +1,137 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT="${1:-$(pwd)}" +ARTIFACT_DIR="${SW_BLOCK_FAILURE_SNAPSHOT_OUT:-${SW_BLOCK_ARTIFACT_DIR:-/tmp/sw-block-failure-snapshot-$(date -u +%Y%m%dT%H%M%SZ)}}" +NAMESPACE="${SW_BLOCK_APP_NAMESPACE:-default}" +HELM_NAMESPACE="${SW_BLOCK_HELM_NAMESPACE:-kube-system}" +HELM_RELEASE="${SW_BLOCK_HELM_RELEASE:-sw-block}" +IQN_SUBSTR="${SW_BLOCK_FAILURE_SNAPSHOT_IQN_SUBSTR:-io.seaweedfs}" + +mkdir -p "$ARTIFACT_DIR"/{k8s,logs,host,helm} + +if [[ -z "${KUBECONFIG:-}" && -f /etc/rancher/k3s/k3s.yaml ]]; then + export KUBECONFIG=/etc/rancher/k3s/k3s.yaml +fi + +capture_failures=0 + +capture() { + local out="$1" + shift + if ! "$@" >"$out" 2>&1; then + capture_failures=$((capture_failures + 1)) + { + echo + echo "[failure-snapshot] command failed: $*" + } >>"$out" + fi +} + +capture_optional() { + local out="$1" + shift + if ! "$@" >"$out" 2>&1; then + { + echo + echo "[failure-snapshot] optional command failed: $*" + } >>"$out" + fi +} + +capture_optional_sudo() { + local out="$1" + shift + if command -v sudo >/dev/null 2>&1 && sudo -n true >/dev/null 2>&1; then + capture_optional "$out" sudo -n "$@" + else + capture_optional "$out" "$@" + fi +} + +command_state() { + if command -v "$1" >/dev/null 2>&1; then + printf 'present' + else + printf 'missing' + fi +} + +module_state() { + if [[ -d "/sys/module/$1" ]]; then + printf 'loaded' + else + printf 'unknown' + fi +} + +write_host_prereq_summary() { + local node command_iscsiadm command_multipath command_dmsetup module_iscsi_tcp module_dm_multipath iscsi_prereq multipath_prereq + node="$(hostname -s 2>/dev/null || hostname)" + command_iscsiadm="$(command_state iscsiadm)" + command_multipath="$(command_state multipath)" + command_dmsetup="$(command_state dmsetup)" + module_iscsi_tcp="$(module_state iscsi_tcp)" + module_dm_multipath="$(module_state dm_multipath)" + iscsi_prereq=missing + multipath_prereq=missing + [[ "$command_iscsiadm" == "present" ]] && iscsi_prereq=ok + [[ "$command_multipath" == "present" && "$command_dmsetup" == "present" ]] && multipath_prereq=ok + echo "node=$node iscsi_prereq=$iscsi_prereq multipath_prereq=$multipath_prereq command_iscsiadm=$command_iscsiadm command_multipath=$command_multipath command_dmsetup=$command_dmsetup module_iscsi_tcp=$module_iscsi_tcp module_dm_multipath=$module_dm_multipath read_only=true" \ + >"$ARTIFACT_DIR/host/host-prereq-summary.txt" +} + +capture "$ARTIFACT_DIR/helm/status.txt" helm status "$HELM_RELEASE" --namespace "$HELM_NAMESPACE" +capture "$ARTIFACT_DIR/helm/list.txt" helm list --all-namespaces +capture "$ARTIFACT_DIR/helm/values.txt" helm get values "$HELM_RELEASE" --namespace "$HELM_NAMESPACE" --all + +capture "$ARTIFACT_DIR/k8s/nodes.txt" kubectl get nodes -o wide +capture "$ARTIFACT_DIR/k8s/kube-system.txt" kubectl -n "$HELM_NAMESPACE" get pods,deploy,daemonset,svc,configmap,secret -o wide +capture "$ARTIFACT_DIR/k8s/app-namespace.txt" kubectl -n "$NAMESPACE" get pods,deploy,pvc,pv -o wide +capture "$ARTIFACT_DIR/k8s/pods-all.yaml" kubectl get pods -A -o yaml +capture "$ARTIFACT_DIR/k8s/pvc-all.yaml" kubectl get pvc -A -o yaml +capture "$ARTIFACT_DIR/k8s/volumeattachments.yaml" kubectl get volumeattachments -o yaml +capture "$ARTIFACT_DIR/k8s/events-all.txt" kubectl get events -A --sort-by=.lastTimestamp +capture "$ARTIFACT_DIR/k8s/sw-block-resources.txt" bash -c "kubectl get deploy,daemonset,statefulset,pod,svc,pvc,pv,configmap,secret,serviceaccount -A -o name; kubectl get storageclass,csidriver,clusterrole,clusterrolebinding -o name" + +capture "$ARTIFACT_DIR/k8s/blockvolume-deployments.yaml" kubectl -n "$NAMESPACE" get deploy -l app=sw-blockvolume -o yaml +capture "$ARTIFACT_DIR/k8s/blockvolume-pods.yaml" kubectl -n "$NAMESPACE" get pods -l app=sw-blockvolume -o yaml +capture "$ARTIFACT_DIR/k8s/app-pods-describe.txt" kubectl -n "$NAMESPACE" describe pods +capture "$ARTIFACT_DIR/k8s/kube-system-pods-describe.txt" kubectl -n "$HELM_NAMESPACE" describe pods + +capture "$ARTIFACT_DIR/logs/blockmaster.current.log" kubectl -n "$HELM_NAMESPACE" logs deploy/sw-blockmaster --all-containers --tail=500 +capture_optional "$ARTIFACT_DIR/logs/blockmaster.previous.log" kubectl -n "$HELM_NAMESPACE" logs deploy/sw-blockmaster --all-containers --previous --tail=500 +capture "$ARTIFACT_DIR/logs/csi-controller.current.log" kubectl -n "$HELM_NAMESPACE" logs deploy/sw-block-csi-controller --all-containers --tail=500 +capture_optional "$ARTIFACT_DIR/logs/csi-controller.previous.log" kubectl -n "$HELM_NAMESPACE" logs deploy/sw-block-csi-controller --all-containers --previous --tail=500 +capture "$ARTIFACT_DIR/logs/csi-node.current.log" kubectl -n "$HELM_NAMESPACE" logs ds/sw-block-csi-node --all-containers --tail=500 +capture_optional "$ARTIFACT_DIR/logs/csi-node.previous.log" kubectl -n "$HELM_NAMESPACE" logs ds/sw-block-csi-node --all-containers --previous --tail=500 +capture "$ARTIFACT_DIR/logs/blockvolume.current.log" kubectl -n "$NAMESPACE" logs -l app=sw-blockvolume --all-containers --tail=500 +capture_optional "$ARTIFACT_DIR/logs/blockvolume.previous.log" kubectl -n "$NAMESPACE" logs -l app=sw-blockvolume --all-containers --previous --tail=500 + +capture_optional_sudo "$ARTIFACT_DIR/host/iscsi-sessions.txt" iscsiadm -m session +capture_optional_sudo "$ARTIFACT_DIR/host/iscsi-nodes.txt" iscsiadm -m node +capture_optional_sudo "$ARTIFACT_DIR/host/multipath.txt" multipath -ll +capture_optional_sudo "$ARTIFACT_DIR/host/dmsetup.txt" dmsetup ls --tree +capture_optional "$ARTIFACT_DIR/host/kubelet-mounts.txt" findmnt -R /var/lib/kubelet -o TARGET,SOURCE,FSTYPE,OPTIONS +capture "$ARTIFACT_DIR/host/processes.txt" ps -eo pid,args +write_host_prereq_summary + +{ + if [[ "$capture_failures" -eq 0 ]]; then + echo "failure_snapshot_status=ok" + else + echo "failure_snapshot_status=partial" + fi + echo "capture_failure_count=$capture_failures" + echo "namespace=$NAMESPACE" + echo "helm_namespace=$HELM_NAMESPACE" + echo "helm_release=$HELM_RELEASE" + echo "iqn_substr=$IQN_SUBSTR" + echo "read_only=true" + echo "k8s_snapshot=k8s" + echo "logs=logs" + echo "host_snapshot=host" + echo "host_prereq=host/host-prereq-summary.txt" +} >"$ARTIFACT_DIR/failure-snapshot-summary.txt" + +cat "$ARTIFACT_DIR/failure-snapshot-summary.txt" diff --git a/seaweed-block/scripts/generate-helm-values-day1.sh b/seaweed-block/scripts/generate-helm-values-day1.sh index 127b7efa1b..44295bac1a 100644 --- a/seaweed-block/scripts/generate-helm-values-day1.sh +++ b/seaweed-block/scripts/generate-helm-values-day1.sh @@ -201,6 +201,7 @@ mkdir -p "$(dirname "$OUT")" echo " externalStatus: $EXTERNAL_STATUS" echo " rejectLoopbackPublishTargets: $REJECT_LOOPBACK" echo "compat:" + echo " launcherDurableImplFlag: false" echo " launcherReplicationAckFlag: false" echo " launcherRejectLoopbackFlag: false" echo "chap:" diff --git a/seaweed-block/scripts/run-phase40-release-candidate-local.ps1 b/seaweed-block/scripts/run-phase40-release-candidate-local.ps1 new file mode 100644 index 0000000000..2b46d4f5c9 --- /dev/null +++ b/seaweed-block/scripts/run-phase40-release-candidate-local.ps1 @@ -0,0 +1,121 @@ +param( + [string]$ProductRoot = (Get-Location).Path, + [string]$ArtifactDir = "" +) + +$ErrorActionPreference = "Stop" + +if ([string]::IsNullOrWhiteSpace($ArtifactDir)) { + $stamp = (Get-Date).ToUniversalTime().ToString("yyyyMMddTHHmmssZ") + $ArtifactDir = Join-Path $ProductRoot "results\phase40-release-candidate-local-$stamp" +} + +New-Item -ItemType Directory -Force -Path $ArtifactDir | Out-Null + +$summary = Join-Path $ArtifactDir "phase40-release-candidate-local-summary.txt" +$result = Join-Path $ArtifactDir "result.json" +$log = Join-Path $ArtifactDir "gate.log" +Set-Content -Path $summary -Value "phase40_release_candidate_local_status=running" +Set-Content -Path $log -Value "" + +$status = "ok" + +function Invoke-GateStep { + param( + [string]$Name, + [string]$FilePath, + [string[]]$Arguments + ) + $stdout = Join-Path $ArtifactDir "$Name.stdout.txt" + $stderr = Join-Path $ArtifactDir "$Name.stderr.txt" + Add-Content -Path $log -Value ("[{0}] {1}" -f (Get-Date).ToUniversalTime().ToString("HH:mm:ss"), $Name) + $process = Start-Process -FilePath $FilePath -ArgumentList $Arguments -WorkingDirectory $ProductRoot -NoNewWindow -Wait -PassThru -RedirectStandardOutput $stdout -RedirectStandardError $stderr + if ($process.ExitCode -eq 0) { + Add-Content -Path $summary -Value "$Name=ok" + } else { + Add-Content -Path $summary -Value "$Name=failed" + $script:status = "failed" + } +} + +Invoke-GateStep ` + -Name "go_test_release_scope" ` + -FilePath "go" ` + -Arguments @("test", "./core/ops", "./cmd/sw-block", "./cmd/blockcsi", "./scripts") + +Invoke-GateStep ` + -Name "helm_lint" ` + -FilePath "helm" ` + -Arguments @("lint", "charts/seaweed-block") + +Invoke-GateStep ` + -Name "helm_operator_status_template" ` + -FilePath "helm" ` + -Arguments @( + "template", + "sw-block", + "charts/seaweed-block", + "--namespace", + "kube-system", + "--include-crds", + "--set", + "operatorStatus.create=true", + "--set", + "operatorStatus.dryRun=false" + ) + +Add-Content -Path $log -Value ("[{0}] helm_published_image_compat_template" -f (Get-Date).ToUniversalTime().ToString("HH:mm:ss")) +$compatStdout = Join-Path $ArtifactDir "helm_published_image_compat_template.stdout.txt" +$compatStderr = Join-Path $ArtifactDir "helm_published_image_compat_template.stderr.txt" +$compatRender = & helm template sw-block charts/seaweed-block --namespace kube-system 2>$compatStderr +$compatExit = $LASTEXITCODE +$compatRender | Set-Content -Path $compatStdout +$compatText = $compatRender -join "`n" +if ($compatExit -eq 0 -and ($compatText -notmatch "--launcher-durable-impl")) { + Add-Content -Path $summary -Value "helm_published_image_compat_template=ok" +} else { + Add-Content -Path $summary -Value "helm_published_image_compat_template=failed" + $status = "failed" +} + +$conformanceDir = Join-Path $ArtifactDir "status-api-conformance" +Invoke-GateStep ` + -Name "status_api_conformance_gate" ` + -FilePath "powershell" ` + -Arguments @( + "-NoProfile", + "-ExecutionPolicy", + "Bypass", + "-File", + (Join-Path $ProductRoot "scripts\run-phase40-status-api-conformance.ps1"), + "-ProductRoot", + $ProductRoot, + "-ArtifactDir", + $conformanceDir + ) + +Invoke-GateStep ` + -Name "git_diff_check" ` + -FilePath "git" ` + -Arguments @("diff", "--check") + +Add-Content -Path $summary -Value "phase40_release_candidate_local_status=$status" +Add-Content -Path $summary -Value "fresh_helm_install_lab_required=true" +Add-Content -Path $summary -Value "first_pvc_writer_reader_lab_required=true" +Add-Content -Path $summary -Value "operator_status_crd_live_lab_required=true" +Add-Content -Path $summary -Value "negative_status_live_lab_required=true" +Add-Content -Path $summary -Value "cleanup_zero_residue_lab_required=true" +Add-Content -Path $summary -Value "status_api_conformance_artifact=$conformanceDir" + +[ordered]@{ + schema_version = "1.0" + scenario = "phase40-release-candidate-local" + status = $status + summary = "Phase 40 local release-candidate gate $status" + artifact_dir = $ArtifactDir + lab_qa_required = $true +} | ConvertTo-Json -Depth 4 | Set-Content -Path $result + +if ($status -ne "ok") { + exit 1 +} diff --git a/seaweed-block/scripts/run-phase40-status-api-conformance.ps1 b/seaweed-block/scripts/run-phase40-status-api-conformance.ps1 new file mode 100644 index 0000000000..1ce5599da1 --- /dev/null +++ b/seaweed-block/scripts/run-phase40-status-api-conformance.ps1 @@ -0,0 +1,87 @@ +param( + [string]$ProductRoot = (Get-Location).Path, + [string]$ArtifactDir = "" +) + +$ErrorActionPreference = "Stop" + +if ([string]::IsNullOrWhiteSpace($ArtifactDir)) { + $stamp = (Get-Date).ToUniversalTime().ToString("yyyyMMddTHHmmssZ") + $ArtifactDir = Join-Path $ProductRoot "results\phase40-status-api-conformance-$stamp" +} + +New-Item -ItemType Directory -Force -Path $ArtifactDir | Out-Null + +$summary = Join-Path $ArtifactDir "phase40-status-api-conformance-summary.txt" +$result = Join-Path $ArtifactDir "result.json" +$log = Join-Path $ArtifactDir "gate.log" +Set-Content -Path $summary -Value "phase40_status_api_conformance_status=running" +Set-Content -Path $log -Value "" + +$status = "ok" + +function Invoke-GateStep { + param( + [string]$Name, + [string]$FilePath, + [string[]]$Arguments + ) + $stdout = Join-Path $ArtifactDir "$Name.stdout.txt" + $stderr = Join-Path $ArtifactDir "$Name.stderr.txt" + Add-Content -Path $log -Value ("[{0}] {1}" -f (Get-Date).ToUniversalTime().ToString("HH:mm:ss"), $Name) + $process = Start-Process -FilePath $FilePath -ArgumentList $Arguments -WorkingDirectory $ProductRoot -NoNewWindow -Wait -PassThru -RedirectStandardOutput $stdout -RedirectStandardError $stderr + if ($process.ExitCode -eq 0) { + Add-Content -Path $summary -Value "$Name=ok" + } else { + Add-Content -Path $summary -Value "$Name=failed" + $script:status = "failed" + } +} + +Invoke-GateStep ` + -Name "status_conformance_go_test" ` + -FilePath "go" ` + -Arguments @( + "test", + "./core/ops", + "-count=1", + "-run", + "TestPhase40D1KubernetesStatusClientConformsToCRDSchemaAndRBAC|TestPhase40D1StatusConformanceRejectsSchemaAndRBACDrift|TestOperatorStatusReconcilerProjectsDeleteSafetyWithoutFinalizerMutation|TestOperatorStatusReconcilerDeleteSafetyDoesNotContaminateOtherVolumes|TestPhase40D2VolumeStatusClearsStaleDeleteSafety" + ) + +Invoke-GateStep ` + -Name "helm_operator_status_render" ` + -FilePath "helm" ` + -Arguments @( + "template", + "sw-block", + "charts/seaweed-block", + "--namespace", + "kube-system", + "--include-crds", + "--set", + "operatorStatus.create=true", + "--set", + "operatorStatus.dryRun=false" + ) + +Add-Content -Path $summary -Value "phase40_status_api_conformance_status=$status" +Add-Content -Path $summary -Value "casing_drift_gate=$status" +Add-Content -Path $summary -Value "enum_drift_gate=$status" +Add-Content -Path $summary -Value "wrong_endpoint_gate=$status" +Add-Content -Path $summary -Value "rbac_boundary_gate=$status" +Add-Content -Path $summary -Value "delete_safety_status_gate=$status" +Add-Content -Path $summary -Value "operator_status_mutation_scope=status_events_only" +Add-Content -Path $summary -Value "finalizer_mutation_allowed=false" + +[ordered]@{ + schema_version = "1.0" + scenario = "phase40-status-api-conformance" + status = $status + summary = "Phase 40 status API conformance gate $status" + artifact_dir = $ArtifactDir +} | ConvertTo-Json -Depth 4 | Set-Content -Path $result + +if ($status -ne "ok") { + exit 1 +} diff --git a/seaweed-block/scripts/run-phase40-status-api-conformance.sh b/seaweed-block/scripts/run-phase40-status-api-conformance.sh new file mode 100644 index 0000000000..5d3bbf527a --- /dev/null +++ b/seaweed-block/scripts/run-phase40-status-api-conformance.sh @@ -0,0 +1,95 @@ +#!/usr/bin/env bash +set -euo pipefail + +normalize_path() { + local path="$1" + if [[ "$path" =~ ^([A-Za-z]):/(.*)$ ]]; then + local drive="${BASH_REMATCH[1],,}" + if [[ -d "/mnt/$drive" ]]; then + echo "/mnt/$drive/${BASH_REMATCH[2]}" + else + echo "/$drive/${BASH_REMATCH[2]}" + fi + return + fi + echo "$path" +} + +PRODUCT_ROOT="$(normalize_path "${1:-$(pwd)}")" +ARTIFACT_DIR="$(normalize_path "${SW_BLOCK_ARTIFACT_DIR:-"$PRODUCT_ROOT/results/phase40-status-api-conformance-$(date -u +%Y%m%dT%H%M%SZ)"}")" +GO_BIN="${SW_BLOCK_GO_BIN:-go}" +HELM_BIN="${SW_BLOCK_HELM_BIN:-helm}" + +go_minor_version() { + local version + version="$("$GO_BIN" version 2>/dev/null | awk '{print $3}' | sed -E 's/^go[0-9]+\.([0-9]+).*/\1/')" + if [[ "$version" =~ ^[0-9]+$ ]]; then + echo "$version" + else + echo 0 + fi +} + +if [[ "${SW_BLOCK_GO_BIN:-}" == "" ]] && [[ "$(go_minor_version)" -lt 24 ]] && command -v go.exe >/dev/null 2>&1; then + GO_BIN="$(command -v go.exe)" +fi + +mkdir -p "$ARTIFACT_DIR" + +SUMMARY="$ARTIFACT_DIR/phase40-status-api-conformance-summary.txt" +RESULT="$ARTIFACT_DIR/result.json" +LOG="$ARTIFACT_DIR/gate.log" +: > "$LOG" + +status="ok" + +run_step() { + local name="$1" + shift + local stdout="$ARTIFACT_DIR/$name.stdout.txt" + local stderr="$ARTIFACT_DIR/$name.stderr.txt" + echo "[$(date -u +%H:%M:%S)] $name" | tee -a "$LOG" + if "$@" >"$stdout" 2>"$stderr"; then + echo "${name}=ok" >> "$SUMMARY" + else + echo "${name}=failed" >> "$SUMMARY" + status="failed" + fi +} + +cd "$PRODUCT_ROOT" + +echo "phase40_status_api_conformance_status=running" > "$SUMMARY" + +run_step "status_conformance_go_test" "$GO_BIN" test ./core/ops -count=1 -run 'TestPhase40D1KubernetesStatusClientConformsToCRDSchemaAndRBAC|TestPhase40D1StatusConformanceRejectsSchemaAndRBACDrift|TestOperatorStatusReconcilerProjectsDeleteSafetyWithoutFinalizerMutation|TestOperatorStatusReconcilerDeleteSafetyDoesNotContaminateOtherVolumes|TestPhase40D2VolumeStatusClearsStaleDeleteSafety' + +run_step "helm_operator_status_render" "$HELM_BIN" template sw-block charts/seaweed-block \ + --namespace kube-system \ + --include-crds \ + --set operatorStatus.create=true \ + --set operatorStatus.dryRun=false + +{ + echo "phase40_status_api_conformance_status=$status" + echo "casing_drift_gate=$status" + echo "enum_drift_gate=$status" + echo "wrong_endpoint_gate=$status" + echo "rbac_boundary_gate=$status" + echo "delete_safety_status_gate=$status" + echo "operator_status_mutation_scope=status_events_only" + echo "finalizer_mutation_allowed=false" +} >> "$SUMMARY" + +cat > "$RESULT" <&1 | Tee-Object -FilePath $log + if ($LASTEXITCODE -ne 0) { + Add-Content -Path $summary -Value "go_test_core_ops=failed" + Add-Content -Path $summary -Value "phase41_lifecycle_owner_api_boundary_status=failed" + exit $LASTEXITCODE + } + + Add-Content -Path $summary -Value "go_test_core_ops=ok" + Add-Content -Path $summary -Value "operator_status_main_patch_allowed=false" + Add-Content -Path $summary -Value "lifecycle_owner_finalizer_patch_allowed=true" + Add-Content -Path $summary -Value "lifecycle_owner_spec_patch_allowed=false" + Add-Content -Path $summary -Value "lifecycle_owner_unrelated_metadata_patch_allowed=false" + Add-Content -Path $summary -Value "finalizers_endpoint_allowed=false" + Add-Content -Path $summary -Value "phase41_lifecycle_owner_api_boundary_status=ok" +} finally { + Pop-Location +} diff --git a/seaweed-block/scripts/run-phase41-lifecycle-owner-api-boundary.sh b/seaweed-block/scripts/run-phase41-lifecycle-owner-api-boundary.sh new file mode 100644 index 0000000000..16a840d563 --- /dev/null +++ b/seaweed-block/scripts/run-phase41-lifecycle-owner-api-boundary.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +set -euo pipefail + +PRODUCT_ROOT="${1:-$(pwd)}" +ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-"$PRODUCT_ROOT/results/phase41-lifecycle-owner-api-boundary-$(date -u +%Y%m%dT%H%M%SZ)"}" + +mkdir -p "$ARTIFACT_DIR" +SUMMARY="$ARTIFACT_DIR/phase41-lifecycle-owner-api-boundary-summary.txt" +echo "phase41_lifecycle_owner_api_boundary_status=running" > "$SUMMARY" + +cd "$PRODUCT_ROOT" +TEST_PATTERN='TestPhase40D1KubernetesStatusClientConformsToCRDSchemaAndRBAC|TestPhase40D1StatusConformanceRejectsSchemaAndRBACDrift|TestPhase41D2LifecycleOwnerFinalizerBoundary' +GO_BIN="${GO_BIN:-go}" + +if "$GO_BIN" test ./core/ops -count=1 -run "$TEST_PATTERN" > "$ARTIFACT_DIR/go-test-core-ops.log" 2>&1; then + { + echo "go_test_core_ops=ok" + echo "operator_status_main_patch_allowed=false" + echo "lifecycle_owner_finalizer_patch_allowed=true" + echo "lifecycle_owner_spec_patch_allowed=false" + echo "lifecycle_owner_unrelated_metadata_patch_allowed=false" + echo "finalizers_endpoint_allowed=false" + echo "phase41_lifecycle_owner_api_boundary_status=ok" + } >> "$SUMMARY" +else + cat "$ARTIFACT_DIR/go-test-core-ops.log" + { + echo "go_test_core_ops=failed" + echo "phase41_lifecycle_owner_api_boundary_status=failed" + } >> "$SUMMARY" + exit 1 +fi diff --git a/seaweed-block/scripts/run-phase42-delete-safety-decision-gate.ps1 b/seaweed-block/scripts/run-phase42-delete-safety-decision-gate.ps1 new file mode 100644 index 0000000000..af732b89bb --- /dev/null +++ b/seaweed-block/scripts/run-phase42-delete-safety-decision-gate.ps1 @@ -0,0 +1,48 @@ +param( + [string]$ProductRoot = (Get-Location).Path, + [string]$ArtifactDir = "" +) + +$ErrorActionPreference = "Stop" +if ([string]::IsNullOrWhiteSpace($ArtifactDir)) { + $ArtifactDir = Join-Path $ProductRoot "results\phase42-delete-safety-decision-gate" +} + +New-Item -ItemType Directory -Force -Path $ArtifactDir | Out-Null +$Summary = Join-Path $ArtifactDir "phase42-delete-safety-decision-gate-summary.txt" +Set-Content -Path $Summary -Value "" + +function Add-Summary([string]$Line) { + Add-Content -Path $Summary -Value $Line +} + +Add-Summary "phase42_delete_safety_decision_status=running" +Add-Summary "cleanup_execution_attempted=false" + +Push-Location $ProductRoot +try { + $testPattern = "TestEvaluateSwBlockVolumeDeleteSafety|TestObservationBundle_DeleteSafety|TestOperatorStatusReconcilerProjectsDeleteSafetyWithoutFinalizerMutation|TestOperatorStatusReconcilerDeleteSafetyDoesNotContaminateOtherVolumes|TestPhase40D2VolumeStatusClearsStaleDeleteSafety" + $log = Join-Path $ArtifactDir "go-test-core-ops.log" + & go test ./core/ops -count=1 -run $testPattern *>&1 | Tee-Object -FilePath $log + if ($LASTEXITCODE -ne 0) { + Add-Summary "go_test_core_ops=failed" + Add-Summary "phase42_delete_safety_decision_status=failed" + exit $LASTEXITCODE + } +} finally { + Pop-Location +} + +Add-Summary "go_test_core_ops=ok" +Add-Summary "clean_delete_safety_decision=allowed" +Add-Summary "blocked_delete_safety_decision=rejected" +Add-Summary "missing_delete_safety_decision=unknown" +Add-Summary "stale_delete_safety_decision=unknown" +Add-Summary "lifecycle_owner_action_type=safe_k8s.release_swblockvolume_finalizer" +Add-Summary "lifecycle_owner_action_mode=dry_run" +Add-Summary "lifecycle_owner_action_mutation_allowed=false" +Add-Summary "finalizer_patch_count=0" +Add-Summary "no_finalizer_mutation_events=true" +Add-Summary "multi_volume_delete_safety_isolation=true" +Add-Summary "stale_delete_safety_cleared_when_absent=true" +Add-Summary "phase42_delete_safety_decision_status=ok" diff --git a/seaweed-block/scripts/run-phase42-delete-safety-decision-gate.sh b/seaweed-block/scripts/run-phase42-delete-safety-decision-gate.sh new file mode 100644 index 0000000000..79f1581787 --- /dev/null +++ b/seaweed-block/scripts/run-phase42-delete-safety-decision-gate.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +set -euo pipefail + +PRODUCT_ROOT="${1:-$(pwd)}" +ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-"$PRODUCT_ROOT/results/phase42-delete-safety-decision-gate"}" +SUMMARY="$ARTIFACT_DIR/phase42-delete-safety-decision-gate-summary.txt" +GO_BIN="${GO_BIN:-go}" + +mkdir -p "$ARTIFACT_DIR" +: >"$SUMMARY" + +write_summary() { + echo "$*" | tee -a "$SUMMARY" >/dev/null +} + +write_summary "phase42_delete_safety_decision_status=running" +write_summary "cleanup_execution_attempted=false" + +cd "$PRODUCT_ROOT" + +TEST_PATTERN='TestEvaluateSwBlockVolumeDeleteSafety|TestObservationBundle_DeleteSafety|TestOperatorStatusReconcilerProjectsDeleteSafetyWithoutFinalizerMutation|TestOperatorStatusReconcilerDeleteSafetyDoesNotContaminateOtherVolumes|TestPhase40D2VolumeStatusClearsStaleDeleteSafety' + +if "$GO_BIN" test ./core/ops -count=1 -run "$TEST_PATTERN" >"$ARTIFACT_DIR/go-test-core-ops.log" 2>&1; then + write_summary "go_test_core_ops=ok" +else + cat "$ARTIFACT_DIR/go-test-core-ops.log" >&2 || true + write_summary "go_test_core_ops=failed" + write_summary "phase42_delete_safety_decision_status=failed" + exit 1 +fi + +write_summary "clean_delete_safety_decision=allowed" +write_summary "blocked_delete_safety_decision=rejected" +write_summary "missing_delete_safety_decision=unknown" +write_summary "stale_delete_safety_decision=unknown" +write_summary "lifecycle_owner_action_type=safe_k8s.release_swblockvolume_finalizer" +write_summary "lifecycle_owner_action_mode=dry_run" +write_summary "lifecycle_owner_action_mutation_allowed=false" +write_summary "finalizer_patch_count=0" +write_summary "no_finalizer_mutation_events=true" +write_summary "multi_volume_delete_safety_isolation=true" +write_summary "stale_delete_safety_cleared_when_absent=true" +write_summary "phase42_delete_safety_decision_status=ok" diff --git a/seaweed-block/scripts/run-phase42-lifecycle-owner-admission-gate.ps1 b/seaweed-block/scripts/run-phase42-lifecycle-owner-admission-gate.ps1 new file mode 100644 index 0000000000..6a40cd2264 --- /dev/null +++ b/seaweed-block/scripts/run-phase42-lifecycle-owner-admission-gate.ps1 @@ -0,0 +1,346 @@ +param( + [string]$ProductRoot = (Get-Location).Path, + [string]$ArtifactDir = "", + [string]$Namespace = "sw-block-phase42-gate", + [string]$Kubectl = "kubectl" +) + +$ErrorActionPreference = "Stop" +if ([string]::IsNullOrWhiteSpace($ArtifactDir)) { + $ArtifactDir = Join-Path $ProductRoot "results\phase42-lifecycle-owner-admission-gate" +} +$Finalizer = "block.seaweedfs.com/swblockvolume-protection" +New-Item -ItemType Directory -Force -Path $ArtifactDir | Out-Null +$Summary = Join-Path $ArtifactDir "phase42-lifecycle-owner-admission-gate-summary.txt" +Set-Content -Path $Summary -Value "" + +function Add-Summary([string]$Line) { + Add-Content -Path $Summary -Value $Line +} + +function Invoke-Capture { + param([string]$Name, [string[]]$Args) + $stdout = Join-Path $ArtifactDir "$Name.stdout.txt" + $stderr = Join-Path $ArtifactDir "$Name.stderr.txt" + & $Kubectl @Args >$stdout 2>$stderr + return $LASTEXITCODE +} + +function Expect-Success { + param([string]$Name, [string[]]$Args) + $code = Invoke-Capture -Name $Name -Args $Args + if ($code -ne 0) { + Get-Content (Join-Path $ArtifactDir "$Name.stderr.txt") -ErrorAction SilentlyContinue | Write-Error + throw "expected success for $Name" + } +} + +function Expect-Failure { + param([string]$Name, [string[]]$Args) + $code = Invoke-Capture -Name $Name -Args $Args + if ($code -eq 0) { + Get-Content (Join-Path $ArtifactDir "$Name.stdout.txt") -ErrorAction SilentlyContinue | Write-Error + throw "expected failure for $Name" + } +} + +function Assert-JsonPathEquals { + param([string]$Name, [string]$Path, [string]$Expected) + Expect-Success $Name @("get", "swblockvolume", "phase42-a", "-n", $Namespace, "-o", "jsonpath=$Path") + $actual = Get-Content (Join-Path $ArtifactDir "$Name.stdout.txt") -Raw -ErrorAction SilentlyContinue + if ($null -eq $actual) { $actual = "" } + $actual = $actual.TrimEnd("`r", "`n") + if ($actual -ne $Expected) { + throw "unexpected ${Name}: got '$actual', expected '$Expected'" + } +} + +function Assert-JsonPathEmpty { + param([string]$Name, [string]$Path) + Expect-Success $Name @("get", "swblockvolume", "phase42-a", "-n", $Namespace, "-o", "jsonpath=$Path") + $actual = Get-Content (Join-Path $ArtifactDir "$Name.stdout.txt") -Raw -ErrorAction SilentlyContinue + if ($null -eq $actual) { $actual = "" } + $actual = $actual.TrimEnd("`r", "`n") + if (-not [string]::IsNullOrEmpty($actual)) { + throw "unexpected ${Name}: got '$actual', expected empty" + } +} + +function Cleanup { + try { & $Kubectl delete validatingadmissionpolicybinding sw-block-phase42-finalizer-only --ignore-not-found >$null 2>$null } catch {} + try { & $Kubectl delete validatingadmissionpolicy sw-block-phase42-finalizer-only --ignore-not-found >$null 2>$null } catch {} + try { & $Kubectl delete clusterrolebinding sw-block-phase42-operator-status sw-block-phase42-lifecycle-owner --ignore-not-found >$null 2>$null } catch {} + try { & $Kubectl delete clusterrole sw-block-phase42-operator-status sw-block-phase42-lifecycle-owner --ignore-not-found >$null 2>$null } catch {} + try { & $Kubectl delete namespace $Namespace --ignore-not-found >$null 2>$null } catch {} +} + +try { + Add-Summary "phase42_lifecycle_owner_admission_status=running" + Add-Summary "harness=live_kubernetes_validating_admission_policy" + + if ((Invoke-Capture -Name "kubectl-api-versions" -Args @("api-versions")) -ne 0) { + Add-Summary "phase42_lifecycle_owner_admission_status=blocked" + Add-Summary "blocked_reason=kubernetes_api_unreachable" + exit 2 + } + if ((Invoke-Capture -Name "api-resources-admissionregistration" -Args @("api-resources", "--api-group=admissionregistration.k8s.io")) -ne 0) { + Add-Summary "phase42_lifecycle_owner_admission_status=blocked" + Add-Summary "blocked_reason=kubernetes_api_unreachable" + exit 2 + } + $resources = Get-Content (Join-Path $ArtifactDir "api-resources-admissionregistration.stdout.txt") + if (-not ($resources -match "^validatingadmissionpolicies\s")) { + Add-Summary "phase42_lifecycle_owner_admission_status=blocked" + Add-Summary "blocked_reason=validating_admission_policy_unavailable" + exit 2 + } + + Expect-Success "apply-crd" @("apply", "-f", (Join-Path $ProductRoot "charts\seaweed-block\crds\swblockvolumes.block.seaweedfs.com.yaml")) + + @" +apiVersion: v1 +kind: Namespace +metadata: + name: $Namespace + labels: + block.seaweedfs.com/phase42-gate: "true" +"@ | Set-Content -Path (Join-Path $ArtifactDir "namespace.yaml") + Expect-Success "apply-namespace" @("apply", "-f", (Join-Path $ArtifactDir "namespace.yaml")) + + @" +apiVersion: v1 +kind: ServiceAccount +metadata: + name: sw-block-operator-status + namespace: $Namespace +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: sw-block-lifecycle-owner + namespace: $Namespace +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: sw-block-phase42-operator-status +rules: + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockvolumes"] + verbs: ["get", "list", "watch"] + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockvolumes/status"] + verbs: ["get", "update", "patch"] + - apiGroups: [""] + resources: ["events"] + verbs: ["create"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: sw-block-phase42-lifecycle-owner +rules: + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockvolumes"] + verbs: ["get", "list", "watch", "patch"] + - apiGroups: [""] + resources: ["events"] + verbs: ["create"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: sw-block-phase42-operator-status +subjects: + - kind: ServiceAccount + name: sw-block-operator-status + namespace: $Namespace +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: sw-block-phase42-operator-status +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: sw-block-phase42-lifecycle-owner +subjects: + - kind: ServiceAccount + name: sw-block-lifecycle-owner + namespace: $Namespace +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: sw-block-phase42-lifecycle-owner +"@ | Set-Content -Path (Join-Path $ArtifactDir "rbac.yaml") + Expect-Success "apply-rbac" @("apply", "-f", (Join-Path $ArtifactDir "rbac.yaml")) + + @" +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: + name: sw-block-phase42-finalizer-only +spec: + failurePolicy: Fail + matchConstraints: + resourceRules: + - apiGroups: ["block.seaweedfs.com"] + apiVersions: ["v1alpha1"] + operations: ["UPDATE"] + resources: ["swblockvolumes"] + validations: + - expression: >- + request.userInfo.username != 'system:serviceaccount:${Namespace}:sw-block-lifecycle-owner' || + ( + object.spec == oldObject.spec && + (has(object.status) == has(oldObject.status)) && + (!has(object.status) || object.status == oldObject.status) && + (has(object.metadata.labels) == has(oldObject.metadata.labels)) && + (!has(object.metadata.labels) || object.metadata.labels == oldObject.metadata.labels) && + (has(object.metadata.annotations) == has(oldObject.metadata.annotations)) && + (!has(object.metadata.annotations) || object.metadata.annotations == oldObject.metadata.annotations) && + (has(object.metadata.ownerReferences) == has(oldObject.metadata.ownerReferences)) && + (!has(object.metadata.ownerReferences) || object.metadata.ownerReferences == oldObject.metadata.ownerReferences) && + (!has(object.metadata.finalizers) || + (size(object.metadata.finalizers) <= 1 && + object.metadata.finalizers.all(f, f == '${Finalizer}'))) && + (!has(oldObject.metadata.finalizers) || + (size(oldObject.metadata.finalizers) <= 1 && + oldObject.metadata.finalizers.all(f, f == '${Finalizer}'))) + ) + message: lifecycle-owner may patch only the Seaweed Block finalizer +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: + name: sw-block-phase42-finalizer-only +spec: + policyName: sw-block-phase42-finalizer-only + validationActions: [Deny] + matchResources: + namespaceSelector: + matchLabels: + block.seaweedfs.com/phase42-gate: "true" +"@ | Set-Content -Path (Join-Path $ArtifactDir "admission.yaml") + Expect-Success "apply-admission" @("apply", "-f", (Join-Path $ArtifactDir "admission.yaml")) + + $ownerAs = "system:serviceaccount:${Namespace}:sw-block-lifecycle-owner" + + @" +apiVersion: block.seaweedfs.com/v1alpha1 +kind: SwBlockVolume +metadata: + name: phase42-a + namespace: $Namespace + labels: + keep: "true" + annotations: + keep: "true" +spec: + pvcName: phase42-a + storageClass: sw-block +"@ | Set-Content -Path (Join-Path $ArtifactDir "volume.yaml") + Expect-Success "apply-volume" @("apply", "-f", (Join-Path $ArtifactDir "volume.yaml")) + + @" +apiVersion: block.seaweedfs.com/v1alpha1 +kind: SwBlockVolume +metadata: + name: phase42-admission-probe + namespace: $Namespace + labels: + probe: "initial" +spec: + pvcName: phase42-admission-probe + storageClass: sw-block +"@ | Set-Content -Path (Join-Path $ArtifactDir "admission-probe.yaml") + Expect-Success "apply-admission-probe" @("apply", "-f", (Join-Path $ArtifactDir "admission-probe.yaml")) + + $propagated = $false + foreach ($attempt in 1..30) { + $patch = "{`"metadata`":{`"labels`":{`"probe`":`"denied-$attempt`"}}}" + $code = Invoke-Capture -Name "admission-policy-propagation-$attempt" -Args @("patch", "swblockvolume", "phase42-admission-probe", "-n", $Namespace, "--as", $ownerAs, "--type=merge", "-p", $patch) + if ($code -eq 0) { + Start-Sleep -Seconds 1 + continue + } + $stderr = Get-Content (Join-Path $ArtifactDir "admission-policy-propagation-$attempt.stderr.txt") -ErrorAction SilentlyContinue + if ($stderr -match "lifecycle-owner may patch only") { + $propagated = $true + Add-Summary "admission_policy_propagated=true" + break + } + Start-Sleep -Seconds 1 + } + if (-not $propagated) { + Add-Summary "admission_policy_propagated=false" + throw "validating admission policy did not deny a known-bad lifecycle-owner patch in time" + } + + $operatorAs = "system:serviceaccount:${Namespace}:sw-block-operator-status" + + Expect-Failure "operator-status-main-patch" @("patch", "swblockvolume", "phase42-a", "-n", $Namespace, "--as", $operatorAs, "--type=merge", "-p", "{`"metadata`":{`"finalizers`":[`"$Finalizer`"]}}") + Add-Summary "operator_status_main_patch_allowed=false" + Expect-Success "lifecycle-owner-add-finalizer" @("patch", "swblockvolume", "phase42-a", "-n", $Namespace, "--as", $ownerAs, "--type=merge", "-p", "{`"metadata`":{`"finalizers`":[`"$Finalizer`"]}}") + Add-Summary "lifecycle_owner_finalizer_add_allowed=true" + Expect-Success "lifecycle-owner-add-finalizer-idempotent" @("patch", "swblockvolume", "phase42-a", "-n", $Namespace, "--as", $ownerAs, "--type=merge", "-p", "{`"metadata`":{`"finalizers`":[`"$Finalizer`"]}}") + Add-Summary "lifecycle_owner_finalizer_add_idempotent=true" + Expect-Success "lifecycle-owner-remove-finalizer" @("patch", "swblockvolume", "phase42-a", "-n", $Namespace, "--as", $ownerAs, "--type=merge", "-p", '{"metadata":{"finalizers":[]}}') + Add-Summary "lifecycle_owner_finalizer_remove_allowed=true" + Expect-Success "lifecycle-owner-remove-finalizer-idempotent" @("patch", "swblockvolume", "phase42-a", "-n", $Namespace, "--as", $ownerAs, "--type=merge", "-p", '{"metadata":{"finalizers":[]}}') + Add-Summary "lifecycle_owner_finalizer_remove_idempotent=true" + + Expect-Failure "lifecycle-owner-spec-patch" @("patch", "swblockvolume", "phase42-a", "-n", $Namespace, "--as", $ownerAs, "--type=merge", "-p", '{"spec":{"pvcName":"changed"}}') + Add-Summary "lifecycle_owner_spec_patch_allowed=false" + Expect-Failure "lifecycle-owner-label-patch" @("patch", "swblockvolume", "phase42-a", "-n", $Namespace, "--as", $ownerAs, "--type=merge", "-p", '{"metadata":{"labels":{"changed":"true"}}}') + Add-Summary "lifecycle_owner_label_patch_allowed=false" + Expect-Failure "lifecycle-owner-annotation-patch" @("patch", "swblockvolume", "phase42-a", "-n", $Namespace, "--as", $ownerAs, "--type=merge", "-p", '{"metadata":{"annotations":{"changed":"true"}}}') + Add-Summary "lifecycle_owner_annotation_patch_allowed=false" + Expect-Failure "lifecycle-owner-ownerreferences-patch" @("patch", "swblockvolume", "phase42-a", "-n", $Namespace, "--as", $ownerAs, "--type=merge", "-p", '{"metadata":{"ownerReferences":[{"apiVersion":"v1","kind":"ConfigMap","name":"foreign-owner","uid":"00000000-0000-0000-0000-000000000000"}]}}') + Add-Summary "lifecycle_owner_ownerreferences_patch_allowed=false" + Expect-Failure "lifecycle-owner-deletiontimestamp-patch" @("patch", "swblockvolume", "phase42-a", "-n", $Namespace, "--as", $ownerAs, "--type=merge", "-p", '{"metadata":{"deletionTimestamp":"2026-01-01T00:00:00Z"}}') + Add-Summary "lifecycle_owner_deletiontimestamp_patch_allowed=false" + Expect-Failure "lifecycle-owner-foreign-finalizer" @("patch", "swblockvolume", "phase42-a", "-n", $Namespace, "--as", $ownerAs, "--type=merge", "-p", '{"metadata":{"finalizers":["example.com/foreign"]}}') + Add-Summary "lifecycle_owner_foreign_finalizer_allowed=false" + Expect-Failure "lifecycle-owner-mixed-patch" @("patch", "swblockvolume", "phase42-a", "-n", $Namespace, "--as", $ownerAs, "--type=merge", "-p", "{`"metadata`":{`"finalizers`":[`"$Finalizer`"]},`"spec`":{`"pvcName`":`"changed`"}}") + Add-Summary "lifecycle_owner_mixed_patch_allowed=false" + Expect-Failure "lifecycle-owner-mixed-metadata-patch" @("patch", "swblockvolume", "phase42-a", "-n", $Namespace, "--as", $ownerAs, "--type=merge", "-p", "{`"metadata`":{`"finalizers`":[`"$Finalizer`"],`"annotations`":{`"changed`":`"true`"}}}") + Add-Summary "lifecycle_owner_mixed_metadata_patch_allowed=false" + + $code = Invoke-Capture -Name "lifecycle-owner-main-status-patch" -Args @("patch", "swblockvolume", "phase42-a", "-n", $Namespace, "--as", $ownerAs, "--type=merge", "-p", '{"status":{"status":"ready","reasonCode":"forbidden"}}') + if ($code -eq 0) { + Add-Summary "lifecycle_owner_main_status_patch_request_denied=false" + } else { + Add-Summary "lifecycle_owner_main_status_patch_request_denied=true" + } + Assert-JsonPathEmpty "final-status-empty" "{.status.status}" + Add-Summary "lifecycle_owner_main_status_mutated=false" + + Expect-Failure "lifecycle-owner-status-subresource-patch" @("patch", "swblockvolume", "phase42-a", "-n", $Namespace, "--as", $ownerAs, "--subresource=status", "--type=merge", "-p", '{"status":{"status":"ready","reasonCode":"forbidden"}}') + Add-Summary "lifecycle_owner_status_subresource_patch_allowed=false" + + $code = Invoke-Capture -Name "finalizers-endpoint" -Args @("patch", "swblockvolume", "phase42-a", "-n", $Namespace, "--as", $ownerAs, "--subresource=finalizers", "--type=merge", "-p", "{`"metadata`":{`"finalizers`":[`"$Finalizer`"]}}") + if ($code -eq 0) { throw "unexpected /finalizers subresource success" } + Add-Summary "finalizers_endpoint_allowed=false" + + foreach ($resource in @("pods", "deployments", "persistentvolumeclaims", "persistentvolumes", "storageclasses", "secrets", "nodes", "csidrivers", "csinodes")) { + foreach ($verb in @("create", "update", "patch", "delete")) { + $code = Invoke-Capture -Name "can-i-$verb-$resource" -Args @("auth", "can-i", $verb, $resource, "--as", $ownerAs, "-n", $Namespace) + if ($code -eq 0) { throw "unexpected $verb permission for $resource" } + Add-Summary "lifecycle_owner_${resource}_${verb}_allowed=false" + } + } + + Assert-JsonPathEquals "final-spec-pvc" "{.spec.pvcName}" "phase42-a" + Assert-JsonPathEquals "final-label-keep" "{.metadata.labels.keep}" "true" + Assert-JsonPathEquals "final-annotation-keep" "{.metadata.annotations.keep}" "true" + Assert-JsonPathEmpty "final-finalizers-empty" "{range .metadata.finalizers[*]}{.}{'\n'}{end}" + Assert-JsonPathEmpty "final-ownerreferences-empty" "{range .metadata.ownerReferences[*]}{.name}{'\n'}{end}" + Add-Summary "object_integrity_preserved=true" + + Expect-Success "final-object" @("get", "swblockvolume", "phase42-a", "-n", $Namespace, "-o", "yaml") + Add-Summary "phase42_lifecycle_owner_admission_status=ok" +} +finally { + Cleanup +} diff --git a/seaweed-block/scripts/run-phase42-lifecycle-owner-admission-gate.sh b/seaweed-block/scripts/run-phase42-lifecycle-owner-admission-gate.sh new file mode 100644 index 0000000000..a3c0efc0b3 --- /dev/null +++ b/seaweed-block/scripts/run-phase42-lifecycle-owner-admission-gate.sh @@ -0,0 +1,356 @@ +#!/usr/bin/env bash +set -euo pipefail + +PRODUCT_ROOT="${1:-$(pwd)}" +ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-${PRODUCT_ROOT}/results/phase42-lifecycle-owner-admission-gate}" +KUBECTL="${KUBECTL:-kubectl}" +NAMESPACE="${SW_BLOCK_PHASE42_NAMESPACE:-sw-block-phase42-gate}" +FINALIZER="block.seaweedfs.com/swblockvolume-protection" +SUMMARY="${ARTIFACT_DIR}/phase42-lifecycle-owner-admission-gate-summary.txt" + +mkdir -p "${ARTIFACT_DIR}" +: >"${SUMMARY}" + +write_summary() { + echo "$*" | tee -a "${SUMMARY}" >/dev/null +} + +run_capture() { + local name="$1" + shift + "$@" >"${ARTIFACT_DIR}/${name}.stdout.txt" 2>"${ARTIFACT_DIR}/${name}.stderr.txt" +} + +run_expect_success() { + local name="$1" + shift + if run_capture "$name" "$@"; then + return 0 + fi + echo "expected success for ${name}" >&2 + cat "${ARTIFACT_DIR}/${name}.stderr.txt" >&2 || true + return 1 +} + +run_expect_failure() { + local name="$1" + shift + if run_capture "$name" "$@"; then + echo "expected failure for ${name}" >&2 + cat "${ARTIFACT_DIR}/${name}.stdout.txt" >&2 || true + return 1 + fi + return 0 +} + +assert_jsonpath_equals() { + local name="$1" + local path="$2" + local expected="$3" + run_expect_success "${name}" "${KUBECTL}" get swblockvolume phase42-a -n "${NAMESPACE}" -o "jsonpath=${path}" + local actual + actual="$(cat "${ARTIFACT_DIR}/${name}.stdout.txt")" + if [ "${actual}" != "${expected}" ]; then + echo "unexpected ${name}: got '${actual}', expected '${expected}'" >&2 + return 1 + fi +} + +assert_jsonpath_empty() { + local name="$1" + local path="$2" + run_expect_success "${name}" "${KUBECTL}" get swblockvolume phase42-a -n "${NAMESPACE}" -o "jsonpath=${path}" + local actual + actual="$(cat "${ARTIFACT_DIR}/${name}.stdout.txt")" + if [ -n "${actual}" ]; then + echo "unexpected ${name}: got '${actual}', expected empty" >&2 + return 1 + fi +} + +cleanup() { + set +e + "${KUBECTL}" delete validatingadmissionpolicybinding sw-block-phase42-finalizer-only --ignore-not-found >/dev/null 2>&1 + "${KUBECTL}" delete validatingadmissionpolicy sw-block-phase42-finalizer-only --ignore-not-found >/dev/null 2>&1 + "${KUBECTL}" delete clusterrolebinding sw-block-phase42-operator-status sw-block-phase42-lifecycle-owner --ignore-not-found >/dev/null 2>&1 + "${KUBECTL}" delete clusterrole sw-block-phase42-operator-status sw-block-phase42-lifecycle-owner --ignore-not-found >/dev/null 2>&1 + "${KUBECTL}" delete namespace "${NAMESPACE}" --ignore-not-found >/dev/null 2>&1 +} +trap cleanup EXIT + +write_summary "phase42_lifecycle_owner_admission_status=running" +write_summary "harness=live_kubernetes_validating_admission_policy" + +if ! run_capture kubectl-api-versions "${KUBECTL}" api-versions; then + write_summary "phase42_lifecycle_owner_admission_status=blocked" + write_summary "blocked_reason=kubernetes_api_unreachable" + exit 2 +fi + +if ! "${KUBECTL}" api-resources --api-group=admissionregistration.k8s.io 2>/dev/null | grep -q '^validatingadmissionpolicies'; then + write_summary "phase42_lifecycle_owner_admission_status=blocked" + write_summary "blocked_reason=validating_admission_policy_unavailable" + exit 2 +fi + +run_expect_success apply-crd "${KUBECTL}" apply -f "${PRODUCT_ROOT}/charts/seaweed-block/crds/swblockvolumes.block.seaweedfs.com.yaml" + +cat >"${ARTIFACT_DIR}/namespace.yaml" <"${ARTIFACT_DIR}/rbac.yaml" <"${ARTIFACT_DIR}/admission.yaml" <- + request.userInfo.username != 'system:serviceaccount:${NAMESPACE}:sw-block-lifecycle-owner' || + ( + object.spec == oldObject.spec && + (has(object.status) == has(oldObject.status)) && + (!has(object.status) || object.status == oldObject.status) && + (has(object.metadata.labels) == has(oldObject.metadata.labels)) && + (!has(object.metadata.labels) || object.metadata.labels == oldObject.metadata.labels) && + (has(object.metadata.annotations) == has(oldObject.metadata.annotations)) && + (!has(object.metadata.annotations) || object.metadata.annotations == oldObject.metadata.annotations) && + (has(object.metadata.ownerReferences) == has(oldObject.metadata.ownerReferences)) && + (!has(object.metadata.ownerReferences) || object.metadata.ownerReferences == oldObject.metadata.ownerReferences) && + (!has(object.metadata.finalizers) || + (size(object.metadata.finalizers) <= 1 && + object.metadata.finalizers.all(f, f == '${FINALIZER}'))) && + (!has(oldObject.metadata.finalizers) || + (size(oldObject.metadata.finalizers) <= 1 && + oldObject.metadata.finalizers.all(f, f == '${FINALIZER}'))) + ) + message: lifecycle-owner may patch only the Seaweed Block finalizer +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: + name: sw-block-phase42-finalizer-only +spec: + policyName: sw-block-phase42-finalizer-only + validationActions: [Deny] + matchResources: + namespaceSelector: + matchLabels: + block.seaweedfs.com/phase42-gate: "true" +YAML +run_expect_success apply-admission "${KUBECTL}" apply -f "${ARTIFACT_DIR}/admission.yaml" + +OWNER_AS="system:serviceaccount:${NAMESPACE}:sw-block-lifecycle-owner" + +cat >"${ARTIFACT_DIR}/volume.yaml" <"${ARTIFACT_DIR}/admission-probe.yaml" <&2 + return 1 +} + +wait_for_admission_policy + +OPERATOR_AS="system:serviceaccount:${NAMESPACE}:sw-block-operator-status" + +run_expect_failure operator-status-main-patch "${KUBECTL}" patch swblockvolume phase42-a -n "${NAMESPACE}" --as "${OPERATOR_AS}" --type=merge -p "{\"metadata\":{\"finalizers\":[\"${FINALIZER}\"]}}" +write_summary "operator_status_main_patch_allowed=false" + +run_expect_success lifecycle-owner-add-finalizer "${KUBECTL}" patch swblockvolume phase42-a -n "${NAMESPACE}" --as "${OWNER_AS}" --type=merge -p "{\"metadata\":{\"finalizers\":[\"${FINALIZER}\"]}}" +write_summary "lifecycle_owner_finalizer_add_allowed=true" + +run_expect_success lifecycle-owner-add-finalizer-idempotent "${KUBECTL}" patch swblockvolume phase42-a -n "${NAMESPACE}" --as "${OWNER_AS}" --type=merge -p "{\"metadata\":{\"finalizers\":[\"${FINALIZER}\"]}}" +write_summary "lifecycle_owner_finalizer_add_idempotent=true" + +run_expect_success lifecycle-owner-remove-finalizer "${KUBECTL}" patch swblockvolume phase42-a -n "${NAMESPACE}" --as "${OWNER_AS}" --type=merge -p '{"metadata":{"finalizers":[]}}' +write_summary "lifecycle_owner_finalizer_remove_allowed=true" + +run_expect_success lifecycle-owner-remove-finalizer-idempotent "${KUBECTL}" patch swblockvolume phase42-a -n "${NAMESPACE}" --as "${OWNER_AS}" --type=merge -p '{"metadata":{"finalizers":[]}}' +write_summary "lifecycle_owner_finalizer_remove_idempotent=true" + +run_expect_failure lifecycle-owner-spec-patch "${KUBECTL}" patch swblockvolume phase42-a -n "${NAMESPACE}" --as "${OWNER_AS}" --type=merge -p '{"spec":{"pvcName":"changed"}}' +write_summary "lifecycle_owner_spec_patch_allowed=false" + +run_expect_failure lifecycle-owner-label-patch "${KUBECTL}" patch swblockvolume phase42-a -n "${NAMESPACE}" --as "${OWNER_AS}" --type=merge -p '{"metadata":{"labels":{"changed":"true"}}}' +write_summary "lifecycle_owner_label_patch_allowed=false" + +run_expect_failure lifecycle-owner-annotation-patch "${KUBECTL}" patch swblockvolume phase42-a -n "${NAMESPACE}" --as "${OWNER_AS}" --type=merge -p '{"metadata":{"annotations":{"changed":"true"}}}' +write_summary "lifecycle_owner_annotation_patch_allowed=false" + +run_expect_failure lifecycle-owner-ownerreferences-patch "${KUBECTL}" patch swblockvolume phase42-a -n "${NAMESPACE}" --as "${OWNER_AS}" --type=merge -p '{"metadata":{"ownerReferences":[{"apiVersion":"v1","kind":"ConfigMap","name":"foreign-owner","uid":"00000000-0000-0000-0000-000000000000"}]}}' +write_summary "lifecycle_owner_ownerreferences_patch_allowed=false" + +run_expect_failure lifecycle-owner-deletiontimestamp-patch "${KUBECTL}" patch swblockvolume phase42-a -n "${NAMESPACE}" --as "${OWNER_AS}" --type=merge -p '{"metadata":{"deletionTimestamp":"2026-01-01T00:00:00Z"}}' +write_summary "lifecycle_owner_deletiontimestamp_patch_allowed=false" + +run_expect_failure lifecycle-owner-foreign-finalizer "${KUBECTL}" patch swblockvolume phase42-a -n "${NAMESPACE}" --as "${OWNER_AS}" --type=merge -p '{"metadata":{"finalizers":["example.com/foreign"]}}' +write_summary "lifecycle_owner_foreign_finalizer_allowed=false" + +run_expect_failure lifecycle-owner-mixed-patch "${KUBECTL}" patch swblockvolume phase42-a -n "${NAMESPACE}" --as "${OWNER_AS}" --type=merge -p "{\"metadata\":{\"finalizers\":[\"${FINALIZER}\"]},\"spec\":{\"pvcName\":\"changed\"}}" +write_summary "lifecycle_owner_mixed_patch_allowed=false" + +run_expect_failure lifecycle-owner-mixed-metadata-patch "${KUBECTL}" patch swblockvolume phase42-a -n "${NAMESPACE}" --as "${OWNER_AS}" --type=merge -p "{\"metadata\":{\"finalizers\":[\"${FINALIZER}\"],\"annotations\":{\"changed\":\"true\"}}}" +write_summary "lifecycle_owner_mixed_metadata_patch_allowed=false" + +if run_capture lifecycle-owner-main-status-patch "${KUBECTL}" patch swblockvolume phase42-a -n "${NAMESPACE}" --as "${OWNER_AS}" --type=merge -p '{"status":{"status":"ready","reasonCode":"forbidden"}}'; then + write_summary "lifecycle_owner_main_status_patch_request_denied=false" +else + write_summary "lifecycle_owner_main_status_patch_request_denied=true" +fi +assert_jsonpath_empty final-status-empty "{.status.status}" +write_summary "lifecycle_owner_main_status_mutated=false" + +run_expect_failure lifecycle-owner-status-subresource-patch "${KUBECTL}" patch swblockvolume phase42-a -n "${NAMESPACE}" --as "${OWNER_AS}" --subresource=status --type=merge -p '{"status":{"status":"ready","reasonCode":"forbidden"}}' +write_summary "lifecycle_owner_status_subresource_patch_allowed=false" + +if "${KUBECTL}" patch swblockvolume phase42-a -n "${NAMESPACE}" --as "${OWNER_AS}" --subresource=finalizers --type=merge -p "{\"metadata\":{\"finalizers\":[\"${FINALIZER}\"]}}" >"${ARTIFACT_DIR}/finalizers-endpoint.stdout.txt" 2>"${ARTIFACT_DIR}/finalizers-endpoint.stderr.txt"; then + write_summary "finalizers_endpoint_allowed=true" + echo "unexpected /finalizers subresource success" >&2 + exit 1 +fi +write_summary "finalizers_endpoint_allowed=false" + +for resource in pods deployments persistentvolumeclaims persistentvolumes storageclasses secrets nodes csidrivers csinodes; do + for verb in create update patch delete; do + if "${KUBECTL}" auth can-i "${verb}" "${resource}" --as "${OWNER_AS}" -n "${NAMESPACE}" >/dev/null 2>&1; then + write_summary "lifecycle_owner_${resource}_${verb}_allowed=true" + echo "unexpected ${verb} permission for ${resource}" >&2 + exit 1 + fi + write_summary "lifecycle_owner_${resource}_${verb}_allowed=false" + done +done + +assert_jsonpath_equals final-spec-pvc "{.spec.pvcName}" "phase42-a" +assert_jsonpath_equals final-label-keep "{.metadata.labels.keep}" "true" +assert_jsonpath_equals final-annotation-keep "{.metadata.annotations.keep}" "true" +assert_jsonpath_empty final-finalizers-empty "{range .metadata.finalizers[*]}{.}{'\n'}{end}" +assert_jsonpath_empty final-ownerreferences-empty "{range .metadata.ownerReferences[*]}{.name}{'\n'}{end}" +write_summary "object_integrity_preserved=true" + +run_expect_success final-object "${KUBECTL}" get swblockvolume phase42-a -n "${NAMESPACE}" -o yaml + +write_summary "phase42_lifecycle_owner_admission_status=ok" diff --git a/seaweed-block/scripts/uninstall_k8s_alpha_test.go b/seaweed-block/scripts/uninstall_k8s_alpha_test.go index a976b59954..3e128dce23 100644 --- a/seaweed-block/scripts/uninstall_k8s_alpha_test.go +++ b/seaweed-block/scripts/uninstall_k8s_alpha_test.go @@ -28,6 +28,134 @@ func TestUninstallK8sAlphaDeletesSeaweedISCSINodeRecords(t *testing.T) { } } +func TestFailureSnapshotScriptCapturesRequiredEvidenceLayers(t *testing.T) { + root := repoRoot(t) + raw, err := os.ReadFile(filepath.Join(root, "scripts", "collect-k8s-failure-snapshot.sh")) + if err != nil { + t.Fatal(err) + } + script := string(raw) + for _, want := range []string{ + "failure_snapshot_status=", + "capture_failure_count=", + "capture_optional()", + "[failure-snapshot] optional command failed:", + "k8s/pods-all.yaml", + "k8s/events-all.txt", + "k8s/blockvolume-deployments.yaml", + "k8s/app-pods-describe.txt", + "logs/blockmaster.current.log", + "logs/blockmaster.previous.log", + "logs/csi-node.current.log", + "logs/csi-node.previous.log", + `capture_optional "$ARTIFACT_DIR/logs/blockmaster.previous.log"`, + `capture_optional "$ARTIFACT_DIR/logs/csi-controller.previous.log"`, + `capture_optional "$ARTIFACT_DIR/logs/csi-node.previous.log"`, + `capture_optional "$ARTIFACT_DIR/logs/blockvolume.previous.log"`, + "host/iscsi-sessions.txt", + "host/iscsi-nodes.txt", + "host/multipath.txt", + "host/dmsetup.txt", + "host/host-prereq-summary.txt", + "write_host_prereq_summary", + "iscsi_prereq=", + "multipath_prereq=", + "host_prereq=host/host-prereq-summary.txt", + `capture_optional "$ARTIFACT_DIR/host/kubelet-mounts.txt"`, + "host/processes.txt", + "read_only=true", + } { + if !strings.Contains(script, want) { + t.Fatalf("failure snapshot script missing %q", want) + } + } +} + +func TestCollectHelmSupportBundleKeepsOptionalDiagnosticsNonFatal(t *testing.T) { + root := repoRoot(t) + raw, err := os.ReadFile(filepath.Join(root, "scripts", "collect-helm-support-bundle.sh")) + if err != nil { + t.Fatal(err) + } + script := string(raw) + for _, want := range []string{ + "capture_optional()", + "[support-bundle] optional command failed:", + `capture_optional "$ARTIFACT_DIR/logs/blockvolume.log"`, + `capture_optional "$ARTIFACT_DIR/iscsi/sessions.txt"`, + `capture_optional "$ARTIFACT_DIR/iscsi/nodes.txt"`, + "host/host-prereq-summary.txt", + "write_host_prereq_summary", + "iscsi_prereq=", + "multipath_prereq=", + "host_prereq=host/host-prereq-summary.txt", + } { + if !strings.Contains(script, want) { + t.Fatalf("support bundle script missing %q", want) + } + } +} + +func TestBuildAlphaImagesImportsLocalCSIImageWhenImportingRemoteK3SNodes(t *testing.T) { + root := repoRoot(t) + raw, err := os.ReadFile(filepath.Join(root, "scripts", "build-alpha-images.sh")) + if err != nil { + t.Fatal(err) + } + script := string(raw) + remoteBranch := `if [[ -n "$IMPORT_K3S_NODES" ]]; then` + idx := strings.Index(script, remoteBranch) + if idx < 0 { + t.Fatalf("build script missing remote k3s import branch %q", remoteBranch) + } + branch := script[idx:] + for _, want := range []string{ + `import_k3s_image "$IMAGE" "k3s-import-local-sw-block.log"`, + `verify_local_k3s_image "$IMAGE" "k3s-images-local-sw-block.txt"`, + `import_k3s_image "$CSI_IMAGE" "k3s-import-local-sw-block-csi.log"`, + `verify_local_k3s_image "$CSI_IMAGE" "k3s-images-local-sw-block-csi.txt"`, + `[alpha-build] k3s_import node=local skipped reason=local_k3s_unavailable`, + `import_k3s_images_to_nodes "$IMPORT_K3S_NODES"`, + } { + if !strings.Contains(branch, want) { + t.Fatalf("remote k3s import branch missing %q", want) + } + } +} + +func TestVerifyHelmCleanupReportsAllResidueDimensions(t *testing.T) { + root := repoRoot(t) + raw, err := os.ReadFile(filepath.Join(root, "scripts", "verify-helm-cleanup.sh")) + if err != nil { + t.Fatal(err) + } + script := string(raw) + for _, want := range []string{ + "cleanup_status=ok", + "cleanup_status=failed", + "k8s_residue_count=", + "iscsi_residue_count=", + "process_residue_count=", + "multipath_residue_count=", + "hostpath_residue_count=", + "failure_count=", + "helm_release_still_present", + "kubernetes_sw_block_resources_present", + "iscsi_sessions_present", + "iscsi_node_records_present", + "multipath_maps_present", + "sw_block_processes_present", + "hostpath_residue_present", + "multipath-residue.after-cleanup.txt", + "dmsetup.after-cleanup.txt", + "cleanup-failures.txt", + } { + if !strings.Contains(script, want) { + t.Fatalf("cleanup verifier missing %q", want) + } + } +} + func repoRoot(t *testing.T) string { t.Helper() dir, err := os.Getwd() diff --git a/seaweed-block/scripts/verify-helm-cleanup.sh b/seaweed-block/scripts/verify-helm-cleanup.sh index 8d9cc44ffc..dcf5101a1e 100644 --- a/seaweed-block/scripts/verify-helm-cleanup.sh +++ b/seaweed-block/scripts/verify-helm-cleanup.sh @@ -234,6 +234,7 @@ fi echo "multipath_residue_count=$(wc -l <"$ARTIFACT_DIR/multipath-residue.after-cleanup.txt")" echo "hostpath_residue_count=$(wc -l <"$ARTIFACT_DIR/hostpath-residue.after-cleanup.txt")" echo "failure_count=$failures" + echo "cleanup_observed_at=$(date -u +%Y-%m-%dT%H:%M:%SZ)" } >"$ARTIFACT_DIR/cleanup-summary.txt" cat "$ARTIFACT_DIR/cleanup-summary.txt" diff --git a/seaweed-block/testops/scenarios/helm-first-volume-via-sw-block-cli-chain.yaml b/seaweed-block/testops/scenarios/helm-first-volume-via-sw-block-cli-chain.yaml index 09daf7695e..50a9f7734a 100644 --- a/seaweed-block/testops/scenarios/helm-first-volume-via-sw-block-cli-chain.yaml +++ b/seaweed-block/testops/scenarios/helm-first-volume-via-sw-block-cli-chain.yaml @@ -20,8 +20,8 @@ env: ssh_key: "C:\\work\\dev_server\\testdev_key" helm_release: "sw-block" helm_namespace: "kube-system" - sw_block_image: "ghcr.io/seaweedfs/seaweed-block:sha-6260e46fd3be" - sw_block_csi_image: "ghcr.io/seaweedfs/seaweed-block-csi:sha-6260e46fd3be" + sw_block_image: "ghcr.io/seaweedfs/seaweed-block:sha-dc2972d0059b" + sw_block_csi_image: "ghcr.io/seaweedfs/seaweed-block-csi:sha-dc2972d0059b" topology: nodes: diff --git a/seaweed-block/testops/scenarios/helm-lifecycle-upgrade-rollback-chain.yaml b/seaweed-block/testops/scenarios/helm-lifecycle-upgrade-rollback-chain.yaml index 81c5479ace..c2b55c0381 100644 --- a/seaweed-block/testops/scenarios/helm-lifecycle-upgrade-rollback-chain.yaml +++ b/seaweed-block/testops/scenarios/helm-lifecycle-upgrade-rollback-chain.yaml @@ -19,8 +19,8 @@ env: ssh_key: "C:\\work\\dev_server\\testdev_key" helm_release: "sw-block" helm_namespace: "kube-system" - sw_block_image: "ghcr.io/seaweedfs/seaweed-block:sha-6260e46fd3be" - sw_block_csi_image: "ghcr.io/seaweedfs/seaweed-block-csi:sha-6260e46fd3be" + sw_block_image: "ghcr.io/seaweedfs/seaweed-block:sha-dc2972d0059b" + sw_block_csi_image: "ghcr.io/seaweedfs/seaweed-block-csi:sha-dc2972d0059b" topology: nodes: diff --git a/seaweed-block/testops/scenarios/helm-rf3-promotion-restart-persistence-chain.yaml b/seaweed-block/testops/scenarios/helm-rf3-promotion-restart-persistence-chain.yaml index 63f94c0677..1d8c300f91 100644 --- a/seaweed-block/testops/scenarios/helm-rf3-promotion-restart-persistence-chain.yaml +++ b/seaweed-block/testops/scenarios/helm-rf3-promotion-restart-persistence-chain.yaml @@ -263,6 +263,191 @@ phases: actual: "{{ reader_after_restart_count }}" threshold: "0" + - name: post_restart_degraded_status_boundary + actions: + - action: exec + node: m02 + timeout: 4m + cmd: | + set -e + out=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-rf3-promotion-restart/after-restart/convergence + mkdir -p "$out" + python3 - "$out" <<'PY' + import json + import socket + import subprocess + import sys + import time + from pathlib import Path + + out = Path(sys.argv[1]) + root = Path("/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-rf3-promotion-restart") + sw_block = root / "bin/sw-block" + restart_summary = root / "restart/restart-promotion-summary.txt" + volume_id = "" + for line in restart_summary.read_text(encoding="utf-8").splitlines(): + if line.startswith("volume_id="): + volume_id = line.split("=", 1)[1] + break + if not volume_id: + raise SystemExit("volume_id unavailable") + + def run(*args, **kwargs): + return subprocess.run(args, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs) + + pods = run( + "kubectl", "-n", "{{ helm_namespace }}", "get", "pods", + "-l", "app.kubernetes.io/component=blockmaster", + "--field-selector=status.phase=Running", + "-o", "json", + check=True, + ) + pod_items = json.loads(pods.stdout).get("items") or [] + if not pod_items: + pods = run( + "kubectl", "-n", "{{ helm_namespace }}", "get", "pods", + "--field-selector=status.phase=Running", + "-o", "json", + check=True, + ) + pod_items = [ + item for item in json.loads(pods.stdout).get("items") or [] + if item.get("metadata", {}).get("name", "").startswith("sw-blockmaster-") + ] + ready_pod = "" + for item in pod_items: + conditions = {c.get("type"): c.get("status") for c in (item.get("status") or {}).get("conditions") or []} + if conditions.get("Ready") == "True": + ready_pod = item["metadata"]["name"] + break + if not ready_pod: + raise SystemExit("no Ready blockmaster pod") + (out / "blockmaster-pod.txt").write_text(ready_pod + "\n", encoding="utf-8") + + sock = socket.socket() + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + sock.close() + (out / "port.txt").write_text(str(port) + "\n", encoding="utf-8") + + pf_log = open(out / "blockmaster-port-forward.log", "w", encoding="utf-8") + pf = subprocess.Popen( + ["kubectl", "-n", "{{ helm_namespace }}", "port-forward", f"pod/{ready_pod}", f"{port}:9333"], + stdout=pf_log, + stderr=subprocess.STDOUT, + text=True, + ) + + def port_ready(): + try: + with socket.create_connection(("127.0.0.1", port), timeout=1): + return True + except OSError: + return False + + try: + deadline = time.time() + 30 + while time.time() < deadline: + if pf.poll() is not None: + raise SystemExit("port-forward exited early") + if port_ready(): + break + time.sleep(0.5) + else: + raise SystemExit("port-forward did not become ready") + + consecutive = 0 + max_consecutive = 0 + observations = [] + final_reason = "" + for attempt in range(1, 31): + report_dir = out / f"report-{attempt:02d}" + evidence_dir = out / f"evidence-{attempt:02d}" + cmd = [ + str(sw_block), "ops", "report", + "--namespace", "default", + "--master", f"127.0.0.1:{port}", + "--out", str(report_dir), + "--evidence-out", str(evidence_dir), + "--timeout", "30s", + ] + proc = run(*cmd) + (out / f"report-{attempt:02d}.stdout.txt").write_text(proc.stdout, encoding="utf-8") + (out / f"report-{attempt:02d}.stderr.txt").write_text(proc.stderr, encoding="utf-8") + if proc.returncode != 0: + observations.append(f"{attempt}: report_failed rc={proc.returncode}") + consecutive = 0 + time.sleep(3) + continue + snap_path = report_dir / "operator-snapshot.json" + snap = json.loads(snap_path.read_text(encoding="utf-8")) + vols = snap.get("volumes") or [] + target = next((v for v in vols if (v.get("status") or {}).get("volume_id") == volume_id), None) + if target is None: + observations.append(f"{attempt}: volume_missing") + consecutive = 0 + time.sleep(3) + continue + status = target.get("status") or {} + conditions = status.get("conditions") or [] + ready_true = any(c.get("type") == "Ready" and c.get("status") == "True" for c in conditions) + blocked_true = any(c.get("type") == "Blocked" and c.get("status") == "True" for c in conditions) + status_value = status.get("status", "") + reason = status.get("reason_code", "") + final_reason = reason + stable_degraded_unknown = status_value == "unknown" and reason == "status_endpoint_unreachable" + stable_ready = status_value == "ready" and ready_true + if (stable_ready or stable_degraded_unknown) and not blocked_true: + consecutive += 1 + else: + consecutive = 0 + max_consecutive = max(max_consecutive, consecutive) + observations.append( + f"{attempt}: status={status_value} reason={reason} ready_true={str(ready_true).lower()} " + f"blocked_true={str(blocked_true).lower()} consecutive_stable={consecutive}" + ) + if consecutive >= 3: + break + time.sleep(3) + + (out / "observations.txt").write_text("\n".join(observations) + "\n", encoding="utf-8") + status = "ok" if consecutive >= 3 else "failed" + with open(out / "convergence-summary.txt", "w", encoding="utf-8") as f: + f.write(f"restart_status_boundary={status}\n") + f.write(f"volume_id={volume_id}\n") + f.write(f"required_consecutive_stable=3\n") + f.write(f"max_consecutive_stable={max_consecutive}\n") + f.write(f"final_reason={final_reason or 'unknown'}\n") + f.write("evidence=observations.txt\n") + if status != "ok": + raise SystemExit("post-restart status did not reach a stable safe surface") + finally: + pf.terminate() + try: + pf.wait(timeout=5) + except subprocess.TimeoutExpired: + pf.kill() + pf.wait(timeout=5) + pf_log.close() + PY + env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-rf3-promotion-restart/after-restart/convergence/convergence-summary.txt" + pattern: "^restart_status_boundary=ok$" + save_as: restart_status_boundary_ok_count + - action: assert_greater + actual: "{{ restart_status_boundary_ok_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-rf3-promotion-restart/after-restart/convergence/convergence-summary.txt" + pattern: "^max_consecutive_stable=3$" + save_as: restart_consecutive_stable_count + - action: assert_greater + actual: "{{ restart_consecutive_stable_count }}" + threshold: "0" + - name: helm_uninstall_cleanup always: true actions: diff --git a/seaweed-block/testops/scenarios/helm-single-node-restart-persistence-chain.yaml b/seaweed-block/testops/scenarios/helm-single-node-restart-persistence-chain.yaml index f0e688faa5..68dccef8f9 100644 --- a/seaweed-block/testops/scenarios/helm-single-node-restart-persistence-chain.yaml +++ b/seaweed-block/testops/scenarios/helm-single-node-restart-persistence-chain.yaml @@ -198,6 +198,187 @@ phases: actual: "{{ managed_volume_ready_count }}" threshold: "0" + - name: post_restart_status_convergence + actions: + - action: exec + node: m02 + timeout: 4m + cmd: | + set -e + out=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-single-node-restart/after-restart/convergence + mkdir -p "$out" + python3 - "$out" <<'PY' + import json + import socket + import subprocess + import sys + import time + from pathlib import Path + + out = Path(sys.argv[1]) + root = Path("/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-single-node-restart") + sw_block = root / "bin/sw-block" + summary = root / "basic-app/first-volume-summary.txt" + volume_id = "" + for line in summary.read_text(encoding="utf-8").splitlines(): + if line.startswith("volume_id="): + volume_id = line.split("=", 1)[1] + break + if not volume_id: + raise SystemExit("volume_id unavailable") + + def run(*args, **kwargs): + return subprocess.run(args, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs) + + pods = run( + "kubectl", "-n", "{{ helm_namespace }}", "get", "pods", + "-l", "app.kubernetes.io/component=blockmaster", + "--field-selector=status.phase=Running", + "-o", "json", + check=True, + ) + pod_items = json.loads(pods.stdout).get("items") or [] + if not pod_items: + pods = run( + "kubectl", "-n", "{{ helm_namespace }}", "get", "pods", + "--field-selector=status.phase=Running", + "-o", "json", + check=True, + ) + pod_items = [ + item for item in json.loads(pods.stdout).get("items") or [] + if item.get("metadata", {}).get("name", "").startswith("sw-blockmaster-") + ] + ready_pod = "" + for item in pod_items: + conditions = {c.get("type"): c.get("status") for c in (item.get("status") or {}).get("conditions") or []} + if conditions.get("Ready") == "True": + ready_pod = item["metadata"]["name"] + break + if not ready_pod: + raise SystemExit("no Ready blockmaster pod") + (out / "blockmaster-pod.txt").write_text(ready_pod + "\n", encoding="utf-8") + + sock = socket.socket() + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + sock.close() + (out / "port.txt").write_text(str(port) + "\n", encoding="utf-8") + + pf_log = open(out / "blockmaster-port-forward.log", "w", encoding="utf-8") + pf = subprocess.Popen( + ["kubectl", "-n", "{{ helm_namespace }}", "port-forward", f"pod/{ready_pod}", f"{port}:9333"], + stdout=pf_log, + stderr=subprocess.STDOUT, + text=True, + ) + + def port_ready(): + try: + with socket.create_connection(("127.0.0.1", port), timeout=1): + return True + except OSError: + return False + + try: + deadline = time.time() + 30 + while time.time() < deadline: + if pf.poll() is not None: + raise SystemExit("port-forward exited early") + if port_ready(): + break + time.sleep(0.5) + else: + raise SystemExit("port-forward did not become ready") + + consecutive = 0 + max_consecutive = 0 + observations = [] + final_reason = "" + for attempt in range(1, 31): + report_dir = out / f"report-{attempt:02d}" + evidence_dir = out / f"evidence-{attempt:02d}" + proc = run( + str(sw_block), "ops", "report", + "--namespace", "default", + "--master", f"127.0.0.1:{port}", + "--out", str(report_dir), + "--evidence-out", str(evidence_dir), + "--timeout", "30s", + ) + (out / f"report-{attempt:02d}.stdout.txt").write_text(proc.stdout, encoding="utf-8") + (out / f"report-{attempt:02d}.stderr.txt").write_text(proc.stderr, encoding="utf-8") + if proc.returncode != 0: + observations.append(f"{attempt}: report_failed rc={proc.returncode}") + consecutive = 0 + time.sleep(3) + continue + snap = json.loads((report_dir / "operator-snapshot.json").read_text(encoding="utf-8")) + vols = snap.get("volumes") or [] + target = next((v for v in vols if (v.get("status") or {}).get("volume_id") == volume_id), None) + if target is None: + observations.append(f"{attempt}: volume_missing") + consecutive = 0 + time.sleep(3) + continue + status = target.get("status") or {} + conditions = status.get("conditions") or [] + ready_true = any(c.get("type") == "Ready" and c.get("status") == "True" for c in conditions) + blocked_true = any(c.get("type") == "Blocked" and c.get("status") == "True" for c in conditions) + status_value = status.get("status", "") + reason = status.get("reason_code", "") + final_reason = reason + if status_value == "ready" and ready_true and not blocked_true: + consecutive += 1 + else: + consecutive = 0 + max_consecutive = max(max_consecutive, consecutive) + observations.append( + f"{attempt}: status={status_value} reason={reason} ready_true={str(ready_true).lower()} " + f"blocked_true={str(blocked_true).lower()} consecutive_ready={consecutive}" + ) + if consecutive >= 3: + break + time.sleep(3) + + (out / "observations.txt").write_text("\n".join(observations) + "\n", encoding="utf-8") + status = "ok" if consecutive >= 3 else "failed" + with open(out / "convergence-summary.txt", "w", encoding="utf-8") as f: + f.write(f"restart_status_convergence={status}\n") + f.write(f"volume_id={volume_id}\n") + f.write(f"required_consecutive_ready=3\n") + f.write(f"max_consecutive_ready={max_consecutive}\n") + f.write(f"final_reason={final_reason or 'unknown'}\n") + f.write("evidence=observations.txt\n") + if status != "ok": + raise SystemExit("post-restart status did not converge to stable Ready") + finally: + pf.terminate() + try: + pf.wait(timeout=5) + except subprocess.TimeoutExpired: + pf.kill() + pf.wait(timeout=5) + pf_log.close() + PY + env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-single-node-restart/after-restart/convergence/convergence-summary.txt" + pattern: "^restart_status_convergence=ok$" + save_as: restart_convergence_ok_count + - action: assert_greater + actual: "{{ restart_convergence_ok_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-single-node-restart/after-restart/convergence/convergence-summary.txt" + pattern: "^max_consecutive_ready=3$" + save_as: restart_consecutive_ready_count + - action: assert_greater + actual: "{{ restart_consecutive_ready_count }}" + threshold: "0" + - name: helm_uninstall_cleanup always: true actions: diff --git a/seaweed-block/testops/scenarios/helm-smartwal-corrupt-restart-chain.yaml b/seaweed-block/testops/scenarios/helm-smartwal-corrupt-restart-chain.yaml new file mode 100644 index 0000000000..0c280ce9ac --- /dev/null +++ b/seaweed-block/testops/scenarios/helm-smartwal-corrupt-restart-chain.yaml @@ -0,0 +1,325 @@ +# Phase 34 D4: live SmartWAL dirty-failure gate. +# +# Goal: +# Prove a dirty storage fault is real evidence, not a self-proof grep: +# Helm installs blockvolumes with smartwal + hostPath, first PVC writes data, +# TestOps corrupts a real SmartWAL WAL record, then the product restarts and +# must not report false Ready=True from corrupted evidence. +# +# Expected current behavior: +# This gate is allowed to fail if the product does not yet surface a stable +# WAL-corruption reason. A green run is valid only if the corruption evidence +# exists and no status surface claims Ready=True afterward. + +name: helm-smartwal-corrupt-restart-chain +timeout: 32m + +env: + product_root: "/tmp/seaweed_block" + ssh_key: "C:\\work\\dev_server\\testdev_key" + helm_release: "sw-block" + helm_namespace: "kube-system" + single_node: "m02" + sw_block_image: "sw-block:local" + sw_block_csi_image: "sw-block-csi:local" + +topology: + nodes: + m02: + host: 192.168.1.184 + user: testdev + key: "{{ ssh_key }}" + +phases: + - name: pre_clean + actions: + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + timeout: 5m + cmd: "helm status {{ helm_release }} --namespace {{ helm_namespace }} >/dev/null 2>&1 && helm uninstall {{ helm_release }} --namespace {{ helm_namespace }} --wait --timeout 180s || true; kubectl -n default delete pod sw-block-example-reader sw-block-example-writer --ignore-not-found=true --wait=true --timeout=120s; kubectl -n default delete pvc sw-block-example-pvc --ignore-not-found=true --wait=true --timeout=120s; kubectl delete storageclass sw-block-example --ignore-not-found=true --wait=true --timeout=120s; kubectl delete clusterrole/sw-block-csi clusterrolebinding/sw-block-csi --ignore-not-found=true; sudo -n iscsiadm -m node 2>/dev/null | awk '/io.seaweedfs/ {print $1, $2}' | while read portal target; do sudo -n iscsiadm -m node -T \"$target\" -p \"$portal\" -o delete || true; done; sudo -n rm -rf /var/lib/sw-block/testops-{{ run_id }}-smartwal-corrupt; rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/bin /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/values /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/install /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/basic-app /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/corrupt /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/after-corrupt /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/cleanup" + env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + + - name: build_tools_and_images + actions: + - action: exec + node: m02 + timeout: 8m + cmd: "cd {{ product_root }} && go build -o /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/bin/sw-block ./cmd/sw-block && go build -o /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/bin/sw-block-testutil ./cmd/sw-block-testutil && bash scripts/build-alpha-images.sh {{ product_root }}" + env.SW_BLOCK_IMPORT_K3S: "1" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/build" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/build/alpha-images.env" + pattern: "SW_BLOCK_IMAGE_ID=" + save_as: image_id_count + - action: assert_greater + actual: "{{ image_id_count }}" + threshold: "0" + + - name: generate_smartwal_values + actions: + - action: exec + node: m02 + timeout: 3m + cmd: | + set -e + out=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/values + /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/bin/sw-block ops generate-helm-values \ + --kubeconfig /etc/rancher/k3s/k3s.yaml \ + --out "$out/values.smartwal.yaml" \ + --image {{ sw_block_image }} \ + --csi-image {{ sw_block_csi_image }} \ + --target-node {{ single_node }} \ + --node-limit 1 \ + --restart-persistence hostpath \ + --state-hostpath /var/lib/sw-block/testops-{{ run_id }}-smartwal-corrupt > "$out/generate.stdout.txt" + python3 - "$out/values.smartwal.yaml" <<'PY' + import sys + from pathlib import Path + path = Path(sys.argv[1]) + lines = path.read_text(encoding="utf-8").splitlines() + out = [] + inserted = False + for line in lines: + stripped = line.strip() + if stripped.startswith("durableImpl:"): + indent = line[: len(line) - len(line.lstrip())] + out.append(f"{indent}durableImpl: smartwal") + inserted = True + continue + out.append(line) + if not inserted and line.rstrip() == "blockmaster:": + out.append(" durableImpl: smartwal") + out.append(" nodeSelector:") + out.append(" kubernetes.io/hostname: {{ single_node }}") + inserted = True + if not inserted: + raise SystemExit("blockmaster block not found; cannot set durableImpl") + path.write_text("\n".join(out) + "\n", encoding="utf-8") + PY + env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/values/values.smartwal.yaml" + pattern: "durableImpl: smartwal" + save_as: durable_impl_smartwal_count + - action: assert_greater + actual: "{{ durable_impl_smartwal_count }}" + threshold: "0" + + - name: helm_install_stack + actions: + - action: exec + node: m02 + timeout: 10m + cmd: "cd {{ product_root }} && helm lint charts/seaweed-block -f /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/values/values.smartwal.yaml > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/install/helm-lint.txt && helm template {{ helm_release }} charts/seaweed-block -f /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/values/values.smartwal.yaml > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/install/helm-template.yaml && grep -q -- '--launcher-durable-impl=smartwal' /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/install/helm-template.yaml && helm install {{ helm_release }} charts/seaweed-block --namespace {{ helm_namespace }} --create-namespace -f /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/values/values.smartwal.yaml --wait --timeout 10m > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/install/helm-install.txt && kubectl -n {{ helm_namespace }} rollout status deploy/sw-blockmaster --timeout=180s && kubectl -n {{ helm_namespace }} rollout status deploy/sw-block-csi-controller --timeout=180s && kubectl -n {{ helm_namespace }} rollout status ds/sw-block-csi-node --timeout=180s" + env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/install/helm-install.txt" + pattern: "STATUS: deployed" + save_as: helm_deployed_count + - action: assert_greater + actual: "{{ helm_deployed_count }}" + threshold: "0" + + - name: first_volume_before_corruption + actions: + - action: exec + node: m02 + timeout: 10m + cmd: "cd {{ product_root }} && bash scripts/run-basic-app-example.sh {{ product_root }}" + env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/basic-app" + env.SW_BLOCK_BASIC_APP_CLEANUP: "0" + env.SW_BLOCK_BASIC_APP_NODE_SELECTOR: "{{ single_node }}" + env.SW_BLOCK_INSTALL_MODE: "helm-single-node-smartwal-corrupt" + env.SW_BLOCK_HELM_RELEASE: "{{ helm_release }}" + env.SW_BLOCK_HELM_NAMESPACE: "{{ helm_namespace }}" + env.SW_BLOCK_HELM_VALUES_FILE: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/values/values.smartwal.yaml" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/basic-app/first-volume-summary.txt" + pattern: "^first_volume_status=ok$" + save_as: first_volume_ok_count + - action: assert_greater + actual: "{{ first_volume_ok_count }}" + threshold: "0" + + - name: corrupt_smartwal_and_reconcile + actions: + - action: exec + node: m02 + timeout: 8m + cmd: | + set -e + root=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt + out="$root/corrupt" + summary="$root/basic-app/first-volume-summary.txt" + vol=$(sed -n 's/^volume_id=//p' "$summary" | head -1) + test -n "$vol" + deploy=$(kubectl -n default get deploy -l app=sw-blockvolume,sw-block.seaweedfs.com/volume="$vol" -o jsonpath='{.items[0].metadata.name}') + test -n "$deploy" + store="/var/lib/sw-block/testops-{{ run_id }}-smartwal-corrupt/${vol}/r1/${vol}.bin" + echo "volume_id=$vol" > "$out/corrupt-context.txt" + echo "deployment=$deploy" >> "$out/corrupt-context.txt" + echo "store=$store" >> "$out/corrupt-context.txt" + test -f "$store" + kubectl -n default delete pod sw-block-example-reader sw-block-example-writer --ignore-not-found=true --wait=true --timeout=120s + kubectl -n default scale "deploy/$deploy" --replicas=0 + for i in $(seq 1 120); do + pods=$(kubectl -n default get pod -l sw-block.seaweedfs.com/volume="$vol" -o name 2>/dev/null | wc -l | tr -d ' ') + test "$pods" = "0" && break + sleep 1 + done + pods=$(kubectl -n default get pod -l sw-block.seaweedfs.com/volume="$vol" -o name 2>/dev/null | wc -l | tr -d ' ') + echo "pods_after_scale_zero=$pods" >> "$out/corrupt-context.txt" + test "$pods" = "0" + sudo -n /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/bin/sw-block-testutil smartwal-corrupt-latest-record --path "$store" --out "$out" > "$out/smartwal-corruption.stdout.txt" 2> "$out/smartwal-corruption.stderr.txt" + kubectl -n default scale "deploy/$deploy" --replicas=1 + deployment_restarted=false + deployment_rollout_ready=false + for i in $(seq 1 180); do + if kubectl -n default get pod -l sw-block.seaweedfs.com/volume="$vol" -o name 2>/dev/null | grep -q .; then + deployment_restarted=true + fi + ready=$(kubectl -n default get "deploy/$deploy" -o jsonpath='{.status.readyReplicas}' 2>/dev/null || true) + if test "$ready" = "1"; then + deployment_rollout_ready=true + break + fi + sleep 1 + done + echo "deployment_restarted=$deployment_restarted" >> "$out/corrupt-context.txt" + echo "deployment_rollout_ready=$deployment_rollout_ready" >> "$out/corrupt-context.txt" + test "$deployment_restarted" = "true" + kubectl -n default rollout status "deploy/$deploy" --timeout=5s > "$out/wait-blockvolume-after-corrupt.txt" 2>&1 || true + kubectl -n default get pods,deploy,pvc,pv -o wide > "$out/default.after-corrupt.txt" + kubectl -n {{ helm_namespace }} get pods,deploy,svc -o wide > "$out/kube-system.after-corrupt.txt" + kubectl -n default describe "deploy/$deploy" > "$out/blockvolume-deploy.describe.txt" 2>&1 || true + kubectl -n default logs -l sw-block.seaweedfs.com/volume="$vol" --all-containers --tail=200 > "$out/blockvolume-pods.log" 2>&1 || true + env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/corrupt/smartwal-corruption-evidence.txt" + pattern: "^target_offset_inside_wal=true$" + save_as: corrupt_inside_wal_count + - action: assert_greater + actual: "{{ corrupt_inside_wal_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/corrupt/smartwal-corruption-evidence.txt" + pattern: "^target_offset_inside_extent=false$" + save_as: corrupt_not_extent_count + - action: assert_greater + actual: "{{ corrupt_not_extent_count }}" + threshold: "0" + + - name: assert_no_false_ready_after_corruption + actions: + - action: exec + node: m02 + timeout: 5m + cmd: | + set -e + root=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt + out="$root/after-corrupt" + mkdir -p "$out" + port=$(python3 - <<'PY' + import socket + s=socket.socket(); s.bind(("127.0.0.1",0)); print(s.getsockname()[1]); s.close() + PY + ) + kubectl -n {{ helm_namespace }} port-forward deploy/sw-blockmaster ${port}:9333 > "$out/blockmaster-port-forward.log" 2>&1 & + pf=$! + trap 'kill $pf >/dev/null 2>&1 || true; wait $pf >/dev/null 2>&1 || true' EXIT + for i in $(seq 1 60); do if (echo >/dev/tcp/127.0.0.1/$port) >/dev/null 2>&1; then break; fi; sleep 1; done + /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/bin/sw-block ops report --master-api 127.0.0.1:${port} --out "$out/report" --timeout 30s > "$out/report.stdout.txt" 2> "$out/report.stderr.txt" + python3 - "$root/basic-app/first-volume-summary.txt" "$out/report/operator-snapshot.json" "$out/corruption-status-summary.txt" <<'PY' + import json, sys + summary, snap_path, out_path = sys.argv[1:4] + volume_id = "" + for line in open(summary, encoding="utf-8"): + if line.startswith("volume_id="): + volume_id = line.strip().split("=", 1)[1] + break + if not volume_id: + raise SystemExit("volume_id missing") + snap = json.load(open(snap_path, encoding="utf-8")) + vols = snap.get("volumes") or [] + target = next((v for v in vols if (v.get("status") or {}).get("volume_id") == volume_id), None) + if target is None: + status = "ok" + reason = "volume_missing_after_corruption" + ready = False + blocked = False + else: + st = target.get("status") or {} + conditions = st.get("conditions") or [] + ready = any(c.get("type") == "Ready" and c.get("status") == "True" for c in conditions) + blocked = any(c.get("type") == "Blocked" and c.get("status") == "True" for c in conditions) + reason = st.get("reason_code", "unknown") + status = "failed" if ready else "ok" + with open(out_path, "w", encoding="utf-8") as f: + f.write(f"smartwal_corruption_status_surface={status}\n") + f.write(f"volume_id={volume_id}\n") + f.write(f"ready_true_after_corruption={str(ready).lower()}\n") + f.write(f"blocked_true_after_corruption={str(blocked).lower()}\n") + f.write(f"reason_after_corruption={reason}\n") + f.write("evidence=report/operator-snapshot.json\n") + if status != "ok": + raise SystemExit("false Ready=True after SmartWAL corruption") + PY + env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/after-corrupt/corruption-status-summary.txt" + pattern: "^smartwal_corruption_status_surface=ok$" + save_as: no_false_ready_count + - action: assert_greater + actual: "{{ no_false_ready_count }}" + threshold: "0" + + - name: helm_uninstall_cleanup + always: true + actions: + - action: exec + node: m02 + timeout: 8m + cmd: "mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/cleanup/diagnostics; kubectl -n {{ helm_namespace }} get pods,deploy,ds,svc -o wide > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/cleanup/diagnostics/kube-system.before-cleanup.txt 2>&1 || true; kubectl -n default get pods,deploy,pvc,pv -o wide > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/cleanup/diagnostics/default.before-cleanup.txt 2>&1 || true; helm status {{ helm_release }} --namespace {{ helm_namespace }} >/dev/null 2>&1 && helm uninstall {{ helm_release }} --namespace {{ helm_namespace }} --wait --timeout 300s > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/cleanup/helm-uninstall.txt || true; kubectl -n default delete pod sw-block-example-reader sw-block-example-writer --ignore-not-found=true --wait=true --timeout=120s; kubectl -n default delete pvc sw-block-example-pvc --ignore-not-found=true --wait=true --timeout=120s; kubectl delete storageclass sw-block-example --ignore-not-found=true --wait=true --timeout=120s; sudo -n iscsiadm -m node 2>/dev/null | awk '/io.seaweedfs/ {print $1, $2}' | while read portal target; do sudo -n iscsiadm -m node -T \"$target\" -p \"$portal\" -o delete || true; done; sudo -n rm -rf /var/lib/sw-block/testops-{{ run_id }}-smartwal-corrupt; cd {{ product_root }} && bash scripts/verify-helm-cleanup.sh" + env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/cleanup/verify" + env.SW_BLOCK_HELM_RELEASE: "{{ helm_release }}" + env.SW_BLOCK_HELM_NAMESPACE: "{{ helm_namespace }}" + env.SW_BLOCK_CLEANUP_HOSTPATH_PREFIX: "testops-{{ run_id }}-smartwal-corrupt" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/cleanup/verify/cleanup-summary.txt" + pattern: "^cleanup_status=ok$" + save_as: helm_cleanup_ok_count + - action: assert_greater + actual: "{{ helm_cleanup_ok_count }}" + threshold: "0" + - action: collect_path + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt" + name: "remote-phases" + ignore_error: true diff --git a/seaweed-block/testops/scenarios/helm-support-bundle-diagnostics-chain.yaml b/seaweed-block/testops/scenarios/helm-support-bundle-diagnostics-chain.yaml index 585465b329..f41240b490 100644 --- a/seaweed-block/testops/scenarios/helm-support-bundle-diagnostics-chain.yaml +++ b/seaweed-block/testops/scenarios/helm-support-bundle-diagnostics-chain.yaml @@ -194,6 +194,57 @@ phases: actual: "{{ blocked_image_pull_count }}" threshold: "0" + - name: failure_snapshot + actions: + - action: exec + node: m02 + timeout: 3m + cmd: "cd {{ product_root }} && bash scripts/collect-k8s-failure-snapshot.sh {{ product_root }}" + env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" + env.SW_BLOCK_FAILURE_SNAPSHOT_OUT: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-support-bundle/failure-snapshot" + env.SW_BLOCK_HELM_RELEASE: "{{ helm_release }}" + env.SW_BLOCK_HELM_NAMESPACE: "{{ helm_namespace }}" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-support-bundle/failure-snapshot/failure-snapshot-summary.txt" + pattern: "^read_only=true$" + save_as: failure_snapshot_readonly_count + - action: assert_greater + actual: "{{ failure_snapshot_readonly_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-support-bundle/failure-snapshot/k8s/events-all.txt" + pattern: "." + save_as: failure_snapshot_events_count + - action: assert_greater + actual: "{{ failure_snapshot_events_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-support-bundle/failure-snapshot/logs/csi-node.current.log" + pattern: "." + save_as: failure_snapshot_csi_log_count + - action: assert_greater + actual: "{{ failure_snapshot_csi_log_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-support-bundle/failure-snapshot/host/iscsi-nodes.txt" + pattern: "." + save_as: failure_snapshot_iscsi_nodes_count + - action: assert_greater + actual: "{{ failure_snapshot_iscsi_nodes_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-support-bundle/failure-snapshot/host/processes.txt" + pattern: "." + save_as: failure_snapshot_process_count + - action: assert_greater + actual: "{{ failure_snapshot_process_count }}" + threshold: "0" + - name: helm_uninstall_cleanup always: true actions: diff --git a/seaweed-block/testops/scenarios/lifecycle-owner-admission-gate-chain.yaml b/seaweed-block/testops/scenarios/lifecycle-owner-admission-gate-chain.yaml new file mode 100644 index 0000000000..d0f0be1b73 --- /dev/null +++ b/seaweed-block/testops/scenarios/lifecycle-owner-admission-gate-chain.yaml @@ -0,0 +1,97 @@ +# Runner-native Phase 42 D1 gate: live lifecycle-owner API/admission boundary. + +name: lifecycle-owner-admission-gate-chain +description: > + Runs the live Kubernetes ValidatingAdmissionPolicy gate that proves the + lifecycle-owner identity can only issue finalizer-shaped SwBlockVolume main + object patches. This is the real API/admission successor to the Phase 41 + schema-aware boundary gate. + +vars: + product_root: "{{ env.PRODUCT_ROOT | default('/mnt/c/work/seaweed_block') }}" + +phases: + - name: admission_gate + actions: + - type: exec + name: run_phase42_admission_gate + cmd: "rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-lifecycle-owner-admission-gate && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-lifecycle-owner-admission-gate && cd {{ product_root }} && SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-lifecycle-owner-admission-gate bash scripts/run-phase42-lifecycle-owner-admission-gate.sh {{ product_root }}" + + - name: asserts + actions: + - type: grep_log + name: admission_gate_ok + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-lifecycle-owner-admission-gate/phase42-lifecycle-owner-admission-gate-summary.txt" + pattern: "^phase42_lifecycle_owner_admission_status=ok$" + - type: grep_log + name: operator_status_no_main_patch + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-lifecycle-owner-admission-gate/phase42-lifecycle-owner-admission-gate-summary.txt" + pattern: "^operator_status_main_patch_allowed=false$" + - type: grep_log + name: admission_policy_propagated + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-lifecycle-owner-admission-gate/phase42-lifecycle-owner-admission-gate-summary.txt" + pattern: "^admission_policy_propagated=true$" + - type: grep_log + name: lifecycle_owner_finalizer_add_allowed + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-lifecycle-owner-admission-gate/phase42-lifecycle-owner-admission-gate-summary.txt" + pattern: "^lifecycle_owner_finalizer_add_allowed=true$" + - type: grep_log + name: lifecycle_owner_finalizer_add_idempotent + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-lifecycle-owner-admission-gate/phase42-lifecycle-owner-admission-gate-summary.txt" + pattern: "^lifecycle_owner_finalizer_add_idempotent=true$" + - type: grep_log + name: lifecycle_owner_finalizer_remove_allowed + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-lifecycle-owner-admission-gate/phase42-lifecycle-owner-admission-gate-summary.txt" + pattern: "^lifecycle_owner_finalizer_remove_allowed=true$" + - type: grep_log + name: lifecycle_owner_finalizer_remove_idempotent + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-lifecycle-owner-admission-gate/phase42-lifecycle-owner-admission-gate-summary.txt" + pattern: "^lifecycle_owner_finalizer_remove_idempotent=true$" + - type: grep_log + name: lifecycle_owner_spec_forbidden + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-lifecycle-owner-admission-gate/phase42-lifecycle-owner-admission-gate-summary.txt" + pattern: "^lifecycle_owner_spec_patch_allowed=false$" + - type: grep_log + name: lifecycle_owner_label_forbidden + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-lifecycle-owner-admission-gate/phase42-lifecycle-owner-admission-gate-summary.txt" + pattern: "^lifecycle_owner_label_patch_allowed=false$" + - type: grep_log + name: lifecycle_owner_annotation_forbidden + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-lifecycle-owner-admission-gate/phase42-lifecycle-owner-admission-gate-summary.txt" + pattern: "^lifecycle_owner_annotation_patch_allowed=false$" + - type: grep_log + name: lifecycle_owner_ownerreferences_forbidden + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-lifecycle-owner-admission-gate/phase42-lifecycle-owner-admission-gate-summary.txt" + pattern: "^lifecycle_owner_ownerreferences_patch_allowed=false$" + - type: grep_log + name: lifecycle_owner_deletiontimestamp_forbidden + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-lifecycle-owner-admission-gate/phase42-lifecycle-owner-admission-gate-summary.txt" + pattern: "^lifecycle_owner_deletiontimestamp_patch_allowed=false$" + - type: grep_log + name: lifecycle_owner_foreign_finalizer_forbidden + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-lifecycle-owner-admission-gate/phase42-lifecycle-owner-admission-gate-summary.txt" + pattern: "^lifecycle_owner_foreign_finalizer_allowed=false$" + - type: grep_log + name: lifecycle_owner_mixed_patch_forbidden + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-lifecycle-owner-admission-gate/phase42-lifecycle-owner-admission-gate-summary.txt" + pattern: "^lifecycle_owner_mixed_patch_allowed=false$" + - type: grep_log + name: lifecycle_owner_mixed_metadata_forbidden + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-lifecycle-owner-admission-gate/phase42-lifecycle-owner-admission-gate-summary.txt" + pattern: "^lifecycle_owner_mixed_metadata_patch_allowed=false$" + - type: grep_log + name: lifecycle_owner_main_status_not_mutated + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-lifecycle-owner-admission-gate/phase42-lifecycle-owner-admission-gate-summary.txt" + pattern: "^lifecycle_owner_main_status_mutated=false$" + - type: grep_log + name: lifecycle_owner_status_subresource_forbidden + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-lifecycle-owner-admission-gate/phase42-lifecycle-owner-admission-gate-summary.txt" + pattern: "^lifecycle_owner_status_subresource_patch_allowed=false$" + - type: grep_log + name: finalizers_endpoint_forbidden + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-lifecycle-owner-admission-gate/phase42-lifecycle-owner-admission-gate-summary.txt" + pattern: "^finalizers_endpoint_allowed=false$" + - type: grep_log + name: object_integrity_preserved + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-lifecycle-owner-admission-gate/phase42-lifecycle-owner-admission-gate-summary.txt" + pattern: "^object_integrity_preserved=true$" diff --git a/seaweed-block/testops/scenarios/lifecycle-owner-api-boundary-chain.yaml b/seaweed-block/testops/scenarios/lifecycle-owner-api-boundary-chain.yaml new file mode 100644 index 0000000000..cf2c227415 --- /dev/null +++ b/seaweed-block/testops/scenarios/lifecycle-owner-api-boundary-chain.yaml @@ -0,0 +1,44 @@ +# Runner-native Phase 41 D2 gate: lifecycle-owner API/RBAC boundary. + +name: lifecycle-owner-api-boundary-chain +description: > + Proves that the released operator-status boundary remains status/events-only + while the future lifecycle-owner boundary permits only finalizer-shaped main + SwBlockVolume patches and rejects spec/unrelated metadata mutation. + +vars: + product_root: "{{ env.PRODUCT_ROOT | default('/mnt/c/work/seaweed_block') }}" + +phases: + - name: api_boundary + actions: + - type: exec + name: run_phase41_api_boundary + cmd: "rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase41-lifecycle-owner-api-boundary && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase41-lifecycle-owner-api-boundary && cd {{ product_root }} && SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase41-lifecycle-owner-api-boundary bash scripts/run-phase41-lifecycle-owner-api-boundary.sh {{ product_root }}" + + - name: asserts + actions: + - type: grep_log + name: api_boundary_ok + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase41-lifecycle-owner-api-boundary/phase41-lifecycle-owner-api-boundary-summary.txt" + pattern: "^phase41_lifecycle_owner_api_boundary_status=ok$" + - type: grep_log + name: operator_status_no_main_patch + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase41-lifecycle-owner-api-boundary/phase41-lifecycle-owner-api-boundary-summary.txt" + pattern: "^operator_status_main_patch_allowed=false$" + - type: grep_log + name: lifecycle_owner_finalizer_only_allowed + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase41-lifecycle-owner-api-boundary/phase41-lifecycle-owner-api-boundary-summary.txt" + pattern: "^lifecycle_owner_finalizer_patch_allowed=true$" + - type: grep_log + name: lifecycle_owner_spec_forbidden + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase41-lifecycle-owner-api-boundary/phase41-lifecycle-owner-api-boundary-summary.txt" + pattern: "^lifecycle_owner_spec_patch_allowed=false$" + - type: grep_log + name: lifecycle_owner_unrelated_metadata_forbidden + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase41-lifecycle-owner-api-boundary/phase41-lifecycle-owner-api-boundary-summary.txt" + pattern: "^lifecycle_owner_unrelated_metadata_patch_allowed=false$" + - type: grep_log + name: finalizers_endpoint_forbidden + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase41-lifecycle-owner-api-boundary/phase41-lifecycle-owner-api-boundary-summary.txt" + pattern: "^finalizers_endpoint_allowed=false$" diff --git a/seaweed-block/testops/scenarios/lifecycle-owner-delete-safety-decision-chain.yaml b/seaweed-block/testops/scenarios/lifecycle-owner-delete-safety-decision-chain.yaml new file mode 100644 index 0000000000..14857e6cb1 --- /dev/null +++ b/seaweed-block/testops/scenarios/lifecycle-owner-delete-safety-decision-chain.yaml @@ -0,0 +1,62 @@ +# Runner-native Phase 42 D5/D6 gate: delete-safety decisions stay external and +# isolated per volume. + +name: lifecycle-owner-delete-safety-decision-chain +description: > + Runs the Phase 42 delete-safety decision gate. This complements the live + admission gate: admission proves the lifecycle-owner can only patch the + approved finalizer shape; this gate proves finalizer-release decisions still + come from cleanup evidence and remain dry-run/status-only until Phase 43. + +vars: + product_root: "{{ env.PRODUCT_ROOT | default('/mnt/c/work/seaweed_block') }}" + +phases: + - name: delete_safety_decision + actions: + - type: exec + name: run_phase42_delete_safety_decision + cmd: "rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-delete-safety-decision && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-delete-safety-decision && cd {{ product_root }} && SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-delete-safety-decision bash scripts/run-phase42-delete-safety-decision-gate.sh {{ product_root }}" + + - name: asserts + actions: + - type: grep_log + name: gate_ok + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-delete-safety-decision/phase42-delete-safety-decision-gate-summary.txt" + pattern: "^phase42_delete_safety_decision_status=ok$" + - type: grep_log + name: clean_allowed + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-delete-safety-decision/phase42-delete-safety-decision-gate-summary.txt" + pattern: "^clean_delete_safety_decision=allowed$" + - type: grep_log + name: blocked_rejected + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-delete-safety-decision/phase42-delete-safety-decision-gate-summary.txt" + pattern: "^blocked_delete_safety_decision=rejected$" + - type: grep_log + name: missing_unknown + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-delete-safety-decision/phase42-delete-safety-decision-gate-summary.txt" + pattern: "^missing_delete_safety_decision=unknown$" + - type: grep_log + name: stale_unknown + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-delete-safety-decision/phase42-delete-safety-decision-gate-summary.txt" + pattern: "^stale_delete_safety_decision=unknown$" + - type: grep_log + name: dry_run_action + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-delete-safety-decision/phase42-delete-safety-decision-gate-summary.txt" + pattern: "^lifecycle_owner_action_mode=dry_run$" + - type: grep_log + name: no_action_mutation + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-delete-safety-decision/phase42-delete-safety-decision-gate-summary.txt" + pattern: "^lifecycle_owner_action_mutation_allowed=false$" + - type: grep_log + name: no_finalizer_patch + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-delete-safety-decision/phase42-delete-safety-decision-gate-summary.txt" + pattern: "^finalizer_patch_count=0$" + - type: grep_log + name: no_finalizer_events + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-delete-safety-decision/phase42-delete-safety-decision-gate-summary.txt" + pattern: "^no_finalizer_mutation_events=true$" + - type: grep_log + name: multi_volume_isolated + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase42-delete-safety-decision/phase42-delete-safety-decision-gate-summary.txt" + pattern: "^multi_volume_delete_safety_isolation=true$" diff --git a/seaweed-block/testops/scenarios/operator-status-api-conformance-chain.yaml b/seaweed-block/testops/scenarios/operator-status-api-conformance-chain.yaml new file mode 100644 index 0000000000..d28d3f201e --- /dev/null +++ b/seaweed-block/testops/scenarios/operator-status-api-conformance-chain.yaml @@ -0,0 +1,91 @@ +# Runner-native Phase 40 D4 gate: operator-status API conformance. +# +# Goal: +# Catch the CRD/RBAC failures that previously escaped mock tests and failed +# only under live Kubernetes API validation: +# snake_case status payload drift +# unsupported condition/action enums +# wrong CRD endpoint usage +# RBAC boundary broadening +# delete-safety status regression + +name: operator-status-api-conformance-chain +timeout: 8m + +env: + product_root: "/tmp/seaweed_block" + ssh_key: "C:\\work\\dev_server\\testdev_key" + +topology: + nodes: + m02: + host: 192.168.1.184 + user: testdev + key: "{{ ssh_key }}" + +phases: + - name: status_api_conformance + actions: + - action: exec + node: m02 + timeout: 5m + cmd: "rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-operator-status-api-conformance && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-operator-status-api-conformance && cd {{ product_root }} && SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-operator-status-api-conformance bash scripts/run-phase40-status-api-conformance.sh {{ product_root }}" + + - name: status_api_conformance_asserts + actions: + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-operator-status-api-conformance/phase40-status-api-conformance-summary.txt" + pattern: "^phase40_status_api_conformance_status=ok$" + save_as: gate_ok_count + - action: assert_greater + actual: "{{ gate_ok_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-operator-status-api-conformance/phase40-status-api-conformance-summary.txt" + pattern: "^casing_drift_gate=ok$" + save_as: casing_ok_count + - action: assert_greater + actual: "{{ casing_ok_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-operator-status-api-conformance/phase40-status-api-conformance-summary.txt" + pattern: "^enum_drift_gate=ok$" + save_as: enum_ok_count + - action: assert_greater + actual: "{{ enum_ok_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-operator-status-api-conformance/phase40-status-api-conformance-summary.txt" + pattern: "^wrong_endpoint_gate=ok$" + save_as: endpoint_ok_count + - action: assert_greater + actual: "{{ endpoint_ok_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-operator-status-api-conformance/phase40-status-api-conformance-summary.txt" + pattern: "^rbac_boundary_gate=ok$" + save_as: rbac_ok_count + - action: assert_greater + actual: "{{ rbac_ok_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-operator-status-api-conformance/phase40-status-api-conformance-summary.txt" + pattern: "^delete_safety_status_gate=ok$" + save_as: delete_safety_ok_count + - action: assert_greater + actual: "{{ delete_safety_ok_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-operator-status-api-conformance/phase40-status-api-conformance-summary.txt" + pattern: "^finalizer_mutation_allowed=false$" + save_as: finalizer_mutation_count + - action: assert_greater + actual: "{{ finalizer_mutation_count }}" + threshold: "0" diff --git a/seaweed-block/testops/scenarios/status-endpoint-unreachable-live-chain.yaml b/seaweed-block/testops/scenarios/status-endpoint-unreachable-live-chain.yaml new file mode 100644 index 0000000000..f4fff2d9b1 --- /dev/null +++ b/seaweed-block/testops/scenarios/status-endpoint-unreachable-live-chain.yaml @@ -0,0 +1,356 @@ +# Phase 34 D2 gate: live status endpoint unreachable. +# +# Goal: +# Upgrade the Phase 33 replay-only unreachable-status check into a live +# injection. The blockvolume process and iSCSI data path stay alive; only the +# replica status endpoint is rejected. Correct behavior is Unknown / +# status_endpoint_unreachable, not Blocked and not Ready=True. + +name: status-endpoint-unreachable-live-chain +timeout: 32m + +env: + product_root: "/tmp/seaweed_block" + ssh_key: "C:\\work\\dev_server\\testdev_key" + helm_release: "sw-block" + helm_namespace: "kube-system" + sw_block_image: "ghcr.io/seaweedfs/seaweed-block:sha-dc2972d0059b" + sw_block_csi_image: "ghcr.io/seaweedfs/seaweed-block-csi:sha-dc2972d0059b" + +topology: + nodes: + m02: + host: 192.168.1.184 + user: testdev + key: "{{ ssh_key }}" + +phases: + - name: pre_clean + actions: + - action: pre_run_cleanup + node: m02 + kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" + nvme_disconnect: "true" + iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" + - action: exec + node: m02 + timeout: 5m + cmd: "helm status {{ helm_release }} --namespace {{ helm_namespace }} >/dev/null 2>&1 && helm uninstall {{ helm_release }} --namespace {{ helm_namespace }} --wait --timeout 180s || true; kubectl -n default delete pod sw-block-example-reader sw-block-example-writer --ignore-not-found=true --wait=true --timeout=120s; kubectl -n default delete pvc sw-block-example-pvc --ignore-not-found=true --wait=true --timeout=120s; kubectl delete storageclass sw-block-example sw-block-dynamic --ignore-not-found=true --wait=true --timeout=120s; kubectl delete clusterrole/sw-block-csi clusterrolebinding/sw-block-csi --ignore-not-found=true; sudo -n iscsiadm -m node 2>/dev/null | awk '/io.seaweedfs/ {print $1, $2}' | while read portal target; do sudo -n iscsiadm -m node -T \"$target\" -p \"$portal\" -o delete || true; done; rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/bin /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/values /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/install /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/basic-app /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/fault /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/live-report /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/dashboard /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/cleanup" + env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + + - name: build_and_install + actions: + - action: exec + node: m02 + timeout: 6m + cmd: "cd {{ product_root }} && go build -o /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/bin/sw-block ./cmd/sw-block && /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/bin/sw-block ops generate-helm-values --kubeconfig /etc/rancher/k3s/k3s.yaml --out /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/values/values.day1.yaml --image {{ sw_block_image }} --csi-image {{ sw_block_csi_image }} > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/values/generate.stdout.txt" + env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/values/generate.stdout.txt" + pattern: "helm_values_status=ok" + save_as: generator_ok_count + - action: assert_greater + actual: "{{ generator_ok_count }}" + threshold: "0" + - action: exec + node: m02 + timeout: 10m + cmd: "cd {{ product_root }} && helm install {{ helm_release }} charts/seaweed-block --namespace {{ helm_namespace }} --create-namespace -f /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/values/values.day1.yaml --wait --timeout 10m > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/install/helm-install.txt && kubectl -n {{ helm_namespace }} get deploy,ds,pods,svc -o wide > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/install/kube-system.after-install.txt" + env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/install/helm-install.txt" + pattern: "STATUS: deployed" + save_as: helm_deployed_count + - action: assert_greater + actual: "{{ helm_deployed_count }}" + threshold: "0" + + - name: first_volume_ready_before_fault + actions: + - action: exec + node: m02 + timeout: 10m + cmd: "cd {{ product_root }} && bash scripts/run-basic-app-example.sh {{ product_root }}" + env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/basic-app" + env.SW_BLOCK_BASIC_APP_CLEANUP: "0" + env.SW_BLOCK_INSTALL_MODE: "helm" + env.SW_BLOCK_HELM_RELEASE: "{{ helm_release }}" + env.SW_BLOCK_HELM_NAMESPACE: "{{ helm_namespace }}" + env.SW_BLOCK_HELM_VALUES_FILE: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/values/values.day1.yaml" + env.SW_BLOCK_CLI: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/bin/sw-block" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/basic-app/first-volume-summary.txt" + pattern: "^first_volume_status=ok$" + save_as: first_volume_ok_count + - action: assert_greater + actual: "{{ first_volume_ok_count }}" + threshold: "0" + - action: exec + node: m02 + timeout: 1m + cmd: | + python3 - <<'PY' + import json + from pathlib import Path + root = Path("/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/basic-app") + snap = json.loads((root / "status/report/operator-snapshot.json").read_text()) + vols = snap.get("volumes") or [] + if len(vols) != 1: + raise SystemExit(f"expected one volume before fault, got {len(vols)}") + status = vols[0].get("status") or {} + if status.get("status") != "ready" or status.get("reason_code") != "first_volume_verified": + raise SystemExit(f"volume was not Ready before fault: {status}") + cluster = snap.get("cluster") or {} + if cluster.get("ready_volume_count") != 1: + raise SystemExit(f"expected ready_volume_count=1 before fault: {cluster}") + PY + + - name: block_status_endpoint + actions: + - action: exec + node: m02 + timeout: 2m + cmd: | + set -eu + OUT=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/fault + mkdir -p "$OUT" + python3 - <<'PY' > "$OUT/status-target.env" + import json + from pathlib import Path + root = Path("/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/basic-app/status") + doc = json.loads((root / "inventory/volume-inventory.json").read_text()) + vols = doc.get("volumes") or [] + if len(vols) != 1: + raise SystemExit(f"expected one volume, got {len(vols)}") + replicas = vols[0].get("replicas") or [] + if len(replicas) != 1: + raise SystemExit(f"expected one replica, got {len(replicas)}") + status_addr = replicas[0].get("status_address") or replicas[0].get("status_addr") or "" + if ":" not in status_addr: + raise SystemExit(f"bad status_addr={status_addr!r}") + host, port = status_addr.rsplit(":", 1) + frontend = replicas[0].get("frontend_address") or replicas[0].get("frontend_addr") or "" + if frontend.endswith(":3260") and frontend.rsplit(":", 1)[0] == host and port == "3260": + raise SystemExit("refusing to block iSCSI data port 3260") + print(f"status_addr={status_addr}") + print(f"status_host={host}") + print(f"status_port={port}") + print(f"volume_id={vols[0].get('volume_id','')}") + print(f"replica_id={replicas[0].get('replica_id','')}") + print(f"frontend_addr={frontend}") + PY + . "$OUT/status-target.env" + test "$status_port" != "3260" + echo "rule=iptables -I INPUT -p tcp --dport ${status_port} -j REJECT --reject-with tcp-reset" > "$OUT/iptables-rule.txt" + run_remote() { + if [ "$status_host" = "192.168.1.184" ] || [ "$status_host" = "127.0.0.1" ]; then + bash -s + else + ssh -i /opt/work/testdev_key -o StrictHostKeyChecking=no "testdev@${status_host}" bash -s + fi + } + run_remote > "$OUT/block-status-port.log" 2>&1 < "$OUT/unexpected-status-response.txt" 2>"$OUT/status-curl-after-block.stderr.txt"; then + echo "status endpoint still reachable after iptables block" >&2 + exit 1 + fi + echo "status_endpoint_blocked=true" > "$OUT/block-summary.txt" + cat "$OUT/status-target.env" >> "$OUT/block-summary.txt" + env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" + + - name: collect_live_unreachable_report + actions: + - action: exec + node: m02 + timeout: 4m + cmd: | + set -eu + ROOT=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live + OUT="$ROOT/live-report" + mkdir -p "$OUT" + port=$(python3 - <<'PY' + import socket + s = socket.socket() + s.bind(("127.0.0.1", 0)) + print(s.getsockname()[1]) + s.close() + PY + ) + echo "$port" > "$OUT/blockmaster-port.txt" + kubectl -n kube-system port-forward deploy/sw-blockmaster "${port}:9333" > "$OUT/blockmaster-port-forward.log" 2>&1 & + pf=$! + trap 'kill $pf >/dev/null 2>&1 || true; wait $pf >/dev/null 2>&1 || true' EXIT + for i in $(seq 1 60); do + if (echo >"/dev/tcp/127.0.0.1/$port") >/dev/null 2>&1; then + break + fi + sleep 1 + done + /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/bin/sw-block ops report --namespace default --master "127.0.0.1:${port}" --out "$OUT/report" --evidence-out "$OUT/evidence" --timeout 30s > "$OUT/report.stdout.txt" 2> "$OUT/report.stderr.txt" + volume_id=$(sed -n 's/^volume_id=//p' "$ROOT/fault/status-target.env" | head -1) + /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/bin/sw-block ops explain volume --from-bundle "$OUT/report" "$volume_id" > "$OUT/explain.txt" 2> "$OUT/explain.stderr.txt" + test -s "$OUT/report/operator-snapshot.json" + test -s "$OUT/report/summary.txt" + test -s "$OUT/explain.txt" + env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" + + - name: unreachable_asserts + actions: + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/fault/block-summary.txt" + pattern: "^status_endpoint_blocked=true$" + save_as: status_blocked_count + - action: assert_greater + actual: "{{ status_blocked_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/live-report/report/summary.txt" + pattern: "status=unknown reason=status_endpoint_unreachable" + save_as: summary_unknown_count + - action: assert_greater + actual: "{{ summary_unknown_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/live-report/explain.txt" + pattern: "managed_volume_condition Ready status=Unknown reason=status_endpoint_unreachable" + save_as: explain_unknown_count + - action: assert_greater + actual: "{{ explain_unknown_count }}" + threshold: "0" + - action: exec + node: m02 + timeout: 2m + cmd: | + set -eu + ROOT=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live + python3 - <<'PY' + import json + from pathlib import Path + snap = json.loads(Path("/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/live-report/report/operator-snapshot.json").read_text()) + if snap.get("read_only") is not True: + raise SystemExit("operator snapshot is not read-only") + if (snap.get("mutation") or {}).get("mutation_allowed") is not False: + raise SystemExit("mutation_allowed is not false") + vols = snap.get("volumes") or [] + if len(vols) != 1: + raise SystemExit(f"expected one volume, got {len(vols)}") + status = vols[0].get("status") or {} + if status.get("status") != "unknown" or status.get("reason_code") != "status_endpoint_unreachable": + raise SystemExit(f"expected unknown/status_endpoint_unreachable, got {status}") + for condition in status.get("conditions") or []: + if condition.get("type") == "Ready" and condition.get("status") == "True": + raise SystemExit("false Ready=True while status endpoint is unreachable") + if condition.get("type") == "Blocked" and condition.get("status") == "True": + raise SystemExit("false Blocked=True for pure status endpoint unreachable") + cluster = snap.get("cluster") or {} + if cluster.get("ready_volume_count", 0) != 0: + raise SystemExit(f"ready_volume_count should be 0 during unreachable evidence: {cluster}") + PY + port=$(python3 - <<'PY' + import socket + s = socket.socket() + s.bind(("127.0.0.1", 0)) + print(s.getsockname()[1]) + s.close() + PY + ) + echo "$port" > "$ROOT/dashboard/port.txt" + /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/bin/sw-block ops dashboard --from-bundle "$ROOT/live-report/report" --listen "127.0.0.1:${port}" > "$ROOT/dashboard/stdout.txt" 2> "$ROOT/dashboard/stderr.txt" & + pid=$! + trap 'kill $pid >/dev/null 2>&1 || true; wait $pid >/dev/null 2>&1 || true' EXIT + for i in $(seq 1 100); do + code=$(curl -s -o "$ROOT/dashboard/operator-snapshot.json" -w '%{http_code}' "http://127.0.0.1:${port}/operator-snapshot.json" || true) + test "$code" = "200" && break + sleep 0.2 + done + python3 - <<'PY' + import json + from pathlib import Path + snap = json.loads(Path("/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/dashboard/operator-snapshot.json").read_text()) + vols = snap.get("volumes") or [] + if len(vols) != 1: + raise SystemExit("dashboard snapshot did not preserve one volume") + status = vols[0].get("status") or {} + if status.get("status") != "unknown" or status.get("reason_code") != "status_endpoint_unreachable": + raise SystemExit(f"dashboard did not preserve unreachable status: {status}") + for condition in status.get("conditions") or []: + if condition.get("type") == "Ready" and condition.get("status") == "True": + raise SystemExit("dashboard false Ready=True") + if condition.get("type") == "Blocked" and condition.get("status") == "True": + raise SystemExit("dashboard false Blocked=True") + PY + + - name: restore_status_endpoint + always: true + actions: + - action: exec + node: m02 + timeout: 2m + cmd: | + set -eu + OUT=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/fault + if [ ! -f "$OUT/status-target.env" ]; then + exit 0 + fi + . "$OUT/status-target.env" + if [ -z "${status_host:-}" ] || [ -z "${status_port:-}" ]; then + echo "status endpoint was not blocked; no restore needed" > "$OUT/restore-summary.txt" + exit 0 + fi + run_remote() { + if [ "$status_host" = "192.168.1.184" ] || [ "$status_host" = "127.0.0.1" ]; then + bash -s + else + ssh -i /opt/work/testdev_key -o StrictHostKeyChecking=no "testdev@${status_host}" bash -s + fi + } + run_remote > "$OUT/restore-status-port.log" 2>&1 </dev/null; do :; done + ! sudo -n iptables -S INPUT | grep -- "--dport $status_port" + REMOTE + echo "status_endpoint_restored=true" > "$OUT/restore-summary.txt" + env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" + + - name: helm_uninstall_cleanup + always: true + actions: + - action: exec + node: m02 + timeout: 8m + cmd: "kubectl -n default delete pod sw-block-example-reader sw-block-example-writer --ignore-not-found=true --wait=true --timeout=120s; kubectl -n default delete pvc sw-block-example-pvc --ignore-not-found=true --wait=true --timeout=120s; kubectl delete storageclass sw-block-example sw-block-dynamic --ignore-not-found=true --wait=true --timeout=120s; helm status {{ helm_release }} --namespace {{ helm_namespace }} >/dev/null 2>&1 && helm uninstall {{ helm_release }} --namespace {{ helm_namespace }} --wait --timeout 240s > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/cleanup/helm-uninstall.txt || true; sudo -n iscsiadm -m node 2>/dev/null | awk '/io.seaweedfs/ {print $1, $2}' | while read portal target; do sudo -n iscsiadm -m node -T \"$target\" -p \"$portal\" -o delete || true; done; cd {{ product_root }} && bash scripts/verify-helm-cleanup.sh" + env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" + env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/cleanup/verify" + env.SW_BLOCK_HELM_RELEASE: "{{ helm_release }}" + env.SW_BLOCK_HELM_NAMESPACE: "{{ helm_namespace }}" + - action: assert_no_active_iscsi_sessions + node: m02 + iqn_substr: "io.seaweedfs" + - action: assert_no_processes + node: m02 + pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable-live/cleanup/verify/cleanup-summary.txt" + pattern: "^cleanup_status=ok$" + save_as: cleanup_ok_count + - action: assert_greater + actual: "{{ cleanup_ok_count }}" + threshold: "0" diff --git a/seaweed-block/testops/scenarios/status-endpoint-unreachable-replay-chain.yaml b/seaweed-block/testops/scenarios/status-endpoint-unreachable-replay-chain.yaml new file mode 100644 index 0000000000..084e112471 --- /dev/null +++ b/seaweed-block/testops/scenarios/status-endpoint-unreachable-replay-chain.yaml @@ -0,0 +1,200 @@ +# Phase 33 F2 gate: status endpoint unreachable replay. +# +# Goal: +# Prove a bundle that cannot reach replica status evidence is rendered as +# Unknown with reason=status_endpoint_unreachable across the user-facing +# read-only surfaces. This is intentionally replay-only: it validates the +# surface contract without introducing a second live failure mechanism. + +name: status-endpoint-unreachable-replay-chain +timeout: 10m + +env: + product_root: "/tmp/seaweed_block" + ssh_key: "C:\\work\\dev_server\\testdev_key" + +topology: + nodes: + m02: + host: 192.168.1.184 + user: testdev + key: "{{ ssh_key }}" + +phases: + - name: prepare + actions: + - action: exec + node: m02 + timeout: 1m + cmd: "rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/bin /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/bundle/demo/product-observation /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/report /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/dashboard" + - action: exec + node: m02 + timeout: 5m + cmd: "cd {{ product_root }} && go build -o /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/bin/sw-block ./cmd/sw-block" + + - name: render_unreachable_bundle + actions: + - action: exec + node: m02 + timeout: 1m + cmd: | + python3 - <<'PY' + import json + from pathlib import Path + + root = Path("/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/bundle/demo/product-observation") + root.mkdir(parents=True, exist_ok=True) + doc = { + "schema_version": "1.0", + "captured_at": "2026-05-28T12:00:00Z", + "product_revision": "phase33-f2-replay", + "status": "unavailable", + "nodes": [], + "volumes": [{ + "volume_id": "pvc-unreachable", + "namespace": "default", + "pvc_name": "demo-pvc", + "pv_name": "pvc-unreachable", + "replication_factor": 1, + "desired_replicas": 1, + "observed_replicas": 1, + "status": "unavailable", + "reason": "status_endpoint_unreachable", + "primary_replica": "r1", + "primary_node": "m01", + "publish_target": "192.168.1.181:3260", + "replicas": [{ + "replica_id": "r1", + "server_id": "node-r1", + "kubernetes_node": "m01", + "observed": True, + "role": "primary", + "replication_role": "none", + "frontend_protocol": "iscsi", + "frontend_addr": "192.168.1.181:3260", + "status_addr": "192.168.1.181:23260" + }] + }], + "events": [{ + "event_id": "phase33-f2-1", + "event_time": "2026-05-28T12:00:01Z", + "volume_id": "pvc-unreachable", + "replica_id": "r1", + "event_type": "status_endpoint_unreachable", + "severity": "warning", + "message": "replica status endpoint unreachable; readiness is not claimed", + "reason_code": "status_endpoint_unreachable", + "evidence_ref": "product-observation/cluster-evidence.json" + }], + "non_claims": [ + "read-only-observation: does not mutate product, Kubernetes, iSCSI, or replica state", + "not-an-admin-action: no promote, repair, rebuild, backup, restore, or cleanup is authorized" + ] + } + (root / "cluster-evidence.json").write_text(json.dumps(doc, indent=2) + "\n") + PY + + - name: replay_surfaces + actions: + - action: exec + node: m02 + timeout: 1m + cmd: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/bin/sw-block ops report --from-bundle /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/bundle --out /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/report > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/report/stdout.txt 2> /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/report/stderr.txt" + - action: exec + node: m02 + timeout: 1m + cmd: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/bin/sw-block ops explain volume --from-bundle /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/bundle pvc-unreachable > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/report/explain.txt" + - action: exec + node: m02 + timeout: 1m + cmd: | + set -e + OUT=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/dashboard + port=$(python3 - <<'PY' + import socket + s = socket.socket() + s.bind(("127.0.0.1", 0)) + print(s.getsockname()[1]) + s.close() + PY + ) + echo "$port" > "$OUT/port.txt" + /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/bin/sw-block ops dashboard --from-bundle /mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/bundle --listen 127.0.0.1:${port} > "$OUT/stdout.txt" 2> "$OUT/stderr.txt" & + pid=$! + trap 'kill $pid >/dev/null 2>&1 || true; wait $pid >/dev/null 2>&1 || true' EXIT + for i in $(seq 1 100); do + code=$(curl -s -o "$OUT/operator-snapshot.json" -w '%{http_code}' "http://127.0.0.1:${port}/operator-snapshot.json" || true) + test "$code" = "200" && break + sleep 0.2 + done + test -s "$OUT/operator-snapshot.json" + + - name: surface_asserts + actions: + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/report/summary.txt" + pattern: "managed_volume=pvc-unreachable status=unknown reason=status_endpoint_unreachable" + save_as: summary_unreachable_count + - action: assert_greater + actual: "{{ summary_unreachable_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/report/operator-snapshot.json" + pattern: "\"reason_code\": \"status_endpoint_unreachable\"" + save_as: report_snapshot_reason_count + - action: assert_greater + actual: "{{ report_snapshot_reason_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/report/operator-snapshot.json" + pattern: "\"mutation_allowed\": false" + save_as: report_snapshot_readonly_count + - action: assert_greater + actual: "{{ report_snapshot_readonly_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/report/explain.txt" + pattern: "managed_volume_condition Ready status=Unknown reason=status_endpoint_unreachable" + save_as: explain_unknown_count + - action: assert_greater + actual: "{{ explain_unknown_count }}" + threshold: "0" + - action: grep_log + node: m02 + path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/dashboard/operator-snapshot.json" + pattern: "\"reason_code\": \"status_endpoint_unreachable\"" + save_as: dashboard_reason_count + - action: assert_greater + actual: "{{ dashboard_reason_count }}" + threshold: "0" + - action: exec + node: m02 + timeout: 1m + cmd: | + python3 - <<'PY' + import json + from pathlib import Path + paths = [ + Path("/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/report/operator-snapshot.json"), + Path("/mnt/smb/work/share/g15d-k8s/{{ run_id }}-status-endpoint-unreachable/dashboard/operator-snapshot.json"), + ] + for path in paths: + doc = json.loads(path.read_text()) + if doc.get("read_only") is not True: + raise SystemExit(f"{path}: read_only not true") + if (doc.get("mutation") or {}).get("mutation_allowed") is not False: + raise SystemExit(f"{path}: mutation_allowed not false") + vols = doc.get("volumes") or [] + if len(vols) != 1: + raise SystemExit(f"{path}: expected one volume") + status = vols[0].get("status") or {} + if status.get("status") != "unknown" or status.get("reason_code") != "status_endpoint_unreachable": + raise SystemExit(f"{path}: bad status {status}") + for condition in status.get("conditions") or []: + if condition.get("type") == "Ready" and condition.get("status") == "True": + raise SystemExit(f"{path}: false Ready=True") + PY
VolumeStatusReasonConditionsSafe Actions