Skip to main content

lean_ctx_cloud/
receipts.rs

1// SPDX-License-Identifier: Apache-2.0
2//! `POST /v1/receipts` (receipts v2, C0 2.5 K2 M3): the Engine receipts of
3//! this machine's Cloud vaults.
4//!
5//! The tool path only notes a receipt: [`note_engine_receipt`] checks one
6//! marker file and, when uploads are on, turns the local v1 receipt into a
7//! closed `leanctx.instance-receipt/v2` document and queues it in the durable
8//! outbox. No lease, network or config work happens in a tool call. The
9//! scheduler keeps the marker in step with what allows receipts — the
10//! release switch, `[cloud] receipts_upload`, the lease's `receipts.upload`
11//! right (Enterprise), the workspace's `org_settings.receipts_upload` and no
12//! `upload_disabled` answer under the current lease — and sends the queue
13//! in signed batches (`leanctx.cloud.receipts/v2`, instance key).
14//!
15//! What leaves the engine (aggregates and opaque values only):
16//! - input and output digests as HMAC-SHA256 under an engine-local key
17//!   (`receipts.hmac-key`, created here, never uploaded): Cloud cannot test
18//!   a guess against them, the engine can re-derive them from its receipt;
19//! - the invocation and receipt ids as HMAC-derived hex, never the local id;
20//! - source references as a count; failure recovery references dropped;
21//! - the session the app names (`LEAN_CTX_SESSION_ID`, V9) only as an
22//!   HMAC under the same key (`session_ref`), never the id; absent outside
23//!   a session and while the enrolled Cloud does not announce `session_ref`
24//!   (`crate::session_ref`);
25//! - measurements with a contract name and unit only;
26//! - no policy reference: the Cloud policy digest is not bound to a local
27//!   invocation, so `policy_digest` is `null`.
28//!
29//! The checkout path stays on this machine: it only selects the Cloud
30//! vault, and a receipt of a checkout Cloud does not know is dropped.
31
32use std::path::Path;
33
34use ed25519_dalek::Signer as _;
35use lean_ctx_time::UtcDateTime;
36use serde_json::{Value, json};
37use sha2::Sha256;
38
39use super::auth::Session;
40use super::config::CloudConfig;
41use super::instance_key::InstanceKeys;
42use super::metrics_v2::gate::Sharing;
43use super::outbox::{CHANNEL_RECEIPTS, Outbox, OutboxItem};
44use super::state::{InstanceRecord, write_private};
45use super::vault::VaultMap;
46use super::{CloudError, CloudStore};
47use lean_ctx_protocol::cloud::CloudUploadKind;
48use lean_ctx_protocol::cloud::lease::{CloudLeaseV1, CloudRight};
49use lean_ctx_protocol::cloud::metrics_v2::{KeyId, SignatureHex, TimeStamp, VaultId};
50use lean_ctx_protocol::cloud::receipts_v2::{
51    AdmissionDecision, CapabilityIdConst, Classification, EngineIdConst, EngineReceiptSchema,
52    EngineReceiptV2, FailureCode, FailureV2, HMAC_PREFIX, InvocationIdV2, MAX_MEASUREMENTS,
53    MAX_RECEIPTS_BODY_BYTES, MAX_RECEIPTS_V2, MAX_SOURCE_COUNT, MeasurementName, MeasurementUnit,
54    MeasurementV2, ObservationStatus, PolicyAdmissionV2, RECEIPTS_ROUTE, ReceiptEngineV2,
55    ReceiptHmac, ReceiptIdV2, ReceiptInvocationV2, ReceiptItemV2, ReceiptObservationV2,
56    ReceiptOperationV2, ReceiptSemver, ReceiptsAckV2, ReceiptsBodyV2, ReceiptsRequestV2,
57    ReceiptsSchema, SchemaVersionOne,
58};
59use lean_ctx_protocol::{
60    EngineFailureCodeV1, EngineInvocationV1, EngineObservationStatusV1, EngineObservationV1,
61    EnginePolicyDecisionV1, EngineValueClassificationV1,
62};
63
64const ENABLED_FILE: &str = "receipts.enabled";
65const DISABLED_FILE: &str = "receipts.disabled-lease";
66/// The engine-local receipt HMAC key (32 random bytes, hex). Never uploaded.
67// Only the unix permission check in the tests reads it.
68#[cfg(all(test, unix))]
69const KEY_FILE: &str = "receipts.hmac-key";
70
71/// The engine-local key that makes input/output values opaque to Cloud. The
72/// same key keys the digests of audit entries v2.
73#[derive(Clone)]
74pub(crate) struct ReceiptKey([u8; 32]);
75
76impl ReceiptKey {
77    /// The key in `cloud_data`, created on first use.
78    pub(crate) fn load_or_create(cloud_data: &Path) -> Option<Self> {
79        lean_ctx::core::audit_trail::load_or_create_hmac_key(cloud_data).map(Self)
80    }
81
82    #[cfg(test)]
83    pub(crate) fn from_bytes(bytes: [u8; 32]) -> Self {
84        Self(bytes)
85    }
86
87    /// HMAC-SHA256(key, `label` ‖ `\n` ‖ `data`), lowercase hex.
88    pub(crate) fn mac_hex(&self, label: &str, data: &str) -> String {
89        lean_ctx::core::audit_trail::hmac_hex(&self.0, label, data.as_bytes())
90    }
91
92    fn hmac(&self, label: &str, data: &str) -> Option<ReceiptHmac> {
93        ReceiptHmac::new(&format!("{HMAC_PREFIX}{}", self.mac_hex(label, data)))
94    }
95}
96
97fn unit_of(unit: &str) -> Option<MeasurementUnit> {
98    // The local receipt says `token`; the contract `tokens`.
99    MeasurementUnit::of(if unit == "token" { "tokens" } else { unit })
100}
101
102fn count(n: usize, floor: u16) -> u16 {
103    u16::try_from(n)
104        .unwrap_or(MAX_SOURCE_COUNT)
105        .clamp(floor, MAX_SOURCE_COUNT)
106}
107
108/// The v2 receipt id and document of a local receipt, or `None` when it
109/// cannot be expressed in the closed contract (it is then not sent).
110/// `session` is the local session id (V9): it leaves only as its HMAC.
111pub(crate) fn to_v2(
112    key: &ReceiptKey,
113    receipt_id: &str,
114    invocation: &EngineInvocationV1,
115    observation: &EngineObservationV1,
116    session: Option<&str>,
117) -> Option<(ReceiptIdV2, EngineReceiptV2)> {
118    let rcpt = ReceiptIdV2::new(&format!(
119        "rcpt_{}",
120        &key.mac_hex("receipt", receipt_id)[..32]
121    ))?;
122    let invocation_id =
123        InvocationIdV2::new(&key.mac_hex("invocation", invocation.invocation_id.as_str())[..32])?;
124    let measurements = observation
125        .measurements
126        .iter()
127        .filter_map(|m| {
128            Some(MeasurementV2 {
129                name: MeasurementName::new(&m.name)?,
130                unit: unit_of(&m.unit)?,
131                classification: match m.classification {
132                    EngineValueClassificationV1::Measured => Classification::Measured,
133                    EngineValueClassificationV1::Estimated => Classification::Estimated,
134                    EngineValueClassificationV1::Unavailable => Classification::Unavailable,
135                },
136                value: m.value,
137            })
138        })
139        .take(MAX_MEASUREMENTS)
140        .collect();
141    let document = EngineReceiptV2 {
142        schema: EngineReceiptSchema,
143        invocation: ReceiptInvocationV2 {
144            schema_version: SchemaVersionOne,
145            invocation_id: invocation_id.clone(),
146            instance: ReceiptEngineV2 {
147                instance_id: EngineIdConst,
148                instance_version: ReceiptSemver::new(invocation.engine.engine_version.as_str())?,
149            },
150            operation: ReceiptOperationV2 {
151                capability_id: (invocation.operation.capability_id.as_str()
152                    == lean_ctx_protocol::cloud::receipts_v2::RECEIPT_CAPABILITY_ID)
153                    .then_some(CapabilityIdConst)?,
154                capability_version: ReceiptSemver::new(
155                    invocation.operation.capability_version.as_str(),
156                )?,
157            },
158            input_hmac: key.hmac("input", invocation.input_digest.as_str())?,
159            source_count: count(invocation.source_refs.len(), 1),
160            session_ref: match session {
161                Some(id) => Some(key.hmac("session", id)?),
162                None => None,
163            },
164            policy_admission: PolicyAdmissionV2 {
165                decision: match invocation.policy_admission.decision {
166                    EnginePolicyDecisionV1::Admitted => AdmissionDecision::Admitted,
167                    EnginePolicyDecisionV1::Rejected => AdmissionDecision::Rejected,
168                },
169                policy_digest: None,
170            },
171        },
172        observation: ReceiptObservationV2 {
173            schema_version: SchemaVersionOne,
174            invocation_id,
175            status: match observation.status {
176                EngineObservationStatusV1::Succeeded => ObservationStatus::Succeeded,
177                EngineObservationStatusV1::Degraded => ObservationStatus::Degraded,
178                EngineObservationStatusV1::Rejected => ObservationStatus::Rejected,
179                EngineObservationStatusV1::Failed => ObservationStatus::Failed,
180            },
181            output_hmac: match &observation.output_digest {
182                Some(digest) => Some(key.hmac("output", digest.as_str())?),
183                None => None,
184            },
185            source_count: count(observation.source_lineage.len(), 0),
186            measurements,
187            failure: observation.failure.as_ref().map(|f| FailureV2 {
188                code: match f.code {
189                    EngineFailureCodeV1::PolicyRejected => FailureCode::PolicyRejected,
190                    EngineFailureCodeV1::SourceUnavailable => FailureCode::SourceUnavailable,
191                    EngineFailureCodeV1::SourceIntegrityMismatch => {
192                        FailureCode::SourceIntegrityMismatch
193                    }
194                    EngineFailureCodeV1::ResourceLimit => FailureCode::ResourceLimit,
195                    EngineFailureCodeV1::UnsupportedOperation => FailureCode::UnsupportedOperation,
196                    EngineFailureCodeV1::Internal => FailureCode::Internal,
197                },
198                retryable_by_host: f.retryable_by_host,
199            }),
200        },
201    };
202    document.validate().ok()?;
203    Some((rcpt, document))
204}
205
206/// Whether receipts are queued now: the last connected pass allowed them
207/// (the marker) and nothing local turned them off since. Task evidence
208/// (`crate::task_evidence`) is queued under the same gate.
209pub(crate) fn queueing(store: &CloudStore) -> bool {
210    // N1: never while disconnected or revoked, whatever a stale marker says.
211    // NEW-3: nor with the [cloud] switches off or a lapsed lease.
212    if !store.data_dir().join(ENABLED_FILE).is_file() || !store.may_record() {
213        return false;
214    }
215    let config = lean_ctx::core::config::Config::load().cloud.clone();
216    config.receipts_upload && store.recording_allowed(&config)
217}
218
219/// Queue an Engine receipt for Cloud, if receipt uploads are on. Cheap and
220/// silent: a failure here never fails the Engine call that produced it.
221pub fn note_engine_receipt(
222    root: &Path,
223    receipt_id: &str,
224    invocation: &EngineInvocationV1,
225    observation: &EngineObservationV1,
226    now: UtcDateTime,
227) {
228    let Ok(store) = CloudStore::open() else {
229        return;
230    };
231    if !queueing(&store) {
232        return;
233    }
234    let Some(key) = ReceiptKey::load_or_create(store.data_dir()) else {
235        return;
236    };
237    // V9: only a Cloud that announced `session_ref` hears the session; an
238    // older one would refuse the whole batch for good.
239    let session = crate::session_ref::announced(&store, crate::session_ref::FEATURE_SESSION_REF)
240        .then(super::policy_sessions::current_session)
241        .flatten();
242    let Some((rcpt, document)) = to_v2(
243        &key,
244        receipt_id,
245        invocation,
246        observation,
247        session.as_deref(),
248    ) else {
249        return;
250    };
251    let Ok(document) = serde_json::to_value(&document) else {
252        return;
253    };
254    // `root` stays in the local outbox: it only selects the vault.
255    let payload = json!({
256        "receipt_id": rcpt.as_str(),
257        "root": root.to_string_lossy(),
258        "created_at": now.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true),
259        "document": document,
260    });
261    let _ = Outbox::at(store.data_dir()).enqueue(CHANNEL_RECEIPTS, payload, now);
262}
263
264/// Why receipts are not sent, or `None` when everything allows them.
265pub(crate) fn blocked_by(
266    released: bool,
267    config: &CloudConfig,
268    lease: &CloudLeaseV1,
269    disabled_under_lease: Option<&str>,
270) -> Option<&'static str> {
271    if !config.receipts_upload {
272        Some("switched off on this instance ([cloud] receipts_upload = false)")
273    } else if !lease.grants(CloudRight::ReceiptsUpload) {
274        Some("the lease does not include receipts.upload (Enterprise)")
275    } else if !lease.org_allows_receipts_upload() {
276        Some("switched off by the workspace")
277    } else if disabled_under_lease == Some(lease.lease_id.as_str()) {
278        Some("switched off by the workspace (the Cloud refused the upload)")
279    } else if !released {
280        Some(NOT_RELEASED)
281    } else {
282        None
283    }
284}
285
286/// Receipts v2 follow the engine-metrics release switch (owner go).
287pub(crate) const NOT_RELEASED: &str = "receipts v2 wait for the instance telemetry release";
288
289fn released(origin: &str) -> bool {
290    super::metrics_v2::upload::released(origin)
291}
292
293fn disabled_lease(store: &CloudStore) -> Option<String> {
294    std::fs::read_to_string(store.data_dir().join(DISABLED_FILE))
295        .ok()
296        .map(|text| text.trim().to_string())
297        .filter(|text| !text.is_empty())
298}
299
300/// Owner decision (K2 review 2, N2): receipts fall under the same rule as
301/// engine metrics, "Share instance metrics" — policy off, not confirmed
302/// (Personal), no valid bundle in force or revoked: nothing is
303/// collected or sent.
304pub(crate) const SHARING_OFF: &str =
305    "off under the workspace rule \"Share instance metrics\" (see Instance metrics)";
306
307fn sharing(
308    store: &CloudStore,
309    config: &CloudConfig,
310    instance: &InstanceRecord,
311    lease: &CloudLeaseV1,
312    now: UtcDateTime,
313) -> Sharing {
314    super::metrics_v2::gate::decide(store, config, instance, lease, now)
315}
316
317/// Why receipts are not sent now, for `cloud status` (local only).
318pub fn status(
319    store: &CloudStore,
320    config: &CloudConfig,
321    instance: &InstanceRecord,
322    lease: &CloudLeaseV1,
323) -> Option<&'static str> {
324    // The receipts switches, then the shared rule, then the release.
325    blocked_by(true, config, lease, disabled_lease(store).as_deref())
326        .or_else(|| {
327            (!sharing(store, config, instance, lease, UtcDateTime::now()).is_on())
328                .then_some(SHARING_OFF)
329        })
330        .or_else(|| (!released(&instance.url)).then_some(NOT_RELEASED))
331}
332
333/// Stop everything this engine records for Cloud on this machine (K2
334/// review 2, N1): the engine-metrics buffer, state and switches (secret
335/// hits and K10/K12/K13 signals) and the receipts marker and queue. Called
336/// when the engine disconnects, is revoked, its scheduler stops or Cloud is
337/// disabled; the next connected pass turns recording on again only when
338/// every gate allows it.
339pub(crate) fn stop_local_recording(cloud_data: &Path) {
340    super::metrics_v2::buffer::forget(cloud_data);
341    super::metrics_v2::buffer::note_local_off(cloud_data);
342    stop_receipts(cloud_data);
343}
344
345/// The receipts half: the marker and every queued receipt.
346fn stop_receipts(cloud_data: &Path) {
347    let _ = std::fs::remove_file(cloud_data.join(ENABLED_FILE));
348    let outbox = Outbox::at(cloud_data);
349    for item in outbox.list(CHANNEL_RECEIPTS) {
350        let _ = outbox.remove(&item);
351    }
352    super::task_evidence::clear(&outbox);
353}
354
355/// K2 review 3 (NEW-2): `config set` of an `[cloud]` off switch applies at
356/// once. `enabled = false` and `metrics_upload = false` stop everything
357/// (receipts follow the metrics rule, N2); `receipts_upload = false` stops
358/// receipts.
359pub(crate) fn apply_off_switches(config: &CloudConfig) {
360    let Ok(store) = CloudStore::open() else {
361        return;
362    };
363    apply_off_switches_in(store.data_dir(), config);
364}
365
366fn apply_off_switches_in(cloud_data: &Path, config: &CloudConfig) {
367    if config.enabled == Some(false) || !config.metrics_upload {
368        stop_local_recording(cloud_data);
369    } else if !config.receipts_upload {
370        stop_receipts(cloud_data);
371    }
372}
373
374/// Turn queueing on or off to match what allows receipts now; when off,
375/// whatever is queued is dropped (it would never be sent).
376fn set_enabled(store: &CloudStore, outbox: &Outbox, on: bool) -> Result<(), CloudError> {
377    let marker = store.data_dir().join(ENABLED_FILE);
378    if on {
379        if !marker.is_file() {
380            write_private(store.data_dir(), ENABLED_FILE, b"1")?;
381        }
382    } else {
383        let _ = std::fs::remove_file(&marker);
384        for item in outbox.list(CHANNEL_RECEIPTS) {
385            outbox.remove(&item)?;
386        }
387        super::task_evidence::clear(outbox);
388    }
389    Ok(())
390}
391
392/// The Cloud vault id of a checkout Cloud resolved on this machine.
393fn vault_of(map: &VaultMap, root: &str) -> Option<VaultId> {
394    map.vaults
395        .values()
396        .find(|record| record.roots.iter().any(|known| known == root))
397        .and_then(|record| VaultId::new(&record.vault_id))
398}
399
400/// The due receipts of the outbox that can be sent with `map`, and how many
401/// were dropped because they cannot (no vault in `map`, not `allowed`).
402/// Without a map (it belongs to another Cloud or account) nothing is ready
403/// and nothing is dropped.
404fn ready_items(
405    outbox: &Outbox,
406    map: Option<&VaultMap>,
407    now: UtcDateTime,
408    allowed: impl Fn(&ReceiptItemV2) -> bool,
409) -> Result<(Vec<(ReceiptItemV2, OutboxItem)>, u64), CloudError> {
410    let (mut ready, mut dropped) = (Vec::new(), 0u64);
411    let Some(map) = map else {
412        return Ok((ready, dropped));
413    };
414    for item in outbox
415        .list(CHANNEL_RECEIPTS)
416        .into_iter()
417        .filter(|item| item.due(now))
418    {
419        if let Some(wire) = wire_item(map, &item).filter(&allowed) {
420            ready.push((wire, item));
421        } else {
422            outbox.remove(&item)?;
423            dropped += 1;
424        }
425    }
426    Ok((ready, dropped))
427}
428
429/// The wire item of a queued receipt, or `None` when it cannot be sent (a
430/// checkout Cloud does not know, or a v1 item queued by an older engine).
431fn wire_item(map: &VaultMap, item: &OutboxItem) -> Option<ReceiptItemV2> {
432    let payload = &item.payload;
433    let document: EngineReceiptV2 = serde_json::from_value(payload["document"].clone()).ok()?;
434    ReceiptItemV2::new(
435        ReceiptIdV2::new(payload["receipt_id"].as_str()?)?,
436        vault_of(map, payload["root"].as_str()?)?,
437        TimeStamp::new(payload["created_at"].as_str()?)?,
438        document,
439    )
440    .ok()
441}
442
443/// Sign a batch with the instance key (as engine metrics).
444pub(crate) fn sign(
445    keys: &InstanceKeys,
446    body: ReceiptsBodyV2,
447) -> Result<ReceiptsRequestV2, CloudError> {
448    let signer = keys.signing_key();
449    let key_id = KeyId::new(&super::workers::key_id(signer))
450        .ok_or_else(|| CloudError::Local("instance key id".into()))?;
451    let input = body
452        .signing_input(&key_id)
453        .map_err(|e| CloudError::Local(e.to_string()))?;
454    let signature = SignatureHex::new(&hex::encode(signer.sign(&input).to_bytes()))
455        .ok_or_else(|| CloudError::Local("signature".into()))?;
456    Ok(body.signed(key_id, signature))
457}
458
459/// Batches of at most 256 items and 1 MiB (signature included).
460fn batches(items: Vec<(ReceiptItemV2, OutboxItem)>) -> Vec<Vec<(ReceiptItemV2, OutboxItem)>> {
461    // `key_id` and `signature` with their JSON framing.
462    const SIGNED_EXTRA: usize = 200;
463    let mut out = Vec::new();
464    let mut current: Vec<(ReceiptItemV2, OutboxItem)> = Vec::new();
465    let mut size = 64usize;
466    for (wire, item) in items {
467        let len = serde_json::to_vec(&wire).map_or(usize::MAX, |v| v.len() + 1);
468        if !current.is_empty()
469            && (current.len() >= MAX_RECEIPTS_V2
470                || size.saturating_add(len) + SIGNED_EXTRA > MAX_RECEIPTS_BODY_BYTES)
471        {
472            out.push(std::mem::take(&mut current));
473            size = 64;
474        }
475        size = size.saturating_add(len);
476        current.push((wire, item));
477    }
478    if !current.is_empty() {
479        out.push(current);
480    }
481    out
482}
483
484/// The same batch always carries the same key, so a retry is idempotent.
485fn idempotency_key(bytes: &[u8]) -> String {
486    use sha2::Digest as _;
487    hex::encode(&Sha256::digest(bytes)[..16])
488}
489
490/// What a receipts run did.
491#[derive(Debug, Clone, PartialEq, Eq)]
492pub enum ReceiptsRun {
493    Off(&'static str),
494    Sent {
495        accepted: u64,
496        duplicates: u64,
497        dropped: u64,
498    },
499}
500
501/// Bring the marker in step with the gates and send what is queued.
502pub fn run(
503    session: &Session,
504    config: &CloudConfig,
505    now: UtcDateTime,
506) -> Result<ReceiptsRun, CloudError> {
507    let store = &session.store;
508    let lease = &session.lease.lease;
509    let outbox = Outbox::at(store.data_dir());
510    let mut refused = disabled_lease(store);
511    // A newer lease that allows receipts lifts an earlier refusal.
512    if refused
513        .as_deref()
514        .is_some_and(|id| id != lease.lease_id && lease.org_allows_receipts_upload())
515    {
516        let _ = std::fs::remove_file(store.data_dir().join(DISABLED_FILE));
517        refused = None;
518    }
519    if let Some(reason) = blocked_by(true, config, lease, refused.as_deref()) {
520        set_enabled(store, &outbox, false)?;
521        return Ok(ReceiptsRun::Off(reason));
522    }
523    let Sharing::On {
524        vaults_off, since, ..
525    } = sharing(store, config, &session.instance, lease, now)
526    else {
527        set_enabled(store, &outbox, false)?;
528        return Ok(ReceiptsRun::Off(SHARING_OFF));
529    };
530    if !released(&session.instance.url) {
531        set_enabled(store, &outbox, false)?;
532        return Ok(ReceiptsRun::Off(NOT_RELEASED));
533    }
534    set_enabled(store, &outbox, true)?;
535    // Task evidence rides the same gates (§36). Its failure never stops
536    // the receipts: a transient one waits in its own queue.
537    let _ = super::task_evidence::send(session, &vaults_off, since, now);
538    // The map of this session's Cloud and account, not of instance.json
539    // on disk (rc3-81, bd 39791 M1): after an enrollment elsewhere nothing
540    // is sent and nothing dropped; the queue waits for its own Cloud.
541    let map = super::vault::map_in(store.data_dir(), &session.instance.vault_scope());
542    let (mut accepted, mut duplicates) = (0u64, 0u64);
543    // Nothing from before the sharing period, nothing of a vault whose own
544    // policy turns the rule off.
545    let allowed = |wire: &ReceiptItemV2| {
546        since.is_none_or(|since| wire.created_at.at() >= since)
547            && !vaults_off.contains(wire.vault_id.as_str())
548    };
549    let (ready, mut dropped) = ready_items(&outbox, map.as_ref(), now, allowed)?;
550    if ready.is_empty() {
551        return Ok(ReceiptsRun::Sent {
552            accepted,
553            duplicates,
554            dropped,
555        });
556    }
557    let keys = InstanceKeys::load(store)?;
558    for batch in batches(ready) {
559        let (wires, sent): (Vec<ReceiptItemV2>, Vec<OutboxItem>) = batch.into_iter().unzip();
560        let body = ReceiptsBodyV2 {
561            schema: ReceiptsSchema,
562            receipts: wires,
563        };
564        if body.validate().is_err() {
565            // Malformed (a duplicate id): Cloud would refuse the batch as a
566            // whole, so it is dropped rather than retried forever.
567            for item in &sent {
568                outbox.remove(item)?;
569                dropped += 1;
570            }
571            continue;
572        }
573        let request = sign(&keys, body)?;
574        let bytes = serde_json::to_vec(&request).map_err(|e| CloudError::Local(e.to_string()))?;
575        let wire: Value =
576            serde_json::from_slice(&bytes).map_err(|e| CloudError::Local(e.to_string()))?;
577        let key = idempotency_key(&bytes);
578        match session.with_client(|client| client.post_idempotent(RECEIPTS_ROUTE, &wire, &key)) {
579            Ok(answer) => {
580                let ack: ReceiptsAckV2 = serde_json::from_value(answer)
581                    .map_err(|e| CloudError::Protocol(format!("receipts ack: {e}")))?;
582                accepted += u64::from(ack.accepted);
583                duplicates += u64::from(ack.duplicates);
584                for item in &sent {
585                    outbox.remove(item)?;
586                }
587            }
588            Err(CloudError::UploadDisabled(
589                CloudUploadKind::Receipts | CloudUploadKind::Unknown,
590            )) => {
591                write_private(store.data_dir(), DISABLED_FILE, lease.lease_id.as_bytes())?;
592                set_enabled(store, &outbox, false)?;
593                return Ok(ReceiptsRun::Off(
594                    "switched off by the workspace (the Cloud refused the upload)",
595                ));
596            }
597            Err(error) if error.is_transient() => {
598                // 429: Retry-After / retry_after_s, or a quota's reset_at.
599                let retry_after = error.retry_after_at(lean_ctx_time::UtcDateTime::now());
600                for item in &sent {
601                    let mut item = item.clone();
602                    outbox.retry_later(&mut item, &error.to_string(), retry_after, now)?;
603                }
604                return Err(error);
605            }
606            Err(error) => {
607                for item in &sent {
608                    let mut item = item.clone();
609                    outbox.fail(&mut item, &error.to_string())?;
610                }
611                return Err(error);
612            }
613        }
614    }
615    Ok(ReceiptsRun::Sent {
616        accepted,
617        duplicates,
618        dropped,
619    })
620}
621
622#[cfg(test)]
623#[path = "receipts_tests.rs"]
624mod tests;