Skip to content

feat(diagnostics): upload diagnostics reports through v2 - #397

Merged
Quick104 merged 3 commits into
mainfrom
apiv2-stack/49-diagnostics-uploads-v2
Sep 23, 2026
Merged

Quick104 merged 3 commits into
mainfrom
apiv2-stack/49-diagnostics-uploads-v2

Conversation

@Quick104

Copy link
Copy Markdown
Contributor

Self-hosted diagnostics reports now upload through the v2 report and chunked-upload routes under one captured owner, and a report whose upload may have reached the server is held instead of sent again.

Problem

Self-hosted diagnostics reports still upload through POST /api/v1/diagnostics/reports and the v1 chunked upload routes (inventory rows 122-126), using plain HTTPClient calls. Three things were wrong with carrying that path to v2:

  • The chunked sequence was fenced by a hand-written server and profile check instead of the shared owner fence.
  • Every failure without an HTTP answer counted as retryable. The report upload, chunked create and complete are non_retryable in openapi, so a report whose upload reached the server could be sent again.
  • v2 folds unsupported_schema, stale_consent, destination_mismatch, archive_mismatch and invalid_bundle into one 400 problem (diagnostics_ingress.go:61-80, claim X1). A path-only switch would turn those into endless retries.

Solution

  • Wire. APIv2Client+Diagnostics.swift adds uploadDiagnosticsReport, createDiagnosticsUpload, putDiagnosticsUploadChunk, completeDiagnosticsUpload and abortDiagnosticsUpload. Each one asserts its documented status (201, 201, 200, 201, 204). APIv2Client gains one owner-bound raw request (ownedRequest), plus captureRequestOwner and isCurrentOwner. The raw request keeps the verbatim manifest splice in the create body and sends the multipart and octet-stream bodies. Upload IDs are percent-encoded. The wire models live in APIv2DiagnosticsModels.swift.
  • Ownership. The coordinator captures one owner before building the bundle, and every request in the upload runs under it through withOwnerFence and expectedAuth. This replaces the destinationUnchanged closure. A switch mid-sequence stops the chunked upload without an abort, as before. ownedRequest reports an owner change caught before the request reached the URL session (its own check, the fence's entry check, or HTTPClient's dispatch gate and owner checks) as APIv2OwnerChangedBeforeDispatch. HTTPClient.requestData takes an optional HTTPDispatchRecord that is marked just before session.data, which is how it tells the two apart. A refusal before dispatch releases the claim and stays retryable. An owner change after sending stays uncertain. The selected profile goes out as X-Profile-Id, which v2 reads as report attribution. The existing captured-vs-active profile checks stay in place.
  • Errors (D3, status-only fallback). Distinct problem types win when present: capability_disabled maps to disabled, capability_not_configured to storage unavailable, and the five domain codes are honored if a server starts sending them as problem types. Otherwise the status decides:
    • 400 and 422 keep the report with no retry and no delete. The report is marked server_rejected and the user sees "Report kept; it can't be uploaded to this server."
    • 413 with a problem document means too large.
    • 413 without one came from a proxy and still triggers the chunked fallback.
    • 429 and 503 stay retryable. 5xx stays retryable.
    • A v1-only server's legacy 404 maps to "needs server update".
  • Uncertain outcomes. Before the first request leaves the device, the report records a delivery_uncertain claim in its state.json. A definite answer releases the claim. An unanswered upload, create or complete keeps it, and so does a process that dies mid-upload. A report holding the claim is never auto-uploaded, prompted or sent again. The user can delete it. A transport failure before any connection (offline, DNS, TLS) counts as definite; DiagnosticsAPI uses the shared APIv2Client.neverConnected list for this. After an uncertain complete the upload session is not aborted.
  • Deletions. The v1 upload methods, the v1 HTTPError code mapping, DiagnosticsChunkedUploadSession, EmptyDiagnosticsResponse, the destinationUnchanged closure and the v1 test routes are gone. HTTPClientDiagnosticsClassificationTests path vectors now use v2 routes (34 v1 matches removed). DiagnosticsChunkedUploadTests became DiagnosticsUploadV2Tests.

Failure outcomes

Request (retry safety) Definite success Definite failure Uncertain
POST /api/v2/diagnostics/reports (non_retryable) 201 with report_id/short_id: report deleted locally, "Sent as …" Any non-2xx, refusal before dispatch (gate, owner changed), or a transport failure before connecting: claim released, and the report is handled per the error table above (retryable, server-rejected, too large, needs server update, or chunked fallback on proxy 413) Lost connection, timeout, response discarded because the owner changed in flight, or an unexpected 2xx: report held (delivery_uncertain) and never sent again. The user can delete it.
POST /api/v2/diagnostics/reports/uploads (non_retryable) 201 session: chunks follow Same as above Same as above: held and never re-created
PUT …/uploads/{upload_id}/chunks/{chunk_index} (natural_idempotent) 200: next chunk Any failure is definite for the report, because nothing is ingested without complete: the session is aborted best-effort and the report kept per the error table. An owner change stops without an abort. Not applicable (treated as definite)
POST …/uploads/{upload_id}/complete (non_retryable) 201: report deleted locally Non-2xx: the session is aborted best-effort, the claim released, and the report kept per the error table. Refusal before dispatch after an owner change: claim released, retryable, no abort (it could only reach the new owner) Held (delivery_uncertain). The session is not aborted, because the report may already be ingested.
DELETE …/uploads/{upload_id} (natural_idempotent) 204 Swallowed (courtesy only). Refused before dispatch after an owner change. Swallowed

Validation

  • iOS, tvOS and macOS builds pass on this branch.
  • Focused tests pass: 144 on iOS and 142 on tvOS, 0 failures, covering DiagnosticsUploadV2Tests, HTTPClientDiagnosticsClassificationTests, HostedDiagnosticsAPITests, DiagnosticsCapabilitiesV2Tests, DiagnosticsReviewFixesTests, DiagnosticsViewModelTests and DiagnosticsContractTests.
  • scripts/ci/check-no-api-v1.sh passes. DiagnosticsAPI.swift, HTTPClientDiagnosticsClassificationTests.swift and HostedDiagnosticsAPITests.swift no longer contain v1 paths, and DiagnosticsChunkedUploadTests.swift is replaced by DiagnosticsUploadV2Tests.swift.
  • The final stack passed the full suites (iOS 1981 tests, tvOS 1792 tests, 0 failures), the macOS build and the v1 path guard, and every branch in the stack builds on its own.
  • New StubURLProtocol coverage:
    • Multipart part order and the X-Profile-Id attribution.
    • The verbatim manifest splice in the create body.
    • The octet-stream chunk content type.
    • The status and problem-type mapping table.
    • Uncertain vs definite transport failures.
    • A single dispatch on a lost connection.
    • Refusal before dispatch after an owner change, caught in DiagnosticsAPI, inside HTTPClient after DiagnosticsAPI's check passed, and at the dispatch gate during an identity transition. All three are retryable and send nothing.
    • An owner change while the upload is at the server stays uncertain.
    • A complete refused before dispatch is retryable and skips the abort.
    • Chunk failure with abort.
    • Owner change mid-chunk without abort.
    • Uncertain complete without abort, and a rejected complete with abort.
    • At the coordinator level: an unanswered upload holds the report, and a second attempt made with the pre-claim report sends nothing. A folded 400 keeps the report as server_rejected with the claim released.
  • Nobody ran a live upload against a v2 server; the evidence is compile and unit tests only.

Risks and follow-ups

  • S2 (not published). Until the server sends distinct problem types, a stale consent or archive mismatch keeps the report as "can't upload to this server" instead of resetting consent or deleting it. The client already honors those types if the server adds them under the v1 code names. If S2 lands with different identifiers, the mapping in DiagnosticsAPI.mapUploadError needs updating.
  • Divergence from Android. Android treats 5xx and 408 on the report upload as uncertain. This PR follows plan §9 (any non-2xx is a definite failure), so a 5xx stays retryable.
  • Uncertain create. A lost create answer holds the report, even though nothing can be ingested without complete. This follows the non_retryable rule literally. Relaxing it would need an owner decision.
  • Held reports. A report held as uncertain stays on the device until the user deletes it or it expires (7 days). The UI has no dedicated "Discard held change" label; the existing report delete action does that job.

AI disclosure

Code and description written by Claude Opus 5.5 (claude-opus-5-5) agents in Claude Code (T3 Code), orchestrated by a Claude Code workflow.


Part 49 of 50 in the Apple API v2 stack. Base: apiv2-stack/48-diagnostics-capabilities-v2. Merge in order from the bottom of the stack. The plan and full index are in PR 01.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: 943fafa3-9ec1-4e84-b69a-29efb06cb4ba

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@greptile-apps greptile-apps 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.

Quick104 has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-23T13:26:05.903237Z 844efc1 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Quick104

Copy link
Copy Markdown
Contributor Author

Code review summary

Reviewed head: a8f1763b (apiv2-stack/49-diagnostics-uploads-v2).

Process: an adversarial review of this PR's diff with each candidate finding independently verified before any fix, a simplify pass for medium and larger PRs, and a whole-stack review across contract conformance, authority and failure handling, data integrity, user-visible behavior and cross-PR integration.

Verified findings, all fixed on this branch:

  • minor: Owner-change refusals before dispatch are classified as delivery uncertain, so a report that was never sent is held permanently

Validation: this branch builds on its own for iOS, tvOS and macOS, and its focused tests passed. The completed stack passed the full iOS suite (1981 tests) and tvOS suite (1792 tests) with 0 failures, the macOS build and the v1 path guard. The final stack was also exercised on iOS and tvOS simulators against a v1/v2 bridge server: sign-in (password and QR), restore, browse, search, detail, favorites and watchlist, playback (direct play, transcode, subtitles, stop), audiobooks, downloads with offline playback, settings, requests, profiles, push registration and diagnostics. Server logs showed no /api/v1 request from the new builds except the retained health probe.

Remaining: no open verified findings. Merge in stack order.

Mergeability: 8/10 — conditional. The approach holds up and every verified finding is fixed. Conditions: this PR's CI must pass (it was pending at review time), and the owner still plans a physical-device check of the completed stack.

Review by Claude Opus 5.5 (claude-opus-5-5) agents in Claude Code (T3 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: a8f1763b08

ℹ️ 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".

APIv2Client.neverConnected.contains(urlError.code) {
return .retryable(HTTPDiagnosticsErrorCode.classify(transport: urlError))
}
return .deliveryUncertain

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 Release the claim when preflight refresh prevents dispatch

When the bearer enters the proactive-refresh window while the bundle is being built and the refresh endpoint returns an UpdateRequirement, HTTPClient throws before perform marks the request as dispatched. ownedRequest only converts pre-dispatch owner-change errors, so this fallback classifies the unsent upload as .deliveryUncertain; the coordinator then retains the delivery claim permanently and tells the user the server may already have the report. Use the dispatch state for other pre-dispatch failures as well, or explicitly classify UpdateRequirement as a definite/not-sent failure so the report can be retried after the required update.

Useful? React with 👍 / 👎.

@Quick104
Quick104 force-pushed the apiv2-stack/48-diagnostics-capabilities-v2 branch from 022c1a8 to e8860c8 Compare September 23, 2026 13:19
@Quick104
Quick104 force-pushed the apiv2-stack/49-diagnostics-uploads-v2 branch from a8f1763 to 844efc1 Compare September 23, 2026 13:19
@Quick104
Quick104 force-pushed the apiv2-stack/48-diagnostics-capabilities-v2 branch from e8860c8 to d529fa5 Compare September 23, 2026 13:46
Base automatically changed from apiv2-stack/48-diagnostics-capabilities-v2 to main September 23, 2026 13:46
Quick104 and others added 3 commits September 23, 2026 09:46
Self-hosted diagnostics reports still went to POST /api/v1/diagnostics/reports
and the v1 chunked upload routes through plain HTTPClient calls. The chunked
sequence was fenced by a hand-written server/profile check, and every failure
without an answer counted as retryable, so a report whose upload had reached
the server could be sent again. v2 also folds unsupported schema, stale
consent, destination and archive mismatches into one 400 problem, which the
v1 error-code mapping would have turned into endless retries.

The report upload and the chunked create, chunk, complete and abort calls now
go through the shared APIv2Client under one owner captured before the bundle
is built. A new owner-bound raw request keeps the manifest splice verbatim
and refuses requests after a server, account or profile switch. Answers map
by problem type where the server sends a distinct one (capability_disabled,
capability_not_configured, and the domain codes if a server adds them) and
by status otherwise: 400 and 422 keep the report with no retry and no
delete, 413 without a problem document still triggers the chunked fallback,
and 413, 429 and 503 keep their existing handling. Before the first request
leaves the device the report records a delivery claim; a definite answer
releases it, while an unanswered upload, create or complete (or a process
that dies mid-upload) leaves the report held and never sent again. The v1
methods, the destinationUnchanged closure and the v1 test routes are gone.

Stack-PR: W5-W2
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…est before it is sent

A server, account or profile switch that landed after DiagnosticsAPI's owner
check could still stop a report upload, chunked create or complete before it
left the device: ownedRequest's own guard, the fence's entry check and
HTTPClient's dispatch gate all refuse with requestIdentityChanged or
authorityChanged. Those are the same errors a sent request gets when its answer
is discarded, so the refusal was classified as delivery uncertain and the
report was held for good although nothing reached the server.

HTTPClient.requestData now takes an optional HTTPDispatchRecord that perform
marks just before session.data. ownedRequest turns an owner-change error with
an unmarked record into APIv2OwnerChangedBeforeDispatch, which DiagnosticsAPI
maps to a retryable destination change: the claim is released and a complete
refused this way skips the abort. An owner change after sending stays
uncertain. Tests cover the refusal inside HTTPClient, at the dispatch gate
during an identity transition, on complete, and the discard after sending.

Stack-PR: W5-W2
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
DiagnosticsAPI kept a private copy of the URLError codes raised before a
connection. It now uses APIv2Client.neverConnected, the one list every v2
lane classifies with.

Stack-PR: W5-W2
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@Quick104
Quick104 force-pushed the apiv2-stack/49-diagnostics-uploads-v2 branch from 844efc1 to 2cd4e12 Compare September 23, 2026 13:46
@Quick104
Quick104 merged commit feb51c2 into main Sep 23, 2026
2 checks passed
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@Quick104
Quick104 deleted the apiv2-stack/49-diagnostics-uploads-v2 branch September 23, 2026 13:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant