Skip to content

feat(diagnostics): client diagnostics server — ingest pipeline, R2 storage, admin API + viewer - #445

Merged
Quick104 merged 13 commits into
mainfrom
feat/client-diagnostics-server
Jul 21, 2026
Merged

Quick104 merged 13 commits into
mainfrom
feat/client-diagnostics-server

Conversation

@Quick104

@Quick104 Quick104 commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

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).
  • Reports land in client_diagnostic_reports (receiving → ready, with failed compensation on any post-insert error) and bundles in the private S3/R2 bucket.
  • GET /api/v1/diagnostics/status capability endpoint (feature detection per v1 API rules; additive only).
  • Admin API: list/get/download/delete reports, download via presigned URL.
  • Admin web viewer for browsing and downloading reports.

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 unsized PutObject streams 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 the playback_session_ids NOT 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, and uncompressed_bytes used a sum-of-payloads definition no client observes. Padding (zeros only, ≤64 KiB) is now accepted and uncompressed_bytes is defined as the full decompressed tar stream; both documented in the spec doc and contract.

Verification

  • Unit + contract tests for ingest, quotas, bundle validation (incl. new padding/trailing-data cases), s3client.
  • Full E2E on dev: upload accepted end-to-end, DB row ready, failed attempts compensated to failed, 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.mod picks up aws-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.
  • Client-side capture/upload (silo-android, silo-apple) is follow-up work per the spec.
  • Admin viewer screenshots can be added on request.

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

  • New Features
    • Added opt-in client diagnostics uploads (consent-gated) with schema-validated manifests and gzip diagnostic bundles covering crash, abnormal exit, device, and logline data.
    • Added /api/v1/diagnostics status and report upload endpoints.
    • Added admin UI and endpoints to list/filter/paginate reports, download only “ready” reports, and delete reports.
    • Added background cleanup for expired, stale, and orphaned diagnostic reports/bundles.
  • Bug Fixes
    • Improved upload/download robustness with stricter bundle parsing, clearer validation, and quota-aware Retry-After behavior.
  • Documentation
    • Added versioned design and schema documentation for the client diagnostics contract (v1).

Quick104 and others added 7 commits July 19, 2026 16:27
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
@coderabbitai

coderabbitai Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

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

Changes

Client diagnostics contract

Layer / File(s) Summary
Versioned schemas and validation
docs/design/schemas/client-diagnostics/*, internal/diagnostics/contract/*, internal/diagnostics/types.go
Defines manifest, device, and log-line contracts with fixtures and Go validators.
Settings and identifiers
internal/diagnostics/settings.go, internal/diagnostics/shortid.go
Adds diagnostics settings defaults, server instance IDs, and normalized short report IDs.

Ingestion and persistence

Layer / File(s) Summary
Report storage
migrations/sql/*, internal/diagnostics/repo.go, internal/diagnostics/store.go, internal/s3client/client.go
Adds the report table, quota-aware repository operations, object storage abstraction, and streaming S3 uploads/downloads.
Bundle ingestion
internal/diagnostics/bundle.go, internal/diagnostics/service.go, internal/diagnostics/*_test.go
Validates bounded gzip/tar bundles, streams uploads, records ready reports, and compensates failed uploads.

HTTP, cleanup, and administration

Layer / File(s) Summary
API and admin integration
internal/api/handlers/*diagnostics*, internal/api/handlers/admin.go, internal/api/router.go, cmd/silo/main.go
Adds client status/upload endpoints, admin listing/download/delete endpoints, diagnostics setting validation, routing, defaults, and cleanup registration.
Retention cleanup
internal/diagnostics/cleanup.go, internal/taskmanager/tasks/cleanup_client_diagnostics.go
Deletes retained and stale reports, reconciles orphan objects, and schedules cleanup execution.

Web administration

Layer / File(s) Summary
Diagnostics admin UI
web/src/pages/AdminDiagnostics.tsx, web/src/hooks/queries/admin/diagnostics.ts, web/src/api/*
Adds typed queries, report filters, pagination, details, download, deletion, and status displays.
Navigation and tests
web/src/App.tsx, web/src/lib/*, web/src/components/*, web/src/hooks/queries/admin/diagnostics.test.ts
Adds the admin route, navigation entry, document title, and UI/download coverage.

Estimated code review effort: 5 (Critical) | ~120 minutes

Suggested labels: v1

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 3.90% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main diagnostics server, storage, admin API, and viewer changes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/client-diagnostics-server

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread internal/diagnostics/bundle.go Outdated
if hdr.Size < 0 {
return "", fmt.Errorf("%w: negative tar entry size", ErrInvalidBundle)
}
name := strings.TrimSpace(hdr.Name)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment thread internal/diagnostics/repo.go Outdated
Comment on lines +140 to +143
SELECT COALESCE(SUM(blob_bytes), 0)
FROM client_diagnostic_reports
WHERE user_id = $1
AND state = 'ready'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +313 to +314
var crash *Crash
if wire.Crash != nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment thread internal/diagnostics/settings.go Outdated
if err != nil {
return err
}
if err := store.Set(ctx, KeyServerInstanceID, instanceID); err != nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (6)
migrations/sql/20260720084550_client_diagnostic_reports.sql (1)

7-12: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Enforce the diagnostics closed sets in the database.

state, report_type, and platform are unconstrained even though the diagnostics contract defines finite values. Add CHECK constraints 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 value

Case-only distinction between two constants is a footgun.

DefaultMaxUncompressed (int64) and defaultMaxUncompressed (string) differ only by initial capitalization, and the string one also breaks the ...Str suffix convention used by its siblings (defaultMaxBundleStr, defaultMaxBytesUserStr). Renaming to defaultMaxUncompressedStr removes 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

rawSentinel returns true for every string, making the branch (and downstream cases) dead code. Both the if 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 the case '"' arm in validateDeviceValue (Line 815-820) unreachable. Consider renaming to rawString and 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 win

Silently swallowed presign error masks storage/config failures.

When PresignReportDownload returns 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 win

Consider role="button" on the clickable row.

Keyboard support (Enter/Space) and aria-label are already present, but the <tr> lacks a role conveying 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 win

Redundant useDateTimeFormat() subscription.

Neither DiagnosticReportRow nor DiagnosticReportDetail (the only consumers of formatDateTime in this file) are memoized, so this page doesn't need its own subscription — ReactiveAppRoutes in App.tsx already 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3457382 and 75c2260.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (57)
  • cmd/silo/main.go
  • docs/design/2026-07-19-client-diagnostics.md
  • docs/design/schemas/client-diagnostics/README.md
  • docs/design/schemas/client-diagnostics/v1/attr-registry.json
  • docs/design/schemas/client-diagnostics/v1/device.schema.json
  • docs/design/schemas/client-diagnostics/v1/fixtures/invalid/archive-entry-outside-allowlist.json
  • docs/design/schemas/client-diagnostics/v1/fixtures/invalid/bad-schema-version.json
  • docs/design/schemas/client-diagnostics/v1/fixtures/invalid/missing-consent.json
  • docs/design/schemas/client-diagnostics/v1/fixtures/invalid/platform-macos-reserved.json
  • docs/design/schemas/client-diagnostics/v1/fixtures/invalid/stack-excerpt-over-8kib.json
  • docs/design/schemas/client-diagnostics/v1/fixtures/invalid/unknown-report-type.json
  • docs/design/schemas/client-diagnostics/v1/fixtures/valid/android-manual-no-profile.json
  • docs/design/schemas/client-diagnostics/v1/fixtures/valid/android-manual.json
  • docs/design/schemas/client-diagnostics/v1/fixtures/valid/android-tv-crash-ueh.json
  • docs/design/schemas/client-diagnostics/v1/fixtures/valid/device.json
  • docs/design/schemas/client-diagnostics/v1/fixtures/valid/ios-hang-metrickit.json
  • docs/design/schemas/client-diagnostics/v1/fixtures/valid/loglines.jsonl
  • docs/design/schemas/client-diagnostics/v1/fixtures/valid/tvos-abnormal-exit.json
  • docs/design/schemas/client-diagnostics/v1/logline.schema.json
  • docs/design/schemas/client-diagnostics/v1/manifest.schema.json
  • go.mod
  • internal/api/handlers/admin.go
  • internal/api/handlers/admin_diagnostics.go
  • internal/api/handlers/diagnostics.go
  • internal/api/handlers/diagnostics_test.go
  • internal/api/router.go
  • internal/diagnostics/admin.go
  • internal/diagnostics/bundle.go
  • internal/diagnostics/bundle_test.go
  • internal/diagnostics/cleanup.go
  • internal/diagnostics/cleanup_test.go
  • internal/diagnostics/contract/contract.go
  • internal/diagnostics/contract/contract_test.go
  • internal/diagnostics/repo.go
  • internal/diagnostics/service.go
  • internal/diagnostics/service_test.go
  • internal/diagnostics/settings.go
  • internal/diagnostics/settings_test.go
  • internal/diagnostics/shortid.go
  • internal/diagnostics/shortid_test.go
  • internal/diagnostics/store.go
  • internal/diagnostics/types.go
  • internal/s3client/client.go
  • internal/taskmanager/tasks/cleanup_client_diagnostics.go
  • migrations/sql/20260720084550_client_diagnostic_reports.sql
  • web/src/App.tsx
  • web/src/api/client.ts
  • web/src/api/types.ts
  • web/src/components/AdminSectionCommandDialog.test.tsx
  • web/src/components/AdminSidebar.test.tsx
  • web/src/hooks/queries/admin/diagnostics.test.ts
  • web/src/hooks/queries/admin/diagnostics.ts
  • web/src/hooks/queries/keys.ts
  • web/src/lib/adminNavigation.ts
  • web/src/lib/documentTitle.test.ts
  • web/src/lib/documentTitle.ts
  • web/src/pages/AdminDiagnostics.tsx

Comment thread internal/diagnostics/admin.go Outdated
Comment on lines +74 to +79
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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.

Comment thread internal/diagnostics/cleanup.go Resolved
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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread internal/diagnostics/bundle.go Outdated
Comment on lines +118 to +120
entryBytes, err := copyTarEntry(tr, buffer, limits, metered, &payloadBytes)
if err != nil {
return BundleInfo{}, err

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment thread internal/diagnostics/admin.go Outdated
if err != nil {
return nil, err
}
if err := deleteReportObjects(ctx, s.store, report, s.logger); err != nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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
@Quick104

Copy link
Copy Markdown
Contributor Author

All 11 review findings addressed in a6348b3 — thanks Codex + CodeRabbit, several were real catches:

  • Padded tar names: now rejected instead of trimmed (manifest.json can no longer masquerade as an allowlisted entry).
  • Byte quota: receiving rows now reserve their expected size in blob_bytes and the quota sums receiving+ready, closing the concurrent/multi-node overshoot.
  • Crash metadata: the contract now requires the crash object for crash/anr/native_crash/hang/abnormal_exit and rejects it on manual reports (all valid fixtures already complied; verified the Apple client sends it for abnormal exits).
  • Instance-ID seeding: atomic via SetIfAbsent + re-read-winner, with a plain-Set fallback for stores without it.
  • Embedded manifest: ValidateBundle now captures the first entry (bounded by the manifest size limit) and Ingest deep-compares it against the multipart manifest minus archive — a stored archive can no longer disagree with its DB row.
  • Delete ordering: DB row first, then blob; blob-delete failures log bucket/key for the reaper instead of stranding a visible-but-undownloadable report.
  • PAX/GNU smuggling: non-USTAR formats and extension records are rejected outright.
  • Migration: CHECK constraints for the state/report_type/platform closed sets.
  • Cleanup: per-report errors now log-and-continue (aggregated via errors.Join) instead of aborting the run; diagnostics got its own diagnostics.cleanup_interval_minutes key instead of borrowing opslog's, and the startup settings lookup is bounded by a timeout.
  • Docs: fence language identifiers added.

🤖 Generated with Claude Code

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between c1cebf5 and a6348b3.

📒 Files selected for processing (15)
  • docs/design/2026-07-19-client-diagnostics.md
  • internal/diagnostics/admin.go
  • internal/diagnostics/bundle.go
  • internal/diagnostics/bundle_test.go
  • internal/diagnostics/cleanup.go
  • internal/diagnostics/cleanup_test.go
  • internal/diagnostics/contract/contract.go
  • internal/diagnostics/contract/contract_test.go
  • internal/diagnostics/repo.go
  • internal/diagnostics/service.go
  • internal/diagnostics/service_test.go
  • internal/diagnostics/settings.go
  • internal/diagnostics/settings_test.go
  • internal/taskmanager/tasks/cleanup_client_diagnostics.go
  • migrations/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

Comment thread internal/diagnostics/settings.go Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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`,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment thread internal/diagnostics/settings.go Outdated
if store == nil {
return settings, nil
}
if raw, err := store.Get(ctx, KeyUploadsEnabled); err == nil && strings.TrimSpace(raw) != "" {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment thread internal/diagnostics/bundle.go Outdated
manifestCapture.Grow(int(hdr.Size))
capture = manifestCapture
}
entryBytes, err := copyTarEntry(tr, buffer, limits, metered, &payloadBytes, capture)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment thread internal/api/router.go
}
r.Route("/diagnostics", func(r chi.Router) {
r.Get("/status", diagnosticsHandler.HandleStatus)
r.Post("/reports", diagnosticsHandler.HandleUpload)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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
@Quick104

Copy link
Copy Markdown
Contributor Author

Round-2 findings all addressed in 2d5d498:

  • Cleanup interval: parsed minutes capped (1 min–7 days) so absurd values can't overflow int64 nanoseconds.
  • Admin download: the web admin now requests ?proxy=1 and streams through the server — presigned URLs broke when the private bucket is only server-reachable, and the separate-window navigation had no way to fall back.
  • Settings reads: real store.Get failures now propagate (missing/empty still defaults) — a DB blip can no longer report the feature as disabled or silently use default quotas.
  • Bundle content validation: non-manifest entries are structurally validated while streaming — device.json/crash/*.json must be a single JSON object (token-streamed, bounded depth), logs.jsonl/breadcrumbs.jsonl must be NDJSON objects with a 64 KiB per-line cap; crash/stack.txt and crash/tombstone.pb stay opaque. Memory stays bounded; size/ratio sentinels keep precedence.
  • Upload read deadline: HandleUpload extends the per-request read deadline to 10 minutes via http.ResponseController — the server-wide 30s ReadTimeout was cutting off slow mobile uploads mid-stream.

🤖 Generated with Claude Code

@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 21, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment thread internal/api/router.go Outdated
Comment on lines +325 to +328
diagnosticsService.SetProfileAttributionValidator(diagnostics.ProfileAttributionValidatorFunc(
func(ctx context.Context, userID int, profileID string) (bool, error) {
_, found, err := checkPrimaryProfile(ctx, userID, profileID)
return found, err

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between a6348b3 and 2d5d498.

📒 Files selected for processing (8)
  • internal/api/handlers/diagnostics.go
  • internal/diagnostics/bundle.go
  • internal/diagnostics/bundle_test.go
  • internal/diagnostics/contract/contract.go
  • internal/diagnostics/settings.go
  • internal/diagnostics/settings_test.go
  • web/src/hooks/queries/admin/diagnostics.test.ts
  • web/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
@Quick104

Copy link
Copy Markdown
Contributor Author

Round-3 findings addressed in 93b851f:

  • Write deadline: HandleUpload now extends the write deadline alongside the read deadline (the global 120s WriteTimeout could still cut off slow uploads after the read-side fix).
  • Child-profile attribution: diagnostics attribution now rejects child profiles server-side via NewProfileAttributionValidator (profile must belong to the user and not be a child) — mirrors the client-side gating, so a nonconforming client can't record reports against a child profile.
  • Download test: the hook test now captures the clicked anchor and asserts the blob href and silo-diagnostics-<SHORTID>.tar.gz filename.

🤖 Generated with Claude Code

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +443 to +448
if profileID != nil {
value = strings.TrimSpace(*profileID)
}
if value == "" {
value = strings.TrimSpace(fallback)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +282 to +284
"contains": {
"const": "manifest.json"
},

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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
@Quick104

Copy link
Copy Markdown
Contributor Author

Round-4 findings addressed in 1f9bd99:

  • Schema/validator alignment: the canonical manifest.schema.json now carries the crash-object conditionals (required for crash/anr/native_crash/hang/abnormal_exit, forbidden for manual) and prefixItems requiring manifest.json as the first archive entry — matching what the Go validator and upload path enforce.
  • Byte vs character limits: JSON Schema can't express UTF-8 byte lengths, so maxLength stays as the character sanity bound with a top-level description stating the server enforces byte lengths, plus per-field notes on the free-text fields where the divergence realistically bites.
  • Profile mismatch: when both X-Profile-Id and manifest.report.profile_id are present and differ, ingest now rejects with 400 profile_mismatch before any row/blob is written (previously the header silently won). Client-side handling is being aligned in the Apple PR.

🤖 Generated with Claude Code

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +484 to +485
if !found {
return nil, nil

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +467 to +469
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment thread internal/diagnostics/cleanup.go Outdated
Comment on lines +97 to +101
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) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +2487 to +2489
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment thread internal/api/router.go
Comment on lines +1822 to +1824
r.Route("/diagnostics", func(r chi.Router) {
r.Get("/status", diagnosticsHandler.HandleStatus)
r.Post("/reports", diagnosticsHandler.HandleUpload)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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
@Quick104

Copy link
Copy Markdown
Contributor Author

Round-5 review findings addressed in dee46f9:

  • service.go child profile: FIXED — a supplied child-profile attribution is now rejected with a distinct ErrChildProfileForbidden (403 child_profile_forbidden) instead of being silently dropped like a not-found profile. A profile that simply isn't the user's still drops attribution and proceeds unattributed.
  • repo.go manifest projection: FIXED — added a manifest-free projection (reportListSelectSQL / scanReportSummary) for admin list and retention/stale cleanup queries; the full manifest projection is reserved for GetByID/DeleteByID, and Report.Manifest is now omitempty.
  • cleanup.go ordering: FIXED — retention and stale loops now delete/mark the DB row before the blob; a blob-delete failure after the row is gone is logged with bucket/keys for orphan cleanup to reap rather than aborting the run (shared helper with the admin DeleteReport path).
  • admin.go settings cross-field: FIXED — reject max_bytes_per_user below max_bundle_bytes and the reciprocal, so /diagnostics/status can't advertise a bundle size every upload would reject as quota_exceeded.
  • router.go demo guard: FIXED — POST /api/v1/diagnostics/reports now routes through DemoGuard, and the reports prefix is blocked in demo mode; GET /api/v1/diagnostics/status stays available.

go build ./... and go test ./internal/diagnostics/... ./internal/api/... -count=1 pass.

🤖 Generated with Claude Code

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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})` : ""}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@Quick104
Quick104 merged commit 8b3bff1 into main Jul 21, 2026
6 checks passed
@Quick104
Quick104 deleted the feat/client-diagnostics-server branch July 21, 2026 18:16
@Quick104

Copy link
Copy Markdown
Contributor Author

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 app_build projection + TS type split), lossless UseNumber manifest comparison, the multipart no-drain rejection, and a documented SKIP for the quota reservation (archiveMatches guarantees claimed==actual, so no stored report exceeds its reservation).

🤖 Generated with Claude Code

Quick104 added a commit that referenced this pull request Jul 21, 2026
fix(diagnostics): post-merge review follow-ups for #445
raiden202 pushed a commit to raiden202/silo-server that referenced this pull request Jul 23, 2026
- 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant