af-agent-session 0.8.0

Append-only Agent session events, invariants and deterministic projections.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! Append-only corrections to measurement facts. Reservation settlement remains immutable.
use af_context::{MeteringCorrectionId, RunId, SubjectId};
use serde::{Deserialize, Serialize};

use crate::{EventError, MeteringDetails, MeteringSource, SessionProjection};

/// Latest measurement for one stable Run operation; revision zero is its original fact.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OperationUsage {
    /// Prompt tokens measured.
    pub prompt_tokens: u64,
    /// Completion tokens measured.
    pub completion_tokens: u64,
    /// Provider-neutral resource weight, never a price.
    pub cost_units: u64,
    /// Attribution; absent only for legacy data.
    pub metering: Option<MeteringDetails>,
    /// Number of accepted corrections to this operation.
    pub revision: u64,
}

/// An original operation used in reservation settlement, never a corrected price.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RunOperationUsage {
    /// Stable operation identity within the Run, suitable for host deduplication.
    pub operation_id: String,
    /// Original immutable measurement, including provider/model or tool attribution.
    pub usage: OperationUsage,
    /// Preparation has no durable result; the usage is a conservative estimate.
    pub pending: bool,
}

/// Privileged report that replaces the derived measurement, never its original event.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MeteringCorrection {
    /// Stable idempotency identity, unique within the Session.
    pub id: MeteringCorrectionId,
    /// Terminal Run whose measurement is corrected.
    pub run_id: RunId,
    /// Original stable operation identity.
    pub operation: String,
    /// Exact measurement revision the reporter observed.
    pub expected_revision: u64,
    /// Corrected prompt tokens.
    pub prompt_tokens: u64,
    /// Corrected completion tokens.
    pub completion_tokens: u64,
    /// Corrected resource units; no monetary meaning in Factory.
    pub cost_units: u64,
    /// Reported attribution, preserving the original operation identity.
    pub metering: MeteringDetails,
    /// Short audit reason, without credentials or provider response bodies.
    pub reason: String,
}

/// Accepted correction with server-derived actor and immutable event position.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AppliedMeteringCorrection {
    /// Caller-supplied report.
    pub correction: MeteringCorrection,
    /// Authenticated reporting subject.
    pub actor_id: SubjectId,
    /// Session event sequence of first acceptance.
    pub seq: u64,
}

impl MeteringCorrection {
    /// Validate bounded, non-overflowing reported measurements before any write.
    pub fn validate(&self) -> Result<(), EventError> {
        self.metering.validate()?;
        let valid_text = |value: &str| {
            !value.trim().is_empty() && value.len() <= 512 && !value.chars().any(char::is_control)
        };
        if !valid_text(self.id.as_str())
            || !valid_text(&self.operation)
            || !valid_text(&self.reason)
            || self.expected_revision == u64::MAX
            || self
                .prompt_tokens
                .checked_add(self.completion_tokens)
                .and_then(|v| v.checked_add(self.cost_units))
                .is_none_or(|v| v > i64::MAX as u64)
            || !matches!(
                self.metering,
                MeteringDetails::Model {
                    source: MeteringSource::Reported,
                    ..
                } | MeteringDetails::Tool {
                    source: MeteringSource::Reported,
                    ..
                }
            )
        {
            return Err(EventError::InvalidMetering);
        }
        Ok(())
    }
}

impl SessionProjection {
    /// Original settlement evidence in stable operation order, including pending estimates.
    /// Corrections are deliberately separate (`operation_usage`); they must never
    /// silently reprice an already settled reservation. Legacy facts lack attribution.
    /// Read through an authorized AgentStore projection; this value grants no access.
    pub fn run_usage_operations(&self, run_id: &RunId) -> Vec<RunOperationUsage> {
        let mut result: std::collections::BTreeMap<String, RunOperationUsage> = self
            .pending_usage_operations
            .iter()
            .filter(|((id, _), _)| id == run_id)
            .map(|((_, operation), (prompt, completion, cost, metering))| {
                (
                    operation.clone(),
                    RunOperationUsage {
                        operation_id: operation.clone(),
                        usage: OperationUsage {
                            prompt_tokens: *prompt,
                            completion_tokens: *completion,
                            cost_units: *cost,
                            metering: metering.clone(),
                            revision: 0,
                        },
                        pending: true,
                    },
                )
            })
            .collect();
        for ((id, operation), (prompt, completion, cost, metering)) in &self.usage_operations {
            if id == run_id {
                result.insert(
                    operation.clone(),
                    RunOperationUsage {
                        operation_id: operation.clone(),
                        usage: OperationUsage {
                            prompt_tokens: *prompt,
                            completion_tokens: *completion,
                            cost_units: *cost,
                            metering: metering.clone(),
                            revision: 0,
                        },
                        pending: false,
                    },
                );
            }
        }
        result.into_values().collect()
    }

    /// Latest authoritative measurement. Original quota settlement is queried separately.
    pub fn operation_usage(&self, run_id: &RunId, operation: &str) -> Option<OperationUsage> {
        let key = (run_id.clone(), operation.to_owned());
        if let Some(value) = self.corrected_usage.get(&key) {
            return Some(value.clone());
        }
        if let Some((prompt_tokens, completion_tokens, cost_units, metering)) =
            self.usage_operations.get(&key)
        {
            return Some(OperationUsage {
                prompt_tokens: *prompt_tokens,
                completion_tokens: *completion_tokens,
                cost_units: *cost_units,
                metering: metering.clone(),
                revision: 0,
            });
        }
        self.pending_usage_operations.get(&key).map(
            |(prompt_tokens, completion_tokens, cost_units, metering)| OperationUsage {
                prompt_tokens: *prompt_tokens,
                completion_tokens: *completion_tokens,
                cost_units: *cost_units,
                metering: metering.clone(),
                revision: 0,
            },
        )
    }

    /// Original receipt for an idempotently accepted correction.
    pub fn metering_correction(
        &self,
        id: &MeteringCorrectionId,
    ) -> Option<&AppliedMeteringCorrection> {
        self.metering_corrections.get(id)
    }

    pub(super) fn apply_metering_correction(
        &mut self,
        correction: &MeteringCorrection,
        actor_id: &SubjectId,
        seq: u64,
    ) -> Result<(), EventError> {
        correction.validate()?;
        if let Some(applied) = self.metering_corrections.get(&correction.id) {
            return if applied.correction == *correction && applied.actor_id == *actor_id {
                Ok(())
            } else {
                Err(EventError::UsageConflict(correction.operation.clone()))
            };
        }
        let previous = self
            .operation_usage(&correction.run_id, &correction.operation)
            .ok_or_else(|| EventError::UsageConflict(correction.operation.clone()))?;
        if !self
            .run_status
            .get(&correction.run_id)
            .is_some_and(|status| status.is_terminal())
            || previous.revision != correction.expected_revision
            || !previous
                .metering
                .as_ref()
                .is_some_and(|details| correction.metering.completes(details))
        {
            return Err(EventError::UsageConflict(correction.operation.clone()));
        }
        self.corrected_usage.insert(
            (correction.run_id.clone(), correction.operation.clone()),
            OperationUsage {
                prompt_tokens: correction.prompt_tokens,
                completion_tokens: correction.completion_tokens,
                cost_units: correction.cost_units,
                metering: Some(correction.metering.clone()),
                revision: previous.revision + 1,
            },
        );
        self.metering_corrections.insert(
            correction.id.clone(),
            AppliedMeteringCorrection {
                correction: correction.clone(),
                actor_id: actor_id.clone(),
                seq,
            },
        );
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{MeteringOutcome, RunState, RunStatus};

    #[test]
    fn original_evidence_keeps_mixed_models_pending_tools_and_excludes_corrections() {
        let mut projection = SessionProjection::default();
        let run: RunId = "run".parse().unwrap();
        for (operation, model) in [("model-a", "model-one"), ("model-b", "model-two")] {
            projection.usage_operations.insert(
                (run.clone(), operation.into()),
                (
                    3,
                    2,
                    0,
                    Some(MeteringDetails::Model {
                        model: model.into(),
                        provider: Some("provider".into()),
                        provider_attempt_id: operation.parse().unwrap(),
                        source: MeteringSource::Reported,
                        outcome: MeteringOutcome::Completed,
                    }),
                ),
            );
        }
        projection.pending_usage_operations.insert(
            (run.clone(), "tool".into()),
            (
                0,
                0,
                7,
                Some(MeteringDetails::Tool {
                    call_id: "call".parse().unwrap(),
                    name: "lookup".into(),
                    source: MeteringSource::Estimated,
                    outcome: MeteringOutcome::Unknown,
                }),
            ),
        );
        projection.usage_operations.insert(
            ("another-run".parse().unwrap(), "model-a".into()),
            (99, 0, 0, None),
        );
        let original = projection.run_usage_operations(&run);
        assert_eq!(original.len(), 3);
        assert!(!original[0].pending);
        assert!(original[2].pending);
        assert_ne!(original[0].usage.metering, original[1].usage.metering);
        assert_eq!(
            original
                .iter()
                .map(|fact| fact.usage.prompt_tokens
                    + fact.usage.completion_tokens
                    + fact.usage.cost_units)
                .sum::<u64>(),
            projection.billable_units_for("run")
        );
        projection.corrected_usage.insert(
            (run.clone(), "model-a".into()),
            OperationUsage {
                prompt_tokens: 1,
                completion_tokens: 1,
                cost_units: 0,
                metering: None,
                revision: 1,
            },
        );
        assert_eq!(projection.run_usage_operations(&run), original);
        assert_eq!(projection.clone().run_usage_operations(&run), original);
        assert!(projection
            .run_usage_operations(&"missing".parse().unwrap())
            .is_empty());
    }

    fn report() -> MeteringCorrection {
        MeteringCorrection {
            id: "correction".parse().unwrap(),
            run_id: "run".parse().unwrap(),
            operation: "operation".into(),
            expected_revision: 0,
            prompt_tokens: 1,
            completion_tokens: 2,
            cost_units: 0,
            metering: MeteringDetails::Model {
                model: "m".into(),
                provider: Some("p".into()),
                provider_attempt_id: "attempt".parse().unwrap(),
                source: MeteringSource::Reported,
                outcome: MeteringOutcome::Completed,
            },
            reason: "provider report".into(),
        }
    }

    #[test]
    fn invalid_reports_and_mismatched_identities_fail_closed() {
        let good = report();
        good.validate().unwrap();
        for mutation in 0..7 {
            let mut invalid = good.clone();
            match mutation {
                0 => invalid.reason.clear(),
                1 => invalid.operation = "a".repeat(513),
                2 => invalid.prompt_tokens = u64::MAX,
                3 => invalid.expected_revision = u64::MAX,
                4 => invalid.id = "bad\nid".parse().unwrap(),
                5 => {
                    if let MeteringDetails::Model { source, .. } = &mut invalid.metering {
                        *source = MeteringSource::Estimated;
                    }
                }
                _ => {
                    if let MeteringDetails::Model { model, .. } = &mut invalid.metering {
                        model.clear();
                    }
                }
            }
            assert!(invalid.validate().is_err());
        }
        let mut projection = SessionProjection::default();
        let actor = "admin".parse().unwrap();
        assert!(projection
            .apply_metering_correction(&good, &actor, 10)
            .is_err());
        projection
            .run_status
            .insert(good.run_id.clone(), RunState::Terminal(RunStatus::Failed));
        let mut pending = good.metering.clone();
        if let MeteringDetails::Model {
            source, outcome, ..
        } = &mut pending
        {
            *source = MeteringSource::Estimated;
            *outcome = MeteringOutcome::Unknown;
        }
        projection.pending_usage_operations.insert(
            (good.run_id.clone(), good.operation.clone()),
            (100, 20, 0, Some(pending)),
        );
        assert_eq!(
            projection
                .operation_usage(&good.run_id, &good.operation)
                .unwrap()
                .prompt_tokens,
            100
        );
        let mut wrong = good.clone();
        if let MeteringDetails::Model { provider, .. } = &mut wrong.metering {
            *provider = Some("wrong".into());
        }
        assert!(projection
            .apply_metering_correction(&wrong, &actor, 10)
            .is_err());
        projection
            .apply_metering_correction(&good, &actor, 10)
            .unwrap();
        projection
            .apply_metering_correction(&good, &actor, 11)
            .unwrap();
        assert_eq!(projection.metering_correction(&good.id).unwrap().seq, 10);
        assert!(projection
            .apply_metering_correction(&good, &"other".parse().unwrap(), 12)
            .is_err());
        assert_eq!(
            projection
                .operation_usage(&good.run_id, &good.operation)
                .unwrap()
                .prompt_tokens,
            1
        );
        assert_eq!(projection.billable_units_for("run"), 120);
        assert!(projection
            .operation_usage(&good.run_id, "missing")
            .is_none());
    }
}