capsule_sdk/staged.rs
1//! The client-side **staged upload scheduler** (SSoT:
2//! [Download & Sync — Upload Tiering (Staged Uploads)]).
3//!
4//! Uploads used to be all-or-nothing; staged uploads add the upload-direction
5//! ladder for low-data situations. The policy is **client-side session ordering
6//! only** — the server has zero mode branches (the canonical [`UploadPolicy`] /
7//! [`UploadTier`] contract lives in `capsule_library::import::upload`). This module is
8//! that ordering's network half:
9//!
10//! - **Ladder ordering + gating.** [`StagedScheduler::plan_sessions`] returns the
11//! blobs to open sessions for *now*, in strict ladder order (T0 index → T1 preview
12//! → T2 original). Under [`UploadPolicy::Full`] every session opens eagerly; under
13//! [`UploadPolicy::Staged`] a tier opens only when the detected
14//! [`ConnectionClass`] permits it ([`ConnectionClass::permits_tier`]) — T0 escapes
15//! on any usable link, T1/T2 wait for a non-metered link (or an explicit
16//! force-sync). Because the tier gate is monotone, the permitted set is always a
17//! ladder *prefix*: T2 never opens before T1, which never opens before T0.
18//! - **Resume from server truth.** Resume needs no durable client state:
19//! [`remaining_tiers`] re-derives the outstanding work from what the server holds
20//! ([`held_from_feed`] reads the held blob roles + `original_held` off a sync feed
21//! entry). Kill the client mid-ladder and the queue rebuilds from the feed; only
22//! missing tiers are re-uploaded, and any tier with an in-flight session resumes
23//! through the [`UploadClient`]'s own create-dedup / `HEAD` offset rather than
24//! restarting.
25//! - **`awaiting-original`.** T2 is exactly what staged defers, so a staged asset is
26//! in the derived [`awaiting-original`](crate::sync::OriginalAvailability) state on
27//! other devices until its original lands (`original_held` flips). The badge and
28//! the transient `error.blob.pending_upload` fetch state are the sync/fetch halves
29//! ([`crate::sync`], [`crate::fetch`]); this scheduler is what makes T2 land last.
30//!
31//! Verify-before-destroy is untouched: a staged asset pins its local original until
32//! T2 is durable, by the same [`ReleaseGate`](capsule_library::library::ReleaseGate)
33//! that always governed release. Staged and streaming import are mutually exclusive
34//! per import — enforced in `capsule_library::import` (planner confirmation + the
35//! streaming executor), so it can never reach this scheduler.
36//!
37//! [Download & Sync — Upload Tiering (Staged Uploads)]: https://docs/design/transfer/upload/#upload-tiering-staged-uploads
38
39use std::collections::HashSet;
40
41use capsule_library::import::{UploadPolicy, UploadTier};
42use tracing::instrument;
43
44use crate::net::ConnectionClass;
45use crate::net::path::{Hold, PathMonitor, TierAdmission, TransferPlan};
46use crate::sync::FeedEntry;
47use crate::upload::{CreateUploadRequest, UploadClient, UploadError, UploadOutcome};
48
49// ─── Bundle shape ─────────────────────────────────────────────────────────────
50
51/// One upload unit within an asset bundle: a single blob, tagged with the
52/// [`UploadTier`] it belongs to and its ciphertext content address.
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct TierBlob {
55 /// Which tier of the ladder this blob belongs to.
56 pub tier: UploadTier,
57 /// The blob's ciphertext content address (lowercase hex) — the resume key.
58 pub hash: String,
59 /// Ciphertext size in bytes.
60 pub size: u64,
61}
62
63impl TierBlob {
64 /// A tier blob from its tier, content address, and size.
65 #[must_use]
66 pub fn new(tier: UploadTier, hash: impl Into<String>, size: u64) -> Self {
67 Self {
68 tier,
69 hash: hash.into(),
70 size,
71 }
72 }
73}
74
75/// An asset's staged upload bundle: its id and the blobs to upload. The blobs may
76/// be supplied in any order — the scheduler sorts them into ladder order.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct StagedAsset {
79 /// The asset id (UUIDv7, as a string).
80 pub asset_id: String,
81 /// The bundle's blobs, in any order.
82 pub blobs: Vec<TierBlob>,
83}
84
85impl StagedAsset {
86 /// A bundle for `asset_id` over `blobs`.
87 #[must_use]
88 pub fn new(asset_id: impl Into<String>, blobs: Vec<TierBlob>) -> Self {
89 Self {
90 asset_id: asset_id.into(),
91 blobs,
92 }
93 }
94
95 /// The bundle's blobs in strict ladder order (T0 → T1 → T2), stable within a
96 /// tier so a caller's intra-tier order (e.g. manifest before metadata) is kept.
97 #[must_use]
98 pub fn ladder_ordered(&self) -> Vec<TierBlob> {
99 let mut blobs = self.blobs.clone();
100 blobs.sort_by_key(|b| b.tier); // stable: preserves within-tier order
101 blobs
102 }
103}
104
105// ─── Server truth (resume) ────────────────────────────────────────────────────
106
107/// The set of blob content addresses the server **durably holds** for an asset,
108/// read from a sync feed entry — the server truth a resume re-derives from.
109///
110/// A derivative/metadata blob ref present on the entry is held (its tier finalized;
111/// the entry's very existence means T0 index finalized), and so is every derivative
112/// manifest the entry inlines, by the digest of its bytes. The original is included
113/// **iff** `original_held` — the `awaiting-original` fact — so T2 is treated as
114/// outstanding until the feed flips it, never as a dangling reference.
115#[must_use]
116pub fn held_from_feed(entry: &FeedEntry) -> HashSet<String> {
117 let mut held = HashSet::new();
118 for derivative in &entry.blobs.derivatives {
119 held.insert(derivative.ciphertext_hash.clone());
120 }
121 // A derivative manifest rides the entry as its bytes rather than as an address, and its
122 // address is the digest of those bytes — the same derivation the push uses to name it.
123 for manifest in &entry.derivative_manifests {
124 held.insert(capsule_core::crypto::hash::hash_bytes(manifest).to_hex());
125 }
126 if entry.original_held
127 && let Some(original) = &entry.blobs.original
128 {
129 held.insert(original.ciphertext_hash.clone());
130 }
131 held
132}
133
134/// Re-derive the outstanding staged work from server truth: keep only the blobs the
135/// server does **not** already hold, in ladder order.
136///
137/// This is the whole resume story (transfer upload doc: "Resume needs no new client
138/// state"). No durable local queue is trusted — `library.sqlite`'s work queue is a
139/// rebuildable cache. Kill the client mid-ladder, pull the feed, pass `held` from
140/// [`held_from_feed`], and this rebuilds exactly the missing tiers. A tier whose
141/// blob is already held is skipped; a tier still in flight is re-driven and resumes
142/// through the [`UploadClient`]'s create-dedup / `HEAD` offset (no bytes re-sent).
143#[must_use]
144pub fn remaining_tiers<H: std::hash::BuildHasher>(
145 asset: &StagedAsset,
146 held: &HashSet<String, H>,
147) -> StagedAsset {
148 StagedAsset {
149 asset_id: asset.asset_id.clone(),
150 blobs: asset
151 .ladder_ordered()
152 .into_iter()
153 .filter(|blob| !held.contains(&blob.hash))
154 .collect(),
155 }
156}
157
158// ─── The scheduler ────────────────────────────────────────────────────────────
159
160/// The staged upload scheduler: given a [`UploadPolicy`], the tiers the path admits, and an
161/// optional force-sync consent, it decides which of an asset's tier sessions open now and in
162/// what order.
163#[derive(Debug, Clone, Copy)]
164pub struct StagedScheduler {
165 policy: UploadPolicy,
166 class: ConnectionClass,
167 admission: TierAdmission,
168 hold: Option<Hold>,
169 force_sync: bool,
170}
171
172impl StagedScheduler {
173 /// A scheduler for `policy` on the detected connection `class` alone, without
174 /// force-sync (the metered/Wi-Fi criteria apply). A caller holding a whole
175 /// [`TransferPlan`] uses [`from_plan`](Self::from_plan), which also honours power, heat
176 /// and the background deadline.
177 #[must_use]
178 pub fn new(policy: UploadPolicy, class: ConnectionClass) -> Self {
179 let (admission, hold) = TierAdmission::for_class(class);
180 Self {
181 policy,
182 class,
183 admission,
184 hold,
185 force_sync: false,
186 }
187 }
188
189 /// A scheduler for the policy the user `requested`, under `plan`: a plan that holds bulk
190 /// back stages the run ([`TransferPlan::upload_policy`]), and every tier is gated on what
191 /// the plan admits.
192 #[must_use]
193 pub fn from_plan(plan: &TransferPlan, requested: UploadPolicy) -> Self {
194 Self {
195 policy: plan.upload_policy(requested),
196 class: plan.class,
197 admission: plan.admission,
198 hold: plan.hold,
199 force_sync: false,
200 }
201 }
202
203 /// Whether `next` closes a tier this scheduler opens: the work running under this one
204 /// includes work `next` forbids.
205 #[must_use]
206 pub fn narrows_to(&self, next: &Self) -> bool {
207 [UploadTier::Index, UploadTier::Preview, UploadTier::Original]
208 .into_iter()
209 .any(|tier| self.tier_opens_now(tier) && !next.tier_opens_now(tier))
210 }
211
212 /// Set the user-consented **force-sync** flag (the two-week-staleness "sync
213 /// now"): it overrides the metered/Wi-Fi criteria for above-index tiers, but
214 /// never resurrects an offline path.
215 #[must_use]
216 pub fn with_force_sync(mut self, force_sync: bool) -> Self {
217 self.force_sync = force_sync;
218 self
219 }
220
221 /// Whether a given tier's session opens right now under this scheduler.
222 ///
223 /// `Full` opens every tier eagerly; `Staged` defers to the tier gate: the class's
224 /// ([`ConnectionClass::permits_tier`]), or the plan's ([`TransferPlan::permits_tier`]).
225 #[must_use]
226 pub fn tier_opens_now(&self, tier: UploadTier) -> bool {
227 match self.policy {
228 UploadPolicy::Full => true,
229 UploadPolicy::Staged => self.admission.permits(self.hold, tier, self.force_sync),
230 }
231 }
232
233 /// The blobs to open sessions for **now**, in strict ladder order.
234 ///
235 /// Under [`UploadPolicy::Full`] this is the whole bundle (still ladder-ordered
236 /// for a deterministic session sequence). Under [`UploadPolicy::Staged`] it is
237 /// the ladder *prefix* the connection currently permits — T0 alone on a metered
238 /// link, the whole bundle on unmetered Wi-Fi (or under force-sync). The deferred
239 /// tiers carry no client state: the next window re-derives them from server
240 /// truth ([`remaining_tiers`]).
241 #[must_use]
242 pub fn plan_sessions(&self, asset: &StagedAsset) -> Vec<TierBlob> {
243 asset
244 .ladder_ordered()
245 .into_iter()
246 .filter(|blob| self.tier_opens_now(blob.tier))
247 .collect()
248 }
249
250 /// Drive each asset's planned tier sessions through `sink`, per asset, in ladder
251 /// order — the session sequence a mock records to prove the ladder. Assets are
252 /// processed in the order given; within an asset, strictly T0 → T1 → T2.
253 #[instrument(skip_all, fields(policy = ?self.policy, class = ?self.class, assets = assets.len()))]
254 pub async fn run<S: TierSink>(
255 &self,
256 assets: &[StagedAsset],
257 sink: &S,
258 ) -> Result<StagedReport, StagedError> {
259 let mut report = StagedReport::default();
260 for asset in assets {
261 for blob in self.plan_sessions(asset) {
262 tracing::debug!(asset = %asset.asset_id, tier = ?blob.tier, hash = %blob.hash, "opening staged tier session");
263 let outcome = sink.open_session(&asset.asset_id, &blob).await?;
264 report.opened.push(OpenedTier {
265 asset_id: asset.asset_id.clone(),
266 tier: blob.tier,
267 hash: blob.hash.clone(),
268 outcome,
269 });
270 }
271 }
272 tracing::info!(
273 opened = report.opened.len(),
274 "staged upload window complete"
275 );
276 Ok(report)
277 }
278}
279
280// ─── Running under a changing path ────────────────────────────────────────────
281
282/// Run `attempt` under the scheduler `monitor`'s current plan allows, and re-plan when the
283/// path changes under it.
284///
285/// `attempt` is handed a [`StagedScheduler`] for `requested` (with `force_sync`) and drives the
286/// work under it — normally one [`push_bundle`](crate::push::push_bundle). Every change of plan
287/// the monitor publishes wakes this run in the same scheduling tick: when the new plan closes a
288/// tier the running scheduler opens, the running attempt is dropped there — cancelling its
289/// in-flight requests — and `attempt` runs again under the new plan. A change that closes
290/// nothing lets the attempt run on. Cancelled work resumes from server truth (create-dedup and
291/// `HEAD` offsets), so a cancel costs at most the bytes in flight.
292///
293/// Each re-run follows a plan that narrowed, so the loop moves only as fast as the path
294/// changes; it never spins on its own.
295#[instrument(skip_all, fields(?requested, force_sync))]
296pub async fn run_under_path<T, F, Fut>(
297 monitor: &PathMonitor,
298 requested: UploadPolicy,
299 force_sync: bool,
300 mut attempt: F,
301) -> T
302where
303 F: FnMut(StagedScheduler) -> Fut,
304 Fut: std::future::Future<Output = T>,
305{
306 let mut plans = monitor.subscribe();
307 loop {
308 let plan = *plans.borrow_and_update();
309 let scheduler = StagedScheduler::from_plan(&plan, requested).with_force_sync(force_sync);
310 tracing::debug!(
311 generation = plan.generation.0,
312 class = ?plan.class,
313 admission = ?plan.admission,
314 "staged: running under the current path"
315 );
316 let mut run = std::pin::pin!(attempt(scheduler));
317 let narrowed = loop {
318 let changed = {
319 let mut changed = std::pin::pin!(plans.changed());
320 let step = std::future::poll_fn(|cx| {
321 if let std::task::Poll::Ready(out) = run.as_mut().poll(cx) {
322 return std::task::Poll::Ready(Ok(out));
323 }
324 changed.as_mut().poll(cx).map(Err)
325 })
326 .await;
327 match step {
328 Ok(out) => return out,
329 Err(changed) => changed,
330 }
331 };
332 if changed.is_err() {
333 // The monitor is borrowed for this whole call, so its sender cannot be gone;
334 // were it, no plan could change again and the attempt simply runs out.
335 return run.await;
336 }
337 let next = *plans.borrow_and_update();
338 let next_scheduler =
339 StagedScheduler::from_plan(&next, requested).with_force_sync(force_sync);
340 if scheduler.narrows_to(&next_scheduler) {
341 break next;
342 }
343 tracing::debug!(
344 generation = next.generation.0,
345 "staged: the plan changed without closing a running tier; running on"
346 );
347 };
348 tracing::info!(
349 from_generation = plan.generation.0,
350 to_generation = narrowed.generation.0,
351 class = ?narrowed.class,
352 admission = ?narrowed.admission,
353 hold = ?narrowed.hold,
354 "staged: the path now forbids running work; cancelling it and re-planning"
355 );
356 }
357}
358
359// ─── Sink seam ────────────────────────────────────────────────────────────────
360
361/// How one opened tier session resolved.
362#[derive(Debug, Clone, PartialEq, Eq)]
363pub enum TierSessionOutcome {
364 /// The tier's blob transferred; the server has begun finalization.
365 Uploaded {
366 /// The session that was driven to completion.
367 session_id: String,
368 },
369 /// The server already held the blob (dedup/merge) — nothing to transfer.
370 AlreadyStored {
371 /// The existing asset the reference merges onto.
372 asset_ref: String,
373 },
374}
375
376/// Errors a staged run can fail with.
377#[derive(Debug, thiserror::Error)]
378pub enum StagedError {
379 /// A tier's underlying upload failed non-recoverably (surfaced from the
380 /// [`UploadClient`]).
381 #[error("staged tier upload failed: {0}")]
382 Upload(#[from] UploadError),
383}
384
385/// The network seam the scheduler drives to open one tier's upload session. Kept a
386/// trait so the ordering + gating are exercised by a deterministic recording mock;
387/// [`UploadClientTierSink`] is the production impl over the hand-written upload
388/// client.
389pub trait TierSink {
390 /// Open (and drive to completion) the upload session for `blob` of `asset_id`.
391 fn open_session(
392 &self,
393 asset_id: &str,
394 blob: &TierBlob,
395 ) -> impl std::future::Future<Output = Result<TierSessionOutcome, StagedError>> + Send;
396}
397
398/// Builds the per-blob upload request + ciphertext the scheduler hands to the
399/// upload client. The **app** implements this — it holds the sealed bytes and the
400/// signed manifest envelope; the scheduler owns only the tier ordering and gating,
401/// so the two policies stay on one code path.
402pub trait TierRequestBuilder {
403 /// The `POST /upload` request and ciphertext bytes for one tier blob.
404 fn build(&self, asset_id: &str, blob: &TierBlob) -> (CreateUploadRequest, Vec<u8>);
405}
406
407/// The production [`TierSink`]: opens each planned tier session through the
408/// hand-written, resumable [`UploadClient`], so staged session ordering rides the
409/// real upload protocol. In-flight tiers resume through the client's create-dedup /
410/// `HEAD` offset — the reason resume needs no extra scheduler state.
411pub struct UploadClientTierSink<'a, R: TierRequestBuilder> {
412 client: &'a UploadClient,
413 builder: R,
414}
415
416impl<'a, R: TierRequestBuilder> UploadClientTierSink<'a, R> {
417 /// A sink over `client`, building each tier's request with `builder`.
418 pub fn new(client: &'a UploadClient, builder: R) -> Self {
419 Self { client, builder }
420 }
421}
422
423impl<R: TierRequestBuilder + Sync> TierSink for UploadClientTierSink<'_, R> {
424 async fn open_session(
425 &self,
426 asset_id: &str,
427 blob: &TierBlob,
428 ) -> Result<TierSessionOutcome, StagedError> {
429 let (request, bytes) = self.builder.build(asset_id, blob);
430 match self.client.upload(&request, &bytes).await? {
431 UploadOutcome::Completed { session_id } => {
432 Ok(TierSessionOutcome::Uploaded { session_id })
433 }
434 UploadOutcome::AlreadyStored { asset_ref } => {
435 Ok(TierSessionOutcome::AlreadyStored { asset_ref })
436 }
437 }
438 }
439}
440
441// ─── Report ───────────────────────────────────────────────────────────────────
442
443/// One opened tier session, in observed order.
444#[derive(Debug, Clone, PartialEq, Eq)]
445pub struct OpenedTier {
446 /// The asset the session was opened for.
447 pub asset_id: String,
448 /// Which tier opened.
449 pub tier: UploadTier,
450 /// The blob's content address.
451 pub hash: String,
452 /// How it resolved.
453 pub outcome: TierSessionOutcome,
454}
455
456/// The outcome of one staged run: the tier sessions opened, in observed order.
457#[derive(Debug, Default, Clone, PartialEq, Eq)]
458pub struct StagedReport {
459 /// The opened tier sessions, in the exact order the scheduler drove them.
460 pub opened: Vec<OpenedTier>,
461}
462
463impl StagedReport {
464 /// The observed tier sequence — the ladder-order proof (`[Index, Preview, …]`).
465 #[must_use]
466 pub fn tier_sequence(&self) -> Vec<UploadTier> {
467 self.opened.iter().map(|o| o.tier).collect()
468 }
469}
470
471#[cfg(test)]
472mod tests;