Skip to content

Deepen listening-sync policy into the core (and let it own device_id) - #19

Merged
JacobStephens2 merged 7 commits into
mainfrom
issue-18
Sep 28, 2026
Merged

JacobStephens2 merged 7 commits into
mainfrom
issue-18

Conversation

@JacobStephens2

@JacobStephens2 JacobStephens2 commented Sep 27, 2026 •

Copy link
Copy Markdown
Owner

Summary

Listening-sync policy moves into the core, and transport stays in the shells. The shell decides when it can talk (signed in, lifecycle). The core decides whether there is anything to say, and what. ADR-0001 decisions 5 and 6 are amended in place.

In CI, setup-android no longer installs the legacy tools package. cmdline-tools 16 removed it, which broke Android setup on main too. Separate commit.

sequenceDiagram
    participant Shell
    participant Core
    participant Server
    Shell->>Core: BeginListeningSync { reason: threshold | flush | refresh }
    Core-->>Shell: PushListening { deviceId, deviceTotalMs }  (or nothing)
    Shell->>Server: PUT /listening (exactly that)
    alt ok
        Shell->>Core: ListeningSyncSucceeded { serverTotalMs }
        Note over Core: syncedThrough := what was sent
    else error
        Shell->>Core: ListeningSyncFailed { unauthorized }
        Core-->>Shell: ClearSession (if 401)
    end
Loading

Shell code before and after (the same in all four):

 deleteData
   await deleteListening(token)
-  rotateDeviceId()                       // persisted write #1
-  dispatch(resetListeningData)           // persisted write #2
+  dispatch(resetListeningData { newDeviceId: uuid() })  // one PersistListening write

 sync
-  if syncing return; syncing = true
-  if unsynced < 30_000 return
-  res = PUT(getDeviceId(), deviceTotal)
-  dispatch(applySyncedTotal { syncedThroughMs: deviceTotal, ... })
-  on 401: sign out
+  push = dispatch(beginListeningSync { reason }).find(pushListening) ?? return
+  PUT(push.deviceId, push.deviceTotalMs)
+  dispatch(listeningSyncSucceeded | listeningSyncFailed { unauthorized })
+  on clearSession effect: sign out
  • The core now owns device_id, inside the listening blob that already round-trips. On restore, a shell passes its old stored id as fallbackDeviceId, so existing server slots carry over. The core only adopts that id if the blob has none.
  • A reset while a PUT is in flight marks that PUT as superseded. Its ack is then dropped, and it can't settle a newer sync.
  • Android persist writes now run in dispatch order, so a tick's write can't land after the reset write and undo it. On Windows, writes are now temp-file + rename and are logged when they fail.
  • Android publishes only playback effects on its effects StateFlow. Sync and persist effects reach their callers directly. Otherwise the per-snapshot BeginListeningSync could replace a pending StartPlayback before PlaybackController applied it.
  • Flush and Refresh are not new behaviour. They name triggers the shells already had: backgrounding and sign-in.

Evidence

  • Before: on main, crates/cascade-core/tests/listening_sync.rs doesn't compile because the protocol doesn't exist. Each shell had its own untested copy of the threshold, the re-entrancy guard, syncedThroughMs and device-id rotation. The Android CI job failed in setup-android on main (run 36332937323) before compiling anything.
    After: cargo test --workspace passes, with 39 core unit tests, 18 listening-sync tests and 10 property tests. cargo clippy --workspace --all-targets is clean. All three shell CI builds pass on this branch: Android, Apple and Windows. That includes the first compile of the Kotlin, Swift and C# ports.

    synced_through_is_exactly_what_was_sent
      begin(threshold) -> push(device-a, 40_000)
      tick 2_000 while in flight
      succeeded(server 1_000_000) -> unsynced == 2_000   ✓
    reset_rotates_the_id_and_zeroes_the_slot_in_one_persisted_write
      reset(device-b) -> exactly 1 PersistListening { deviceId: device-b, deviceTotalMs: 0 }
      restart from that blob -> push(device-b, 0)          ✓
    a_new_sync_waits_for_the_old_slots_put_to_settle_after_a_reset  ✓
    unauthorized_clears_the_session_and_keeps_local_listening        ✓
    proptest synced_mark_never_exceeds_device_total (ticks/syncs/acks/failures/resets in any order)  ✓
    
  • Web: tsc wasn't run this round, because the machine has no local TypeScript install. The last web change is one status string.

  • None of the shells has its own tests. The Android effect-stream fix is checked only by the compile.

Merge Danger

Door: two-way, mostly.

The listening blob gains a deviceId field. Older builds ignore unknown fields, so they still read it. Shells now only read the old device-id key and no longer update it. That means rolling back after a user has deleted their data would bring back the pre-delete id. The pushed total would be the zeroed one, so this can't resurrect deleted time.

Blast Radius: sync

Listening sync on all four shells, and sign-out on a 401. On Android, playback effect delivery is also affected. Timers and settings are not. A shell that fails to settle a PUT would stop syncing until restart, since the core allows only one PUT in flight. All four shells settle on every path, including exceptions and cancellation.

Unaddressed findings

Standards

  • Data Clumps (begin_sync -> Option<(String, u64)>): it's internal to the ledger, and the wire type PushListening already names the pair.
  • Middle Man (the shell computes 401, then the core emits ClearSession): kept on purpose. The issue asks for "one definition of … the 401 rule" in the core.
  • Repeated Switches (the Windows SyncReasonConverter): it follows the existing TimerKindConverter pattern. On net8, the attribute form of JsonStringEnumConverter can't take a camelCase policy.
  • Divergent Change (ListeningLedger holds the in-flight state): kept together on purpose. A reset has to supersede the in-flight PUT atomically with the slot change.
  • Speculative Generality (the server still echoes syncedThroughMs): removing it is a server API change outside this issue. The comment now says nothing reads it.
  • Duplicated Code (the two resetListeningData(uuid) calls per shell): each is one line, and extracting them wouldn't be clearer.
  • Duplicated Code (the settle-and-sign-out tail in all four shells): ADR-0001 expects four thin adapters. The only drift was in the status text, and that is now aligned.
  • Mysterious Name (Windows Send vs Dispatch): Send already existed on main and is called by the views. Renaming it is churn outside this issue.
  • Speculative Generality (InFlight re-exported from the crate root): it is the type of the public ListeningLedger::in_flight field, and sibling types are re-exported the same way.
  • Idiom drifts:
    • Swift keeps the last pushListening and the others keep the first. The core emits at most one, so the result is the same.
    • Swift uses an inline clearSession match rather than a helper. It's used once.
    • Kotlin catches Throwable on purpose, so that even an Error settles the in-flight sync.
    • The legacy-key field names differ between shells. They're read-only now, so renaming them adds nothing.

Spec

  • Legacy device-id key never cleared: only reachable when the listening blob can't be read. Restore then starts at 0, so re-adopting the old id can't resurrect a deleted total, and the server merges with GREATEST. Clearing the key has its own failure mode: if the adopt-write fails, the device loses its slot and double-counts.
  • Windows write failure still best-effort: writes are now atomic and logged. Showing a failed reset write in the UI would need new plumbing, and a torn write, the likely case, can no longer happen.
  • Scope: Flush/Refresh/ClearSession, dispatch returning effects: this is what the shells already did, and it's the minimum needed to read the core's answer synchronously.
  • Apple checks the threshold only on ticks: sync dispatches and then calls apply(), so checking from apply() would recurse. Only ticks add unsynced time. A failed sync retries on the next tick, on flush (backgrounding) or on refresh (sign-in).
  • Delete can race an old-slot PUT that is still in flight: this is on main too. Closing it means making the delete wait for the in-flight sync, which is a separate change to how delete works.
  • Scope creep: the CI setup-android fix: kept, as a separate commit. Without it, Android CI can't run at all, and this branch is the first compile of the Kotlin port.
  • No shell tests (open question 5 in the issue): left open, as the issue does. The policy moved into the core so that it could be tested there.

Closes #18

🤖 Generated with Claude Code

JacobStephens2 and others added 5 commits September 27, 2026 14:05
2026-09-27T14:05:34Z, host tracewake. Uncommitted work at the time of failure is included in this commit.
The core now owns the sync threshold, the payload, the synced high-water
mark, the 401 rule and the device id. BeginListeningSync answers with a
PushListening effect carrying exactly what to send; ListeningSyncSucceeded
marks exactly that as synced. ResetListeningData takes the new device id so
rotation and zeroing land in one persisted write.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each shell keeps its HTTP client and lifecycle triggers, and now asks the
core whether to sync (BeginListeningSync), PUTs exactly the PushListening it
gets back, and settles it. The threshold, the re-entrancy guard, the 401
rule and device-id storage/rotation are gone from the shells. Legacy stored
device ids are passed once as the restore fallback so existing server slots
carry over. ADR-0001 decisions 5 and 6 are amended to match.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Core: a reset marks an in-flight PUT as superseded instead of forgetting
  it, so its ack can't settle a newer sync for the rotated slot.
- Android: persist writes run one at a time in dispatch order, so a tick's
  write can't land after (and undo) the reset write.
- Windows: write via temp file + rename, and log failures.
- ADR wording fixes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-09-27T16:25:12Z, host tracewake. Uncommitted work at the time of failure is included in this commit.
JacobStephens2 and others added 2 commits September 28, 2026 14:56
The per-snapshot BeginListeningSync dispatch could replace a pending
StartPlayback in the conflating effects StateFlow before
PlaybackController applied it. Publish only handler-bound effects.

Also: name InFlight::Sent's field, align the web sign-out copy with the
other shells, and group the listening-sync tests under their headers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@JacobStephens2
JacobStephens2 marked this pull request as ready for review September 28, 2026 15:12
@JacobStephens2
JacobStephens2 merged commit 1127f2a into main Sep 28, 2026
3 checks passed
@JacobStephens2
JacobStephens2 deleted the issue-18 branch September 28, 2026 15:12
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.

Deepen listening-sync policy into the core (and let it own device_id)

1 participant