Repository navigation
feat(diagnostics): client diagnostics server — ingest pipeline, R2 storage, admin API + viewer - #445
Conversation
Cross-repo spec and rollout plan for opt-in client crash reporting and debug-log upload to the user's own Silo server: silo-server ingest, storage, admin API, and retention; silo-android and silo-apple capture, consent, and upload. Disabled by default on both server and client. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01XppCCycoaskCsW7ja1fZct
Implements slice 1 of docs/design/2026-07-19-client-diagnostics.md: the versioned contract (schemas, fixtures, Go validator), storage-validated diagnostics.uploads_enabled gate, account-scoped status endpoint, hardened streaming multipart ingest with quota reservation and a receiving/ready/ failed report state machine, S3 streaming puts, acting-admin report API (list/detail/download/delete with audit events), and the retention + orphan-reconciliation cleanup task. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01XppCCycoaskCsW7ja1fZct
List/detail/download/delete for uploaded diagnostic reports at /admin/diagnostics, beside the Logs viewer: server-filter parity with the admin API, cursor pagination, manifest + device summary detail sheet, playback-session links into the filtered logs view, presign/stream download handling, and feature-state banner. Extracts a shared authenticated apiResponse() helper used by api() and apiDownload(). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01XppCCycoaskCsW7ja1fZct
…mpatibility PutObjectStream omitted Content-Length because client-reported sizes are untrusted, but Cloudflare R2 rejects unsized PutObject bodies with 411 MissingContentLength. Route streaming uploads through the SDK's multipart manager, which buffers fixed-size parts (8 MiB, sequential) and sends each with a known length, preserving bounded memory for untrusted stream sizes. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012e3QjbPo96ed9Mn2qRiUkh
…ures
pgx binds a nil Go slice as SQL NULL, which bypasses the column's '{}'
default and violates its NOT NULL constraint, so reports without
playback session ids failed to insert. Bind an empty slice instead.
The ingest path also swallowed the underlying insert and bundle
validation errors, logging only a generic rejection reason; both sites
now log the real error so failures are diagnosable from server logs.
Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012e3QjbPo96ed9Mn2qRiUkh
Two validator behaviors made the contract unimplementable for clients using standard tar libraries: - Any byte after the tar end-of-archive marker was rejected, but GNU tar, Python tarfile, and Apache Commons Compress all pad the archive with zero blocks to a record boundary. Accept up to 64 KiB of zero padding; any non-zero trailing data is still rejected. - uncompressed_bytes was computed as the sum of entry payloads, which no tar-producing client observes. Define it as the total decompressed tar stream (headers, end-of-archive marker, and padding included) — the byte count between a client's tar writer and gzip writer, and what gzip -l reports. Documented in the design doc and contract. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012e3QjbPo96ed9Mn2qRiUkh
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughIntroduces a self-hosted client diagnostics subsystem with versioned contracts, bounded bundle ingestion, PostgreSQL and S3 storage, admin APIs, scheduled cleanup, and a web administration page. ChangesClient diagnostics contract
Ingestion and persistence
HTTP, cleanup, and administration
Web administration
Estimated code review effort: 5 (Critical) | ~120 minutes Suggested labels: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 75c2260897
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if hdr.Size < 0 { | ||
| return "", fmt.Errorf("%w: negative tar entry size", ErrInvalidBundle) | ||
| } | ||
| name := strings.TrimSpace(hdr.Name) |
There was a problem hiding this comment.
Reject padded allowlist names instead of trimming them
When an authenticated client uploads a tar entry whose raw name differs only by leading/trailing whitespace, such as manifest.json , this line trims it before the safety, allowlist, and archive-metadata checks. The report can therefore be accepted and recorded as containing manifest.json even though the downloaded archive contains a distinct non-allowlisted member, breaking the fixed-entry contract for any admin or tool that later processes the bundle. Reject names whose raw value is not already trimmed rather than normalizing them into the allowlist.
Useful? React with 👍 / 👎.
| SELECT COALESCE(SUM(blob_bytes), 0) | ||
| FROM client_diagnostic_reports | ||
| WHERE user_id = $1 | ||
| AND state = 'ready' |
There was a problem hiding this comment.
Count receiving uploads against the byte quota
In multi-API deployments, or after a restart leaves an earlier upload in receiving, this quota check only sums ready rows even though the new row reserves storage before the bundle upload runs. Because the handler's in-flight limiter is process-local, two instances can each pass the advisory-locked check with a near-limit ExpectedBlobBytes, upload both bundles, and mark both ready, exceeding diagnostics.max_bytes_per_user. Store/count reserved bytes for receiving rows, or otherwise keep the DB-side reservation live until the upload finishes.
Useful? React with 👍 / 👎.
| var crash *Crash | ||
| if wire.Crash != nil { |
There was a problem hiding this comment.
Require crash metadata for non-manual reports
When a client sends report.type as crash, anr, native_crash, hang, or abnormal_exit but omits the crash object, this branch is skipped and the upload can be accepted as a ready diagnostic report. The contract describes crash as absent for manual reports, and accepting event reports without it leaves admins with rows that have no crash summary/source/occurred_at to diagnose the failure instead of rejecting a malformed client bundle.
Useful? React with 👍 / 👎.
| if err != nil { | ||
| return err | ||
| } | ||
| if err := store.Set(ctx, KeyServerInstanceID, instanceID); err != nil { |
There was a problem hiding this comment.
Seed the diagnostics instance ID atomically
When two API nodes start with no existing diagnostics.server_instance_id, both can observe the empty setting, generate different IDs, and this unconditional Set lets the last writer overwrite the first. A client that fetched /diagnostics/status from the first node during that race can later upload with the now-overwritten destination ID and be rejected as destination_mismatch; use an insert-if-absent/conditional write and then reload the winning value for this generated setting.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (6)
migrations/sql/20260720084550_client_diagnostic_reports.sql (1)
7-12: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winEnforce the diagnostics closed sets in the database.
state,report_type, andplatformare unconstrained even though the diagnostics contract defines finite values. AddCHECKconstraints so invalid rows cannot bypass repository validation and break cleanup or admin behavior.Proposed constraints
CREATE TABLE client_diagnostic_reports ( id UUID PRIMARY KEY, short_id TEXT NOT NULL, user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, - state TEXT NOT NULL, + state TEXT NOT NULL CHECK (state IN ('receiving', 'ready', 'failed')), captured_at TIMESTAMPTZ NOT NULL, received_at TIMESTAMPTZ NOT NULL DEFAULT now(), - report_type TEXT NOT NULL, - platform TEXT NOT NULL, + report_type TEXT NOT NULL CHECK (report_type IN ('crash', 'anr', 'native_crash', 'hang', 'abnormal_exit', 'manual')), + platform TEXT NOT NULL CHECK (platform IN ('android', 'android-tv', 'ios', 'tvos')),Based on the server design's declared state, report-type, and platform values.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@migrations/sql/20260720084550_client_diagnostic_reports.sql` around lines 7 - 12, Add database CHECK constraints in the diagnostics table migration for state, report_type, and platform, restricting each column to the finite values declared by the server diagnostics contract. Ensure the constraints reject any value outside those sets while preserving the existing NOT NULL and default definitions.internal/diagnostics/settings.go (1)
23-30: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueCase-only distinction between two constants is a footgun.
DefaultMaxUncompressed(int64) anddefaultMaxUncompressed(string) differ only by initial capitalization, and the string one also breaks the...Strsuffix convention used by its siblings (defaultMaxBundleStr,defaultMaxBytesUserStr). Renaming todefaultMaxUncompressedStrremoves the ambiguity.♻️ Suggested rename
- defaultMaxUncompressed = "67108864" + defaultMaxUncompressedStr = "67108864"Then update the reference in
SeedDefaults:- KeyMaxUncompressedBytes: defaultMaxUncompressed, + KeyMaxUncompressedBytes: defaultMaxUncompressedStr,🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/diagnostics/settings.go` around lines 23 - 30, Rename the string constant defaultMaxUncompressed to defaultMaxUncompressedStr in the diagnostics settings defaults, preserving its value and the naming convention used by defaultMaxBundleStr and defaultMaxBytesUserStr. Update the corresponding reference in SeedDefaults and leave the int64 DefaultMaxUncompressed constant unchanged.internal/diagnostics/contract/contract.go (1)
1024-1036: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
rawSentinelreturnstruefor every string, making the branch (and downstream cases) dead code. Both theif s == "unknown" || s == "not_collected"and the fall-through return identical values, so the function really means "is this a JSON string". Callers already re-validate the sentinel value, so behavior is correct, but this also renders thecase '"'arm invalidateDeviceValue(Line 815-820) unreachable. Consider renaming torawStringand dropping the redundant conditional for clarity.♻️ Suggested simplification
-func rawSentinel(raw json.RawMessage) (string, bool, error) { +func rawString(raw json.RawMessage) (string, bool, error) { if firstRawByte(raw) != '"' { return "", false, nil } var s string if err := json.Unmarshal(raw, &s); err != nil { return "", false, fieldError("device", "contains invalid string") } - if s == "unknown" || s == "not_collected" { - return s, true, nil - } return s, true, nil }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/diagnostics/contract/contract.go` around lines 1024 - 1036, Rename rawSentinel to rawString and remove the redundant sentinel-value conditional, returning the unmarshaled string with true for any valid JSON string. Update all callers, including validateDeviceValue’s case '"' path, to use the renamed helper while preserving their existing sentinel validation behavior.internal/api/handlers/admin_diagnostics.go (1)
100-110: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winSilently swallowed presign error masks storage/config failures.
When
PresignReportDownloadreturns an error, the code discards it and falls back to proxy streaming. That fallback is fine functionally, but a persistently failing presign (misconfigured/unavailable presign endpoint) will silently route every admin download through the server with no diagnostic signal. Consider logging the presign failure before falling back.🔭 Log presign failure before proxy fallback
if !diagnosticsProxyDownloadRequested(r) { - if url, err := admin.PresignReportDownload(r.Context(), report, ttl); err == nil && strings.TrimSpace(url) != "" { + url, err := admin.PresignReportDownload(r.Context(), report, ttl) + if err != nil { + h.diagnosticsLogger().WarnContext(r.Context(), "diagnostic report presign failed; falling back to proxy stream", + "component", "diagnostics", + "report_id", report.ID, + "error", err, + ) + } + if err == nil && strings.TrimSpace(url) != "" { h.auditDownload(r, report.ID) writeJSON(w, http.StatusOK, diagnosticsDownloadURLResponse{ DownloadURL: url, ExpiresAt: time.Now().UTC().Add(ttl), }) return } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/api/handlers/admin_diagnostics.go` around lines 100 - 110, The presign failure in the non-proxy path is discarded before proxy fallback. Update the PresignReportDownload handling to capture and log the error through the handler’s existing logging mechanism, while preserving the current fallback to proxy streaming and successful URL response behavior.web/src/pages/AdminDiagnostics.tsx (2)
430-437: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winConsider
role="button"on the clickable row.Keyboard support (Enter/Space) and
aria-labelare already present, but the<tr>lacks aroleconveying it's interactive to assistive tech.♿ Proposed tweak
<TableRow className="cursor-pointer" tabIndex={0} + role="button" onClick={() => onSelect(report.id)} onKeyDown={handleKeyDown} aria-label={`Open diagnostic report ${report.short_id}`} >🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/AdminDiagnostics.tsx` around lines 430 - 437, Add role="button" to the clickable TableRow in the diagnostic report rendering, alongside its existing keyboard handlers and aria-label, so assistive technologies identify the row as an interactive control.
58-58: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRedundant
useDateTimeFormat()subscription.Neither
DiagnosticReportRownorDiagnosticReportDetail(the only consumers offormatDateTimein this file) are memoized, so this page doesn't need its own subscription —ReactiveAppRoutesinApp.tsxalready re-renders the routed tree on preference changes.Based on learnings: "individual pages ... generally should NOT add their own preference subscription for non-memoized content—they will re-render via the parent tree. However, any memoized descendant components ... must call
useDateTimeFormat()... themselves."🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/AdminDiagnostics.tsx` at line 58, Remove the redundant useDateTimeFormat() call from the page component in AdminDiagnostics.tsx. Keep DiagnosticReportRow and DiagnosticReportDetail unchanged because they are not memoized and already re-render through ReactiveAppRoutes when preferences change.Source: Learnings
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@docs/design/2026-07-19-client-diagnostics.md`:
- Around line 137-154: Add language identifiers to the two fenced examples in
the diagnostics design document: mark the architecture diagram fence with text
and the commented manifest example fence with jsonc. Do not alter the example
contents.
In `@internal/diagnostics/admin.go`:
- Around line 74-79: Update the report deletion flow around deleteReportObjects
and s.reports.DeleteByID to persist a durable deleting or unavailable state
before removing blob objects. Ensure database failure leaves the report marked
for cleanup/retry rather than visible as ready with a missing download object,
and preserve retryable cleanup until both stores are deleted.
In `@internal/diagnostics/cleanup.go`:
- Around line 83-145: Update the retention and stale-report loops in the cleanup
function to continue processing later reports when deleteReportObjects,
DeleteByID, or MarkFailed encounters a non-not-found error. Record each
per-report failure and return an aggregated error after all report and
orphan-object cleanup has been attempted, while preserving the existing
successful deletion counters and not-found handling.
In `@internal/taskmanager/tasks/cleanup_client_diagnostics.go`:
- Around line 48-56: Update ClientDiagnosticsCleanupTask.DefaultTriggers to use
a diagnostics-specific cleanup interval setting instead of
opslog.LoadCleanupInterval, and add or reuse the corresponding diagnostics
configuration key in t.settings. Keep the interval conversion to milliseconds
and startup trigger unchanged.
- Around line 48-56: Update ClientDiagnosticsCleanupTask.DefaultTriggers to
avoid context.Background() for the opslog.LoadCleanupInterval settings lookup;
use the startup context if available, or create a short bounded timeout context,
while preserving the existing interval conversion and default fallback behavior.
---
Nitpick comments:
In `@internal/api/handlers/admin_diagnostics.go`:
- Around line 100-110: The presign failure in the non-proxy path is discarded
before proxy fallback. Update the PresignReportDownload handling to capture and
log the error through the handler’s existing logging mechanism, while preserving
the current fallback to proxy streaming and successful URL response behavior.
In `@internal/diagnostics/contract/contract.go`:
- Around line 1024-1036: Rename rawSentinel to rawString and remove the
redundant sentinel-value conditional, returning the unmarshaled string with true
for any valid JSON string. Update all callers, including validateDeviceValue’s
case '"' path, to use the renamed helper while preserving their existing
sentinel validation behavior.
In `@internal/diagnostics/settings.go`:
- Around line 23-30: Rename the string constant defaultMaxUncompressed to
defaultMaxUncompressedStr in the diagnostics settings defaults, preserving its
value and the naming convention used by defaultMaxBundleStr and
defaultMaxBytesUserStr. Update the corresponding reference in SeedDefaults and
leave the int64 DefaultMaxUncompressed constant unchanged.
In `@migrations/sql/20260720084550_client_diagnostic_reports.sql`:
- Around line 7-12: Add database CHECK constraints in the diagnostics table
migration for state, report_type, and platform, restricting each column to the
finite values declared by the server diagnostics contract. Ensure the
constraints reject any value outside those sets while preserving the existing
NOT NULL and default definitions.
In `@web/src/pages/AdminDiagnostics.tsx`:
- Around line 430-437: Add role="button" to the clickable TableRow in the
diagnostic report rendering, alongside its existing keyboard handlers and
aria-label, so assistive technologies identify the row as an interactive
control.
- Line 58: Remove the redundant useDateTimeFormat() call from the page component
in AdminDiagnostics.tsx. Keep DiagnosticReportRow and DiagnosticReportDetail
unchanged because they are not memoized and already re-render through
ReactiveAppRoutes when preferences change.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: ce2c412a-a285-4be4-b6f9-2765d076f445
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (57)
cmd/silo/main.godocs/design/2026-07-19-client-diagnostics.mddocs/design/schemas/client-diagnostics/README.mddocs/design/schemas/client-diagnostics/v1/attr-registry.jsondocs/design/schemas/client-diagnostics/v1/device.schema.jsondocs/design/schemas/client-diagnostics/v1/fixtures/invalid/archive-entry-outside-allowlist.jsondocs/design/schemas/client-diagnostics/v1/fixtures/invalid/bad-schema-version.jsondocs/design/schemas/client-diagnostics/v1/fixtures/invalid/missing-consent.jsondocs/design/schemas/client-diagnostics/v1/fixtures/invalid/platform-macos-reserved.jsondocs/design/schemas/client-diagnostics/v1/fixtures/invalid/stack-excerpt-over-8kib.jsondocs/design/schemas/client-diagnostics/v1/fixtures/invalid/unknown-report-type.jsondocs/design/schemas/client-diagnostics/v1/fixtures/valid/android-manual-no-profile.jsondocs/design/schemas/client-diagnostics/v1/fixtures/valid/android-manual.jsondocs/design/schemas/client-diagnostics/v1/fixtures/valid/android-tv-crash-ueh.jsondocs/design/schemas/client-diagnostics/v1/fixtures/valid/device.jsondocs/design/schemas/client-diagnostics/v1/fixtures/valid/ios-hang-metrickit.jsondocs/design/schemas/client-diagnostics/v1/fixtures/valid/loglines.jsonldocs/design/schemas/client-diagnostics/v1/fixtures/valid/tvos-abnormal-exit.jsondocs/design/schemas/client-diagnostics/v1/logline.schema.jsondocs/design/schemas/client-diagnostics/v1/manifest.schema.jsongo.modinternal/api/handlers/admin.gointernal/api/handlers/admin_diagnostics.gointernal/api/handlers/diagnostics.gointernal/api/handlers/diagnostics_test.gointernal/api/router.gointernal/diagnostics/admin.gointernal/diagnostics/bundle.gointernal/diagnostics/bundle_test.gointernal/diagnostics/cleanup.gointernal/diagnostics/cleanup_test.gointernal/diagnostics/contract/contract.gointernal/diagnostics/contract/contract_test.gointernal/diagnostics/repo.gointernal/diagnostics/service.gointernal/diagnostics/service_test.gointernal/diagnostics/settings.gointernal/diagnostics/settings_test.gointernal/diagnostics/shortid.gointernal/diagnostics/shortid_test.gointernal/diagnostics/store.gointernal/diagnostics/types.gointernal/s3client/client.gointernal/taskmanager/tasks/cleanup_client_diagnostics.gomigrations/sql/20260720084550_client_diagnostic_reports.sqlweb/src/App.tsxweb/src/api/client.tsweb/src/api/types.tsweb/src/components/AdminSectionCommandDialog.test.tsxweb/src/components/AdminSidebar.test.tsxweb/src/hooks/queries/admin/diagnostics.test.tsweb/src/hooks/queries/admin/diagnostics.tsweb/src/hooks/queries/keys.tsweb/src/lib/adminNavigation.tsweb/src/lib/documentTitle.test.tsweb/src/lib/documentTitle.tsweb/src/pages/AdminDiagnostics.tsx
| if err := deleteReportObjects(ctx, s.store, report, s.logger); err != nil { | ||
| return nil, err | ||
| } | ||
| deleted, err := s.reports.DeleteByID(ctx, id) | ||
| if err != nil { | ||
| return nil, err |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Make deletion recoverable across blob and database stores.
Line 74 deletes the blob before DeleteByID. If the database deletion fails, the ready report remains visible but its download object is gone. Persist a durable deleting/unavailable state before object removal, then let cleanup/retry finish deletion.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/diagnostics/admin.go` around lines 74 - 79, Update the report
deletion flow around deleteReportObjects and s.reports.DeleteByID to persist a
durable deleting or unavailable state before removing blob objects. Ensure
database failure leaves the report marked for cleanup/retry rather than visible
as ready with a missing download object, and preserve retryable cleanup until
both stores are deleted.
The report detail already rendered app_version (app_build); the list rows showed only v<app_version>. TestFlight triage needs the build number at a glance, so list rows now render it from the stored manifest, e.g. "v1.4.2 (20841)". Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012e3QjbPo96ed9Mn2qRiUkh
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c1cebf519d
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| entryBytes, err := copyTarEntry(tr, buffer, limits, metered, &payloadBytes) | ||
| if err != nil { | ||
| return BundleInfo{}, err |
There was a problem hiding this comment.
Validate the embedded manifest before storing bundles
When a client puts a different JSON document in the required first manifest.json entry, this path drains the entry like any other file while Ingest validates and stores only the separate multipart manifest. That lets an accepted report later download as a self-contained archive whose manifest disagrees with the DB row (for example different profile/crash metadata), which breaks admin or support tooling that treats the bundle as authoritative; compare the embedded manifest to the part-1 manifest with archive omitted, or reject mismatches.
Useful? React with 👍 / 👎.
| if err != nil { | ||
| return nil, err | ||
| } | ||
| if err := deleteReportObjects(ctx, s.store, report, s.logger); err != nil { |
There was a problem hiding this comment.
Delete report rows before deleting blobs
When the database delete fails after object deletion has already succeeded, this ordering leaves a ready report row pointing at a missing bundle. In that transient DB-failure scenario admins keep seeing a report that can no longer be downloaded, and retrying cannot recover the original artifact; delete the row first using the returned blob location and let orphan cleanup remove any leftover object instead.
Useful? React with 👍 / 👎.
| }() | ||
|
|
||
| uncompressed := &uncompressedCounter{r: gz} | ||
| tr := tar.NewReader(uncompressed) |
There was a problem hiding this comment.
Reject PAX headers hidden by archive/tar
When an uploaded tar stream contains PAX extended headers, Go's archive/tar reader consumes those records internally before returning the next file header, so they never reach the allowlist/count checks driven by this reader. A bundle can therefore be accepted with extra non-allowlisted tar records carrying arbitrary metadata/bytes while info.Entries still matches the manifest; reject archives that contain extended headers or validate at a layer that exposes every raw tar record.
Useful? React with 👍 / 👎.
- bundle: reject tar entry names that differ from their trimmed form instead of normalizing padded names into the allowlist - repo: reserve expected bytes on receiving rows and count receiving+ready in the per-user byte quota so concurrent/multi-node uploads can't overshoot - contract: require the crash object for event report types and keep it absent for manual; add contract tests - settings/service: seed diagnostics.server_instance_id atomically via insert-if-absent and adopt the winning value across nodes - bundle/service: capture the embedded manifest.json during ValidateBundle and reject reports whose embedded manifest disagrees with the part-1 manifest (minus archive); add tests - admin: delete the DB row before the blob on DeleteReport; log bucket/key when the blob delete fails instead of leaving a visible report with a missing bundle - bundle: reject PAX/GNU tar formats and extension records that smuggle bytes past validation; add a PAX-archive rejection test - migration: add CHECK constraints for state, report_type, and platform - docs: add text/jsonc language identifiers to the two unfenced code blocks - cleanup: log-and-continue per report and aggregate errors so one poisoned report no longer blocks the whole run; update tests - tasks: give diagnostics its own cleanup interval key instead of reusing the opslog key, and bound the startup settings lookup Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012e3QjbPo96ed9Mn2qRiUkh
|
All 11 review findings addressed in a6348b3 — thanks Codex + CodeRabbit, several were real catches:
🤖 Generated with Claude Code |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/diagnostics/settings.go`:
- Around line 139-152: Update LoadCleanupInterval to cap parsed positive cleanup
minutes at the existing maximum bound before converting them to time.Duration,
preserving the default for invalid values. Add a boundary test covering the
maximum accepted value and an over-limit value that would otherwise overflow.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 6e083f57-9bd5-41de-b125-3cf2813e2e95
📒 Files selected for processing (15)
docs/design/2026-07-19-client-diagnostics.mdinternal/diagnostics/admin.gointernal/diagnostics/bundle.gointernal/diagnostics/bundle_test.gointernal/diagnostics/cleanup.gointernal/diagnostics/cleanup_test.gointernal/diagnostics/contract/contract.gointernal/diagnostics/contract/contract_test.gointernal/diagnostics/repo.gointernal/diagnostics/service.gointernal/diagnostics/service_test.gointernal/diagnostics/settings.gointernal/diagnostics/settings_test.gointernal/taskmanager/tasks/cleanup_client_diagnostics.gomigrations/sql/20260720084550_client_diagnostic_reports.sql
🚧 Files skipped from review as they are similar to previous changes (11)
- internal/taskmanager/tasks/cleanup_client_diagnostics.go
- internal/diagnostics/bundle_test.go
- internal/diagnostics/cleanup_test.go
- internal/diagnostics/contract/contract_test.go
- migrations/sql/20260720084550_client_diagnostic_reports.sql
- internal/diagnostics/service.go
- internal/diagnostics/cleanup.go
- docs/design/2026-07-19-client-diagnostics.md
- internal/diagnostics/contract/contract.go
- internal/diagnostics/repo.go
- internal/diagnostics/bundle.go
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a6348b3dc5
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
|
||
| try { | ||
| const response = await apiResponse( | ||
| `/admin/diagnostics/reports/${encodeURIComponent(report.id)}/download`, |
There was a problem hiding this comment.
Use the proxy download for private diagnostic stores
When S3Private is configured with an endpoint that only the server can reach, such as an internal MinIO/R2 gateway, this default download request lets the handler return a presigned JSON URL as soon as signing succeeds, and the browser is then navigated to an unreachable host. Because that navigation happens in a separate window, the UI cannot detect the failure and never retries the handler's ?proxy=1 fallback; request the proxy path here or otherwise choose it for private/internal endpoints.
Useful? React with 👍 / 👎.
| if store == nil { | ||
| return settings, nil | ||
| } | ||
| if raw, err := store.Get(ctx, KeyUploadsEnabled); err == nil && strings.TrimSpace(raw) != "" { |
There was a problem hiding this comment.
Propagate diagnostics setting read failures
When server_settings.Get returns an error for diagnostics settings, such as a transient database failure while reading diagnostics.uploads_enabled, this branch silently falls back to the default value and LoadSettings still returns nil. In an enabled deployment that can make /diagnostics/status and uploads report disabled or use default quota limits instead of failing retryably, so clients can make decisions from incorrect server state; propagate read errors and reserve defaults for missing/invalid values.
Useful? React with 👍 / 👎.
| manifestCapture.Grow(int(hdr.Size)) | ||
| capture = manifestCapture | ||
| } | ||
| entryBytes, err := copyTarEntry(tr, buffer, limits, metered, &payloadBytes, capture) |
There was a problem hiding this comment.
Validate non-manifest bundle entries before accepting
When a bundle contains an allowed device.json or logs.jsonl entry with malformed contents, this path only captures manifest.json and drains every other member as opaque bytes. The report can still be marked ready as long as the archive metadata matches, even though the commit ships versioned device/logline schemas and validators, leaving admin/support tooling to fail on an accepted diagnostic bundle; validate known JSON/JSONL entries while streaming or reject malformed contents.
Useful? React with 👍 / 👎.
| } | ||
| r.Route("/diagnostics", func(r chi.Router) { | ||
| r.Get("/status", diagnosticsHandler.HandleStatus) | ||
| r.Post("/reports", diagnosticsHandler.HandleUpload) |
There was a problem hiding this comment.
Avoid the 30s server read timeout for uploads
When the integrated server handles this newly mounted upload route, cmd/silo/main.go still configures ReadTimeout: 30 * time.Second, while diagnostics advertises bundles of 10 MiB by default and admin-tunable larger limits. Mobile crash uploads over slow uplinks that take more than 30 seconds are cut off by net/http mid-stream before the diagnostics service can return its retryable errors, so normal reports can never complete in that environment; use a route/listener without the short read timeout or cap the advertised upload size accordingly.
Useful? React with 👍 / 👎.
- settings.go: cap the parsed cleanup interval at 7 days before converting to time.Duration so a huge configured value can't overflow int64 nanoseconds and wrap into a tiny/negative interval; add boundary tests. - settings.go: propagate genuine settings read failures from LoadSettings (missing/empty -> default, error -> fail) so a transient DB error surfaces retryably instead of silently reporting uploads disabled or wrong quotas. - bundle.go: validate non-manifest bundle entries while streaming with bounded memory -- device.json and crash/*.json must be a single JSON object, logs.jsonl/breadcrumbs.jsonl must be newline-delimited JSON objects with a per-line byte cap (new contract.MaxLogLineBytes); binary members stay opaque. - diagnostics upload handler: extend the read deadline per-route via http.ResponseController.SetReadDeadline (10m) so slow mobile uploads of large bundles aren't cut off by the shared 30s server ReadTimeout. - web admin download: request the ?proxy=1 streaming path directly so downloads work when S3Private is only server-reachable and errors can surface in-page. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012e3QjbPo96ed9Mn2qRiUkh
|
Round-2 findings all addressed in 2d5d498:
🤖 Generated with Claude Code |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2d5d4980de
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| // Extend the read deadline for this request only; the server-wide | ||
| // ReadTimeout is too short for slow, large bundle uploads (see the constant). | ||
| rc := http.NewResponseController(w) | ||
| if err := rc.SetReadDeadline(time.Now().Add(diagnosticsUploadReadTimeout)); err != nil { |
There was a problem hiding this comment.
Extend the write deadline for slow uploads
This only extends the request read deadline, but the integrated API server still has WriteTimeout: 120 * time.Second in cmd/silo/main.go; when an accepted diagnostics upload takes more than two minutes but less than this new 10-minute read window, Ingest can store and mark the report ready and then writeJSON runs after the connection's write deadline, so the client may see a timeout and retry a report that already succeeded. Clear or extend the write deadline for this upload path before reading the body as well.
Useful? React with 👍 / 👎.
| diagnosticsService.SetProfileAttributionValidator(diagnostics.ProfileAttributionValidatorFunc( | ||
| func(ctx context.Context, userID int, profileID string) (bool, error) { | ||
| _, found, err := checkPrimaryProfile(ctx, userID, profileID) | ||
| return found, err |
There was a problem hiding this comment.
Reject child profiles in diagnostics attribution
When a client sends X-Profile-Id or a manifest profile_id for a child profile, this validator only checks that the profile exists for the account and then Ingest records the report under that profile. The diagnostics design says child profiles must not perform diagnostics actions, and these bundles can include device/log/crash context, so a buggy or nonconforming client can bypass that privacy boundary unless the server also checks profile.IsChild here.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@web/src/hooks/queries/admin/diagnostics.test.ts`:
- Around line 41-46: Update the diagnostics download test around the click spy
to capture the clicked anchor element, then assert its href is blob:diagnostic
and its download filename is silo-diagnostics-ABCDEF123456.tar.gz. Keep the
existing click, object URL, cleanup, and revokeObjectURL assertions intact.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: cccc5384-6a38-43ed-8d1c-47b3e1d21588
📒 Files selected for processing (8)
internal/api/handlers/diagnostics.gointernal/diagnostics/bundle.gointernal/diagnostics/bundle_test.gointernal/diagnostics/contract/contract.gointernal/diagnostics/settings.gointernal/diagnostics/settings_test.goweb/src/hooks/queries/admin/diagnostics.test.tsweb/src/hooks/queries/admin/diagnostics.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- internal/api/handlers/diagnostics.go
- internal/diagnostics/bundle_test.go
- internal/diagnostics/contract/contract.go
- Extend the upload write deadline alongside the read deadline so a slow upload finishing after the integrated server's 120s WriteTimeout can still return its success response instead of timing out a report that succeeded. - Reject child-profile attribution for diagnostics: wire the attribution validator through a shared profile lookup that reports IsChild and drop attribution for child profiles, which must not perform diagnostics actions. - Assert the download test captures the clicked anchor and checks its blob: href and silo-diagnostics-<short_id>.tar.gz filename, not just cleanup. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012e3QjbPo96ed9Mn2qRiUkh
|
Round-3 findings addressed in 93b851f:
🤖 Generated with Claude Code |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 93b851fe81
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| }, | ||
| "additionalProperties": true | ||
| }, | ||
| "crash": { |
There was a problem hiding this comment.
Add the crash/type conditional to the schema
When clients vendor this canonical schema and validate manifests locally, crash is still just an optional property here: a crash/anr/native_crash/hang/abnormal_exit manifest without it, or a manual manifest with it, passes the schema but is then rejected by the server's ValidateManifest. Add a oneOf/if-then-else tying report.type to crash presence so client-generated bundles don't fail only at upload time.
Useful? React with 👍 / 👎.
| if profileID != nil { | ||
| value = strings.TrimSpace(*profileID) | ||
| } | ||
| if value == "" { | ||
| value = strings.TrimSpace(fallback) | ||
| } |
There was a problem hiding this comment.
Reject mismatched diagnostic profile IDs
When a queued report was captured under profile A but uploaded after the client has switched to profile B, the request carries B in X-Profile-Id and A in manifest.report.profile_id. This helper unconditionally prefers the header and never compares it with the manifest fallback, so any same-account non-child profile B is validated and the DB row is attributed to B while the stored manifest/download remains for A. Reject mismatches, or make the manifest's captured profile authoritative, to avoid corrupting report attribution.
Useful? React with 👍 / 👎.
| "contains": { | ||
| "const": "manifest.json" | ||
| }, |
There was a problem hiding this comment.
Require manifest.json as the first schema entry
When clients validate archive.entries with this schema, manifest.json only has to appear somewhere in the array, but the upload path requires the first tar entry to be manifest.json and then compares the manifest's entry order to the bundle. A client can therefore produce entries: ["logs.jsonl", "manifest.json"] that passes the vendored schema and is rejected only after upload; add a first-item constraint such as prefixItems with const: "manifest.json".
Useful? React with 👍 / 👎.
| "manufacturer": { | ||
| "type": "string", | ||
| "minLength": 1, | ||
| "maxLength": 128 |
There was a problem hiding this comment.
Align schema string limits with byte validators
When a client includes non-ASCII text near a documented cap, this maxLength passes by counting characters while the server's validateStringBytes rejects by UTF-8 byte length. For example, a 128-character CJK model string is valid against the vendored schema but exceeds the server's 128-byte limit, so clients can ship schema-valid reports that fail only at ingest; expose/enforce byte limits in the schema contract or lower the character limits to a safe bound.
Useful? React with 👍 / 👎.
- schema: add crash/report.type conditionals (allOf if/then) so a crash/anr/native_crash/hang/abnormal_exit manifest requires `crash` and a `manual` manifest forbids it, matching ValidateManifest. - service: reject uploads where X-Profile-Id and manifest.report.profile_id are both present but differ (new ErrProfileMismatch, mapped to 400 profile_mismatch) instead of silently preferring the header; single-source and matching cases unchanged. Adds service tests for mismatch, match, and header-only attribution. - schema: require manifest.json as the first archive.entries element via prefixItems (contains retained for validators without prefixItems support). - schema: document that maxLength is a character-count bound while the server enforces UTF-8 byte length, via a top-level note and per-field notes on the free-text device_summary and crash fields. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012e3QjbPo96ed9Mn2qRiUkh
|
Round-4 findings addressed in 1f9bd99:
🤖 Generated with Claude Code |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1f9bd99990
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if !found { | ||
| return nil, nil |
There was a problem hiding this comment.
Return an error for child diagnostic profiles
Fresh evidence after the latest changes: the router now reports child profiles through NewProfileAttributionValidator, but this branch still treats any validator false result as “drop attribution” and lets the upload proceed. When a child profile is active and sends X-Profile-Id or manifest.report.profile_id, the diagnostics route bypasses viewer/profile middleware, so the server accepts the bundle under the account instead of enforcing the design's non-child requirement; return a rejecting error for supplied-but-invalid child profile attribution rather than silently clearing it.
Useful? React with 👍 / 👎.
| return `SELECT id::text, short_id, user_id, profile_id, state, captured_at, received_at, | ||
| report_type, platform, app_version, crash_summary, manifest, playback_session_ids, | ||
| blob_bucket, blob_key, blob_bytes, uncompressed_bytes, blob_sha256 |
There was a problem hiding this comment.
Project out manifests from list and cleanup queries
Because this shared projection includes the full manifest JSONB, every admin list page and every retention/stale cleanup candidate query fetches and scans up to 64 KiB of manifest data per report even though those paths only need summary/blob fields; with the max list limit of 200 or a large cleanup batch this turns routine browsing/cleanup into multi-megabyte DB reads and JSON allocations. Use a separate lightweight projection for list/cleanup and reserve the manifest column for detail/download workflows.
AGENTS.md reference: AGENTS.md:L13-L15
Useful? React with 👍 / 👎.
| if err := deleteReportObjects(ctx, store, &report, logger); err != nil { | ||
| errs = append(errs, fmt.Errorf("delete diagnostic retention blob %s: %w", report.ID, err)) | ||
| continue | ||
| } | ||
| if _, err := repo.DeleteByID(ctx, report.ID); err != nil && !IsReportNotFound(err) { |
There was a problem hiding this comment.
Delete cleanup rows before deleting blobs
When retention cleanup hits a transient database failure after deleteReportObjects has already removed the bundle, the ready report row remains visible until a later cleanup pass but now points at a missing object, so admin downloads 404 during that window; the stale-report loop below uses the same blob-first ordering. Delete/mark the row first and let orphan cleanup reap blobs that fail to delete, matching the safer admin delete path.
AGENTS.md reference: AGENTS.md:L13-L15
Useful? React with 👍 / 👎.
| case diagnostics.KeyMaxBytesPerUser: | ||
| if value < 10*mib || value > 10*gib { | ||
| return "", fmt.Errorf("%s must be between 10 MiB (%d bytes) and 10 GiB (%d bytes)", key, 10*mib, 10*gib) |
There was a problem hiding this comment.
Keep per-user byte cap above bundle size
When an admin lowers diagnostics.max_bytes_per_user below the current diagnostics.max_bundle_bytes, this validation still accepts the setting, so /diagnostics/status can advertise a max bundle size that InsertReceiving rejects as quota_exceeded for any single upload above the smaller per-user cap. Validate max_bytes_per_user >= max_bundle_bytes here, and apply the reciprocal check when raising the bundle limit, so clients are not told that impossible upload sizes are supported.
Useful? React with 👍 / 👎.
| r.Route("/diagnostics", func(r chi.Router) { | ||
| r.Get("/status", diagnosticsHandler.HandleStatus) | ||
| r.Post("/reports", diagnosticsHandler.HandleUpload) |
There was a problem hiding this comment.
Apply demo restrictions to diagnostics uploads
In demo deployments where an admin has enabled diagnostics, this new POST /api/v1/diagnostics/reports route is mounted before the group that applies DemoGuard, and DemoGuard also has no diagnostics prefix, so non-admin demo users can still write report rows and private-bucket blobs. Route the upload through the demo guard and block this POST prefix while keeping the read-only status endpoint available.
Useful? React with 👍 / 👎.
- service: reject supplied child-profile attribution with a distinct ErrChildProfileForbidden (403 child_profile_forbidden) instead of silently dropping it as if the profile were not found; a profile that is simply not the user's still drops attribution unchanged - repo: add a manifest-free list projection (reportListSelectSQL / scanReportSummary) for admin list and retention/stale cleanup queries so they no longer drag the full manifest JSONB per row; keep the full projection for GetByID/DeleteByID and mark Manifest omitempty - cleanup: delete/mark the DB row before the blob in retention and stale loops so a mid-run DB failure can't leave a ready report pointing at a missing bundle; blob-delete failures are logged with bucket/keys for orphan cleanup to reap rather than aborting the run (shared helper with the admin DeleteReport path) - admin: reject diagnostics settings where max_bytes_per_user would fall below max_bundle_bytes (and the reciprocal), which would make every max-size upload fail quota - router/demo: route POST /diagnostics/reports through DemoGuard and block the reports prefix in demo mode while keeping GET /diagnostics/status available Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012e3QjbPo96ed9Mn2qRiUkh
|
Round-5 review findings addressed in dee46f9:
🤖 Generated with Claude Code |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dee46f9398
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| <div>{formatPlatform(report.platform)}</div> | ||
| <div className="text-muted-foreground text-xs"> | ||
| v{report.app_version} | ||
| {report.manifest.report.app_build ? ` (${report.manifest.report.app_build})` : ""} |
There was a problem hiding this comment.
Stop dereferencing omitted list manifests
When the admin diagnostics list returns rows, the repository now uses the lightweight summary projection (reportListSelectSQL() / scanReportSummary), so list JSON omits manifest. This row still dereferences report.manifest.report.app_build, which throws as soon as the page renders any listed report and prevents admins from browsing or opening the detail sheet. Use only fields returned by the list response here, or add an app-build summary field separately and keep manifest access to the detail fetch.
Useful? React with 👍 / 👎.
|
|
||
| func decodeJSONObject(data []byte) (map[string]any, error) { | ||
| var obj map[string]any | ||
| if err := json.Unmarshal(data, &obj); err != nil { |
There was a problem hiding this comment.
Preserve JSON numbers when comparing manifests
Fresh evidence after the embedded-manifest fix: this decoder uses json.Unmarshal into map[string]any, which converts all numbers to float64 before DeepEqual. If the multipart manifest and embedded manifest.json differ only in an integer above 2^53, such as log_summary.lines, both values round to the same float and the bundle is accepted even though the stored DB manifest and downloaded archive manifest disagree. Decode with UseNumber (or compare canonical JSON with lossless numbers) so numeric mismatches cannot slip through.
Useful? React with 👍 / 👎.
| CrashSummary: crashSummary, | ||
| Manifest: append(json.RawMessage(nil), manifestJSON...), | ||
| PlaybackSessionIDs: manifest.PlaybackSessionIDs, | ||
| ExpectedBlobBytes: manifest.Archive.Bytes, |
There was a problem hiding this comment.
Do not reserve quota from untrusted byte claims
When an authenticated client under-reports manifest.archive.bytes (for example 1) while sending a max-size bundle, this reserves only the claimed byte count before the stream is uploaded to object storage; the archive mismatch is detected only after that bandwidth/storage work has already happened and the row is marked failed. Because failed rows are not counted by the per-user quotas, a buggy or malicious client can repeatedly bypass diagnostics.max_bytes_per_user as an upload-churn limit. Reserve a conservative amount (such as the configured max) until validation records the actual size, or reject implausibly small archive byte claims before inserting.
Useful? React with 👍 / 👎.
| return nil, err | ||
| } | ||
| if part.FormName() != expectedName { | ||
| _ = part.Close() |
There was a problem hiding this comment.
Reject bad multipart parts without draining them
When the first upload part has the wrong name or content type, such as a max-size bundle part sent before manifest, multipart.Part.Close drains the unread part before this immediate rejection returns. That lets an invalid diagnostics request consume up to the advertised bundle limit while holding the per-user/global in-flight slot before it gets a 400; skip draining the rejected part (or close the request body) so malformed uploads fail promptly under load.
AGENTS.md reference: AGENTS.md:L13-L15
Useful? React with 👍 / 👎.
|
The four review comments posted here just before this PR merged are addressed in follow-up PR #450 (#450): the list-manifest dereference regression (server-side 🤖 Generated with Claude Code |
fix(diagnostics): post-merge review follow-ups for #445
- AdminDiagnostics list: fix regression where rows dereferenced the now-omitted manifest for app_build. Project app_build server-side out of manifest JSONB into both list and detail responses (cheap COALESCE(manifest->'report'->>'app_build','')), split the TS type into DiagnosticReportSummary (list, no manifest) and DiagnosticReport (detail, with manifest), and read report.app_build in the row/detail. - embeddedManifestMatches: decode with json.Decoder + UseNumber so large integers above 2^53 (e.g. log_summary.lines) can't collapse to the same float and falsely match; re-assert no-trailing-data strictness. - Quota reservation (SKIP): reserving the client-claimed archive.bytes is sound because archiveMatches requires claimed==actual before MarkReady, so no stored report exceeds its reservation; documented in a code comment. - Multipart parts: reject a wrong-name/wrong-content-type part without calling part.Close(), which would drain up to the bundle limit while holding the in-flight slot; abandon it so malformed uploads fail promptly. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012e3QjbPo96ed9Mn2qRiUkh
Problem
Clients (Android, Apple) have no way to deliver crash reports or opt-in debug logs to the user's server, so playback/browsing issues reported from the field are undiagnosable. The design for this capability is in #430 (cross-repo spec, included here as the first commit).
What this adds
Server side of the client diagnostics capability, per the spec:
POST /api/v1/diagnostics/reports— authenticated multipart ingest (manifest + tar.gz bundle) with schema validation, server-instance binding, consent gating, per-user/day and byte quotas, and streaming bundle validation (entry allowlist, size/ratio limits, no trailing data).client_diagnostic_reports(receiving→ready, withfailedcompensation on any post-insert error) and bundles in the private S3/R2 bucket.GET /api/v1/diagnostics/statuscapability endpoint (feature detection per v1 API rules; additive only).Fixes found by end-to-end verification on dev
The final three commits are bugs found by exercising the full pipeline against the dev deployment (Cloudflare R2 storage) rather than fakes:
fix(s3client): R2 rejects unsizedPutObjectstreams with 411; streaming uploads now go through the SDK multipart manager (8 MiB sequential parts, bounded memory, sizes stay untrusted).fix(diagnostics): pgx binds nil slices as SQL NULL, violating theplayback_session_idsNOT NULL default; ingest also swallowed underlying insert/validation errors, which made every failure a generic 500.fix(diagnostics): the bundle contract was unimplementable with standard tar writers — end-of-archive zero padding (emitted by GNU tar, Python tarfile, Commons Compress) was rejected, anduncompressed_bytesused a sum-of-payloads definition no client observes. Padding (zeros only, ≤64 KiB) is now accepted anduncompressed_bytesis defined as the full decompressed tar stream; both documented in the spec doc and contract.Verification
ready, failed attempts compensated tofailed, admin list/detail correct, and the bundle downloaded via the admin presigned URL is byte-identical (SHA-256) to the uploaded artifact.Risks / follow-ups
go.modpicks upaws-sdk-go-v2/feature/s3/manager(bumps the s3 service module). Full test suite passes apart from pre-existing environment-dependent failures (playback NVENC probes, jellycompat process locks) that reproduce on the unmodified base commit.Part of the client diagnostics capability — spec: #430.
AI-use disclosure: implemented and verified with Claude Code.
🤖 Generated with Claude Code
https://claude.ai/code/session_012e3QjbPo96ed9Mn2qRiUkh
Summary by CodeRabbit
/api/v1/diagnosticsstatus and report upload endpoints.Retry-Afterbehavior.