fix(block): preserve unknown outcomes for unlisted HTTP statuses (#13525)

* test: preserve unknown outcomes for unlisted proxy HTTP statuses

* fix: preserve unknown outcomes for unlisted HTTP statuses

* docs: split HTTP outcome invariants into individual properties

* test: verify retained HTTP status and scope recovery guidance
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-12-06 06:18:38 -08:00
1 parent b063945815
commit c1c7679a29
8 files changed
+173 -4

No files matched your search

@@ -0,0 +1,59 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
func TestSnapshotProxyUnlistedHTTPStatusIsUnknown(t *testing.T) {
for _, code := range []int{408, 421, 423, 431, 499, 505, 520, 524} {
t.Run(fmt.Sprint(code), func(t *testing.T) {
received := make(chan string, 1)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body struct {
RequestID string `json:"requestID"`
}
if r.Method != http.MethodPost || r.URL.Path != "/chunk/snapshot" {
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Error(err)
}
received <- body.RequestID
w.WriteHeader(code)
fmt.Fprint(w, "<html>proxy could not observe the origin outcome</html>")
}))
defer srv.Close()
var out, diag bytes.Buffer
var admission snapshotCLIAdmission
exit := chunkPost("snapshot", srv.URL, "/chunk/snapshot", 3*time.Second, map[string]any{"requestID": "same-original-snapshot"}, &out, &diag, &admission)
got := chunkErrorOut(t, out.String())
if exit != 3 || got.Code != "outcome_unknown" || !got.Retryable || admission.Accepted || !strings.Contains(got.Message, "replay key") {
t.Fatalf("exit=%d answer=%+v accepted=%v stderr=%s", exit, got, admission.Accepted, &diag)
}
select {
case id := <-received:
if id != "same-original-snapshot" {
t.Fatalf("wire ID=%q", id)
}
default:
t.Fatal("POST never reached proxy")
}
})
}
}
func TestOperatorUnlistedHTTPStatusIsUnknown(t *testing.T) {
p, err := operatorAnswer(answer.HTTPStatusFailure(418, fmt.Errorf("proxy lost origin answer")), answer.Failover)
if p.Code != "outcome_unknown" || !p.Retryable || p.Retry != answer.Recover || p.Exit != 3 || !strings.Contains(err.Error(), "current authority line") {
t.Fatalf("policy=%+v err=%v", p, err)
}
}
+8 -1
View File
@@ -15,7 +15,14 @@ func HTTPStatusFailure(status int, cause error) error {
}
// The response status belongs to this attempt; a nested body-read
// failure cannot replace it. Keep outer operation records authoritative.
return &failure{phase: PossiblyAdmitted, kind: httpStatusKind(status), cause: &httpStatusFailure{status: status, cause: cause}}
kind := httpStatusKind(status)
if _, listed := registry[key{PossiblyAdmitted, kind}]; !listed {
// A proxy status outside the registry cannot establish the origin's
// outcome. Use the canonical unknown policy for every wire contract;
// keep the actual HTTP status and cause in the error chain.
kind = rpcKindKey(codes.Unknown)
}
return &failure{phase: PossiblyAdmitted, kind: kind, cause: &httpStatusFailure{status: status, cause: cause}}
}
type httpStatusFailure struct {
@@ -0,0 +1,39 @@
package answer
import (
"errors"
"fmt"
"testing"
)
func TestHTTPStatusFailureRetainsStatusAndCause(t *testing.T) {
for _, code := range []int{401, 408, 501, 520, 524, 599} {
t.Run(fmt.Sprint(code), func(t *testing.T) {
cause := errors.New("proxy body was unreadable")
original := HTTPStatusFailure(code, cause)
for _, row := range []struct {
name string
err error
}{
{"direct", original},
{"wrapped", fmt.Errorf("snapshot observation: %w", original)},
{"chunk", Present(original, Chunk)},
{"failover", Present(original, Failover)},
{"ops", Present(original, Ops)},
} {
t.Run(row.name, func(t *testing.T) {
var received *httpStatusFailure
if !errors.As(row.err, &received) {
t.Fatalf("HTTP response record missing from error chain: %v", row.err)
}
if received.status != code {
t.Fatalf("stored status=%d want=%d", received.status, code)
}
if !errors.Is(row.err, cause) {
t.Fatalf("original cause missing from error chain: %v", row.err)
}
})
}
})
}
}
@@ -0,0 +1,41 @@
package answer_test
import (
"errors"
"fmt"
"testing"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
func TestUnlistedHTTPStatusPreservesUnknownOutcome(t *testing.T) {
for _, code := range []int{408, 418, 421, 423, 431, 499, 505, 520, 524, 599} {
t.Run(fmt.Sprint(code), func(t *testing.T) {
cause := errors.New("proxy returned an HTML error after the POST")
err := answer.HTTPStatusFailure(code, cause)
if answer.DefiniteAnswer(err) || !errors.Is(err, cause) {
t.Fatalf("definite=%v cause preserved=%v", answer.DefiniteAnswer(err), errors.Is(err, cause))
}
for _, contract := range []answer.Contract{answer.Chunk, answer.Workspace, answer.Cluster, answer.Restore, answer.Failover, answer.VolumeJob, answer.VolumeStop, answer.VolumePlacement, answer.Shell, answer.Ops} {
p, check := answer.PolicyOf(err, contract)
if check != nil || p.Code != "outcome_unknown" || !p.Retryable || p.Retry != answer.Recover || p.Exit != 3 {
t.Fatalf("contract=%s policy=%+v check=%v", contract, p, check)
}
}
for _, row := range []struct {
contract answer.Contract
exit int
retry answer.RetryRule
}{
{answer.ChunkVerify, 1, answer.Resend},
{answer.VolumeCreate, 75, answer.Recover},
{answer.VolumeResolve, 75, answer.Recover},
} {
p, check := answer.PolicyOf(err, row.contract)
if check != nil || p.Code != "outcome_unknown" || !p.Retryable || p.Retry != row.retry || p.Exit != row.exit {
t.Fatalf("legacy contract=%s policy=%+v check=%v", row.contract, p, check)
}
}
})
}
}
@@ -34,7 +34,7 @@ func TestPresentationPreservesProtocolErrorChain(t *testing.T) {
}
func TestUnlistedHTTPStatusFailsPolicyCheck(t *testing.T) {
if _, err := answer.PolicyOf(answer.HTTPStatusFailure(599, errors.New("unlisted HTTP status"))); err == nil {
if _, err := answer.Lookup(answer.PossiblyAdmitted, answer.Kind{Name: "http/599"}); err == nil {
t.Fatal("unlisted HTTP status passed the registry")
}
}
@@ -266,3 +266,22 @@ delegated 409 returns in `chunkErrorCode`. Each direct code expression needs
an explicit outcome class; dynamic stored and catalog answers require their
typed body. The negative control rejects an unclassified new 409 code. These
classes never authorize a non-admission inference from status alone.
## Unlisted HTTP response statuses
A failed HTTP response whose status has no registry row does not prove the
origin refused the operation. The shared HTTP boundary retains the received
status and cause and selects the existing possibly-admitted unknown policy.
Snapshot/non-plain-detach POST and failover answers are `outcome_unknown`,
retryable, exit 3. Recovery depends on the operation:
- Snapshot: recover the original request with its replay key and unchanged
parameters, or poll an already obtained handle.
- Non-plain detach has no replay key or handle: keep the writer stopped and
inspect the original holder's HEAD/logs for a confirmed seal or abort.
Preserve diagnostics and investigate if the outcome remains unproven.
- Failover: read the current authority line before another move.
Documented contract-specific legacy exits remain in the single exit projection.
Listed statuses retain their existing policies, including 401/403 auth
refusals and 501 unsupported. A typed domain reply remains authoritative.
+4
View File
@@ -1326,6 +1326,10 @@ Notes:
| `INV-SNAPSHOT-REPLAY-FLAG-001` | A successful same-ID snapshot admission reports replayed true without changing HEAD or its retained outcome. First creation reports false; the flag decorates only the response. | M9 snapshot outcome projection | `core/host/volume/snapshot_operation.go`, `chunk_control.go`; `cmd/sw-block/snapshot_operation.go` | `TestSnapshotReplayFlagDoesNotRewriteOutcome`, `TestSnapshotCLIUsesReplayedAdmissionAnswer` | SnapOps.Poll; SnapOps.Start (no transition change) | STUB |
| `INV-CLI-UNSENT-REQUEST-001` | An observed operation's initial typed dial failure sends no admission and is remote_unavailable (75) through the shared classifier. A lost answer after send, or a dial failure while polling an admitted handle, retains outcome_unknown. | CLI pre-admission error projection; no server transition | `cmd/sw-block/cut_progress_poll.go` `chunkObserveHandle`; `chunkTransportFailure`, `chunkFail` | `TestPlainDetachRefusedDialIsRemoteUnavailable`, `TestPlainDetachLostAnswerAfterSendStaysUnknown`, `TestPlainDetachPollDialFailureKeepsAdmittedOutcomeUnknown`, `TestOpsChunk_ErrorsAreJSONOnStdout` | CutTime Poll/CliGiveUp boundary; pre-admission transport proof | ACTIVE |
| `INV-CLI-MINI-EXECUTABLE-001` | Mini records and launches the executable selected by --weed without changing symlink/.. resolution; fresh and legacy runs use an absolute path. | TrialLauncher path wiring, no protocol transition | `cmd/sw-block/mini.go` `miniExecutablePath`, `mini`, `reuseMiniRecord` | `TestMiniWeedSymlinkParentKeepsSelectedExecutable`, `TestMiniRelativeWeedIsRecordedAndPrintedAbsolutely` (`cmd/sw-block`); `TestMiniCleanupFailStopAndSettlement` (`cmd/blockvolume`: failed-start proof rejects watchdog intervention; settled capture completes and live residue refuses cleanup) | NONE (path selection and test ownership only; fresh Linux qualification pending) | STUB |
| `INV-CLI-UNLISTED-HTTP-001` | An HTTP failure status absent from the registry is possibly admitted and projects outcome_unknown with recovery of the same operation. | Answer policy (pure function) | `core/rpc/answer/http_status.go` `HTTPStatusFailure` | `TestUnlistedHTTPStatusPreservesUnknownOutcome` (`core/rpc/answer/http_unlisted_test.go`); `TestSnapshotProxyUnlistedHTTPStatusIsUnknown`, `TestOperatorUnlistedHTTPStatusIsUnknown` (`cmd/sw-block/http_unlisted_test.go`) | NONE (pure error projection; no protocol transition) | ACTIVE |
| `INV-CLI-UNLISTED-HTTP-002` | HTTP failure projection preserves the received status and original cause. | Answer policy (pure function) | `core/rpc/answer/http_status.go` `HTTPStatusFailure` | `TestHTTPStatusFailureRetainsStatusAndCause` (`core/rpc/answer/http_status_retention_test.go`) | NONE (pure error projection; no protocol transition) | ACTIVE |
| `INV-CLI-UNLISTED-HTTP-003` | Documented contract-specific legacy exits remain in the global exit projection. | Answer policy (pure function) | `core/rpc/answer/http_status.go` `HTTPStatusFailure` | `TestUnlistedHTTPStatusPreservesUnknownOutcome` (`core/rpc/answer/http_unlisted_test.go`) | NONE (pure error projection; no protocol transition) | ACTIVE |
| `INV-CLI-UNLISTED-HTTP-004` | Listed HTTP failure statuses retain their existing policy. | Answer policy (pure function) | `core/rpc/answer/http_status.go` `HTTPStatusFailure` | `TestProducedHTTPStatusPolicyRows` (`core/rpc/answer/http_status_test.go`); `TestReviewCompleteBodyKeepsStatusAndAdmission` (`cmd/sw-block/review_complete_answer_test.go`) | NONE (pure error projection; no protocol transition) | ACTIVE |
| `INV-TLS-CA-BUNDLE-PARSE-001` | CA loading skips unparseable or PEM-header certificate blocks, retaining loadable alternatives as AppendCertsFromPEM does. No loadable root is a local credential refusal; the selected TLS chain still must verify. | Local credential parsing (pure function) | `core/rpc/answer/credentials.go` `CertificatePool`; `core/rpc/link/tls.go` `pool` | `TestCertificatePoolSkipsUnparseableAlternatives` (`core/rpc/answer/credentials_bundle_test.go`); `TestMasterLinkCARotationUsesTheVerifiedChain/malformed` (`core/rpc/link/ca_rotation_test.go`) | NONE (pure certificate parsing; no protocol transition) | ACTIVE |
| `INV-CLI-CATALOG-ERROR-001` | The chunk CLI preserves admission evidence and definite domain/certificate answers. Possibly-sent requests require replay/poll. Incomplete verify never exits 3; non-retryable server answers never exit 75. Absent snapshot delete is snapshot_not_found. | M9 client error projection; M4 census refusal, no transition change | `core/rpc/answer` `Lookup`; `cmd/sw-block/chunk_answer.go` `chunkAnswer`; `cmd/sw-block/chunk.go` `chunkResult`; `cmd/sw-block/catalog_snapshot_operation.go` `catalogSnapshotDeleteRefusal`; `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `core/frontend/chunkstore/layout/delete.go` `RunMarkDeleting` | `TestOpsChunkTransportFailureMatrix`, `TestOpsChunkVerifyUnreachableCensusPreservesTransport`, `TestCheckSingleFilerKeepsTransportCause`, `TestSingleFilerConfigurationErrorDeadlineBetweenReads`, `TestCheckSingleFilerSlowDialOrdering`, `TestDialBCatalogKeepsCustomCallerDeadline`, `TestMasterCensusKeepsCustomCallerDeadline`, `TestCheckSingleFilerValidatesAllMasterAddressesBeforeCensus`; `TestOpsChunkCatalogUnavailableIsTyped`, `TestCatalogTransportClassificationKeepsDefiniteAnswers`, `TestSnapshotDeleteAbsentCLIUsesContractCodeAndKeepsReceipt`; `TestLinkNeverTurnsASentRequestIntoSafeResend`; `TestChunkHTTPPostLostAnswerIsUnknown`; `TestCommandFamilyTransportGrid`; `TestLocalCredentialsFailBeforeDialWithTypedPolicy`; `TestHTTPCancellationBeforeDispatchKeepsOperationPhase`; `TestDeclaredDomainCodesHaveRegistryRows`; `TestOwnedClientTransportsKeepAdmissionEvidence`; `TestPresentationFailsClosedForUnknownContract`; `TestUnsentRPCWithMixedPeerFailuresIsRetryable`; `TestRPCPeerCertificateFailureDoesNotHideHandshakeTimeout`; `TestRPCSucceedsOnGoodPeerAfterBadCertificate`; `TestPeerCertificateProofRequiresEveryFreshCompletedAttempt`; `TestPeerDiagnosticTruncationNeverAuthorizesTerminalClassification`; `TestTypedRemoteUnavailableRespectsRetryable`; `TestNonRetryableServerAnswerNeverInvitesTemporaryRetry`; `TestVerifyStartCheckLostAnswerNeverLooksLikeFindings`; `TestVerifyIncompleteTransportPreservesPartialProgress`; `TestOpsFailoverUsesSharedDefiniteExitProjection`; `TestBlobHTTPAnswerSurvivesLayoutFetch`; `TestPlaintextPrefaceFailureKeepsUnsentRetryAndTLSHint`; `TestHTTPPartialCustomTraceCannotProveUnsentAfterReceivedPOST`; `TestHTTPRegisteredProtocolCannotProveUnsentAfterReceivedPOST`; `TestHTTPOwnedTransportDoesNotInheritRegisteredDefault`; `TestDelayedPeerNotificationCannotRefreshAnOldTLSFailure`; `TestObservedTLSForwardsPerCallAuthorityValidation`; `TestChunkCensusPreflightPreservesOpaqueContextCause`; `TestSingleFilerReviewPreservesDefiniteAndCallerWinner`; `TestReviewContextAndDefiniteAnswerPrecedence`; `TestReviewOldPickerCannotBorrowNewPeerGeneration`; `TestReviewContractProjectionAndReadOnlyRecovery`; `TestReviewAdmittedPollTLSFailureKeepsOperationRecoverable`; `TestReviewPickerCannotReplaceCustomCallerDeadline`; `TestReviewSelectedTLSCannotReplaceCallerCompletion`; `TestReviewHTTPStatusOverridesNestedTransport`; `TestReviewVerifyPreservesServerRetryRefusal`; `TestReviewInitialPostBodyFailurePreservesStatus`; `TestReviewForceMovePreservesServerPolicyExit`; `TestReviewFailoverDomainAnswerRequiresRecovery`; `TestSnapshotOperationCLIInterruptThenResumeUsesPrintedID`; `TestSnapshotOperationCLIInterruptedTLSKeepsUnknownAndHandle`; `TestReviewCompleteBodyKeepsStatusAndAdmission`; `TestChunkUnusableConflictAnswerIsUnknown`; `TestChunkConflictLoopKeepsOriginalRequest`; `TestReviewInvalidAdmissionKeepsOriginalRequest`; `TestReviewUnsafeSnapshotLocationKeepsOriginalUnknown`; `TestReviewAdmittedMissingResultKeepsUnknown`; `TestCutBusyHasItsOwnLegacyExitClass`; `TestCutCLIBusyIsDistinctAndDoesNotStartAnotherCut` | SnapOps.Poll; CutTime.Poll; CutTime.CliGiveUp (result projection; no new transition) | STUB |
| `INV-CLI-CHUNK-LOOP-001` | Above the per-request bound, sw-block ops chunk snapshot\|detach repeats the SAME request (same name and request id) only after a retryable or outcome_unknown answer. Manual cut and plain detach use the separate one-POST/read-only-poll contract. | client (no state machine): the CLI side of M5 requests | `cmd/sw-block/chunk_loop.go` `chunkPostLoop`; `cmd/sw-block/chunk.go` `chunkPostUntil` | `TestChunkSnapshotRepeatsTimedOutRequestsWithTheSameBody`, `TestChunkSnapshotLoopReusesTheGeneratedRequestID`, `TestChunkLoopRepeatsAnOutcomeUnknownNotMarkedRetryable` (`cmd/sw-block`) | — | ACTIVE |
+2 -2
View File
@@ -121,8 +121,8 @@ second non-idempotent operation after an uncertain answer.
| Snapshot observation: succeeded without a result, at admission or poll | 1 | 3 with `outcome_unknown` | Recover the original request id/handle; the incomplete observation does not settle it. |
| Plain detach: malformed seal result | 1 | 3 with `outcome_unknown` | The operator must stop and keep the guest writer stopped, with authority unchanged, a granted lease for the same holder and epoch, and the same HEAD claim recorded before the first attempt. Recheck all prerequisites in the [repeat procedure](../volume-lifecycle.md#recover-an-unknown-plain-detach). Under those conditions, repeat the same plain detach to complete the intended final detach: if already sealed it publishes nothing and answers the sealed HEAD from a fresh read; otherwise it can complete the seal. `plain_detach_busy` is not proof that the writer is stopped. The repeat does not establish what the first attempt did; inspect `ops chunk show` for the resulting seal. |
| Snapshot observation: JSON decoder failure | 75 | 3 with `outcome_unknown` | Recover the original operation; malformed data does not settle it. |
| Snapshot/non-plain-detach initial HTTP answer: unusable 4xx body, except 409/429 | 1 | 1 / 2 / 5 | Preserve the received auth/argument/refusal class; do not infer it from a nested transport error. |
| Snapshot/non-plain-detach initial HTTP answer: unusable 409/429, 5xx except 501, other non-200 answer excluding 4xx and 501, or oversized success/admission | 1 | 3 with `outcome_unknown` | Snapshot: recover with the original request id and unchanged parameters or an already obtained handle. Non-plain detach has no such identifier: keep the writer stopped and inspect the original holder HEAD/logs for a confirmed seal or abort; unproven outcomes require investigation. An unusable 409 never proves non-admission. |
| Snapshot/non-plain-detach initial HTTP answer: unusable listed 4xx body, except 409/429 | 1 | 1 / 2 / 5 | Preserve the received auth/argument/refusal class; do not infer it from a nested transport error. |
| Snapshot/non-plain-detach initial HTTP answer: unusable 409/429, 5xx except 501, unlisted HTTP status (including 408/421/423/431/499), other non-200 answer excluding listed 4xx and 501, or oversized success/admission | 1 | 3 with `outcome_unknown` | Snapshot: recover with the original request id and unchanged parameters or an already obtained handle. Non-plain detach has no such identifier: keep the writer stopped and inspect the original holder HEAD/logs for a confirmed seal or abort; unproven outcomes require investigation. An unusable 409 never proves non-admission. |
| Snapshot/non-plain-detach initial HTTP answer: unusable 501 body | 1 | 1 with `unsupported` | The server does not implement the operation; use a server that supports it. This status is excluded from the unknown-response row above. |
| Cut/plain-detach observer: readable malformed initial 409 or unsupported version | 3 | 3 with `unsupported_api_version`, non-retryable | The observer cannot establish the original outcome. Query a previously printed handle if available; without one, cut may establish a later durable point, while detach requires confirming the original seal or abort from holder HEAD/logs before proceeding. |
| Snapshot admission: invalid identity/body or unsafe operation URL | 1 | 3 with `outcome_unknown` | Refuse the unsafe URL and retain the original request id; retry that id against the original status address. |