scope-lock -> pod-registry

This commit is contained in:
2026-04-29 20:01:32 +09:00
parent 1aa06dba60
commit 8a8fd225bf
22 changed files with 128 additions and 132 deletions
+1 -1
View File
@@ -12,7 +12,7 @@ session-store = { version = "0.1.0", path = "../session-store" }
manifest = { version = "0.1.0", path = "../manifest" }
protocol = { version = "0.1.0", path = "../protocol" }
provider = { version = "0.1.0", path = "../provider" }
scope-lock = { version = "0.1.0", path = "../scope-lock" }
pod-registry = { version = "0.1.0", path = "../pod-registry" }
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.149"
thiserror = "2.0"
+6 -6
View File
@@ -8,7 +8,7 @@
//! logging failures without blocking the child.
//! - **Render** a variant into a human-readable string that the parent's
//! LLM sees via the notification buffer.
//! - **Apply side effects** on the parent (registry / scope-lock
//! - **Apply side effects** on the parent (registry / pod-registry
//! updates) so that the receive path is idempotent and tolerant of
//! out-of-order delivery.
//!
@@ -27,7 +27,7 @@ use std::sync::Arc;
use protocol::{Method, PodEvent, ScopeRule};
use crate::runtime::dir::SpawnedPodRecord;
use crate::runtime::scope_lock::{self, ScopeLockError};
use crate::runtime::pod_registry::{self, ScopeLockError};
use crate::spawn::comm_tools::connect_and_send;
use crate::spawn::registry::SpawnedPodRegistry;
@@ -146,21 +146,21 @@ pub async fn apply_event_side_effects(
}
fn release_scope_silently(pod_name: &str) {
let lock_path = match scope_lock::default_lock_path() {
let lock_path = match pod_registry::default_registry_path() {
Ok(p) => p,
Err(e) => {
tracing::warn!(error = %e, "default_lock_path failed");
tracing::warn!(error = %e, "default_registry_path failed");
return;
}
};
let mut guard = match scope_lock::LockFileGuard::open(&lock_path) {
let mut guard = match pod_registry::LockFileGuard::open(&lock_path) {
Ok(g) => g,
Err(e) => {
tracing::warn!(error = %e, "LockFileGuard open failed");
return;
}
};
match scope_lock::release_pod(&mut guard, pod_name) {
match pod_registry::release_pod(&mut guard, pod_name) {
Ok(()) => {}
Err(ScopeLockError::UnknownPod(_)) => {}
Err(e) => tracing::warn!(error = ?e, pod = %pod_name, "release_pod failed"),
+1 -1
View File
@@ -46,7 +46,7 @@ struct Cli {
/// Restore a Pod from an existing session. The Pod re-uses the
/// given session id and appends new turns to the same jsonl;
/// concurrent writers are prevented by the `scope.lock` registry.
/// concurrent writers are prevented by the pod-registry.
/// Mutually exclusive with `--adopt` (spawned children always start
/// fresh).
#[arg(long, value_name = "UUID", conflicts_with = "adopt")]
+14 -14
View File
@@ -26,7 +26,7 @@ use crate::prompt::catalog::{CatalogError, PromptCatalog};
use crate::prompt::loader::PromptLoader;
use crate::prompt::system::{SystemPromptContext, SystemPromptError, SystemPromptTemplate};
use crate::runtime::dir;
use crate::runtime::scope_lock::{self, ScopeAllocationGuard, ScopeLockError};
use crate::runtime::pod_registry::{self, ScopeAllocationGuard, ScopeLockError};
use async_trait::async_trait;
use llm_worker::interceptor::PreRequestAction;
use protocol::{AlertLevel, AlertSource, Event, Segment};
@@ -727,11 +727,11 @@ impl<C: LlmClient, St: Store> Pod<C, St> {
)
.await?;
// ensure_head_or_fork mints a fresh session_id when it auto-
// forks. Sync that to scope.lock so a concurrent
// forks. Sync that to pods.json so a concurrent
// restore_from_manifest can't see "no live writer" for the new
// session and grab it.
if self.session_id != prev_session_id && self.scope_allocation.is_some() {
scope_lock::update_session(&self.manifest.pod.name, self.session_id)?;
pod_registry::update_session(&self.manifest.pod.name, self.session_id)?;
}
Ok(())
}
@@ -1164,14 +1164,14 @@ impl<C: LlmClient, St: Store> Pod<C, St> {
// until its first LLM call.
self.session_id = new_session_id;
self.head_hash = Some(new_head_hash);
// Keep scope.lock pointing at the live session_id. Without this
// Keep pods.json pointing at the live session_id. Without this
// a concurrent `restore_from_manifest(new_session_id)` would
// see no live writer and grab the session this Pod just moved
// into, causing two writers to race on the same jsonl. Skipped
// when no allocation is installed (e.g. compact under
// `Pod::new` in tests).
if self.scope_allocation.is_some() {
scope_lock::update_session(&self.manifest.pod.name, new_session_id)?;
pod_registry::update_session(&self.manifest.pod.name, new_session_id)?;
}
let worker = self.worker.as_mut().unwrap();
worker.set_history(new_history);
@@ -1493,18 +1493,18 @@ impl<St: Store> Pod<Box<dyn LlmClient>, St> {
// Session creation is deferred to the first run (see
// `ensure_session_head`) so the SessionStart entry can capture
// the rendered system prompt, not the raw template source. The
// session_id is allocated here so the scope-lock registration
// session_id is allocated here so the pod-registry registration
// can record it from the start.
let session_id = session_store::new_session_id();
// Register this Pod in the machine-wide scope-lock registry
// Register this Pod in the machine-wide pod-registry
// before building anything else, so a spawn that conflicts on
// scope fails fast.
let socket_path = dir::default_base()
.map_err(ScopeLockError::from)?
.join(&manifest.pod.name)
.join("sock");
let scope_allocation = scope_lock::install_top_level(
let scope_allocation = pod_registry::install_top_level(
manifest.pod.name.clone(),
std::process::id(),
socket_path,
@@ -1548,7 +1548,7 @@ impl<St: Store> Pod<Box<dyn LlmClient>, St> {
///
/// Behaves like [`Pod::from_manifest`] but claims the scope
/// allocation that the spawner pre-registered via
/// [`scope_lock::delegate_scope`], rather than installing a new
/// [`pod_registry::delegate_scope`], rather than installing a new
/// top-level entry. `callback_socket` carries the spawner's
/// Unix-socket path so the spawned Pod can send `Method::Notify`
/// back to the spawner.
@@ -1562,7 +1562,7 @@ impl<St: Store> Pod<Box<dyn LlmClient>, St> {
let session_id = session_store::new_session_id();
let scope_allocation =
scope_lock::adopt_allocation(manifest.pod.name.clone(), std::process::id(), session_id)?;
pod_registry::adopt_allocation(manifest.pod.name.clone(), std::process::id(), session_id)?;
let mut worker = Worker::new(common.client);
apply_worker_manifest(&mut worker, &manifest.worker);
@@ -1599,14 +1599,14 @@ impl<St: Store> Pod<Box<dyn LlmClient>, St> {
/// Restore a Pod from an existing session log.
///
/// Resolves the manifest cascade exactly like [`Self::from_manifest`]
/// (pwd / scope / scope-lock / client / prompt catalog), seeds a
/// (pwd / scope / pod-registry / client / prompt catalog), seeds a
/// fresh Worker from the source session's `RestoredState`, and
/// reuses the same `session_id` so subsequent turns append to the
/// source jsonl as a continuation of the same conversation.
///
/// Concurrent writers are prevented by the `scope.lock` registry:
/// Concurrent writers are prevented by the pod-registry:
/// the registration carries `session_id`, and this constructor
/// refuses to start when `scope_lock::lookup_session` already finds
/// refuses to start when `pod_registry::lookup_session` already finds
/// a live Pod writing to `session_id`. So there is no need to fork —
/// resume is "the same session, a different process owning it".
///
@@ -1636,7 +1636,7 @@ impl<St: Store> Pod<Box<dyn LlmClient>, St> {
.map_err(ScopeLockError::from)?
.join(&manifest.pod.name)
.join("sock");
let scope_allocation = scope_lock::install_top_level(
let scope_allocation = pod_registry::install_top_level(
manifest.pod.name.clone(),
std::process::id(),
socket_path,
+1 -1
View File
@@ -11,7 +11,7 @@ use crate::shared_state::PodSharedState;
///
/// Written by the spawner after a successful `SpawnPod` tool call so
/// `ListPods` (future ticket) and a restored spawner can enumerate
/// their live children without re-querying `scope.lock`.
/// their live children without re-querying `pods.json`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpawnedPodRecord {
/// Spawned Pod's identity.
+1 -1
View File
@@ -1,2 +1,2 @@
pub mod dir;
pub use ::scope_lock;
pub use ::pod_registry;
+5 -5
View File
@@ -22,7 +22,7 @@ use serde::Deserialize;
use tokio::net::UnixStream;
use crate::runtime::dir::SpawnedPodRecord;
use crate::runtime::scope_lock::{self, LockFileGuard};
use crate::runtime::pod_registry::{self, LockFileGuard};
use crate::spawn::registry::SpawnedPodRegistry;
/// Timeout applied to each socket-level operation — connect, write,
@@ -283,10 +283,10 @@ impl Tool for ListPodsTool {
// allocation table doesn't keep growing indefinitely when
// children crash without a clean exit path.
if !stale_names.is_empty() {
if let Ok(lock_path) = scope_lock::default_lock_path()
if let Ok(lock_path) = pod_registry::default_registry_path()
&& let Ok(mut guard) = LockFileGuard::open(&lock_path)
{
scope_lock::reclaim_stale(&mut guard);
pod_registry::reclaim_stale(&mut guard);
}
}
@@ -475,11 +475,11 @@ fn summarize_scope(record: &SpawnedPodRecord) -> String {
/// effects (Method::Shutdown was sent), and stale-reclaim will clean
/// up whatever we couldn't.
fn release_scope(pod_name: &str) {
let Ok(lock_path) = scope_lock::default_lock_path() else {
let Ok(lock_path) = pod_registry::default_registry_path() else {
return;
};
let Ok(mut guard) = LockFileGuard::open(&lock_path) else {
return;
};
let _ = scope_lock::release_pod(&mut guard, pod_name);
let _ = pod_registry::release_pod(&mut guard, pod_name);
}
+9 -9
View File
@@ -1,9 +1,9 @@
//! `SpawnPod` tool — launch a new Pod process as a child of this one.
//!
//! Wires scope-lock delegation, overlay-TOML construction, subprocess
//! Wires pod-registry delegation, overlay-TOML construction, subprocess
//! launch, and socket handoff into a single `Tool` implementation. When
//! the LLM calls `SpawnPod`, a fresh `pod` binary is exec'd in its own
//! process group, the scope lock is updated atomically, and the child's
//! process group, the pod-registry is updated atomically, and the child's
//! first turn is kicked off by handing its socket a `Method::Run`.
use std::path::{Path, PathBuf};
@@ -26,7 +26,7 @@ use tokio::time::sleep;
use crate::ipc::event;
use crate::runtime::dir::SpawnedPodRecord;
use crate::runtime::scope_lock::{self, LockFileGuard, ScopeLockError};
use crate::runtime::pod_registry::{self, LockFileGuard, ScopeLockError};
use crate::spawn::registry::SpawnedPodRegistry;
use protocol::PodEvent;
@@ -93,7 +93,7 @@ impl From<PermissionInput> for Permission {
/// controller once per Pod lifetime.
pub struct SpawnPodTool {
/// Spawner's own pod name — becomes the spawned Pod's
/// `delegated_from` in the scope-lock registry.
/// `delegated_from` in the pod-registry.
spawner_name: String,
/// Path to the spawner's Unix socket. Handed to the child via
/// `--callback` so its `PodEvent` callbacks have somewhere to land.
@@ -167,7 +167,7 @@ impl Tool for SpawnPodTool {
.unwrap_or_else(|| DEFAULT_INSTRUCTION.to_string());
let predicted_socket = self.runtime_base.join(&input.name).join("sock");
let lock_path = scope_lock::default_lock_path()
let lock_path = pod_registry::default_registry_path()
.map_err(|e| ToolError::ExecutionFailed(format!("scope lock path: {e}")))?;
// Reserve the allocation up front. Spawner's pid is a live
@@ -175,7 +175,7 @@ impl Tool for SpawnPodTool {
{
let mut guard = LockFileGuard::open(&lock_path)
.map_err(|e| ToolError::ExecutionFailed(format!("scope lock open: {e}")))?;
scope_lock::delegate_scope(
pod_registry::delegate_scope(
&mut guard,
&self.spawner_name,
input.name.clone(),
@@ -183,7 +183,7 @@ impl Tool for SpawnPodTool {
predicted_socket.clone(),
scope_allow.clone(),
)
.map_err(scope_lock_err_to_tool)?;
.map_err(pod_registry_err_to_tool)?;
}
// `start_outcome` covers steps that happen before the child is
@@ -312,7 +312,7 @@ impl SpawnPodTool {
fn release_reservation(&self, lock_path: &Path, pod_name: &str) {
if let Ok(mut g) = LockFileGuard::open(lock_path) {
let _ = scope_lock::release_pod(&mut g, pod_name);
let _ = pod_registry::release_pod(&mut g, pod_name);
}
}
}
@@ -436,7 +436,7 @@ async fn send_run(socket: &Path, task: &str) -> Result<(), ToolError> {
Ok(())
}
fn scope_lock_err_to_tool(e: ScopeLockError) -> ToolError {
fn pod_registry_err_to_tool(e: ScopeLockError) -> ToolError {
match e {
ScopeLockError::NotSubset { .. }
| ScopeLockError::WriteConflict { .. }
+6 -6
View File
@@ -15,7 +15,7 @@ use llm_worker::llm_client::types::{ContentPart, Item, Role};
use llm_worker::tool::ToolOutput;
use manifest::{Permission, ScopeRule};
use pod::runtime::dir::{RuntimeDir, SpawnedPodRecord};
use pod::runtime::scope_lock::{self, LockFileGuard};
use pod::runtime::pod_registry::{self, LockFileGuard};
use pod::spawn::comm_tools::{
list_pods_tool, read_pod_output_tool, send_to_pod_tool, stop_pod_tool,
};
@@ -86,7 +86,7 @@ async fn setup_registry() -> (TempDir, Arc<SpawnedPodRegistry>, Arc<RuntimeDir>)
/// Register a fake spawned-child record pointing at a given socket
/// path, with a trivial write-scope for `scope_path`. Does not touch
/// scope.lock.
/// pods.json.
async fn register_child(
registry: &SpawnedPodRegistry,
name: &str,
@@ -334,14 +334,14 @@ async fn stop_pod_sends_shutdown_and_releases_scope() {
unsafe {
std::env::set_var("INSOMNIA_RUNTIME_DIR", tmp.path());
}
let lock_path = tmp.path().join("scope.lock");
let lock_path = tmp.path().join("pods.json");
// Seed scope.lock with a top-level `spawner` allocation plus a
// Seed pods.json with a top-level `spawner` allocation plus a
// delegated `child` allocation — mimics what SpawnPod would have
// done so StopPod has something to release.
{
let mut g = LockFileGuard::open(&lock_path).unwrap();
scope_lock::register_pod(
pod_registry::register_pod(
&mut g,
"spawner".into(),
std::process::id(),
@@ -354,7 +354,7 @@ async fn stop_pod_sends_shutdown_and_releases_scope() {
session_store::new_session_id(),
)
.unwrap();
scope_lock::delegate_scope(
pod_registry::delegate_scope(
&mut g,
"spawner",
"child".into(),
+5 -5
View File
@@ -11,7 +11,7 @@ use std::time::Duration;
use pod::ipc::event::{apply_event_side_effects, fire_and_forget, render_event};
use pod::runtime::dir::{RuntimeDir, SpawnedPodRecord};
use pod::runtime::scope_lock::{self, LockFileGuard};
use pod::runtime::pod_registry::{self, LockFileGuard};
use pod::spawn::registry::SpawnedPodRegistry;
use protocol::stream::JsonLineReader;
use protocol::{Method, Permission, PodEvent, ScopeRule};
@@ -62,8 +62,8 @@ impl Drop for EnvGuard {
}
}
/// Point `INSOMNIA_RUNTIME_DIR` at `dir`. The scope-lock then lives at
/// `<dir>/scope.lock` and Pod runtime sub-dirs at `<dir>/{pod_name}/`.
/// Point `INSOMNIA_RUNTIME_DIR` at `dir`. The pod-registry then lives at
/// `<dir>/pods.json` and Pod runtime sub-dirs at `<dir>/{pod_name}/`.
fn set_runtime_dir(dir: &std::path::Path) {
unsafe {
std::env::set_var("INSOMNIA_RUNTIME_DIR", dir);
@@ -348,12 +348,12 @@ async fn apply_turn_ended_and_errored_are_system_noops() {
async fn shutdown_releases_scope_allocation_when_present() {
let _env = EnvGuard::acquire();
let scope_dir = TempDir::new().unwrap();
let lock_path = scope_dir.path().join("scope.lock");
let lock_path = scope_dir.path().join("pods.json");
set_runtime_dir(scope_dir.path());
// Install a top-level allocation for "kid" so ShutDown has
// something to release.
let guard = scope_lock::install_top_level(
let guard = pod_registry::install_top_level(
"kid".into(),
std::process::id(),
"/tmp/kid.sock".into(),
+1 -1
View File
@@ -2,7 +2,7 @@
//! validation paths.
//!
//! These cases all return before `prepare_pod_common` runs, so they
//! do not need a real LLM client or scope-lock environment — only the
//! do not need a real LLM client or pod-registry environment — only the
//! session store needs to be present.
use std::sync::{LazyLock, Mutex};
+8 -8
View File
@@ -1,6 +1,6 @@
//! Integration tests for the `SpawnPod` tool.
//!
//! These tests exercise the tool's scope-lock delegation, subprocess
//! These tests exercise the tool's pod-registry delegation, subprocess
//! launch, socket handoff, and `spawned_pods.json` write without relying
//! on the real `pod` binary. `INSOMNIA_POD_COMMAND` is pointed at
//! `/bin/true` (which exits immediately) while a test-owned Unix
@@ -13,7 +13,7 @@ use std::sync::{LazyLock, Mutex};
use llm_worker::tool::{ToolError, ToolOutput};
use manifest::{AuthRef, ModelManifest, Permission, SchemeKind, ScopeRule};
use pod::runtime::dir::{RuntimeDir, SpawnedPodRecord};
use pod::runtime::scope_lock::{self, LockFileGuard};
use pod::runtime::pod_registry::{self, LockFileGuard};
use pod::spawn::registry::SpawnedPodRegistry;
use pod::spawn::tool::spawn_pod_tool;
use protocol::Method;
@@ -40,7 +40,7 @@ impl EnvGuard {
}
/// Set up a tempdir, point `INSOMNIA_RUNTIME_DIR` at it (so
/// `scope.lock` and per-Pod runtime subdirs both land in the
/// `pods.json` and per-Pod runtime subdirs both land in the
/// sandbox), and install a live top-level "spawner" allocation so the
/// tool has something to delegate from. Returns the tempdir (keeps it
/// alive for the test's lifetime), runtime base, spawner socket, and
@@ -64,7 +64,7 @@ async fn setup_spawner(
.unwrap();
let spawner_socket = spawner_rd.socket_path();
let _guard = scope_lock::install_top_level(
let _guard = pod_registry::install_top_level(
spawner_name.into(),
std::process::id(),
spawner_socket.clone(),
@@ -207,8 +207,8 @@ async fn spawn_pod_delegates_scope_and_sends_run() {
other => panic!("expected Run, got {other:?}"),
}
// Verify scope_lock has the child allocation under `root`.
let lock_path = scope_lock::default_lock_path().unwrap();
// Verify pod_registry has the child allocation under `root`.
let lock_path = pod_registry::default_registry_path().unwrap();
let guard = LockFileGuard::open(&lock_path).unwrap();
let child = guard
.data()
@@ -273,7 +273,7 @@ async fn spawn_pod_rejects_scope_outside_spawner() {
}
// The spawner's allocation is unchanged; no "child" appeared.
let lock_path = scope_lock::default_lock_path().unwrap();
let lock_path = pod_registry::default_registry_path().unwrap();
let guard = LockFileGuard::open(&lock_path).unwrap();
assert!(guard.data().find("child").is_none());
@@ -334,7 +334,7 @@ async fn spawn_pod_rolls_back_reservation_when_socket_never_appears() {
}
// Rollback assertion: the reserved "ghost" allocation is gone.
let lock_path = scope_lock::default_lock_path().unwrap();
let lock_path = pod_registry::default_registry_path().unwrap();
let guard = LockFileGuard::open(&lock_path).unwrap();
assert!(
guard.data().find("ghost").is_none(),