1use std::collections::BTreeMap;
5use std::fs;
6use std::io::Read;
7#[cfg(unix)]
8use std::io::Write;
9use std::path::{Path, PathBuf};
10
11use serde::{Deserialize, Serialize};
12
13use crate::core::agents::FileLock;
14use crate::core::work_graph::BoundedWorkGraph;
15
16const STORE_SCHEMA_VERSION: u16 = 1;
17const MAX_STORE_BYTES: u64 = 4 * 1024 * 1024;
18const MAX_GRAPHS: usize = 32;
19
20#[cfg(test)]
21thread_local! {
22 static FAIL_NEXT_SAVE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
23}
24
25#[cfg(test)]
26pub(crate) fn with_save_failure<T>(action: impl FnOnce() -> T) -> T {
27 struct Reset;
28 impl Drop for Reset {
29 fn drop(&mut self) {
30 FAIL_NEXT_SAVE.set(false);
31 }
32 }
33 let _reset = Reset;
34 FAIL_NEXT_SAVE.set(true);
35 action()
36}
37
38#[derive(Debug, Serialize, Deserialize)]
39#[serde(deny_unknown_fields)]
40pub struct WorkGraphStore {
41 schema_version: u16,
42 project_root_hash: String,
43 graphs: BTreeMap<String, BoundedWorkGraph>,
44}
45
46pub enum ClaimNodeExecution {
47 Claimed(Box<crate::core::work_graph::WorkNode>),
48 RecoveredExpired,
49}
50
51impl WorkGraphStore {
52 fn empty(project_root: &str) -> Self {
53 Self {
54 schema_version: STORE_SCHEMA_VERSION,
55 project_root_hash: crate::core::project_hash::hash_project_root(project_root),
56 graphs: BTreeMap::new(),
57 }
58 }
59
60 pub fn graph(&self, graph_id: &str) -> Option<&BoundedWorkGraph> {
61 self.graphs.get(graph_id)
62 }
63
64 pub(crate) fn child_delivery_authority(
67 &self,
68 certificate: &crate::core::a2a::task::delivery_delegation::DeliveryDelegationV1,
69 policy: &crate::core::a2a::task::TaskAuthorityConfigV1,
70 expected: &crate::core::a2a::task::TaskAuthorityExpectationV1<'_>,
71 ) -> Result<crate::core::a2a::task::TaskAuthorityConfigV1, String> {
72 use crate::core::a2a::task::delivery_delegation::DeliveryExecutionBindingV1;
73 let graph = self
74 .graph(&certificate.execution.graph_id)
75 .ok_or("delegated graph is missing")?;
76 let node = graph
77 .get_node(&certificate.execution.node_id)
78 .ok_or("delegated node is missing")?;
79 let now_ms = u64::try_from(expected.now.timestamp_millis())
80 .map_err(|_| "invalid verification time")?;
81 if node.status != crate::core::work_graph::NodeStatus::Active
82 || !node.execution_started
83 || node
84 .lease_expires_epoch_ms
85 .is_none_or(|expiry| expiry <= now_ms)
86 {
87 return Err("delegated execution is not live".into());
88 }
89 let fence = node
90 .execution_fence
91 .as_deref()
92 .ok_or("execution fence missing")?;
93 let attempt = node.delivery_attempt.ok_or("execution attempt missing")?;
94 let task = crate::core::work_graph_executor::execution_key_for_scope(
95 &self.project_root_hash,
96 graph.graph_id(),
97 &node.node_id,
98 fence,
99 )?;
100 let live = DeliveryExecutionBindingV1 {
101 graph_id: graph.graph_id().into(),
102 node_id: node.node_id.clone(),
103 fence: fence.into(),
104 task_id: format!("{task}:attempt-{attempt}"),
105 attempt,
106 };
107 let host = graph
108 .root_agent_for(&node.node_id)
109 .map_err(|error| error.to_string())?;
110 let expected_host = crate::core::a2a::task::TaskAuthorityExpectationV1 {
111 sender: host,
112 recipient: expected.recipient,
113 tenant_id: expected.tenant_id,
114 project_id: expected.project_id,
115 now: expected.now,
116 };
117 certificate
118 .verify_for_execution(policy, &expected_host, &live, &node.agent_id)
119 .map_err(|error| error.to_string())
120 }
121
122 pub fn graph_revision(&self, graph_id: &str) -> Result<String, String> {
125 validate_id(graph_id, "graph_id")?;
126 let graph = self
127 .graph(graph_id)
128 .ok_or_else(|| format!("graph not found: {graph_id}"))?;
129 let bytes = serde_json::to_vec(&(&self.project_root_hash, graph_id, graph))
130 .map_err(|error| error.to_string())?;
131 let mut hash = blake3::Hasher::new();
132 hash.update(b"lean-ctx:work-graph-write-revision:v1\0");
133 hash.update(&bytes);
134 Ok(hash.finalize().to_hex().to_string())
135 }
136
137 pub fn mutate_graph_if_revision<T>(
140 project_root: &str,
141 graph_id: &str,
142 expected_revision: &str,
143 mutate: impl FnOnce(&mut BoundedWorkGraph) -> Result<T, String>,
144 ) -> Result<T, String> {
145 if expected_revision.len() != 64
146 || !expected_revision
147 .bytes()
148 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
149 {
150 return Err("invalid work graph write revision".into());
151 }
152 Self::mutate(project_root, |store| {
153 if store.graph_revision(graph_id)? != expected_revision {
154 return Err("work graph revision conflict".into());
155 }
156 mutate(store.graph_mut(graph_id)?)
157 })
158 }
159
160 pub fn graph_ids(&self) -> impl Iterator<Item = &str> {
161 self.graphs.keys().map(String::as_str)
162 }
163
164 pub fn graph_ids_for_agent<'a>(&'a self, agent_id: &'a str) -> impl Iterator<Item = &'a str> {
165 self.graphs
166 .iter()
167 .filter(move |(_, graph)| graph.contains_agent(agent_id))
168 .map(|(graph_id, _)| graph_id.as_str())
169 }
170
171 pub fn create(&mut self, graph_id: &str, mut graph: BoundedWorkGraph) -> Result<(), String> {
172 validate_id(graph_id, "graph_id")?;
173 if self.graphs.contains_key(graph_id) {
174 return Err(format!("duplicate graph: {graph_id}"));
175 }
176 if self.graphs.len() >= MAX_GRAPHS {
177 return Err(format!("work graph store at capacity ({MAX_GRAPHS})"));
178 }
179 graph
180 .bind_graph_id(graph_id)
181 .map_err(|error| error.to_string())?;
182 self.graphs.insert(graph_id.to_string(), graph);
183 Ok(())
184 }
185
186 pub fn graph_mut(&mut self, graph_id: &str) -> Result<&mut BoundedWorkGraph, String> {
187 validate_id(graph_id, "graph_id")?;
188 self.graphs
189 .get_mut(graph_id)
190 .ok_or_else(|| format!("graph not found: {graph_id}"))
191 }
192
193 pub fn claim_node_execution(
194 &mut self,
195 graph_id: &str,
196 node_id: &str,
197 now_epoch_ms: u64,
198 lease_expires_epoch_ms: u64,
199 ) -> Result<ClaimNodeExecution, String> {
200 validate_id(graph_id, "graph_id")?;
201 validate_id(node_id, "node_id")?;
202 let requested = self
203 .graph(graph_id)
204 .and_then(|graph| graph.get_node(node_id))
205 .ok_or_else(|| format!("node not found: {node_id}"))?
206 .path_claims
207 .clone();
208 if !requested.is_empty()
209 && self.graphs.iter().any(|(candidate_graph_id, graph)| {
210 graph.has_live_path_conflict(
211 &requested,
212 now_epoch_ms,
213 (candidate_graph_id == graph_id).then_some(node_id),
214 )
215 })
216 {
217 return Err("path claim conflicts with a live work graph execution".into());
218 }
219 let execution_scope = self.project_root_hash.clone();
220 let graph = self.graph_mut(graph_id)?;
221 let stopped = graph
222 .recover_expired_execution(node_id, now_epoch_ms)
223 .map_err(|error| error.to_string())?;
224 if !stopped.is_empty() {
225 let cancellation_keys = stopped
226 .iter()
227 .filter_map(|stopped_id| {
228 graph
229 .get_node(stopped_id)
230 .and_then(|node| node.execution_fence.as_deref())
231 .map(|fence| {
232 crate::core::work_graph_executor::execution_key_for_scope(
233 &execution_scope,
234 graph_id,
235 stopped_id,
236 fence,
237 )
238 })
239 })
240 .collect::<Result<Vec<_>, _>>()?;
241 crate::core::agent_connector::timeout::request_cancellations(
242 cancellation_keys.iter().map(String::as_str),
243 )
244 .map_err(|error| error.to_string())?;
245 return Ok(ClaimNodeExecution::RecoveredExpired);
246 }
247 graph
248 .claim_or_resume_active_until(node_id, lease_expires_epoch_ms)
249 .cloned()
250 .map(Box::new)
251 .map(ClaimNodeExecution::Claimed)
252 .map_err(|error| error.to_string())
253 }
254
255 pub fn load(project_root: &str) -> Result<Self, String> {
256 let path = store_path(project_root)?;
257 let parent = path
258 .parent()
259 .ok_or_else(|| "invalid work graph path".to_string())?;
260 fs::create_dir_all(parent).map_err(|error| error.to_string())?;
261 reject_symlink(parent)?;
262 let _lock = FileLock::acquire(&path.with_extension("lock"))?;
263 load_at(&path, project_root)
264 }
265
266 pub(crate) fn execution_stop_requested(
269 project_root: &str,
270 graph_id: &str,
271 node_id: &str,
272 fence: &str,
273 ) -> Result<bool, String> {
274 let path = store_path(project_root)?;
275 #[cfg(unix)]
276 let store = {
277 let directory = open_parent_directory(&path).map_err(|error| error.to_string())?;
278 load_in_directory(&directory, &path, project_root)?
279 };
280 #[cfg(not(unix))]
281 let store = load_at(&path, project_root)?;
282 let node = store
283 .graph(graph_id)
284 .and_then(|graph| graph.get_node(node_id))
285 .ok_or_else(|| "watched execution is missing".to_string())?;
286 if node.execution_fence.as_deref() != Some(fence) || !node.execution_started {
287 return Err("watched execution fence is no longer current".into());
288 }
289 match node.status {
290 crate::core::work_graph::NodeStatus::Active => Ok(false),
291 crate::core::work_graph::NodeStatus::Stopped => Ok(true),
292 _ => Err("watched execution is no longer active".into()),
293 }
294 }
295
296 pub fn mutate<T>(
297 project_root: &str,
298 mutate: impl FnOnce(&mut Self) -> Result<T, String>,
299 ) -> Result<T, String> {
300 let path = store_path(project_root)?;
301 let parent = path
302 .parent()
303 .ok_or_else(|| "invalid work graph path".to_string())?;
304 fs::create_dir_all(parent).map_err(|error| error.to_string())?;
305 reject_symlink(parent)?;
306 #[cfg(unix)]
307 let directory = open_parent_directory(&path).map_err(|error| error.to_string())?;
308 let _lock = FileLock::acquire(&path.with_extension("lock"))?;
309 #[cfg(unix)]
310 let mut store = load_in_directory(&directory, &path, project_root)?;
311 #[cfg(not(unix))]
312 let mut store = load_at(&path, project_root)?;
313 let result = mutate(&mut store)?;
314 store.validate()?;
315 #[cfg(test)]
316 if FAIL_NEXT_SAVE.replace(false) {
317 return Err("injected work graph persistence failure".into());
318 }
319 #[cfg(unix)]
320 save_in_directory(&directory, &path, &store)?;
321 #[cfg(not(unix))]
322 save_at(&path, &store)?;
323 Ok(result)
324 }
325
326 fn validate(&self) -> Result<(), String> {
327 if self.graphs.len() > MAX_GRAPHS {
328 return Err(format!("work graph store exceeds {MAX_GRAPHS} graphs"));
329 }
330 for (graph_id, graph) in &self.graphs {
331 validate_id(graph_id, "graph_id")?;
332 if graph.graph_id() != graph_id {
333 return Err("work graph key/id mismatch".to_string());
334 }
335 graph
336 .validate_invariants()
337 .map_err(|error| error.to_string())?;
338 }
339 Ok(())
340 }
341}
342
343pub fn validate_id(value: &str, field: &str) -> Result<(), String> {
344 if value.is_empty()
345 || value.len() > 128
346 || !value
347 .bytes()
348 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
349 {
350 return Err(format!(
351 "invalid {field}: expected 1..=128 ASCII [A-Za-z0-9._-]"
352 ));
353 }
354 Ok(())
355}
356
357fn store_path(project_root: &str) -> Result<PathBuf, String> {
358 let hash = crate::core::project_hash::hash_project_root(project_root);
359 Ok(crate::core::paths::state_dir()?
360 .join("work-graphs")
361 .join(format!("{hash}.json")))
362}
363
364fn load_at(path: &Path, project_root: &str) -> Result<WorkGraphStore, String> {
365 let bytes = match read_bounded_regular_nofollow(path) {
366 Ok(bytes) => bytes,
367 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
368 return Ok(WorkGraphStore::empty(project_root));
369 }
370 Err(error) => return Err(error.to_string()),
371 };
372 let mut store: WorkGraphStore =
373 serde_json::from_slice(&bytes).map_err(|error| error.to_string())?;
374 let expected = crate::core::project_hash::hash_project_root(project_root);
375 if store.schema_version != STORE_SCHEMA_VERSION || store.project_root_hash != expected {
376 return Err("work graph store scope or schema mismatch".to_string());
377 }
378 for (graph_id, graph) in &mut store.graphs {
379 graph
380 .bind_graph_id(graph_id)
381 .map_err(|error| error.to_string())?;
382 }
383 store.validate()?;
384 Ok(store)
385}
386
387#[cfg(unix)]
388fn load_in_directory(
389 directory: &fs::File,
390 path: &Path,
391 project_root: &str,
392) -> Result<WorkGraphStore, String> {
393 let leaf = path
394 .file_name()
395 .ok_or_else(|| "work graph store has no filename".to_string())?;
396 let bytes = match read_bounded_regular_from_directory(directory, leaf) {
397 Ok(bytes) => bytes,
398 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
399 return Ok(WorkGraphStore::empty(project_root));
400 }
401 Err(error) => return Err(error.to_string()),
402 };
403 decode_store(&bytes, project_root)
404}
405
406#[cfg(unix)]
407fn decode_store(bytes: &[u8], project_root: &str) -> Result<WorkGraphStore, String> {
408 let mut store: WorkGraphStore =
409 serde_json::from_slice(bytes).map_err(|error| error.to_string())?;
410 let expected = crate::core::project_hash::hash_project_root(project_root);
411 if store.schema_version != STORE_SCHEMA_VERSION || store.project_root_hash != expected {
412 return Err("work graph store scope or schema mismatch".to_string());
413 }
414 for (graph_id, graph) in &mut store.graphs {
415 graph
416 .bind_graph_id(graph_id)
417 .map_err(|error| error.to_string())?;
418 }
419 store.validate()?;
420 Ok(store)
421}
422
423#[cfg(unix)]
424fn read_bounded_regular_nofollow(path: &Path) -> std::io::Result<Vec<u8>> {
425 let leaf = path
426 .file_name()
427 .ok_or_else(|| std::io::Error::other("work graph store has no filename"))?;
428 let directory = open_parent_directory(path)?;
429 read_bounded_regular_from_directory(&directory, leaf)
430}
431
432#[cfg(unix)]
433fn open_parent_directory(path: &Path) -> std::io::Result<fs::File> {
434 use std::os::unix::fs::OpenOptionsExt;
435 let parent = path
436 .parent()
437 .ok_or_else(|| std::io::Error::other("work graph store has no parent"))?;
438 fs::OpenOptions::new()
439 .read(true)
440 .custom_flags(libc::O_CLOEXEC | libc::O_NOFOLLOW | libc::O_DIRECTORY)
441 .open(parent)
442}
443
444#[cfg(unix)]
445fn read_bounded_regular_from_directory(
446 directory: &fs::File,
447 leaf: &std::ffi::OsStr,
448) -> std::io::Result<Vec<u8>> {
449 use std::ffi::CString;
450 use std::os::fd::{AsRawFd, FromRawFd};
451 use std::os::unix::ffi::OsStrExt;
452
453 let leaf = CString::new(leaf.as_bytes())
454 .map_err(|_| std::io::Error::other("work graph filename contains NUL"))?;
455 let fd = unsafe {
457 libc::openat(
458 directory.as_raw_fd(),
459 leaf.as_ptr(),
460 libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW | libc::O_NONBLOCK,
461 )
462 };
463 if fd < 0 {
464 return Err(std::io::Error::last_os_error());
465 }
466 let file = unsafe { fs::File::from_raw_fd(fd) };
468 read_opened_store(file)
469}
470
471#[cfg(not(unix))]
472fn read_bounded_regular_nofollow(path: &Path) -> std::io::Result<Vec<u8>> {
473 if let Ok(metadata) = fs::symlink_metadata(path) {
474 if crate::core::pathutil::is_symlink_or_reparse(&metadata) {
475 return Err(std::io::Error::other("refusing linked work graph store"));
476 }
477 }
478 read_opened_store(fs::OpenOptions::new().read(true).open(path)?)
479}
480
481fn read_opened_store(mut file: fs::File) -> std::io::Result<Vec<u8>> {
482 let before = file.metadata()?;
483 if !before.file_type().is_file() {
484 return Err(std::io::Error::other(
485 "work graph store must be a regular file",
486 ));
487 }
488 if before.len() > MAX_STORE_BYTES {
489 return Err(std::io::Error::other(format!(
490 "work graph store exceeds {MAX_STORE_BYTES} bytes"
491 )));
492 }
493 let mut bytes = Vec::with_capacity(before.len() as usize);
494 (&mut file)
495 .take(MAX_STORE_BYTES + 1)
496 .read_to_end(&mut bytes)?;
497 if bytes.len() as u64 > MAX_STORE_BYTES {
498 return Err(std::io::Error::other(format!(
499 "work graph store exceeds {MAX_STORE_BYTES} bytes"
500 )));
501 }
502 let after = file.metadata()?;
503 if before.len() != after.len()
504 || before
505 .modified()
506 .ok()
507 .zip(after.modified().ok())
508 .is_some_and(|(before, after)| before != after)
509 {
510 return Err(std::io::Error::other(
511 "work graph store changed during read",
512 ));
513 }
514 Ok(bytes)
515}
516
517#[cfg(not(unix))]
518fn save_at(path: &Path, store: &WorkGraphStore) -> Result<(), String> {
519 let bytes = serde_json::to_vec(store).map_err(|error| error.to_string())?;
520 if bytes.len() as u64 > MAX_STORE_BYTES {
521 return Err(format!("work graph store exceeds {MAX_STORE_BYTES} bytes"));
522 }
523 #[cfg(unix)]
524 {
525 secure_atomic_write_nofollow(path, &bytes).map_err(|error| error.to_string())
526 }
527 #[cfg(not(unix))]
528 {
529 crate::core::atomic_fs::try_atomic_write(path, &bytes, None)
530 .map_err(|error| error.to_string())
531 }
532}
533
534#[cfg(unix)]
535fn save_in_directory(
536 directory: &fs::File,
537 path: &Path,
538 store: &WorkGraphStore,
539) -> Result<(), String> {
540 let bytes = serde_json::to_vec(store).map_err(|error| error.to_string())?;
541 if bytes.len() as u64 > MAX_STORE_BYTES {
542 return Err(format!("work graph store exceeds {MAX_STORE_BYTES} bytes"));
543 }
544 let leaf = path
545 .file_name()
546 .ok_or_else(|| "work graph store has no filename".to_string())?;
547 secure_atomic_write_in_directory(directory, leaf, &bytes).map_err(|error| error.to_string())
548}
549
550#[cfg(unix)]
551fn secure_atomic_write_in_directory(
552 directory: &fs::File,
553 leaf: &std::ffi::OsStr,
554 bytes: &[u8],
555) -> std::io::Result<()> {
556 use std::ffi::CString;
557 use std::os::fd::{AsRawFd, FromRawFd};
558 use std::os::unix::ffi::OsStrExt;
559 use std::time::{SystemTime, UNIX_EPOCH};
560
561 let leaf = CString::new(leaf.as_bytes())
562 .map_err(|_| std::io::Error::other("work graph filename contains NUL"))?;
563 let nonce = SystemTime::now()
564 .duration_since(UNIX_EPOCH)
565 .map_or(0, |duration| duration.as_nanos());
566 let temp = CString::new(format!(".work-graph.tmp.{}.{}", std::process::id(), nonce))
567 .expect("generated work graph temp name contains no NUL");
568 let directory_fd = directory.as_raw_fd();
569 let temp_fd = unsafe {
571 libc::openat(
572 directory_fd,
573 temp.as_ptr(),
574 libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_CLOEXEC | libc::O_NOFOLLOW,
575 0o600,
576 )
577 };
578 if temp_fd < 0 {
579 return Err(std::io::Error::last_os_error());
580 }
581 let mut file = unsafe { fs::File::from_raw_fd(temp_fd) };
583 let write_result = (|| {
584 file.write_all(bytes)?;
585 file.sync_all()?;
586 if unsafe { libc::fchmod(file.as_raw_fd(), 0o600) } != 0 {
588 return Err(std::io::Error::last_os_error());
589 }
590 if unsafe { libc::renameat(directory_fd, temp.as_ptr(), directory_fd, leaf.as_ptr()) } != 0
592 {
593 return Err(std::io::Error::last_os_error());
594 }
595 directory.sync_all()
596 })();
597 if write_result.is_err() {
598 unsafe {
600 libc::unlinkat(directory_fd, temp.as_ptr(), 0);
601 }
602 }
603 write_result
604}
605
606fn reject_symlink(path: &Path) -> Result<(), String> {
607 let metadata = fs::symlink_metadata(path).map_err(|error| error.to_string())?;
608 if metadata.file_type().is_symlink() {
609 return Err(format!(
610 "refusing symlink work graph path: {}",
611 path.display()
612 ));
613 }
614 Ok(())
615}
616
617#[cfg(test)]
618mod tests {
619 use super::*;
620 use crate::core::work_graph::WorkNodeBudget;
621
622 fn graph_with_claim(root: &str, child: &str, claim: &str) -> BoundedWorkGraph {
623 let mut graph = BoundedWorkGraph::default();
624 graph
625 .add_root(
626 root.into(),
627 format!("{root}-agent"),
628 format!("capsule:{root}"),
629 WorkNodeBudget {
630 tokens_allocated: 100,
631 tokens_consumed: 0,
632 cost_micros_allocated: 100,
633 cost_micros_consumed: 0,
634 },
635 )
636 .unwrap();
637 graph
638 .queue_child(
639 root,
640 child.into(),
641 format!("{child}-agent"),
642 format!("capsule:{child}"),
643 WorkNodeBudget {
644 tokens_allocated: 20,
645 tokens_consumed: 0,
646 cost_micros_allocated: 20,
647 cost_micros_consumed: 0,
648 },
649 )
650 .unwrap();
651 graph.set_path_claims(child, vec![claim.into()]).unwrap();
652 graph
653 }
654
655 #[test]
656 fn write_revision_detects_hidden_changes_and_rejects_stale_mutation() {
657 let isolated = crate::core::data_dir::isolated_data_dir();
658 let project = isolated.path().to_str().unwrap();
659 WorkGraphStore::mutate(project, |store| {
660 store.create("graph", graph_with_claim("root", "child", "path:src/old"))
661 })
662 .unwrap();
663 let before = WorkGraphStore::load(project).unwrap();
664 let revision = before.graph_revision("graph").unwrap();
665 let observation = before.graph("graph").unwrap().observation();
666 WorkGraphStore::mutate_graph_if_revision(project, "graph", &revision, |graph| {
667 graph
668 .set_path_claims("child", vec!["path:src/new".into()])
669 .map_err(|error| error.to_string())
670 })
671 .unwrap();
672 let after = WorkGraphStore::load(project).unwrap();
673 assert_eq!(observation, after.graph("graph").unwrap().observation());
674 assert_ne!(revision, after.graph_revision("graph").unwrap());
675 let mut invoked = false;
676 let result = WorkGraphStore::mutate_graph_if_revision(project, "graph", &revision, |_| {
677 invoked = true;
678 Ok(())
679 });
680 assert_eq!(result.unwrap_err(), "work graph revision conflict");
681 assert!(!invoked);
682 assert_eq!(
683 after.graph_revision("graph").unwrap(),
684 WorkGraphStore::load(project)
685 .unwrap()
686 .graph_revision("graph")
687 .unwrap()
688 );
689 }
690
691 #[test]
692 fn ids_are_bounded_and_path_safe() {
693 assert!(validate_id("graph-1.node", "graph_id").is_ok());
694 assert!(validate_id("../escape", "graph_id").is_err());
695 assert!(validate_id("", "graph_id").is_err());
696 assert!(validate_id(&"a".repeat(129), "graph_id").is_err());
697 }
698
699 #[cfg(unix)]
700 #[test]
701 fn durable_cancel_writer_process() {
702 let Some(path) = std::env::var_os("LEANCTX_TEST_CANCEL_STORE") else {
703 return;
704 };
705 let project = std::env::var("LEANCTX_TEST_CANCEL_PROJECT").unwrap();
706 std::thread::sleep(std::time::Duration::from_millis(150));
707 let path = PathBuf::from(path);
708 let mut store = load_at(&path, &project).unwrap();
709 store
710 .graph_mut("graph")
711 .unwrap()
712 .stop("child", crate::core::work_graph::StopReason::ManualStop)
713 .unwrap();
714 let directory = open_parent_directory(&path).unwrap();
715 save_in_directory(&directory, &path, &store).unwrap();
716 }
717
718 #[cfg(unix)]
719 #[test]
720 fn durable_cancel_observes_another_process_and_reaps_owned_child() {
721 let _isolation = crate::core::data_dir::isolated_data_dir();
722 let project_dir = tempfile::tempdir().unwrap();
723 let project = project_dir.path().to_str().unwrap();
724 let fence = WorkGraphStore::mutate(project, |store| {
725 store.create(
726 "graph",
727 graph_with_claim("root", "child", "path:src/owned.rs"),
728 )?;
729 let ClaimNodeExecution::Claimed(node) =
730 store.claim_node_execution("graph", "child", 1, u64::MAX)?
731 else {
732 return Err("fixture claim failed".into());
733 };
734 Ok(node.execution_fence.unwrap())
735 })
736 .unwrap();
737 let path = store_path(project).unwrap();
738 let _writer_lock = FileLock::acquire(&path.with_extension("lock")).unwrap();
740 assert!(
741 !WorkGraphStore::execution_stop_requested(project, "graph", "child", &fence).unwrap()
742 );
743 assert!(
744 WorkGraphStore::execution_stop_requested(project, "graph", "child", "stale").is_err()
745 );
746 let _watch = crate::core::agent_connector::timeout::durable::Guard::install(
747 project, "graph", "child", &fence,
748 )
749 .unwrap();
750 let mut writer = std::process::Command::new(std::env::current_exe().unwrap())
751 .args([
752 "--exact",
753 "core::work_graph_store::tests::durable_cancel_writer_process",
754 "--nocapture",
755 ])
756 .env("LEANCTX_TEST_CANCEL_STORE", &path)
757 .env("LEANCTX_TEST_CANCEL_PROJECT", project)
758 .spawn()
759 .unwrap();
760 let key = crate::core::work_graph_executor::execution_key(
761 project_dir.path(),
762 "graph",
763 "child",
764 &fence,
765 )
766 .unwrap();
767 let marker = project_dir.path().join("descendant-survived");
768 let mut command = std::process::Command::new("sh");
769 command
770 .args([
771 "-c",
772 "(sleep 1; printf leaked > \"$1\") & wait",
773 "cancel-test",
774 ])
775 .arg(&marker);
776 let output = crate::core::agent_connector::timeout::run_with_timeout_cancellable(
777 &mut command,
778 5_000,
779 Some(&format!("{key}:attempt-1")),
780 )
781 .unwrap();
782 assert!(writer.wait().unwrap().success());
783 assert!(output.cancelled);
784 assert!(!output.timed_out);
785 assert!(
786 WorkGraphStore::execution_stop_requested(project, "graph", "child", &fence).unwrap()
787 );
788 std::thread::sleep(std::time::Duration::from_millis(1100));
789 assert!(!marker.exists(), "cancelled descendant continued running");
790 }
791
792 #[cfg(unix)]
793 #[test]
794 fn durable_cancel_corrupt_snapshot_is_failure_not_acknowledgement() {
795 let _isolation = crate::core::data_dir::isolated_data_dir();
796 let directory = tempfile::tempdir().unwrap();
797 let project = directory.path().to_str().unwrap();
798 let fence = WorkGraphStore::mutate(project, |store| {
799 store.create(
800 "graph",
801 graph_with_claim("root", "child", "path:src/owned.rs"),
802 )?;
803 let ClaimNodeExecution::Claimed(node) =
804 store.claim_node_execution("graph", "child", 1, u64::MAX)?
805 else {
806 return Err("fixture claim failed".into());
807 };
808 Ok(node.execution_fence.unwrap())
809 })
810 .unwrap();
811 let watch = crate::core::agent_connector::timeout::durable::Guard::install(
812 project, "graph", "child", &fence,
813 )
814 .unwrap();
815 assert!(
816 crate::core::agent_connector::timeout::durable::Guard::install(
817 project, "graph", "child", &fence
818 )
819 .is_err()
820 );
821 let key = crate::core::work_graph_executor::execution_key(
822 directory.path(),
823 "graph",
824 "child",
825 &fence,
826 )
827 .unwrap();
828 fs::write(store_path(project).unwrap(), b"{malformed").unwrap();
829 let mut command = std::process::Command::new("sh");
830 command.args(["-c", "sleep 2"]);
831 let result = crate::core::agent_connector::timeout::run_with_timeout_cancellable(
832 &mut command,
833 5_000,
834 Some(&key),
835 );
836 let Err(error) = result else {
837 panic!("corrupt snapshot must not report cancellation success");
838 };
839 assert!(
840 error
841 .to_string()
842 .contains("durable cancellation observation failed")
843 );
844 assert!(error.to_string().contains("child reaped"));
845 drop(watch);
846 let mut command = std::process::Command::new("sh");
847 command.args(["-c", "printf done"]);
848 let output = crate::core::agent_connector::timeout::run_with_timeout_cancellable(
849 &mut command,
850 1_000,
851 Some(&key),
852 )
853 .unwrap();
854 assert!(!output.cancelled);
855 assert_eq!(output.output.stdout, b"done");
856 }
857
858 #[test]
859 fn store_round_trip_preserves_project_scope_and_graph() {
860 let temp = tempfile::tempdir().expect("tempdir");
861 let path = temp.path().join("graph.json");
862 let mut store = WorkGraphStore::empty("/project/a");
863 let mut graph = BoundedWorkGraph::default();
864 graph
865 .add_root(
866 "root".to_string(),
867 "agent-1".to_string(),
868 "capsule:sha256:abc".to_string(),
869 WorkNodeBudget {
870 tokens_allocated: 100,
871 tokens_consumed: 0,
872 cost_micros_allocated: 50,
873 cost_micros_consumed: 0,
874 },
875 )
876 .expect("root");
877 store.create("graph-1", graph).expect("create");
878 #[cfg(unix)]
879 {
880 let directory = open_parent_directory(&path).expect("parent");
881 save_in_directory(&directory, &path, &store).expect("save");
882 }
883 #[cfg(not(unix))]
884 save_at(&path, &store).expect("save");
885
886 let loaded = load_at(&path, "/project/a").expect("load");
887 assert_eq!(loaded.graph("graph-1").expect("graph").total_count(), 1);
888 assert!(load_at(&path, "/project/b").is_err());
889 }
890
891 #[cfg(unix)]
892 #[test]
893 fn store_rejects_symlink_target() {
894 use std::os::unix::fs::symlink;
895
896 let temp = tempfile::tempdir().expect("tempdir");
897 let target = temp.path().join("target.json");
898 fs::write(&target, b"{}").expect("target");
899 let link = temp.path().join("graph.json");
900 symlink(&target, &link).expect("symlink");
901 assert!(load_at(&link, "/project/a").is_err());
902 }
903
904 #[cfg(unix)]
905 #[test]
906 fn store_rejects_symlink_parent_directory() {
907 use std::os::unix::fs::symlink;
908
909 let temp = tempfile::tempdir().expect("tempdir");
910 let target = temp.path().join("target");
911 fs::create_dir(&target).expect("target dir");
912 fs::write(target.join("graph.json"), b"{}").expect("target");
913 let link = temp.path().join("linked-parent");
914 symlink(&target, &link).expect("symlink");
915 assert!(load_at(&link.join("graph.json"), "/project/a").is_err());
916 }
917
918 #[test]
919 fn store_rejects_oversized_regular_file_before_allocation() {
920 let temp = tempfile::tempdir().expect("tempdir");
921 let path = temp.path().join("graph.json");
922 let file = fs::File::create(&path).expect("file");
923 file.set_len(MAX_STORE_BYTES + 1).expect("set length");
924 assert!(load_at(&path, "/project/a").is_err());
925 }
926
927 #[cfg(unix)]
928 #[test]
929 fn store_rejects_fifo_without_blocking() {
930 use std::ffi::CString;
931 use std::os::unix::ffi::OsStrExt;
932
933 let temp = tempfile::tempdir().expect("tempdir");
934 let path = temp.path().join("graph.fifo");
935 let raw = CString::new(path.as_os_str().as_bytes()).expect("path");
936 assert_eq!(unsafe { libc::mkfifo(raw.as_ptr(), 0o600) }, 0);
938 assert!(load_at(&path, "/project/a").is_err());
939 }
940
941 #[cfg(unix)]
942 #[test]
943 fn store_write_stays_with_held_parent_after_path_replacement() {
944 use std::os::unix::fs::{OpenOptionsExt, symlink};
945
946 let temp = tempfile::tempdir().expect("tempdir");
947 let parent = temp.path().join("store");
948 let relocated = temp.path().join("relocated");
949 let attacker = temp.path().join("attacker");
950 fs::create_dir(&parent).expect("parent");
951 fs::create_dir(&attacker).expect("attacker");
952 let directory = fs::OpenOptions::new()
953 .read(true)
954 .custom_flags(libc::O_CLOEXEC | libc::O_NOFOLLOW | libc::O_DIRECTORY)
955 .open(&parent)
956 .expect("held parent");
957 let store = WorkGraphStore::empty("/project/a");
958 save_in_directory(&directory, &parent.join("graph.json"), &store).expect("initial store");
959 let loaded = load_in_directory(&directory, &parent.join("graph.json"), "/project/a")
960 .expect("load through held directory");
961 fs::rename(&parent, &relocated).expect("replace parent");
962 symlink(&attacker, &parent).expect("attacker symlink");
963
964 save_in_directory(&directory, &parent.join("graph.json"), &loaded)
965 .expect("write through held directory");
966
967 assert!(load_at(&relocated.join("graph.json"), "/project/a").is_ok());
968 assert!(!attacker.join("graph.json").exists());
969 }
970
971 #[test]
972 fn store_serializes_overlapping_path_claims_across_graphs() {
973 let mut store = WorkGraphStore::empty("/project/a");
974 store
975 .create(
976 "g1",
977 graph_with_claim("root1", "child1", "path:project/src"),
978 )
979 .unwrap();
980 store
981 .create(
982 "g2",
983 graph_with_claim("root2", "child2", "path:project/src/lib.rs"),
984 )
985 .unwrap();
986
987 store.claim_node_execution("g1", "child1", 10, 100).unwrap();
988 assert!(store.claim_node_execution("g2", "child2", 10, 100).is_err());
989 assert!(matches!(
990 store
991 .claim_node_execution("g1", "child1", 100, 200)
992 .unwrap(),
993 ClaimNodeExecution::RecoveredExpired
994 ));
995 assert_eq!(
996 store
997 .graph("g1")
998 .unwrap()
999 .get_node("child1")
1000 .unwrap()
1001 .status,
1002 crate::core::work_graph::NodeStatus::Stopped
1003 );
1004 assert!(
1005 store
1006 .claim_node_execution("g2", "child2", 100, 200)
1007 .is_err(),
1008 "lease expiry is not evidence of process exit"
1009 );
1010 let graph = store.graph_mut("g1").unwrap();
1011 let fence = graph
1012 .get_node("child1")
1013 .unwrap()
1014 .execution_fence
1015 .clone()
1016 .unwrap();
1017 assert!(
1018 graph
1019 .acknowledge_execution_exit("child1", "stale-fence")
1020 .is_err()
1021 );
1022 graph.acknowledge_execution_exit("child1", &fence).unwrap();
1023 graph.acknowledge_execution_exit("child1", &fence).unwrap();
1024 let bytes = serde_json::to_vec(&store).unwrap();
1025 let mut store: WorkGraphStore = serde_json::from_slice(&bytes).unwrap();
1026 store.validate().unwrap();
1027 assert!(store.claim_node_execution("g2", "child2", 100, 200).is_ok());
1028 assert_eq!(
1029 store
1030 .graph("g2")
1031 .unwrap()
1032 .get_node("child2")
1033 .unwrap()
1034 .status,
1035 crate::core::work_graph::NodeStatus::Active
1036 );
1037 }
1038}