Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Fix Docker report size contract drift
rcourtman0c1792205528
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 6a6f76eb99..a08b946279 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -32,6 +32,11 @@ one compressed unified-agent report without a collector-side suffix cap.websocket payloads. Carrying plural availability facets through that serializeris an adjacent monitoring/API projection and does not change agent enrollment,report admission, removal, update, profile, or command authority.+Docker / Podman report sizing is a two-dimensional transport contract:+`pkg/agents/docker/report_limits.go` owns the inclusive encoded HTTP-body and+decoded JSON byte ceilings, derives the 80% early-warning boundaries, and+generates the operator-facing limit description consumed by server ingress+and every supported `pulse-agent` release target built from this source.## Canonical Files@@ -46,6 +51,7 @@ report admission, removal, update, profile, or command authority.5c. `internal/dockeragent/container_update_typed.go`5d. `internal/kubernetesagent/agent.go`5e. `internal/agentexec/verifier_postconditions.go`+ 5f. `pkg/agents/docker/report_limits.go`6. `cmd/pulse-agent/main.go`7. `scripts/install.sh`8. `scripts/install.ps1`@@ -116,6 +122,17 @@ report admission, removal, update, profile, or command authority.## Shared Boundaries+Docker / Podman report transport is shared with `api-contracts`.+`internal/dockeragent/agent.go` measures the gzip-encoded HTTP entity and the+decoded JSON before attempting any destination, while+`internal/api/docker_agents.go` enforces the same+`pkg/agents/docker/report_limits.go` contract. Exactly 2,097,152 encoded bytes+and 10,485,760 decoded bytes are accepted; only the first byte above either+ceiling is rejected. Warning copy must derive its limit wording from that+contract and retain exact structured byte fields, so Docker, Podman, native,+containerized, updated, and restarted Unified Agent runtimes cannot silently+return to a stale hard-coded threshold.+Docker container update recreation under `internal/dockeragent/` is lifecyclemutation authority, not monitoring collection. The module must translatedaemon inspect output into a desired create plan before the original container@@ -1806,6 +1823,11 @@ the intentionally sparse public response.## Completion Obligations+Any Docker / Podman report-size change must update the shared contract, agent+diagnostic proof, API encoded/decoded boundary proof, and the API-contract+dependency in one slice. A handler-local literal, agent-local threshold, or+freehand limit string is incomplete even if one side's tests pass.+The shared router's canonical RBAC initialization is an adjacentsecurity/API-contract boundary. It must remain a one-time startup and shutdowndependency and must not alter agent registration, install tokens, profiles,@@ -2056,6 +2078,17 @@ Agent` secondary handoff against the live setup wizard instead of relying## Current State+### Docker and Podman report sizes share one exact-byte contract++The Unified Agent now measures the encoded gzip body and decoded report JSON+against the same constants used by server ingress. The 80% warning boundaries+are derived with integer ceiling semantics, the old 400 KiB/512 KB warning is+retired, and diagnostics identify both byte counts and both ceilings before a+send is attempted. All supported native release binaries and the+container-agent entrypoint compile the same `internal/dockeragent` module; an+installed older agent adopts this behavior only after the normal agent update+and process/service restart loads a build containing the shared contract.+### Docker updates recreate desired configuration and replay terminal truthThe Docker module now builds an immutable recreate plan from inspect outputdiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex d7d199f4ec..14bad75e8a 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -1903,6 +1903,14 @@ a new API state machine, queue contract, or verification-accounting field.hide/unhide, pending uninstall, display-name, and host metadata paths mustuse Docker / Podman module or host wording instead of generic containerruntime labels.+ 3ba. Route Docker / Podman report body sizing through+ `pkg/agents/docker/report_limits.go` and+ `internal/api/docker_agents.go`. The endpoint accepts exact inclusive+ ceilings of 2,097,152 encoded HTTP-body bytes and 10,485,760 decoded JSON+ bytes, preserves empty-encoding and gzip compatibility, and returns+ `413 report_too_large` with `dimension` and `limitBytes` diagnostics for the+ first byte over either boundary. Unsupported encodings remain `415`;+ malformed gzip and invalid JSON remain distinct `400` failures.3c. Route Assistant finding handoff context changes through`internal/api/ai_handler.go`, `internal/api/ai_handler_test.go`, and`internal/api/contract_test.go` together. Patrol-originated handoffs must@@ -2999,6 +3007,12 @@ a new API state machine, queue contract, or verification-accounting field.## Completion Obligations+Docker / Podman report transport changes must prove uncompressed and gzip+ingress, exact inclusive boundaries, encoded and decoded 413 rejection,+ordinary and 163-container Docker/Podman fleets, and typed compression+diagnostics. The handler must consume the agent-lifecycle-owned shared+contract rather than restating size constants or warning text.+RBAC transport changes must prove that settings, SSO role mapping, andauthorization share one default-organization manager; that healthy emptycollections serialize as arrays; and that provider, migration, or read errors@@ -3608,6 +3622,15 @@ binary request names the exact returned target version. Query values affectintermediary cache identity only; they do not select an arbitrary serverrelease, bypass artifact validation, or replace the canonical response body.+### Docker and Podman report ingress enforces the shared size contract++`POST /api/agents/docker/report` reads the complete encoded entity through+`http.MaxBytesReader` before decoding, preventing unread gzip trailers or+trailing entity bytes from evading the 2 MiB boundary. The shared decoder then+applies the 10 MiB decoded ceiling and `json.Unmarshal` validates the complete+JSON document. Boundary rejections are 413 responses with exact byte+dimensions; compression-format and JSON failures retain separate diagnostics.+### vSphere host composition on the vCenter system rowGrouped systems in `GET /api/connections` now project ESXi host resources asdiff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.jsonindex 5a98a72927..c6c2a7d1cf 100644--- a/docs/release-control/v6/internal/subsystems/registry.json+++ b/docs/release-control/v6/internal/subsystems/registry.json@@ -1250,6 +1250,7 @@"internal/monitoring/monitor_agents.go","internal/remoteconfig/client.go","internal/securityutil/httpurl.go",+ "pkg/agents/docker/report_limits.go","pkg/agents/host/report.go","pkg/securityutil/httpurl.go","scripts/install.ps1",@@ -1382,6 +1383,7 @@"internal/kubernetesagent/agent.go","internal/remoteconfig/client.go","internal/securityutil/httpurl.go",+ "pkg/agents/docker/report_limits.go","pkg/securityutil/httpurl.go"],"allow_same_subsystem_tests": false,@@ -1391,11 +1393,13 @@"internal/agenttls/config_test.go","internal/dockeragent/agent_internal_test.go","internal/dockeragent/multi_target_test.go",+ "internal/dockeragent/report_size_test.go","internal/kubernetesagent/agent_new_test.go","internal/kubernetesagent/multi_target_test.go","internal/remoteconfig/client_additional_test.go","internal/remoteconfig/client_test.go",- "internal/securityutil/httpurl_test.go"+ "internal/securityutil/httpurl_test.go",+ "pkg/agents/docker/report_limits_test.go"]},{@@ -2849,6 +2853,7 @@"internal/api/ai_handlers_more_test.go","internal/api/ai_handlers_patrol_actions_additional_test.go","internal/api/contract_test.go",+ "internal/api/docker_agents_report_size_test.go","internal/api/host_agent_removal_lifecycle_integration_test.go","internal/api/metadata_handlers_test.go","internal/api/patrol_autopilot_test.go"diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex e7e1c2e820..635621a430 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -119,6 +119,14 @@ states do not change the underlying storage evidence or active lifecycle.## Extension Points+Docker / Podman report ingress under `internal/api/docker_agents.go` is outside+storage/recovery ownership even though storage/recovery routes share the broad+`internal/api/` extension boundary. Encoded/decoded report ceilings,+compression diagnostics, and agent warning behavior remain owned by+`api-contracts` and `agent-lifecycle`; storage/recovery consumers must not+reinterpret an accepted large inventory report as backup coverage, recovery+freshness, or restore evidence.+Commercial v5-to-v6 migration posture may be carried by `internal/api/`handlers that storage/recovery references for setup or support-adjacent flows,but it remains API/cloud-paid state. Storage and recovery surfaces may pointdiff --git a/internal/api/docker_agents.go b/internal/api/docker_agents.goindex 655f1c1f52..114cba6e37 100644--- a/internal/api/docker_agents.go+++ b/internal/api/docker_agents.go@@ -4,7 +4,10 @@ import ("context""encoding/json""errors"+ "fmt"+ "io""net/http"+ "strconv""strings""time"@@ -83,21 +86,42 @@ func (h *DockerAgentHandlers) HandleReport(w http.ResponseWriter, r *http.Requesreturn}- // Limit request body to 2MB to prevent memory exhaustion- // (512KB was too small for users with 100+ containers)- r.Body = http.MaxBytesReader(w, r.Body, 2*1024*1024)+ // The shared report contract separately caps the encoded HTTP body and the+ // decoded JSON body. Exact boundary values are accepted.+ r.Body = http.MaxBytesReader(w, r.Body, agentsdocker.ReportEncodedBodyLimitBytes)defer r.Body.Close()- // Support gzip-compressed reports from agents (backward compatible with uncompressed)- body, err := utils.DecompressBodyIfGzipped(r, 10*1024*1024)+ encodedBody, err := io.ReadAll(r.Body)if err != nil {- writeErrorResponse(w, http.StatusUnsupportedMediaType, "unsupported_encoding", err.Error(), nil)+ var maxBytesErr *http.MaxBytesError+ if errors.As(err, &maxBytesErr) {+ writeDockerReportSizeError(w, &agentsdocker.ReportSizeError{+ Dimension: agentsdocker.ReportSizeEncodedBody,+ LimitBytes: agentsdocker.ReportEncodedBodyLimitBytes,+ })+ return+ }+ writeErrorResponse(w, http.StatusBadRequest, "invalid_body", "Failed to read request body", map[string]string{"error": err.Error()})+ return+ }++ body, err := agentsdocker.DecodeReportBody(encodedBody, r.Header.Get("Content-Encoding"))+ if err != nil {+ var sizeErr *agentsdocker.ReportSizeError+ var encodingErr *agentsdocker.UnsupportedReportContentEncodingError+ switch {+ case errors.As(err, &sizeErr):+ writeDockerReportSizeError(w, sizeErr)+ case errors.As(err, &encodingErr):+ writeErrorResponse(w, http.StatusUnsupportedMediaType, "unsupported_encoding", encodingErr.Error(), nil)+ default:+ writeErrorResponse(w, http.StatusBadRequest, "invalid_compression", "Failed to decompress request body", map[string]string{"error": err.Error()})+ }return}- defer body.Close()var report agentsdocker.Report- if err := json.NewDecoder(body).Decode(&report); err != nil {+ if err := json.Unmarshal(body, &report); err != nil {writeErrorResponse(w, http.StatusBadRequest, "invalid_json", "Failed to decode request body", map[string]string{"error": err.Error()})return}@@ -144,6 +168,27 @@ func (h *DockerAgentHandlers) HandleReport(w http.ResponseWriter, r *http.Reques}}+func writeDockerReportSizeError(w http.ResponseWriter, sizeErr *agentsdocker.ReportSizeError) {+ details := map[string]string{+ "dimension": string(sizeErr.Dimension),+ "limitBytes": strconv.FormatInt(sizeErr.LimitBytes, 10),+ }+ if sizeErr.ActualBytes > 0 {+ details["actualBytes"] = strconv.FormatInt(sizeErr.ActualBytes, 10)+ }++ writeErrorResponse(+ w,+ http.StatusRequestEntityTooLarge,+ "report_too_large",+ fmt.Sprintf(+ "Docker / Podman report exceeds the server size limit (%s)",+ agentsdocker.ReportSizeLimitDescription(),+ ),+ details,+ )+}+// HandleDockerHostActions routes docker host management actions based on path and method.func (h *DockerAgentHandlers) HandleDockerHostActions(w http.ResponseWriter, r *http.Request) {// Check if this is an allow reenroll requestdiff --git a/internal/api/docker_agents_report_size_test.go b/internal/api/docker_agents_report_size_test.gonew file mode 100644index 0000000000..7f62642cd8--- /dev/null+++ b/internal/api/docker_agents_report_size_test.go@@ -0,0 +1,303 @@+package api++import (+ "bytes"+ "compress/gzip"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strconv"+ "testing"+ "time"++ agentsdocker "github.com/rcourtman/pulse-go-rewrite/pkg/agents/docker"+)++func TestDockerAgentReportSizeContractAcceptsOrdinaryAndLargeFleets(t *testing.T) {+ tests := []struct {+ name string+ runtime string+ containers int+ compressed bool+ }{+ {name: "ordinary Docker uncompressed", runtime: "docker", containers: 1},+ {name: "large Docker compressed", runtime: "docker", containers: 163, compressed: true},+ {name: "ordinary Podman compressed", runtime: "podman", containers: 1, compressed: true},+ {name: "large Podman uncompressed", runtime: "podman", containers: 163},+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ handler, _ := newDockerAgentHandlers(t, nil)+ body := dockerFleetReportBody(t, test.runtime, test.containers)+ if test.compressed {+ body = gzipAPIReportBody(t, body)+ }++ req := httptest.NewRequest(http.MethodPost, "/api/agents/docker/report", bytes.NewReader(body))+ if test.compressed {+ req.Header.Set("Content-Encoding", "gzip")+ }+ rec := httptest.NewRecorder()+ handler.HandleReport(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200: %s", rec.Code, rec.Body.String())+ }+ })+ }+}++func TestDockerAgentReportSizeContractBoundaries(t *testing.T) {+ t.Run("uncompressed exact encoded limit accepted", func(t *testing.T) {+ handler, _ := newDockerAgentHandlers(t, nil)+ body := padDockerReportBody(t, dockerFleetReportBody(t, "docker", 1), agentsdocker.ReportEncodedBodyLimitBytes)+ rec := postDockerReport(handler, body, "")+ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200: %s", rec.Code, rec.Body.String())+ }+ })++ t.Run("uncompressed byte over encoded limit rejected", func(t *testing.T) {+ handler := &DockerAgentHandlers{}+ body := padDockerReportBody(t, dockerFleetReportBody(t, "docker", 1), agentsdocker.ReportEncodedBodyLimitBytes+1)+ rec := postDockerReport(handler, body, "")+ assertDockerReportTooLarge(t, rec, agentsdocker.ReportSizeEncodedBody, agentsdocker.ReportEncodedBodyLimitBytes, 0)+ })++ t.Run("gzip exact encoded limit accepted", func(t *testing.T) {+ handler, _ := newDockerAgentHandlers(t, nil)+ body := gzipAPIReportBodyWithEncodedSize(+ t,+ dockerFleetReportBody(t, "docker", 1),+ agentsdocker.ReportEncodedBodyLimitBytes,+ )+ rec := postDockerReport(handler, body, "gzip")+ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200: %s", rec.Code, rec.Body.String())+ }+ })++ t.Run("gzip byte over encoded limit rejected before decompression", func(t *testing.T) {+ handler := &DockerAgentHandlers{}+ body := gzipAPIReportBodyWithEncodedSize(+ t,+ dockerFleetReportBody(t, "docker", 1),+ agentsdocker.ReportEncodedBodyLimitBytes+1,+ )+ rec := postDockerReport(handler, body, "gzip")+ assertDockerReportTooLarge(t, rec, agentsdocker.ReportSizeEncodedBody, agentsdocker.ReportEncodedBodyLimitBytes, 0)+ })++ t.Run("gzip exact decoded limit accepted", func(t *testing.T) {+ handler, _ := newDockerAgentHandlers(t, nil)+ decoded := padDockerReportBody(t, dockerFleetReportBody(t, "podman", 1), agentsdocker.ReportDecodedBodyLimitBytes)+ rec := postDockerReport(handler, gzipAPIReportBody(t, decoded), "gzip")+ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200: %s", rec.Code, rec.Body.String())+ }+ })++ t.Run("gzip byte over decoded limit rejected", func(t *testing.T) {+ handler := &DockerAgentHandlers{}+ decoded := padDockerReportBody(t, dockerFleetReportBody(t, "podman", 1), agentsdocker.ReportDecodedBodyLimitBytes+1)+ rec := postDockerReport(handler, gzipAPIReportBody(t, decoded), "gzip")+ assertDockerReportTooLarge(+ t,+ rec,+ agentsdocker.ReportSizeDecodedBody,+ agentsdocker.ReportDecodedBodyLimitBytes,+ agentsdocker.ReportDecodedBodyLimitBytes+1,+ )+ })+}++func TestDockerAgentReportCompressionDiagnostics(t *testing.T) {+ t.Run("unsupported encoding", func(t *testing.T) {+ handler := &DockerAgentHandlers{}+ rec := postDockerReport(handler, []byte("{}"), "zstd")+ if rec.Code != http.StatusUnsupportedMediaType {+ t.Fatalf("status = %d, want 415: %s", rec.Code, rec.Body.String())+ }+ assertDockerReportErrorCode(t, rec, "unsupported_encoding")+ })++ t.Run("malformed gzip", func(t *testing.T) {+ handler := &DockerAgentHandlers{}+ rec := postDockerReport(handler, []byte("not-gzip"), "gzip")+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("status = %d, want 400: %s", rec.Code, rec.Body.String())+ }+ assertDockerReportErrorCode(t, rec, "invalid_compression")+ })+}++func dockerFleetReportBody(t *testing.T, runtime string, containerCount int) []byte {+ t.Helper()++ containers := make([]agentsdocker.Container, containerCount)+ for index := range containers {+ containers[index] = agentsdocker.Container{+ ID: "container-" + strconv.Itoa(index),+ Name: runtime + "-container-" + strconv.Itoa(index),+ Image: "example/image:latest",+ State: "running",+ Status: "Up",+ }+ }++ report := agentsdocker.Report{+ Agent: agentsdocker.AgentInfo{+ ID: runtime + "-agent-" + strconv.Itoa(containerCount),+ Version: "6.1.1",+ Type: "unified",+ IntervalSeconds: 30,+ },+ Host: agentsdocker.HostInfo{+ Hostname: runtime + "-host-" + strconv.Itoa(containerCount),+ MachineID: runtime + "-machine-" + strconv.Itoa(containerCount),+ Runtime: runtime,+ },+ Containers: containers,+ Timestamp: time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC),+ }++ body, err := json.Marshal(report)+ if err != nil {+ t.Fatalf("marshal report: %v", err)+ }+ return body+}++func padDockerReportBody(t *testing.T, body []byte, size int64) []byte {+ t.Helper()++ if int64(len(body)) > size {+ t.Fatalf("base report is %d bytes, exceeds requested size %d", len(body), size)+ }+ return append(body, bytes.Repeat([]byte(" "), int(size)-len(body))...)+}++func gzipAPIReportBody(t *testing.T, body []byte) []byte {+ t.Helper()++ var encoded bytes.Buffer+ writer := gzip.NewWriter(&encoded)+ if _, err := writer.Write(body); err != nil {+ t.Fatalf("write gzip report: %v", err)+ }+ if err := writer.Close(); err != nil {+ t.Fatalf("close gzip report: %v", err)+ }+ return encoded.Bytes()+}++func gzipAPIReportBodyWithEncodedSize(t *testing.T, body []byte, size int64) []byte {+ t.Helper()++ encoded := gzipAPIReportBody(t, body)+ remaining := size - int64(len(encoded))+ if remaining <= 0 {+ t.Fatalf("base gzip body is %d bytes, cannot pad to %d", len(encoded), size)+ }++ // Concatenated empty gzip members keep the decoded JSON unchanged. Their+ // bounded FEXTRA fields deterministically fill the remaining encoded bytes+ // while preserving a format-valid gzip entity.+ baseMemberSize := int64(len(gzipAPIReportBody(t, nil)))+ const maxExtraSize = int64(0xffff)+ maxMemberSize := baseMemberSize + 2 + maxExtraSize+ memberCount := (remaining + maxMemberSize - 1) / maxMemberSize+ if remaining < memberCount*baseMemberSize {+ t.Fatalf("remaining gzip padding = %d, cannot fit %d members", remaining, memberCount)+ }++ additionalBytes := remaining - memberCount*baseMemberSize+ for memberIndex := int64(0); memberIndex < memberCount; memberIndex++ {+ memberAdditionalBytes := additionalBytes / (memberCount - memberIndex)+ additionalBytes -= memberAdditionalBytes+ if memberAdditionalBytes == 1 || memberAdditionalBytes > maxExtraSize+2 {+ t.Fatalf("gzip member additional bytes = %d, want 0 or [2,%d]", memberAdditionalBytes, maxExtraSize+2)+ }++ var member bytes.Buffer+ writer := gzip.NewWriter(&member)+ if memberAdditionalBytes >= 2 {+ writer.Extra = bytes.Repeat([]byte("x"), int(memberAdditionalBytes-2))+ }+ if err := writer.Close(); err != nil {+ t.Fatalf("close padding gzip member: %v", err)+ }+ encoded = append(encoded, member.Bytes()...)+ }+ if int64(len(encoded)) != size {+ t.Fatalf("encoded gzip size = %d, want %d", len(encoded), size)+ }+ return encoded+}++func postDockerReport(handler *DockerAgentHandlers, body []byte, contentEncoding string) *httptest.ResponseRecorder {+ req := httptest.NewRequest(http.MethodPost, "/api/agents/docker/report", bytes.NewReader(body))+ if contentEncoding != "" {+ req.Header.Set("Content-Encoding", contentEncoding)+ }+ rec := httptest.NewRecorder()+ handler.HandleReport(rec, req)+ return rec+}++func assertDockerReportTooLarge(+ t *testing.T,+ rec *httptest.ResponseRecorder,+ dimension agentsdocker.ReportSizeDimension,+ limit int64,+ actual int64,+) {+ t.Helper()++ if rec.Code != http.StatusRequestEntityTooLarge {+ t.Fatalf("status = %d, want 413: %s", rec.Code, rec.Body.String())+ }++ var response struct {+ Code string `json:"code"`+ Error string `json:"error"`+ Details map[string]string `json:"details"`+ }+ if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if response.Code != "report_too_large" {+ t.Fatalf("code = %q, want report_too_large", response.Code)+ }+ if response.Details["dimension"] != string(dimension) {+ t.Fatalf("dimension = %q, want %q", response.Details["dimension"], dimension)+ }+ if response.Details["limitBytes"] != strconv.FormatInt(limit, 10) {+ t.Fatalf("limitBytes = %q, want %d", response.Details["limitBytes"], limit)+ }+ if !bytes.Contains([]byte(response.Error), []byte(agentsdocker.ReportSizeLimitDescription())) {+ t.Fatalf("error does not use shared limit description: %q", response.Error)+ }+ if actual == 0 {+ if _, present := response.Details["actualBytes"]; present {+ t.Fatalf("actualBytes = %q, want omitted when MaxBytesReader only proves an overage", response.Details["actualBytes"])+ }+ } else if response.Details["actualBytes"] != strconv.FormatInt(actual, 10) {+ t.Fatalf("actualBytes = %q, want %d", response.Details["actualBytes"], actual)+ }+}++func assertDockerReportErrorCode(t *testing.T, rec *httptest.ResponseRecorder, code string) {+ t.Helper()++ var response struct {+ Code string `json:"code"`+ }+ if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if response.Code != code {+ t.Fatalf("code = %q, want %q", response.Code, code)+ }+}diff --git a/internal/dockeragent/agent.go b/internal/dockeragent/agent.goindex bbac57f1bb..c327fab344 100644--- a/internal/dockeragent/agent.go+++ b/internal/dockeragent/agent.go@@ -965,9 +965,10 @@ func (a *Agent) sendReport(ctx context.Context, report agentsdocker.Report) erroreturn fmt.Errorf("compress report: %w", err)}- var errs []errorcontainerCount := len(report.Containers)+ a.logReportSize(containerCount, int64(len(compressed)), int64(len(payload)))+ var errs []errorfor _, target := range a.targets {err := a.sendReportToTarget(ctx, target, compressed, containerCount)if err == nil {@@ -983,25 +984,51 @@ func (a *Agent) sendReport(ctx context.Context, report agentsdocker.Report) erroreturn errors.Join(errs...)}- // Warn if payload is approaching the server's 512KB limit- const warnThresholdKB = 400payloadSizeKB := len(payload) / 1024- if payloadSizeKB >= warnThresholdKB {- a.logger.Warn().- Int("containers", containerCount).- Int("payloadSizeKB", payloadSizeKB).- Msg("Report payload is large and approaching the 512KB limit. Consider reducing container count or running 'docker container prune' to remove stopped containers.")- }-a.logger.Debug().Int("containers", containerCount).Int("payloadSizeKB", payloadSizeKB).Int("payloadBytes", len(payload)).+ Int("reportEncodedBytes", len(compressed)).+ Int64("reportEncodedLimitBytes", agentsdocker.ReportEncodedBodyLimitBytes).+ Int64("reportDecodedLimitBytes", agentsdocker.ReportDecodedBodyLimitBytes).Int("targets", len(a.targets)).Msg("Report sent to Pulse targets")return nil}+func (a *Agent) logReportSize(containerCount int, encodedBytes, decodedBytes int64) {+ assessment := agentsdocker.AssessReportSize(encodedBytes, decodedBytes)+ if !assessment.ApproachingLimit() {+ return+ }++ event := a.logger.Warn()+ message := fmt.Sprintf(+ "Docker / Podman report is approaching the server size limit (%s). Review the reported container inventory and remove stale containers if appropriate.",+ agentsdocker.ReportSizeLimitDescription(),+ )+ if assessment.ExceedsLimit() {+ event = a.logger.Error()+ message = fmt.Sprintf(+ "Docker / Podman report exceeds the server size limit (%s) and is expected to be rejected. Reduce the reported container inventory or metadata before the next cycle.",+ agentsdocker.ReportSizeLimitDescription(),+ )+ }++ event.+ Int("containers", containerCount).+ Int64("reportEncodedBytes", encodedBytes).+ Int64("reportDecodedBytes", decodedBytes).+ Int64("reportEncodedWarningBytes", agentsdocker.ReportEncodedBodyWarningBytes).+ Int64("reportDecodedWarningBytes", agentsdocker.ReportDecodedBodyWarningBytes).+ Int64("reportEncodedLimitBytes", agentsdocker.ReportEncodedBodyLimitBytes).+ Int64("reportDecodedLimitBytes", agentsdocker.ReportDecodedBodyLimitBytes).+ Bool("reportEncodedLimitExceeded", encodedBytes > agentsdocker.ReportEncodedBodyLimitBytes).+ Bool("reportDecodedLimitExceeded", decodedBytes > agentsdocker.ReportDecodedBodyLimitBytes).+ Msg(message)+}+func (a *Agent) sendReportToTarget(ctx context.Context, target TargetConfig, payload []byte, _ int) error {url := fmt.Sprintf("%s/api/agents/docker/report", target.URL)req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(payload))diff --git a/internal/dockeragent/report_size_test.go b/internal/dockeragent/report_size_test.gonew file mode 100644index 0000000000..2d64bf9880--- /dev/null+++ b/internal/dockeragent/report_size_test.go@@ -0,0 +1,123 @@+package dockeragent++import (+ "bytes"+ "encoding/json"+ "strings"+ "testing"++ agentsdocker "github.com/rcourtman/pulse-go-rewrite/pkg/agents/docker"+ "github.com/rs/zerolog"+)++func TestLogDockerReportSizeUsesSharedContract(t *testing.T) {+ tests := []struct {+ name string+ encodedBytes int64+ decodedBytes int64+ wantLog bool+ wantLevel string+ wantEncodedExceeded bool+ wantDecodedExceeded bool+ }{+ {+ name: "ordinary fleet",+ encodedBytes: 64 * 1024,+ decodedBytes: 512 * 1024,+ },+ {+ name: "reported 890 KiB fleet no longer warns",+ encodedBytes: 100 * 1024,+ decodedBytes: 890 * 1024,+ },+ {+ name: "encoded warning boundary",+ encodedBytes: agentsdocker.ReportEncodedBodyWarningBytes,+ decodedBytes: 890 * 1024,+ wantLog: true,+ wantLevel: "warn",+ },+ {+ name: "decoded warning boundary",+ encodedBytes: 100 * 1024,+ decodedBytes: agentsdocker.ReportDecodedBodyWarningBytes,+ wantLog: true,+ wantLevel: "warn",+ },+ {+ name: "encoded over limit",+ encodedBytes: agentsdocker.ReportEncodedBodyLimitBytes + 1,+ decodedBytes: agentsdocker.ReportDecodedBodyWarningBytes,+ wantLog: true,+ wantLevel: "error",+ wantEncodedExceeded: true,+ },+ {+ name: "decoded over limit",+ encodedBytes: agentsdocker.ReportEncodedBodyWarningBytes,+ decodedBytes: agentsdocker.ReportDecodedBodyLimitBytes + 1,+ wantLog: true,+ wantLevel: "error",+ wantDecodedExceeded: true,+ },+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ var output bytes.Buffer+ agent := &Agent{logger: zerolog.New(&output)}++ agent.logReportSize(163, test.encodedBytes, test.decodedBytes)++ if !test.wantLog {+ if output.Len() != 0 {+ t.Fatalf("unexpected size diagnostic: %s", output.String())+ }+ return+ }++ var event map[string]any+ if err := json.Unmarshal(output.Bytes(), &event); err != nil {+ t.Fatalf("decode log event: %v: %s", err, output.String())+ }+ if event["level"] != test.wantLevel {+ t.Fatalf("level = %v, want %q", event["level"], test.wantLevel)+ }+ if event["containers"] != float64(163) {+ t.Fatalf("containers = %v, want 163", event["containers"])+ }+ if event["reportEncodedBytes"] != float64(test.encodedBytes) {+ t.Fatalf("reportEncodedBytes = %v, want %d", event["reportEncodedBytes"], test.encodedBytes)+ }+ if event["reportDecodedBytes"] != float64(test.decodedBytes) {+ t.Fatalf("reportDecodedBytes = %v, want %d", event["reportDecodedBytes"], test.decodedBytes)+ }+ if event["reportEncodedLimitBytes"] != float64(agentsdocker.ReportEncodedBodyLimitBytes) {+ t.Fatalf("encoded limit = %v", event["reportEncodedLimitBytes"])+ }+ if event["reportDecodedLimitBytes"] != float64(agentsdocker.ReportDecodedBodyLimitBytes) {+ t.Fatalf("decoded limit = %v", event["reportDecodedLimitBytes"])+ }+ if event["reportEncodedWarningBytes"] != float64(agentsdocker.ReportEncodedBodyWarningBytes) {+ t.Fatalf("encoded warning = %v", event["reportEncodedWarningBytes"])+ }+ if event["reportDecodedWarningBytes"] != float64(agentsdocker.ReportDecodedBodyWarningBytes) {+ t.Fatalf("decoded warning = %v", event["reportDecodedWarningBytes"])+ }+ if event["reportEncodedLimitExceeded"] != test.wantEncodedExceeded {+ t.Fatalf("encoded exceeded = %v, want %v", event["reportEncodedLimitExceeded"], test.wantEncodedExceeded)+ }+ if event["reportDecodedLimitExceeded"] != test.wantDecodedExceeded {+ t.Fatalf("decoded exceeded = %v, want %v", event["reportDecodedLimitExceeded"], test.wantDecodedExceeded)+ }++ message, _ := event["message"].(string)+ if !strings.Contains(message, agentsdocker.ReportSizeLimitDescription()) {+ t.Fatalf("message does not use shared limit description: %q", message)+ }+ if strings.Contains(message, "512") || strings.Contains(message, "KB") {+ t.Fatalf("message contains obsolete limit wording: %q", message)+ }+ })+ }+}diff --git a/pkg/agents/docker/report_limits.go b/pkg/agents/docker/report_limits.gonew file mode 100644index 0000000000..fb2af91b30--- /dev/null+++ b/pkg/agents/docker/report_limits.go@@ -0,0 +1,167 @@+package dockeragent++import (+ "bytes"+ "compress/gzip"+ "fmt"+ "io"+ "strings"+)++const (+ // ReportEncodedBodyLimitBytes is the inclusive maximum size of the HTTP+ // request body after content encoding. It excludes HTTP headers and framing.+ ReportEncodedBodyLimitBytes int64 = 2 * 1024 * 1024++ // ReportDecodedBodyLimitBytes is the inclusive maximum size of the JSON+ // report after gzip decompression.+ ReportDecodedBodyLimitBytes int64 = 10 * 1024 * 1024++ reportWarningNumerator int64 = 4+ reportWarningDenominator int64 = 5++ // ReportEncodedBodyWarningBytes is the first encoded size that is at least+ // 80% of ReportEncodedBodyLimitBytes.+ ReportEncodedBodyWarningBytes = (ReportEncodedBodyLimitBytes*reportWarningNumerator + reportWarningDenominator - 1) / reportWarningDenominator++ // ReportDecodedBodyWarningBytes is the first decoded size that is at least+ // 80% of ReportDecodedBodyLimitBytes.+ ReportDecodedBodyWarningBytes = (ReportDecodedBodyLimitBytes*reportWarningNumerator + reportWarningDenominator - 1) / reportWarningDenominator+)++// ReportSizeDimension identifies which byte boundary rejected a report.+type ReportSizeDimension string++const (+ ReportSizeEncodedBody ReportSizeDimension = "encoded_http_body"+ ReportSizeDecodedBody ReportSizeDimension = "decoded_json"+)++// ReportSizeAssessment is the shared agent/server interpretation of report+// sizes. Exact limit values are accepted; only values above a limit exceed it.+type ReportSizeAssessment struct {+ EncodedBytes int64+ DecodedBytes int64+}++// AssessReportSize evaluates encoded HTTP-body and decoded JSON byte counts+// against the canonical Docker / Podman report contract.+func AssessReportSize(encodedBytes, decodedBytes int64) ReportSizeAssessment {+ return ReportSizeAssessment{+ EncodedBytes: encodedBytes,+ DecodedBytes: decodedBytes,+ }+}++// ApproachingLimit reports whether either byte count has reached its derived+// 80% early-warning threshold.+func (a ReportSizeAssessment) ApproachingLimit() bool {+ return a.EncodedBytes >= ReportEncodedBodyWarningBytes ||+ a.DecodedBytes >= ReportDecodedBodyWarningBytes+}++// ExceedsLimit reports whether either byte count is outside the inclusive+// server contract.+func (a ReportSizeAssessment) ExceedsLimit() bool {+ return a.EncodedBytes > ReportEncodedBodyLimitBytes ||+ a.DecodedBytes > ReportDecodedBodyLimitBytes+}++// ReportSizeError describes an encoded or decoded report-size rejection.+type ReportSizeError struct {+ Dimension ReportSizeDimension+ LimitBytes int64+ ActualBytes int64+}++func (e *ReportSizeError) Error() string {+ if e.ActualBytes <= 0 {+ return fmt.Sprintf(+ "Docker / Podman report %s exceeds the %d byte limit",+ e.Dimension,+ e.LimitBytes,+ )+ }+ return fmt.Sprintf(+ "Docker / Podman report %s is %d bytes and exceeds the %d byte limit",+ e.Dimension,+ e.ActualBytes,+ e.LimitBytes,+ )+}++// UnsupportedReportContentEncodingError describes a content encoding that the+// Docker / Podman report endpoint does not accept.+type UnsupportedReportContentEncodingError struct {+ Encoding string+}++func (e *UnsupportedReportContentEncodingError) Error() string {+ return fmt.Sprintf("unsupported Content-Encoding: %s", e.Encoding)+}++// DecodeReportBody validates the encoded byte ceiling and returns the decoded+// JSON bytes. Empty Content-Encoding preserves uncompressed compatibility;+// gzip additionally enforces the decoded byte ceiling.+func DecodeReportBody(encoded []byte, contentEncoding string) ([]byte, error) {+ if int64(len(encoded)) > ReportEncodedBodyLimitBytes {+ return nil, &ReportSizeError{+ Dimension: ReportSizeEncodedBody,+ LimitBytes: ReportEncodedBodyLimitBytes,+ ActualBytes: int64(len(encoded)),+ }+ }++ encoding := strings.ToLower(strings.TrimSpace(contentEncoding))+ switch encoding {+ case "":+ return encoded, nil+ case "gzip":+ reader, err := gzip.NewReader(bytes.NewReader(encoded))+ if err != nil {+ return nil, fmt.Errorf("open gzip report: %w", err)+ }+ defer reader.Close()++ decoded, err := io.ReadAll(io.LimitReader(reader, ReportDecodedBodyLimitBytes+1))+ if err != nil {+ return nil, fmt.Errorf("decompress gzip report: %w", err)+ }+ if int64(len(decoded)) > ReportDecodedBodyLimitBytes {+ return nil, &ReportSizeError{+ Dimension: ReportSizeDecodedBody,+ LimitBytes: ReportDecodedBodyLimitBytes,+ ActualBytes: int64(len(decoded)),+ }+ }+ return decoded, nil+ default:+ return nil, &UnsupportedReportContentEncodingError{Encoding: encoding}+ }+}++// ReportSizeLimitDescription derives operator-facing limit text from the same+// byte constants used for enforcement.+func ReportSizeLimitDescription() string {+ return fmt.Sprintf(+ "%s encoded HTTP body or %s decoded JSON",+ formatBinaryBytes(ReportEncodedBodyLimitBytes),+ formatBinaryBytes(ReportDecodedBodyLimitBytes),+ )+}++func formatBinaryBytes(size int64) string {+ const (+ kib = int64(1024)+ mib = 1024 * kib+ )++ switch {+ case size%mib == 0:+ return fmt.Sprintf("%d MiB", size/mib)+ case size%kib == 0:+ return fmt.Sprintf("%d KiB", size/kib)+ default:+ return fmt.Sprintf("%d bytes", size)+ }+}diff --git a/pkg/agents/docker/report_limits_test.go b/pkg/agents/docker/report_limits_test.gonew file mode 100644index 0000000000..6af1189ac8--- /dev/null+++ b/pkg/agents/docker/report_limits_test.go@@ -0,0 +1,182 @@+package dockeragent++import (+ "bytes"+ "compress/gzip"+ "errors"+ "testing"+)++func TestDockerReportSizeContractExactBytes(t *testing.T) {+ if ReportEncodedBodyLimitBytes != 2_097_152 {+ t.Fatalf("encoded limit = %d, want 2097152", ReportEncodedBodyLimitBytes)+ }+ if ReportDecodedBodyLimitBytes != 10_485_760 {+ t.Fatalf("decoded limit = %d, want 10485760", ReportDecodedBodyLimitBytes)+ }+ if ReportEncodedBodyWarningBytes != 1_677_722 {+ t.Fatalf("encoded warning = %d, want 1677722", ReportEncodedBodyWarningBytes)+ }+ if ReportDecodedBodyWarningBytes != 8_388_608 {+ t.Fatalf("decoded warning = %d, want 8388608", ReportDecodedBodyWarningBytes)+ }+ if got := ReportSizeLimitDescription(); got != "2 MiB encoded HTTP body or 10 MiB decoded JSON" {+ t.Fatalf("limit description = %q", got)+ }+}++func TestAssessDockerReportSizeBoundaries(t *testing.T) {+ tests := []struct {+ name string+ encoded int64+ decoded int64+ approaching bool+ exceeds bool+ }{+ {+ name: "ordinary report",+ encoded: 64 * 1024,+ decoded: 512 * 1024,+ },+ {+ name: "old 890 KiB warning case is now ordinary",+ encoded: 100 * 1024,+ decoded: 890 * 1024,+ },+ {+ name: "encoded byte below warning",+ encoded: ReportEncodedBodyWarningBytes - 1,+ decoded: ReportDecodedBodyWarningBytes - 1,+ approaching: false,+ },+ {+ name: "encoded warning boundary",+ encoded: ReportEncodedBodyWarningBytes,+ approaching: true,+ },+ {+ name: "decoded warning boundary",+ decoded: ReportDecodedBodyWarningBytes,+ approaching: true,+ },+ {+ name: "exact encoded limit is accepted",+ encoded: ReportEncodedBodyLimitBytes,+ approaching: true,+ },+ {+ name: "exact decoded limit is accepted",+ decoded: ReportDecodedBodyLimitBytes,+ approaching: true,+ },+ {+ name: "encoded byte over limit",+ encoded: ReportEncodedBodyLimitBytes + 1,+ approaching: true,+ exceeds: true,+ },+ {+ name: "decoded byte over limit",+ decoded: ReportDecodedBodyLimitBytes + 1,+ approaching: true,+ exceeds: true,+ },+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ assessment := AssessReportSize(test.encoded, test.decoded)+ if got := assessment.ApproachingLimit(); got != test.approaching {+ t.Fatalf("ApproachingLimit() = %v, want %v", got, test.approaching)+ }+ if got := assessment.ExceedsLimit(); got != test.exceeds {+ t.Fatalf("ExceedsLimit() = %v, want %v", got, test.exceeds)+ }+ })+ }+}++func TestDecodeDockerReportBodyBoundaries(t *testing.T) {+ t.Run("uncompressed exact encoded limit", func(t *testing.T) {+ body := bytes.Repeat([]byte("x"), int(ReportEncodedBodyLimitBytes))+ decoded, err := DecodeReportBody(body, "")+ if err != nil {+ t.Fatalf("DecodeReportBody: %v", err)+ }+ if len(decoded) != len(body) {+ t.Fatalf("decoded length = %d, want %d", len(decoded), len(body))+ }+ })++ t.Run("uncompressed byte over encoded limit", func(t *testing.T) {+ body := bytes.Repeat([]byte("x"), int(ReportEncodedBodyLimitBytes+1))+ _, err := DecodeReportBody(body, "")+ var sizeErr *ReportSizeError+ if !errors.As(err, &sizeErr) {+ t.Fatalf("error = %v, want ReportSizeError", err)+ }+ if sizeErr.Dimension != ReportSizeEncodedBody ||+ sizeErr.LimitBytes != ReportEncodedBodyLimitBytes ||+ sizeErr.ActualBytes != ReportEncodedBodyLimitBytes+1 {+ t.Fatalf("size error = %#v", sizeErr)+ }+ })++ t.Run("gzip exact decoded limit", func(t *testing.T) {+ body := bytes.Repeat([]byte("x"), int(ReportDecodedBodyLimitBytes))+ encoded := gzipDockerReportBody(t, body)+ decoded, err := DecodeReportBody(encoded, " GZip ")+ if err != nil {+ t.Fatalf("DecodeReportBody: %v", err)+ }+ if len(decoded) != len(body) {+ t.Fatalf("decoded length = %d, want %d", len(decoded), len(body))+ }+ })++ t.Run("gzip byte over decoded limit", func(t *testing.T) {+ body := bytes.Repeat([]byte("x"), int(ReportDecodedBodyLimitBytes+1))+ encoded := gzipDockerReportBody(t, body)+ _, err := DecodeReportBody(encoded, "gzip")+ var sizeErr *ReportSizeError+ if !errors.As(err, &sizeErr) {+ t.Fatalf("error = %v, want ReportSizeError", err)+ }+ if sizeErr.Dimension != ReportSizeDecodedBody ||+ sizeErr.LimitBytes != ReportDecodedBodyLimitBytes ||+ sizeErr.ActualBytes != ReportDecodedBodyLimitBytes+1 {+ t.Fatalf("size error = %#v", sizeErr)+ }+ })++ t.Run("unsupported encoding", func(t *testing.T) {+ _, err := DecodeReportBody([]byte("{}"), "zstd")+ var encodingErr *UnsupportedReportContentEncodingError+ if !errors.As(err, &encodingErr) {+ t.Fatalf("error = %v, want UnsupportedReportContentEncodingError", err)+ }+ if encodingErr.Encoding != "zstd" {+ t.Fatalf("encoding = %q, want zstd", encodingErr.Encoding)+ }+ })++ t.Run("malformed gzip", func(t *testing.T) {+ if _, err := DecodeReportBody([]byte("not-gzip"), "gzip"); err == nil {+ t.Fatal("expected malformed gzip error")+ }+ })+}++func gzipDockerReportBody(t *testing.T, body []byte) []byte {+ t.Helper()++ var encoded bytes.Buffer+ writer := gzip.NewWriter(&encoded)+ if _, err := writer.Write(body); err != nil {+ t.Fatalf("write gzip body: %v", err)+ }+ if err := writer.Close(); err != nil {+ t.Fatalf("close gzip body: %v", err)+ }+ return encoded.Bytes()+}diff --git a/scripts/release_control/canonical_completion_guard_test.py b/scripts/release_control/canonical_completion_guard_test.pyindex 8a508571b4..c0bb033f3b 100644--- a/scripts/release_control/canonical_completion_guard_test.py+++ b/scripts/release_control/canonical_completion_guard_test.py@@ -1158,6 +1158,7 @@ class CanonicalCompletionGuardTest(unittest.TestCase):"internal/api/ai_handlers_more_test.go","internal/api/ai_handlers_patrol_actions_additional_test.go","internal/api/contract_test.go",+ "internal/api/docker_agents_report_size_test.go","internal/api/host_agent_removal_lifecycle_integration_test.go","internal/api/metadata_handlers_test.go","internal/api/patrol_autopilot_test.go",@@ -2247,6 +2248,7 @@ None yet."frontend-modern/src/components/Alerts/__tests__/BulkEditDialog.test.tsx","frontend-modern/src/components/Alerts/__tests__/InvestigateAlertButton.test.tsx","frontend-modern/src/components/Alerts/__tests__/ThresholdsTable.test.tsx",+ "frontend-modern/src/features/alerts/AlertDeliveryHealthCard.test.tsx","frontend-modern/src/features/alerts/__tests__/AlertIntentPolicyPanel.test.tsx","frontend-modern/src/features/alerts/__tests__/OverviewTab.emptystate.test.tsx","frontend-modern/src/features/alerts/__tests__/OverviewTab.timelineerror.test.tsx",@@ -2254,6 +2256,7 @@ None yet."frontend-modern/src/features/alerts/__tests__/ThresholdsTab.test.tsx","frontend-modern/src/features/alerts/__tests__/alertsConfigurationModel.test.ts","frontend-modern/src/features/alerts/__tests__/helpers.test.ts",+ "frontend-modern/src/features/alerts/__tests__/useAlertDestinationsTabState.test.tsx","frontend-modern/src/features/alerts/identity.test.ts","frontend-modern/src/features/alerts/thresholds/__tests__/helpers.test.ts","frontend-modern/src/features/alerts/thresholds/hooks/__tests__/truenasThresholdPersistence.test.tsx",