Repository navigation
feat(settings): write setting values through v2 - #366
Conversation
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Advanced Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
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. Comment |
There was a problem hiding this comment.
Quick104 has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Code review summaryReviewed head: 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:
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 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 ( |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bfb413157c
ℹ️ 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".
| private var heldSubtitleEditorValues: [SubtitleWriteIdentity: String] = [:] | ||
| /// The metadata language write that ran out of automatic retries. | ||
| private var heldMetadataWrite: MetadataWrite? |
There was a problem hiding this comment.
Persist held profile changes beyond the editor
When a profile write exhausts its retries, these in-memory properties are the only record of the held value. SettingsView owns the editor through a newly created @State SettingsViewModel, so recreating the Settings view or terminating the app destroys the value and its Try Again/Discard state, despite the UI saying it stays on the device. Persist held values per profile and key, as the other settings outboxes do.
Useful? React with 👍 / 👎.
| pendingSyncWrites.removeValue(forKey: key.rawValue) | ||
| saveCache(for: context.cacheKey) |
There was a problem hiding this comment.
Reconcile optimistic values after a definitive refusal
When a value write receives a definite refusal such as 403 or 422, this removes the durable outbox entry but leaves the optimistically assigned storedPrimaryMenu or storedCardPresentation in the cache, and it does not schedule the “next refresh” mentioned by the comment. The app therefore continues applying a setting the server rejected—potentially across restart—until an unrelated refresh occurs. Restore the prior value or fetch the effective value before permanently releasing the entry.
Useful? React with 👍 / 👎.
| for (key, write) in pendingSyncWrites where write.retry.isHeld { | ||
| pendingSyncWrites.removeValue(forKey: key) | ||
| if let settingKey = SettingKey(rawValue: key) { setSyncError(nil, for: settingKey) } |
There was a problem hiding this comment.
Keep held values when offline discard cannot reconcile
If the user discards a held value while the server is still unreachable—the common condition that created the hold—this removes the outbox entry and persists the optimistic value before refresh() is attempted. The failed refresh leaves that discarded menu or card presentation active in the cache while hasHeldChanges becomes false, so the user can no longer retry or discard it. Keep the hold until an authoritative read succeeds, or retain enough prior state to roll it back locally.
Useful? React with 👍 / 👎.
bfb4131 to
b46bf1c
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b46bf1c73a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if pendingMetadataWrite == held { pendingMetadataWrite = nil } | ||
| preferredMetadataLanguage = savedBaseline.metadataLanguage ?? PlaybackPrefSentinel.none | ||
| } | ||
| heldSubtitleEditorValues.removeAll() |
There was a problem hiding this comment.
Preserve held changes for inactive profiles
When this editor survives a profile switch, heldSubtitleEditorValues can contain entries for both the previously bound profile and the current one, but discarding the current profile's held change removes the entire dictionary. For example, if profile A has a held subtitle change and profile B later has one, choosing Discard while viewing B silently deletes A's retry state as well. Remove only entries whose profileId matches boundProfileId so another profile's unsaved change remains recoverable.
Useful? React with 👍 / 👎.
01c8da7 to
cca0d4b
Compare
The setting value writes (PUT and DELETE /api/v1/settings/values/{key}
and PUT .../nav.shortcuts/item) still used v1 and its mutation-id replay:
X-Silo-Mutation-Id, X-Silo-Idempotent-Replay and 409
mutation_id_conflict. v2 has no replay. It ignores the header, rejects a
mutation_id body member, and marks all three writes natural_idempotent.
Main also carried an unwired dispatchSettingCommand with its command
types.
The writes now go through the shared APIv2Client (updateSettingValue,
updateNavigationShortcut and deleteSettingValue) via a new owner-fenced
settingsWrite. It refuses another profile and a stale pinned identity,
asserts 200 or 204, checks the receipt against the addressed row, and
maps a DELETE 404 to noValueAtScope. SettingsAPIError maps v2 problems
by rejected location, gains ownerChanged, and sorts every failure into
the D4 classes retry, release, ownerChanged and waitForCondition.
Per owner decision D4, each surface keeps one pending value per key and
retries only the latest value on a bounded backoff while its owner still
matches. After the bound it holds that key and offers "Try Again" and
"Discard Held Change". This covers the player flusher (whose journal and
background flush stay), the profile subtitle and metadata editor, and
the interface customization outbox. Old journals and caches that carry
mutation ids still decode. Refused changes are released and reported
once. The v1 write methods, SettingValueWriteReceipt,
newSettingMutationId, dispatchSettingCommand and the SettingsMutation*
types are deleted.
Stack-PR: W4-B
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Use HeldSettingChange.message directly instead of a private forwarding property, and share the flusher's locked held-key computation between heldKeys and publishHeldKeys. Stack-PR: W4-B Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Discarding a held subtitle or metadata change relied on the reload to repaint the control. Offline, the reload fails and leaves the discarded value on screen, so the next edit of any subtitle control sent it along with that edit. A subtitle value the server definitely refused (422, 403) was also kept as owed and sent again with the next edit. Discard now puts each control still showing a discarded value back to its last saved value before reloading. A definite refusal is released: the control goes back to its saved value and nothing is queued. Owner changes and missing-profile or v1-only conditions stay owed as before. Stack-PR: W4-B Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… server "Discard Held Change" for player device settings dropped the hold and then refreshed. Offline, the refresh reapplied the local cache, which holds the discarded value, so playback kept using it while the screen no longer marked it unsaved. Discard now reads the effective values first and drops the hold only when that read succeeds, then paints the server's values. If the server can't be reached, the change stays held and the Playback rows say so. A v1-only server stores nothing, so there the hold is dropped and the local value stays. Stack-PR: W4-B Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Settings value PUT/DELETE are natural_idempotent, but HTTPClient kept them on the single-dispatch exclusion list. A write after the access token expired got a 401 with no refresh, and the D4 retry loop resent the same stale bearer until the change was held. Drop the exclusion so a 401 refreshes once and resends under the same captured owner. A 401 that survives the refresh still maps to .retry. Stack-PR: W4-B Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
b46bf1c to
ffba129
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ffba12961d
ℹ️ 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".
| profileID: profileID, | ||
| expectedIdentity: expectedIdentity | ||
| ) | ||
| return try Self.settingReceipt(response, key: key, scope: scope, profileID: profileID) |
There was a problem hiding this comment.
Reject PUT receipts that contain a different value
When a whole-value PUT returns 200 for the expected key and scope but the receipt contains a stale or incorrectly encoded value, this call accepts it because the requested value is never passed into settingReceipt. The settings surfaces then retire their pending operation or advance their saved baseline even though the receipt says the desired value was not stored, leaving no retry path. Pass the requested value into the receipt validator and compare it using isSemanticallyEquivalent(to:).
Useful? React with 👍 / 👎.
| case .release: | ||
| pendingDeletes.removeValue(forKey: identity) | ||
| saveCache(for: context.cacheKey) |
There was a problem hiding this comment.
Restore reset state after a definitive DELETE refusal
When resetCardPresentationToInherited() receives a definitive DELETE refusal such as 403 or 422, it has already persisted storedCardPresentationSource = nil; this branch removes the only pending delete and records an error, which also prevents the reset method's follow-up refresh. The UI therefore reports the card setting as inherited and hides the reset action even though the server still has the explicit family override, until an unrelated refresh occurs. Restore the prior source or reconcile with an authoritative read before releasing the delete.
Useful? React with 👍 / 👎.
Setting value writes now go through
/api/v2on the sharedAPIv2Client, without mutation IDs. Each settings surface keeps one pending value per key and retries only that latest value, on a bounded backoff, while its owner still matches. When the retries run out, the surface holds that key and offers "Try Again" and "Discard Held Change" (owner decision D4). The v1 write methods, the mutation-ID plumbing and the unwireddispatchSettingCommandare gone.Problem
Inventory rows 44, 45 and 46 are live v1 writes in
SiloAPI+Settings.swift:putValue:PUT /api/v1/settings/values/{key}putNavigationShortcutItem:PUT /api/v1/settings/values/nav.shortcuts/itemdeleteValue:DELETE /api/v1/settings/values/{key}Three settings surfaces call them: the player's device settings (
PlayerSettingsFlusher), the profile subtitle and metadata preferences (ProfileSettingsWriter/ProfilePrefsEditor), and the interface customization outbox (UICustomizationPreferences).All three surfaces depended on v1 idempotent replay. They sent
X-Silo-Mutation-Idand readX-Silo-Idempotent-Replay. They also retried under the same ID and handled 409mutation_id_conflict.v2 has none of that. The server ignores the header, rejects a
mutation_idbody member with 422, and replays nothing (claim A4). Every accepted write advances the row's revision. The openapi contract marks all three operationsnatural_idempotent, and D4 sets the retry rule.Main also had an unwired v2 path,
APIv2Client.dispatchSettingCommand, plus itsSettingsMutationCommand,SettingsMutationAuthorityandSettingsMutationHoldtypes. Nothing called any of it.Solution
Wire layer.
APIv2Client+Settings.swiftgainsupdateSettingValue,updateNavigationShortcutanddeleteSettingValue. All three go through a new internalsettingsWriteinAPIv2Client.swift, which replacesdispatchSettingCommand.settingsWriteworks likesettingsRead:profile_idquery is never sent.requestIdentityno longer matches.withOwnerFence.All three are
natural_idempotent, soHTTPClient.shouldAttemptRefreshno longer excludes settings valuePUT/DELETE: a write sent with an expired bearer refreshes once and re-sends the same value under the same captured owner, instead of entering the D4 backoff with the stale token.docs/native-api-v2.mdnow says so.Each operation asserts its one success status: 200 for a PUT, 204 for a DELETE (I2). A PUT receipt must describe the row that was addressed: the key, the scope, a revision above 0, the profile, this device's id for
profile_device, this client family forprofile_client, and the stringlibrary_idorseries_id. Any other receipt throws the newAPIv2Error.unexpectedSettingReceipt, and the write counts as uncertain. A DELETE 404 problem means nothing is stored there and becomesSettingsAPIError.noValueAtScope. Request bodies are exactly{"value": …}and{"item": …, "present": …}, coded withSettingsWireCoding, so value keys stay verbatim.Errors.
SettingsAPIError.fromnow maps v2 problems:path.keyorquery.keysbecomesunknownSetting.query.scopebecomesscopeNotAllowed.body.valueorbody.itembecomesinvalidValue.server(status:code:message:).HTTPError.requestIdentityChangedandauthorityChangedbecome the newownerChanged.The v1 envelope mapping and the
mutationIdConflictandclientLocalSettingcases are deleted, because v2 cannot produce them. The effective read now reports a row for another profile as a refused response, not as an owner change.D4 failure classes. A new
SettingsAPIError.writeFailureputs every failure in one class:retry: transport failure, 5xx, 408, 429, a 409 compare-and-set conflict, a 401 that outlived refresh, or a mismatched receipt.release: any other definite refusal.ownerChangedwaitForCondition: no profile selected, or a v1-only server.SettingWriteRetryPolicycarries the bound. The default allows 5 retries at 1, 2, 4, 8 and 16 s, capped at 60 s. Theinteractivepolicy allows 3 retries at 1, 2 and 4 s.Surfaces.
PlayerSettingsFlusher). Theplayer.pendingDeviceSettingWrites.*journal and its partitioning stay (I7). The background flush stays.PendingSettingWritedropsmutationIdand gainsfailedAttemptsandisHeld. Entries from earlier builds still decode, and theirmutationIdis ignored (I17).PlayerSettingsexposesheldDeviceSettingKeysandrejectedDeviceSettingChange.discardHeldDeviceSettingChanges()reads the effective values before dropping the hold. If that read fails, the hold stays, because the discarded value is the only copy on the device. A v1-only server has no stored value, so there the hold is dropped and the local value stays.refreshFromServerkeeps painting unsettled values over the server's older answer. The legacy import never overwrites a key with its own pending change.ProfileSettingsWriter.writeretries on theinteractivepolicy while the editor confirms the value is still the latest for its key and profile. It throwsHeldChangeafter the bound andSupersededwhen a newer edit arrives. The mutation-ID map is gone.ProfilePrefsEditorrecords held values per key and profile, keeps showing them across reloads, and never re-sends them on its own. Editing that control again sends the new value, even when it matches the baseline, because the held value may have reached the server.hasHeldChanges,retryHeldChanges(),discardHeldChanges()and a.heldsave state.discardHeldChanges()repaints each discarded control from its last saved value before it reloads, so an offline discard cannot leave the value on screen to be sent with the next edit.body.valueor a 403) is released: the control goes back to its saved value, and the refused value is not queued again. Only owner changes and missing-profile or v1-only conditions stay owed for the next save.UICustomizationPreferences). Outbox entries carry a localoperationId, which is never sent, and a retry state. Caches that storedmutationIdstill decode.hasHeldChangesis observable.retryHeldChanges()anddiscardHeldChanges()are new; discarding also rolls back a held shortcut.UI. New
HeldSettingChangesSection(iOS and macOS) andTVHeldSettingChangesRows(tvOS, plain buttons in the pane's native focus graph) show the text "A change couldn't be saved to the server. It stays on this device until you try again or discard it." next to "Try Again" and "Discard Held Change". They appear in Playback, Subtitles and Interface settings on iOS and macOS, and in the Playback, Subtitles and General panes on tvOS. The tvOS Playback rows sit above Reset, so pane entry focus is unchanged. Playback settings also show a one-time "Not Saved" notice with OK when the server refuses a device setting change. If "Discard Held Change" can't reach the server, the Playback rows keep the held change and change their footer to "Couldn't reach the server to discard this change. It stays on this device until the server can be reached."Deleted.
SiloAPI.putValue(…mutationId:…)and the v1 shortcut and delete bodies,SettingValueWriteReceipt,newSettingMutationId(),dispatchSettingCommand,SettingsMutationCommand,SettingsMutationAuthorityandSettingsMutationHold. The v1 write tests and their stub routes are removed fromSettingValuesAPITests.StoredSettingValueis nowDecodableand takes the stringlibrary_id.Failure outcomes
All three operations are
natural_idempotent(openapix-silo-retry-safety).D4 is the plan's one named exception to "uncertain: hold, never auto-replay". It allows a bounded replay of the latest value only, and only while the captured owner matches. No request carries a mutation ID.
Validation
SiloTests/SettingValueWritesTests SiloTests/SettingValuesAPITests SiloTests/PlayerSettingsFlushTests SiloTests/UICustomizationPreferencesTests SiloTests/ProfileAndQualitySettingsTests SiloTests/OverlayPrefsStoreTests SiloTests/APIv2ContractTests SiloTests/PlaybackProtocolV3Tests SiloTests/DurableCommandStoreTests SiloTests/CredentialIdentityTests) passed: 408 tests, 0 failures. The same classes underSiloTVTestspassed: 403 tests, 0 failures.SiloTestssuite passed (1626 tests, 2 skipped, 0 failures) and the fullSiloTVTestssuite passed (1483 tests, 2 skipped, 0 failures) on this branch.ProfileAndQualitySettingsTests,PlayerSettingsFlushTests,SettingValueWritesTestsandUICustomizationPreferencesTestspassed on iOS (209 tests) and tvOS (204 tests) with 0 failures. The two newProfileAndQualitySettingsTestscases fail against the editor without the fix.scripts/ci/check-no-api-v1.shpassed. The v1 literal counts drop inSiloAPI+Settings.swift,SettingValueModels.swift,PlayerSettingsFlusher.swiftandSettingValuesAPITests.swift.withOwnerFence/sameCredentialIdentitylines iniosApp/iosApp) stays at 60.settingsWritereplaces the fence thatdispatchSettingCommandheld.SettingValueWritesTests(onStubURLProtocolthroughAPIv2TestStub) covers:scopeand stringlibrary_idquery, and the profile, device and client-family headers, with noX-Silo-Mutation-Idand noprofile_idSettingsAPIErrorand write-failure classtestExpiredBearerRefreshesAndResendsTheWriteOnce)PlayerSettingsFlushTestscovers:mutationIdstill restoringPlayerSettingskeeping a held value across a refresh until it is discardedProfileAndQualitySettingsTestscovers:subtitleLanguage(422 atbody.value, and 403) that goes back to the saved value and is sent exactly once across a latersubtitleModeeditUICustomizationPreferencesTestscovers a hold after the bound that survives a restart, is skipped by refresh, and is discarded without a write, plus "Try Again" with a fresh budget. The shortcut and card-presentation replay tests now assert that the same desired value is re-sent, not the same mutation ID.Risks and follow-ups
revision. Last writer wins across devices, as on v1. This is the accepted D4 trade-off.settingsWriterefuses any other owner. Plan §9's "sign-out clears barriers" is left for a follow-up that adds a key enumeration toSharedDefaults.supports_idempotent_writes: true(settings_values.go:328). Nothing reads it.SettingScopeIdentity.profileLibrarystill takes anIntand is sent as a string. No write surface targetsprofile_librarytoday.Buttons in the pane's native focus graph, placed after the existing sections.APIv2Client.swiftnear the settings helpers. feat(watch-party): add iOS and tvOS rooms and synchronized playback #347 and the auth lane editHTTPClient.swift, where this PR changes therequestDatadoc comment and removes the settings-write line fromshouldAttemptRefresh.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 18 of 50 in the Apple API v2 stack. Base:
apiv2-stack/17-settings-reads-v2. Merge in order from the bottom of the stack. The plan and full index are in PR 01.🤖 Generated with Claude Code