stateknot 0.1.0-alpha.1

Durable agent orchestration for Rust
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
414
// Copyright 2026 StateKnot contributors
// SPDX-License-Identifier: Apache-2.0

use super::*;
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use stateknot::{
    agent_host::{AgentHost, AgentHostStatus},
    postgres::JournalPageSize,
};
use stateknot_testkit::{
    FaultCaseId, FaultPlan, IntegrityEnvelope, LatencySignal, MachineEnvironment, OperationOutcome,
    PostgresEnvironment, QualificationEnvironment, QualificationProfile, QualificationRun,
    QualificationScenario, QualificationWindow, SourceIdentity, StandbyMode, Topology,
};
use std::time::Instant;

struct Events {
    response: reqwest::Response,
    buffer: String,
}

impl Events {
    async fn open(host: &AgentHost, run: RunId, last_event_id: Option<&str>) -> Self {
        let mut request = host::client()
            .get(format!(
                "http://{}/v1/agent-runs/{run}/events",
                host.local_addr()
            ))
            .bearer_auth(fixture::TOKEN)
            .header(reqwest::header::ACCEPT, "text/event-stream");
        if let Some(last_event_id) = last_event_id {
            request = request.header("last-event-id", last_event_id);
        }
        let response = request.send().await.unwrap();
        assert_eq!(response.status(), 200);
        Self {
            response,
            buffer: String::new(),
        }
    }

    async fn next(&mut self, kind: &str) -> (Option<String>, Value) {
        timeout(Duration::from_secs(5), async {
            loop {
                if let Some(frame) = take_frame(&mut self.buffer, kind) {
                    let id = frame
                        .lines()
                        .find_map(|line| line.strip_prefix("id: "))
                        .map(str::to_owned);
                    let data = frame
                        .lines()
                        .find_map(|line| line.strip_prefix("data: "))
                        .unwrap();
                    return (id, serde_json::from_str(data).unwrap());
                }
                let chunk =
                    self.response.chunk().await.unwrap().unwrap_or_else(|| {
                        panic!("qualification SSE ended while waiting for {kind}")
                    });
                self.buffer.push_str(std::str::from_utf8(&chunk).unwrap());
                assert!(self.buffer.len() <= 8_388_608);
            }
        })
        .await
        .unwrap()
    }
}

fn take_frame(buffer: &mut String, kind: &str) -> Option<String> {
    let prefix = format!("event: {kind}\n");
    let mut offset = 0;
    for frame in buffer.split_inclusive("\n\n") {
        if !frame.ends_with("\n\n") {
            break;
        }
        let end = offset + frame.len();
        if frame.starts_with(&prefix) {
            return Some(buffer.drain(offset..end).collect());
        }
        offset = end;
    }
    None
}

fn env(name: &str) -> String {
    std::env::var(name)
        .unwrap_or_else(|_| panic!("mandatory qualification metadata missing: {name}"))
}

async fn environment(f: &Fixture) -> QualificationEnvironment {
    let started = Instant::now();
    f.store.observe_database_clock().await.unwrap();
    let database_rtt = micros(started.elapsed());
    let cpus = env("STATEKNOT_QUALIFICATION_LOGICAL_CPUS")
        .parse::<u16>()
        .unwrap();
    let memory = env("STATEKNOT_QUALIFICATION_MEMORY_BYTES")
        .parse::<u64>()
        .unwrap();
    let cpu_model = env("STATEKNOT_QUALIFICATION_CPU_MODEL");
    let kernel = env("STATEKNOT_QUALIFICATION_KERNEL");
    let source = SourceIdentity::new(
        env("STATEKNOT_QUALIFICATION_SOURCE_COMMIT"),
        env("STATEKNOT_QUALIFICATION_SOURCE_TREE"),
        env("STATEKNOT_QUALIFICATION_CARGO_LOCK_SHA256"),
        env("STATEKNOT_QUALIFICATION_DATASET_SHA256"),
        env("STATEKNOT_QUALIFICATION_CONFIGURATION_SHA256"),
    )
    .unwrap();
    QualificationEnvironment::new(
        source,
        MachineEnvironment::new(
            cpus,
            memory,
            &cpu_model,
            "github-actions-ephemeral",
            &kernel,
            "github-actions-host",
        )
        .unwrap(),
        MachineEnvironment::new(
            cpus,
            memory,
            cpu_model,
            "github-actions-ephemeral",
            kernel,
            "github-actions-service-container",
        )
        .unwrap(),
        PostgresEnvironment::new(
            env("STATEKNOT_QUALIFICATION_POSTGRES_MAJOR")
                .parse()
                .unwrap(),
            true,
            StandbyMode::None,
        )
        .unwrap(),
        Topology::new(1, 1, 1, 1).unwrap(),
        database_rtt,
    )
    .unwrap()
}

fn micros(duration: Duration) -> u64 {
    u64::try_from(duration.as_micros())
        .unwrap()
        .clamp(1, 3_600_000_000)
}

async fn qualification_until(label: &str, mut predicate: impl FnMut() -> bool) {
    timeout(Duration::from_secs(30), async {
        while !predicate() {
            sleep(Duration::from_millis(10)).await;
        }
    })
    .await
    .unwrap_or_else(|_| panic!("qualification timed out waiting for {label}"));
}

async fn runnable_claim_latency(f: &Fixture, run: RunId) -> Duration {
    let page = f
        .store
        .load_journal_page(
            f.caller.tenant_id(),
            run,
            None,
            JournalPageSize::new(64).unwrap(),
        )
        .await
        .unwrap();
    assert!(!page.has_more());
    let admitted = page
        .events()
        .iter()
        .find(|event| event.payload().kind().as_str() == "agent-admitted")
        .unwrap()
        .recorded_at()
        .unix_micros();
    let claimed = page
        .events()
        .iter()
        .find(|event| event.payload().kind().as_str() == "graph-node-attempt-started")
        .unwrap()
        .recorded_at()
        .unix_micros();
    Duration::from_micros(
        u64::try_from(claimed.checked_sub(admitted).unwrap())
            .unwrap()
            .max(1),
    )
}

fn encoded_head(head: &JournalHead) -> String {
    format!(
        "sk1.{}",
        URL_SAFE_NO_PAD.encode(serde_json::to_vec(head).unwrap())
    )
}

async fn submit_and_complete(
    host: &AgentHost,
    f: &Fixture,
    recorder: &stateknot_testkit::QualificationRecorder,
) -> RunId {
    let operation = recorder.begin_operation().unwrap();
    let started = Instant::now();
    let response = host::submit(host, f).await;
    recorder
        .record_latency(LatencySignal::AdmissionCommit, started.elapsed(), None)
        .unwrap();
    assert_eq!(response.status(), 201);
    let run = response
        .json::<AgentHttpRunResponse>()
        .await
        .unwrap()
        .snapshot
        .provenance()
        .run_id();
    succeeded(f, run).await;
    recorder
        .record_latency(
            LatencySignal::RunnableClaim,
            runnable_claim_latency(f, run).await,
            None,
        )
        .unwrap();
    operation.finish(OperationOutcome::Completed).unwrap();
    run
}

#[tokio::test]
async fn postgres_reduced_host_qualification_emits_verified_non_release_evidence() {
    let Some(f) = Fixture::new().await else {
        return;
    };
    let plan = FaultPlan::ci_default();
    let run = QualificationRun::start(
        QualificationProfile::CiReduced,
        QualificationScenario::AgentHostControlPlaneV1,
        QualificationWindow::new(
            Duration::from_millis(1),
            Duration::from_millis(1),
            Duration::from_millis(1),
        )
        .unwrap(),
        environment(&f).await,
        &plan,
    )
    .unwrap();
    let checks_a = host::checks();
    let (mut host_a, _) = host::launch(&f, &checks_a, evidence(&f), host::limits()).await;
    host::ready(&host_a).await;
    let (mut operations, _) =
        operations::start(&host_a, operations::auth(&f), |options| options).await;
    sleep(Duration::from_millis(2)).await;
    run.begin_measurement().unwrap();
    let recorder = run.recorder();

    let first = submit_and_complete(&host_a, &f, &recorder).await;
    let mut replay = Events::open(&host_a, first, None).await;
    replay.next("snapshot").await;
    let (cursor, _) = replay.next("activity").await;
    let reconnect_started = Instant::now();
    let mut reconnected = Events::open(&host_a, first, cursor.as_deref()).await;
    reconnected.next("snapshot").await;
    reconnected.next("activity").await;
    recorder
        .record_latency(
            LatencySignal::SseReconnect,
            reconnect_started.elapsed(),
            None,
        )
        .unwrap();
    drop(replay);
    drop(reconnected);

    f.node_block.store(true, Ordering::SeqCst);
    let blocked = host::submit(&host_a, &f).await;
    assert_eq!(blocked.status(), 201);
    let blocked = blocked
        .json::<AgentHttpRunResponse>()
        .await
        .unwrap()
        .snapshot
        .provenance()
        .run_id();
    qualification_until("the live-SSE node to enter execution", || {
        host_a.health().worker().unwrap().active_nodes() > 0
    })
    .await;
    let page = f
        .store
        .load_journal_page(
            f.caller.tenant_id(),
            blocked,
            None,
            JournalPageSize::new(64).unwrap(),
        )
        .await
        .unwrap();
    let head = page.next_cursor().unwrap();
    let mut live = Events::open(&host_a, blocked, Some(&encoded_head(&head))).await;
    live.next("snapshot").await;
    let delivery_started = Instant::now();
    f.service
        .request_cancellation(f.caller.clone(), blocked, AgentCancellationIds::generate())
        .await
        .unwrap();
    live.next("activity").await;
    recorder
        .record_latency(LatencySignal::SseDelivery, delivery_started.elapsed(), None)
        .unwrap();
    drop(live);
    f.node_block.store(false, Ordering::SeqCst);
    f.node_release.notify_one();
    timeout(Duration::from_secs(12), async {
        loop {
            let snapshot = f.service.load(f.caller.clone(), blocked).await.unwrap();
            if snapshot.status() == RunStatus::Cancelled {
                break;
            }
            assert!(matches!(
                snapshot.status(),
                RunStatus::Active | RunStatus::CancellationRequested
            ));
            sleep(Duration::from_millis(20)).await;
        }
    })
    .await
    .unwrap();

    recorder
        .fault_injected(FaultCaseId::HostDependencyUnavailable)
        .unwrap();
    checks_a[2].mode.store(1, Ordering::SeqCst);
    qualification_until("the host dependency gate to fail closed", || {
        host_a.health().status() == AgentHostStatus::Unavailable
    })
    .await;
    assert_eq!(host::submit(&host_a, &f).await.status(), 503);
    recorder
        .fault_invariant_checked(FaultCaseId::HostDependencyUnavailable)
        .unwrap();
    assert_eq!(
        operations::get(&operations, "/v1/host/ready", "ops-fixture")
            .await
            .status(),
        503
    );
    checks_a[2].mode.store(0, Ordering::SeqCst);
    host::ready(&host_a).await;
    recorder
        .fault_recovered(FaultCaseId::HostDependencyUnavailable)
        .unwrap();
    assert_eq!(
        operations::get(&operations, "/v1/host/ready", "ops-fixture")
            .await
            .status(),
        200
    );
    recorder
        .fault_invariant_checked(FaultCaseId::HostDependencyUnavailable)
        .unwrap();

    recorder
        .fault_injected(FaultCaseId::HostRollingReplacement)
        .unwrap();
    let checks_b = host::checks();
    let (mut host_b, _) = host::launch(&f, &checks_b, evidence(&f), host::limits()).await;
    host::ready(&host_b).await;
    recorder
        .fault_invariant_checked(FaultCaseId::HostRollingReplacement)
        .unwrap();
    host_a.shutdown().await.unwrap();
    host::joined(&host_a, &f).await;
    recorder
        .fault_invariant_checked(FaultCaseId::HostRollingReplacement)
        .unwrap();
    let stopped = operations::get(&operations, "/v1/host/status", "ops-fixture").await;
    assert_eq!(stopped.status(), 200);
    let second = submit_and_complete(&host_b, &f, &recorder).await;
    assert_ne!(first, second);
    assert_eq!(f.node_calls.load(Ordering::SeqCst), 3);
    recorder
        .fault_invariant_checked(FaultCaseId::HostRollingReplacement)
        .unwrap();
    recorder
        .fault_recovered(FaultCaseId::HostRollingReplacement)
        .unwrap();

    host_b.shutdown().await.unwrap();
    host::joined(&host_b, &f).await;
    operations.shutdown().await.unwrap();
    sleep(Duration::from_millis(2)).await;
    run.begin_drain().unwrap();
    sleep(Duration::from_millis(2)).await;
    let report = run.finish().unwrap();
    assert!(report.evidence_valid());
    assert!(!report.release_qualified());
    let envelope = report.to_integrity_envelope().unwrap();
    let bytes = envelope.canonical_bytes().unwrap();
    assert_eq!(IntegrityEnvelope::from_json(&bytes).unwrap(), envelope);
    let text = String::from_utf8(bytes).unwrap();
    for secret in [
        f.caller.tenant_id().as_str(),
        fixture::TOKEN,
        &first.to_string(),
        &second.to_string(),
    ] {
        assert!(!text.contains(secret));
    }
    f.store.close().await;
    println!("\nSTATEKNOT_HOST_QUALIFICATION_REPORT={text}");
}