awaken-runtime 0.6.0

Phase-based execution engine, plugin system, and agent loop for Awaken
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
use std::sync::Arc;

use crate::state::KeyScope;
use awaken_runtime_contract::{StateError, UnknownKeyPolicy};

use super::{PersistedState, StateMap, StateStore};

impl StateStore {
    /// Export all persistent keys (every scope) into one `PersistedState`.
    pub fn export_persisted(&self) -> Result<PersistedState, StateError> {
        self.export_filtered(|_| true)
    }

    /// Export only thread-scoped persistent keys (for `ThreadCommit.thread_state`).
    pub fn export_thread_scoped(&self) -> Result<PersistedState, StateError> {
        self.export_filtered(|scope| scope == KeyScope::Thread)
    }

    /// Export persistent keys NOT in the thread scope (run-scoped et al.) — the
    /// portion that rides on the run record.
    pub fn export_run_scoped(&self) -> Result<PersistedState, StateError> {
        self.export_filtered(|scope| scope != KeyScope::Thread)
    }

    fn export_filtered(
        &self,
        include: impl Fn(KeyScope) -> bool,
    ) -> Result<PersistedState, StateError> {
        let registry = self.registry.lock();
        let state = self.inner.read();
        let mut extensions = std::collections::HashMap::new();

        for reg in registry.keys_by_type.values() {
            if !reg.options.persistent || !include(reg.scope) {
                continue;
            }

            if let Some(json) = (reg.export)(state.ext.as_ref()).map_err(|err| match err {
                StateError::KeyEncode { key, message } => StateError::KeyEncode { key, message },
                other => StateError::KeyEncode {
                    key: reg.key.clone(),
                    message: other.to_string(),
                },
            })? {
                extensions.insert(reg.key.clone(), json);
            }
        }

        Ok(PersistedState {
            revision: state.revision,
            extensions,
        })
    }

    pub fn restore_persisted(
        &self,
        persisted: PersistedState,
        unknown_policy: UnknownKeyPolicy,
    ) -> Result<(), StateError> {
        let registry = self.registry.lock();
        let mut next_ext = StateMap::default();

        for (key, json) in persisted.extensions {
            let Some(reg) = registry.keys_by_name.get(&key) else {
                match unknown_policy {
                    UnknownKeyPolicy::Error => return Err(StateError::UnknownKey { key }),
                    UnknownKeyPolicy::Skip => continue,
                }
            };

            (reg.import)(&mut next_ext, json).map_err(|err| match err {
                StateError::KeyDecode { key, message } => StateError::KeyDecode { key, message },
                other => StateError::KeyDecode {
                    key: reg.key.clone(),
                    message: other.to_string(),
                },
            })?;
        }

        let mut state = self.inner.write();
        state.ext = Arc::new(next_ext);
        state.revision = persisted.revision;
        Ok(())
    }

    /// Restore only `Thread`-scoped keys from a persisted state snapshot.
    ///
    /// Run-scoped keys in `persisted` are ignored. Unknown keys follow `unknown_policy`.
    pub fn restore_thread_scoped(
        &self,
        persisted: PersistedState,
        unknown_policy: UnknownKeyPolicy,
    ) -> Result<(), StateError> {
        let registry = self.registry.lock();
        let mut state = self.inner.write();
        let ext = Arc::make_mut(&mut state.ext);

        for (key, json) in persisted.extensions {
            let Some(reg) = registry.keys_by_name.get(&key) else {
                match unknown_policy {
                    UnknownKeyPolicy::Error => return Err(StateError::UnknownKey { key }),
                    UnknownKeyPolicy::Skip => continue,
                }
            };

            if reg.scope != KeyScope::Thread {
                continue;
            }

            (reg.import)(ext, json).map_err(|err| match err {
                StateError::KeyDecode { key, message } => StateError::KeyDecode { key, message },
                other => StateError::KeyDecode {
                    key: reg.key.clone(),
                    message: other.to_string(),
                },
            })?;
        }

        Ok(())
    }

    /// Seed the store with values from a `PersistedState`, merging into
    /// existing state instead of replacing it.
    ///
    /// Unlike [`Self::restore_persisted`], this preserves keys not present in
    /// `persisted` (typically values committed by plugin activation hooks).
    /// Used by child-run helpers to seed a freshly-prepared store with
    /// parent-derived state.
    ///
    /// The seed's `revision` field is ignored — the store keeps its current
    /// revision and does not bump it for the seed application (no commit
    /// hooks are fired).
    pub fn apply_seed(
        &self,
        persisted: PersistedState,
        unknown_policy: UnknownKeyPolicy,
    ) -> Result<(), StateError> {
        let registry = self.registry.lock();
        let mut state = self.inner.write();
        let mut next_ext = state.ext.as_ref().clone();

        for (key, json) in persisted.extensions {
            let Some(reg) = registry.keys_by_name.get(&key) else {
                match unknown_policy {
                    UnknownKeyPolicy::Error => return Err(StateError::UnknownKey { key }),
                    UnknownKeyPolicy::Skip => continue,
                }
            };

            (reg.import)(&mut next_ext, json).map_err(|err| match err {
                StateError::KeyDecode { key, message } => StateError::KeyDecode { key, message },
                other => StateError::KeyDecode {
                    key: reg.key.clone(),
                    message: other.to_string(),
                },
            })?;
        }

        state.ext = Arc::new(next_ext);
        Ok(())
    }

    /// Clear all `Run`-scoped keys, preserving `Thread`-scoped keys.
    pub fn clear_run_scoped(&self) {
        let registry = self.registry.lock();
        let mut state = self.inner.write();
        let ext = Arc::make_mut(&mut state.ext);

        for reg in registry.keys_by_type.values() {
            if reg.scope == KeyScope::Run {
                (reg.clear)(ext);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plugins::{Plugin, PluginDescriptor, PluginRegistrar};
    use crate::state::{StateKey, StateKeyOptions};
    use awaken_runtime_contract::UnknownKeyPolicy;

    struct PersistentCounter;

    impl StateKey for PersistentCounter {
        const KEY: &'static str = "test.persist_counter";
        type Value = i64;
        type Update = i64;

        fn apply(value: &mut Self::Value, update: Self::Update) {
            *value += update;
        }
    }

    struct TransientFlag;

    impl StateKey for TransientFlag {
        const KEY: &'static str = "test.transient_flag";
        type Value = bool;
        type Update = bool;

        fn apply(value: &mut Self::Value, update: Self::Update) {
            *value = update;
        }
    }

    struct ThreadCounter;

    impl StateKey for ThreadCounter {
        const KEY: &'static str = "test.thread_counter";
        type Value = i64;
        type Update = i64;

        fn apply(value: &mut Self::Value, update: Self::Update) {
            *value += update;
        }
    }

    struct PersistenceTestPlugin;

    impl Plugin for PersistenceTestPlugin {
        fn descriptor(&self) -> PluginDescriptor {
            PluginDescriptor {
                name: "persistence-test-plugin",
            }
        }

        fn register(
            &self,
            registrar: &mut PluginRegistrar,
        ) -> Result<(), awaken_runtime_contract::StateError> {
            registrar.register_key::<PersistentCounter>(StateKeyOptions {
                persistent: true,
                ..Default::default()
            })?;
            registrar.register_key::<TransientFlag>(StateKeyOptions {
                persistent: false,
                ..Default::default()
            })?;
            registrar.register_key::<ThreadCounter>(StateKeyOptions {
                persistent: true,
                scope: crate::state::KeyScope::Thread,
                ..Default::default()
            })?;
            Ok(())
        }
    }

    #[test]
    fn export_import_roundtrip() {
        let store = StateStore::new();
        store.install_plugin(PersistenceTestPlugin).unwrap();

        let mut batch = store.begin_mutation();
        batch.update::<PersistentCounter>(42);
        store.commit(batch).unwrap();

        let exported = store.export_persisted().unwrap();

        // Create a new store, install same plugin, restore
        let store2 = StateStore::new();
        store2.install_plugin(PersistenceTestPlugin).unwrap();
        store2
            .restore_persisted(exported, UnknownKeyPolicy::Error)
            .unwrap();

        let val = store2.read::<PersistentCounter>().unwrap();
        assert_eq!(val, 42);
    }

    #[test]
    fn export_splits_thread_and_run_scoped_keys() {
        let store = StateStore::new();
        store.install_plugin(PersistenceTestPlugin).unwrap();

        let mut batch = store.begin_mutation();
        batch.update::<PersistentCounter>(5); // run-scoped
        batch.update::<ThreadCounter>(9); // thread-scoped
        store.commit(batch).unwrap();

        let thread = store.export_thread_scoped().unwrap();
        assert!(thread.extensions.contains_key(ThreadCounter::KEY));
        assert!(!thread.extensions.contains_key(PersistentCounter::KEY));

        let run = store.export_run_scoped().unwrap();
        assert!(run.extensions.contains_key(PersistentCounter::KEY));
        assert!(!run.extensions.contains_key(ThreadCounter::KEY));

        let all = store.export_persisted().unwrap();
        assert!(all.extensions.contains_key(PersistentCounter::KEY));
        assert!(all.extensions.contains_key(ThreadCounter::KEY));
    }

    #[test]
    fn export_skips_non_persistent_keys() {
        let store = StateStore::new();
        store.install_plugin(PersistenceTestPlugin).unwrap();

        let mut batch = store.begin_mutation();
        batch.update::<PersistentCounter>(10);
        batch.update::<TransientFlag>(true);
        store.commit(batch).unwrap();

        let exported = store.export_persisted().unwrap();

        // Only the persistent key should be in the export
        assert!(
            exported.extensions.contains_key(PersistentCounter::KEY),
            "persistent key should be exported"
        );
        assert!(
            !exported.extensions.contains_key(TransientFlag::KEY),
            "non-persistent key should NOT be exported"
        );
    }

    #[test]
    fn apply_seed_merges_without_clobbering_existing_keys() {
        let store = StateStore::new();
        store.install_plugin(PersistenceTestPlugin).unwrap();

        // Pre-existing key value not in the seed should be preserved.
        let mut batch = store.begin_mutation();
        batch.update::<TransientFlag>(true);
        store.commit(batch).unwrap();

        let mut extensions = std::collections::HashMap::new();
        extensions.insert(PersistentCounter::KEY.to_string(), serde_json::json!(99i64));
        let seed = PersistedState {
            revision: 0,
            extensions,
        };

        store.apply_seed(seed, UnknownKeyPolicy::Error).unwrap();

        assert_eq!(
            store.read::<PersistentCounter>(),
            Some(99),
            "seed should set the listed key"
        );
        assert_eq!(
            store.read::<TransientFlag>(),
            Some(true),
            "seed must preserve keys it did not list"
        );
    }

    #[test]
    fn apply_seed_rejects_unknown_keys_under_error_policy() {
        let store = StateStore::new();
        store.install_plugin(PersistenceTestPlugin).unwrap();

        let mut batch = store.begin_mutation();
        batch.update::<PersistentCounter>(10);
        batch.update::<TransientFlag>(true);
        store.commit(batch).unwrap();

        let mut extensions = std::collections::HashMap::new();
        extensions.insert(PersistentCounter::KEY.to_string(), serde_json::json!(99i64));
        extensions.insert("unregistered.key".to_string(), serde_json::json!("x"));
        let seed = PersistedState {
            revision: 0,
            extensions,
        };

        let err = store.apply_seed(seed, UnknownKeyPolicy::Error).unwrap_err();
        assert!(matches!(
            err,
            awaken_runtime_contract::StateError::UnknownKey { .. }
        ));
        assert_eq!(
            store.read::<PersistentCounter>(),
            Some(10),
            "failed seeds must not leave partial mutations behind"
        );
        assert_eq!(
            store.read::<TransientFlag>(),
            Some(true),
            "unlisted keys must remain intact after failed seed application"
        );
    }

    #[test]
    fn apply_seed_decode_error_is_atomic() {
        let store = StateStore::new();
        store.install_plugin(PersistenceTestPlugin).unwrap();

        let mut batch = store.begin_mutation();
        batch.update::<PersistentCounter>(10);
        batch.update::<TransientFlag>(true);
        store.commit(batch).unwrap();

        let mut extensions = std::collections::HashMap::new();
        extensions.insert(
            PersistentCounter::KEY.to_string(),
            serde_json::json!("not an integer"),
        );
        let seed = PersistedState {
            revision: 0,
            extensions,
        };

        let err = store.apply_seed(seed, UnknownKeyPolicy::Error).unwrap_err();
        assert!(matches!(
            err,
            awaken_runtime_contract::StateError::KeyDecode { .. }
        ));
        assert_eq!(
            store.read::<PersistentCounter>(),
            Some(10),
            "decode failures must preserve the original value"
        );
        assert_eq!(
            store.read::<TransientFlag>(),
            Some(true),
            "unlisted keys must remain intact after decode failure"
        );
    }

    #[test]
    fn apply_seed_skip_policy_ignores_unknown_and_merges_known_keys() {
        let store = StateStore::new();
        store.install_plugin(PersistenceTestPlugin).unwrap();

        let mut batch = store.begin_mutation();
        batch.update::<TransientFlag>(true);
        store.commit(batch).unwrap();

        let mut extensions = std::collections::HashMap::new();
        extensions.insert("unknown.key".to_string(), serde_json::json!("some_value"));
        extensions.insert(PersistentCounter::KEY.to_string(), serde_json::json!(44i64));
        let seed = PersistedState {
            revision: 0,
            extensions,
        };

        store.apply_seed(seed, UnknownKeyPolicy::Skip).unwrap();
        assert_eq!(
            store.read::<PersistentCounter>(),
            Some(44),
            "known keys should merge under skip policy"
        );
        assert_eq!(
            store.read::<TransientFlag>(),
            Some(true),
            "skip policy must still preserve unlisted state"
        );
    }

    #[test]
    fn import_unknown_key_with_skip_policy() {
        let store = StateStore::new();
        store.install_plugin(PersistenceTestPlugin).unwrap();

        // Build a PersistedState with an unknown key
        let mut extensions = std::collections::HashMap::new();
        extensions.insert("unknown.key".to_string(), serde_json::json!("some_value"));
        let persisted = PersistedState {
            revision: 5,
            extensions,
        };

        // Should succeed with Skip policy
        let result = store.restore_persisted(persisted, UnknownKeyPolicy::Skip);
        assert!(
            result.is_ok(),
            "skip policy should not error on unknown keys"
        );
    }
}