From 1c47d7b3130b67aaf334dfc64993574e7fa953b0 Mon Sep 17 00:00:00 2001 From: huihui Date: Fri, 27 Nov 2026 21:55:56 +0800 Subject: [PATCH 01/16] fix(app-server): admit only lowercase ASCII Session ids and reject case-colliding writes (#2204) New ids admitted through CreateSessionOptions::prepare, the store face's createOwnedSession and a fork's target are limited to [a-z0-9_-]{1,64} without the Windows reserved device names, rejected with InvalidInput before anything prepares, writes or publishes; lowercase ASCII has no folding variants, so ids admitted under the rule can never share an output directory on a volume that folds case. The store gains the derived index agent_sessions_session_id_nocase on agent_sessions(session_id COLLATE NOCASE), created at open with the other derived indexes and ignored by the schema comparison, so the format marker stays at 53. The creation insert helper and a fork copy check it for a stored id equal to the candidate under the case-insensitive collation: a byte-identical duplicate keeps its Storage error while a case-only variant is rejected with InvalidInput. A fork copy checks before its first chunk transaction and again inside the final IMMEDIATE transaction; the pre-check refusal writes nothing and runs no cleanup, so a target byte-identical to a stored Session can no longer drop that Session's rows through the copy's cleanup. Restoration, deletion and use as a fork source are unchanged: ids stored before the rule keep their bytes and stay operable, and legacy mixed-case records are neither migrated nor rewritten. Refs #2202. --- crates/dim-agent-runtime/src/agent.rs | 31 +- crates/dim-app-server/src/storage/sqlite.rs | 13 +- crates/dim-app-server/src/storage/timeline.rs | 56 ++ crates/dim-app-server/tests/storage_flow.rs | 13 +- .../tests/storage_flow/admission.rs | 492 ++++++++++++++++++ .../design/appserver/native-storage-format.md | 14 +- 6 files changed, 606 insertions(+), 13 deletions(-) create mode 100644 crates/dim-app-server/tests/storage_flow/admission.rs diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index 26edd54103..bd5c4fe3c6 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -62,7 +62,8 @@ impl CreateSessionOptions { /// completes. Without it, the Session is created under a generated UUIDv4. /// /// The id must be one normal path component, which is what Session - /// command-output storage addresses ([`check_session_id`]); + /// command-output storage addresses ([`check_session_id`]), and have the + /// shape every newly admitted id has ([`check_new_session_id`]); /// [`Agent::create_session`] rejects any other id before it prepares, /// writes or publishes. pub fn prepare(mut self, id: impl Into, prepare: F) -> Self @@ -110,6 +111,33 @@ pub fn check_session_id(id: &str) -> Result<()> { } Ok(()) } +/// The Windows device names a directory can never be named, with or without +/// an extension: on a Windows output volume they alias the device. +const WINDOWS_DEVICE_NAMES: &[&str] = &[ + "con", "prn", "aux", "nul", "com0", "com1", "com2", "com3", "com4", "com5", "com6", "com7", + "com8", "com9", "lpt0", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", +]; +/// Requires the shape every newly admitted Session id has (#2204): one to +/// sixty-four characters, each a lowercase ASCII letter, digit, underscore or +/// hyphen, and never a Windows reserved device name. Lowercase ASCII has no +/// folding variants, so two ids admitted under this rule can never address +/// the same output directory on a volume that folds case; the length bound +/// and the reserved names close the Windows aliasing and overlong-name +/// hazards by construction. Only creation entries apply it — deletion, a +/// fork's source and restoration keep [`check_session_id`], so ids stored +/// before this rule stay operable. +pub fn check_new_session_id(id: &str) -> Result<()> { + if id.is_empty() + || id.len() > 64 + || !id.bytes().all(|byte| { + byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_' || byte == b'-' + }) + || WINDOWS_DEVICE_NAMES.contains(&id) + { + return Err(AgentError::InvalidInput(format!("invalid Session id {id}"))); + } + Ok(()) +} impl Agent { pub(crate) fn new(builder: AgentBuilder, assembly: Assembly, placement: Placement) -> Self { Self(Arc::new(AgentInner { @@ -144,6 +172,7 @@ impl Agent { let (id, start) = match prepare { Some((id, prepare)) => { check_session_id(&id)?; + check_new_session_id(&id)?; (id, SessionStart::Prepared(prepare)) } None => (Uuid::new_v4().to_string(), SessionStart::Create), diff --git a/crates/dim-app-server/src/storage/sqlite.rs b/crates/dim-app-server/src/storage/sqlite.rs index f6ab5ec27c..4c70d3a777 100644 --- a/crates/dim-app-server/src/storage/sqlite.rs +++ b/crates/dim-app-server/src/storage/sqlite.rs @@ -628,10 +628,11 @@ fn same_schema(actual: &[(String, String)], mut expected: Vec<(&str, String)>) - } /// The read indexes the daemon creates at open: the latest-turn window's /// ([session-history-window §5.1](../../../../docs/design/appserver/session-history-window.md#51-the-derived-index)), -/// the policy window's turn starts, and the event query's by kind, which carries -/// the event id so a kind read needs no table body for it (ADR 019 D4). They -/// carry no data and no decode rule, so they are not part of the format: `schema` -/// and the format gate ignore them, and every open recreates them. +/// the policy window's turn starts, the event query's by kind, which carries +/// the event id so a kind read needs no table body for it (ADR 019 D4), and the +/// case-insensitive Session id lookup the creation collision checks run (#2204). +/// They carry no data and no decode rule, so they are not part of the format: +/// `schema` and the format gate ignore them, and every open recreates them. const DERIVED_INDEXES: &[(&str, &str)] = &[ ( "timeline_history_anchors", @@ -645,6 +646,10 @@ const DERIVED_INDEXES: &[(&str, &str)] = &[ "timeline_policy_turns", "CREATE INDEX IF NOT EXISTS timeline_policy_turns ON timeline_events(session_id, branch_id, kind, sequence, event_id) WHERE kind = 'turn/start'", ), + ( + "agent_sessions_session_id_nocase", + "CREATE INDEX IF NOT EXISTS agent_sessions_session_id_nocase ON agent_sessions(session_id COLLATE NOCASE)", + ), ]; /// The schema objects of `connection`'s database that belong to the format, /// sorted by name. diff --git a/crates/dim-app-server/src/storage/timeline.rs b/crates/dim-app-server/src/storage/timeline.rs index 4e4b4229b4..049f66b53b 100644 --- a/crates/dim-app-server/src/storage/timeline.rs +++ b/crates/dim-app-server/src/storage/timeline.rs @@ -1700,6 +1700,7 @@ impl SessionStore { ) -> Result<()> { dim_agent_runtime::check_session_id(source)?; dim_agent_runtime::check_session_id(fork)?; + dim_agent_runtime::check_new_session_id(fork)?; let _ownership = self.ownership.lock().await; if let Some(cwd) = config_cwd(config) { self.reject_deletion(&cwd).await?; @@ -1726,6 +1727,7 @@ impl SessionStore { worktree: Option, ) -> Result<()> { dim_agent_runtime::check_session_id(session_id)?; + dim_agent_runtime::check_new_session_id(session_id)?; let session = session_id.to_owned(); let config = config.clone(); let agent = agent_id.to_owned(); @@ -2359,6 +2361,26 @@ impl DynPlugin for SessionStorePlugin { } } +/// The stored Session ids equal to `candidate` under the case-insensitive +/// collation (#2204). The covering derived index `agent_sessions_session_id_nocase` +/// resolves the lookup; the caller compares bytes to tell a case-only variant, +/// which it rejects with InvalidInput, from a byte-identical duplicate, which +/// keeps its Storage error. +fn case_conflicts(connection: &Connection, candidate: &str) -> Result> { + let mut rows = Vec::new(); + let mut statement = connection + .prepare_cached( + "SELECT session_id FROM agent_sessions WHERE session_id = ?1 COLLATE NOCASE", + ) + .map_err(error)?; + for row in statement + .query_map([candidate], |row| row.get::<_, String>(0)) + .map_err(error)? + { + rows.push(row.map_err(error)?); + } + Ok(rows) +} fn create_session( connection: &Connection, session: &str, @@ -2366,6 +2388,14 @@ fn create_session( leader: Option<&str>, origin: SessionOrigin, ) -> Result<()> { + if case_conflicts(connection, session)? + .iter() + .any(|stored| stored != session) + { + return Err(AgentError::InvalidInput(format!( + "Session id {session} differs from a stored one only by case" + ))); + } let config = serde_json::to_string(config).map_err(error)?; connection .execute( @@ -3116,6 +3146,11 @@ fn chunk(connection: &mut Connection, step: impl FnOnce(&Connection) -> Resul /// Copies a fork's rows in bounded transactions; the final transaction /// inserts the session row, so an interrupted copy leaves no Session. +/// +/// A fork id that already names a stored Session — byte-identical or only by +/// case — is refused before the first chunk transaction (#2204): the refusal +/// writes nothing and runs no cleanup, so the cleanup's drop of every row of +/// the id can never reach the Session that already owned it. fn copy_fork( connection: &mut Connection, source: &str, @@ -3125,6 +3160,7 @@ fn copy_fork( arrays: &BTreeMap, config: &str, ) -> Result<()> { + reject_conflicting_id(connection, fork)?; let copied = copy_fork_rows(connection, source, fork, at, content, arrays, config); if copied.is_err() && let Err(cleanup) = drop_session(connection, fork) @@ -3134,6 +3170,23 @@ fn copy_fork( copied } +/// Rejects `candidate` when a stored Session id equals it under the +/// case-insensitive collation: byte-identical keeps the duplicate's Storage +/// error, a case-only variant is InvalidInput (#2204). +fn reject_conflicting_id(connection: &Connection, candidate: &str) -> Result<()> { + let conflicts = case_conflicts(connection, candidate)?; + if conflicts.is_empty() { + return Ok(()); + } + Err(if conflicts.iter().any(|stored| stored != candidate) { + AgentError::InvalidInput(format!( + "Session id {candidate} differs from a stored one only by case" + )) + } else { + error(format!("Session id {candidate} already exists")) + }) +} + fn copy_fork_rows( connection: &mut Connection, source: &str, @@ -3273,6 +3326,9 @@ fn copy_fork_rows( .pragma_update(None, "synchronous", "FULL") .map_err(error)?; chunk(connection, |tx| { + // The pre-check covered the copy's start; this re-check closes the + // race against an insertion committed while the chunks copied (#2204). + reject_conflicting_id(tx, fork)?; // A fork is a new Session of the client that forked it, never its // source's origin (session classification §3.2). tx.execute( diff --git a/crates/dim-app-server/tests/storage_flow.rs b/crates/dim-app-server/tests/storage_flow.rs index e9689ef492..62b09dd784 100644 --- a/crates/dim-app-server/tests/storage_flow.rs +++ b/crates/dim-app-server/tests/storage_flow.rs @@ -55,6 +55,9 @@ mod prompt_migration; #[path = "storage_flow/reclaim.rs"] mod reclaim; +#[path = "storage_flow/admission.rs"] +mod admission; + const INTERPRETER: &str = "dim/context-projection/v4"; fn snapshot(sequence: u64, checkpoint: &ProjectionCheckpoint) -> RecoverySnapshot { let mut snapshot = RecoverySnapshot { @@ -686,7 +689,7 @@ fn schema(connection: &Connection) -> Vec { .prepare( "SELECT sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' \ AND name NOT IN ('timeline_history_anchors', 'timeline_events_by_kind', \ - 'timeline_policy_turns') + 'timeline_policy_turns', 'agent_sessions_session_id_nocase') AND name NOT IN (SELECT name FROM pragma_table_list WHERE type='shadow' AND name LIKE 'timeline_text_fts_%')", ) .unwrap() @@ -8481,7 +8484,13 @@ async fn a_v41_store_upgrades_in_place_once_keeping_internal_launches() { .unwrap() .collect::>() .unwrap(); - assert_eq!(indexed, ["agent_sessions_by_leader"]); + assert_eq!( + indexed, + [ + "agent_sessions_by_leader", + "agent_sessions_session_id_nocase" + ] + ); for (session, expected) in [("s1", "client"), ("member", "internal")] { let origin: String = connection .query_row( diff --git a/crates/dim-app-server/tests/storage_flow/admission.rs b/crates/dim-app-server/tests/storage_flow/admission.rs new file mode 100644 index 0000000000..12df720f63 --- /dev/null +++ b/crates/dim-app-server/tests/storage_flow/admission.rs @@ -0,0 +1,492 @@ +//! #2204: a new Session id admitted through `CreateSessionOptions::prepare`, +//! `createOwnedSession` or a fork's target is lowercase ASCII — one to +//! sixty-four characters of `[a-z0-9_-]`, and never a Windows reserved device +//! name — and is rejected with InvalidInput before anything is written. The +//! store refuses a write whose id differs from a stored one only by case: +//! the case variant is InvalidInput, while a byte-identical duplicate keeps +//! its Storage error. A fork refused before its copy starts writes nothing +//! and drops nothing, so a target byte-identical to a stored Session cannot +//! delete that Session's rows. Ids already stored keep their bytes: +//! restoration reads them as written, and deletion plus use as a fork source +//! are unchanged. + +use super::*; + +fn seed_owner(connection: &Connection) { + connection + .execute( + "INSERT INTO agents(agent_id, profile, is_default) VALUES ('owner', ?1, 1)", + [serde_json::to_string(&AgentProfile { + name: "owner".into(), + description: String::new(), + system_prompt: String::new(), + tools: Some(vec![]), + model: None, + }) + .unwrap()], + ) + .unwrap(); +} + +/// A stored record written around every validation, the way a pre-#2204 or +/// external writer could leave it: uppercase letters and all. +fn seed_stored_session(connection: &Connection, session_id: &str) { + let config = serde_json::to_string(&SessionConfig::default()).unwrap(); + connection + .execute( + "INSERT INTO agent_sessions (session_id, config, created_at_ms, origin) \ + VALUES (?1, ?2, 0, 'client')", + params![session_id, config], + ) + .unwrap(); +} + +fn stored_events(connection: &Connection, session_id: &str) -> Vec { + connection + .prepare("SELECT sequence || ':' || body FROM timeline_events WHERE session_id=?1 ORDER BY sequence") + .unwrap() + .query_map([session_id], |row| row.get::<_, String>(0)) + .unwrap() + .collect::>>() + .unwrap() +} + +fn stored_rows(connection: &Connection, session_id: &str) -> i64 { + connection + .query_row( + "SELECT (SELECT count(*) FROM agent_sessions WHERE session_id=?1) + \ + (SELECT count(*) FROM timeline_branches WHERE session_id=?1) + \ + (SELECT count(*) FROM timeline_events WHERE session_id=?1)", + [session_id], + |row| row.get(0), + ) + .unwrap() +} + +#[tokio::test] +async fn prepared_creation_admits_only_lowercase_ascii_ids() { + let database = Database::new(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let store = SqliteTimelineStore::new(db.clone()); + let mut builder = AgentBuilder::new(AgentConfig::default()); + dim_agent_capabilities::defaults::mock_hosts(&mut builder); + dim_agent_capabilities::defaults::install(&mut builder); + builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); + let agent = MinimalHost::start(&builder).await.unwrap(); + let connection = Connection::open(&database.0).unwrap(); + + let overlong = "x".repeat(65); + for id in [ + "Uppercase", + "with space", + "con", + "com0", + "lpt9", + "unicode-é", + overlong.as_str(), + ] { + let prepared_store = store.clone(); + let options = + dim_agent_runtime::CreateSessionOptions::default().prepare(id, move |id: String| { + Box::pin(async move { + prepared_store + .create_session(&id, &SessionConfig::default()) + .await + }) + }); + let result = agent + .create_session(SessionConfig::default(), options) + .await; + assert!( + matches!(result, Err(AgentError::InvalidInput(_))), + "prepared creation with id {id:?} must be rejected with InvalidInput, got {:?}", + result.err() + ); + assert_eq!( + stored_rows(&connection, id), + 0, + "nothing of {id:?} may be written" + ); + } + + let prepared_store = store.clone(); + let options = dim_agent_runtime::CreateSessionOptions::default().prepare( + "valid-id_1", + move |id: String| { + Box::pin(async move { + prepared_store + .create_session(&id, &SessionConfig::default()) + .await + }) + }, + ); + agent + .create_session(SessionConfig::default(), options) + .await + .unwrap(); + + drop(connection); + agent.close().await.unwrap(); + store.close().await.unwrap(); + db.close().await.unwrap(); +} + +#[tokio::test] +async fn owned_creation_admits_only_lowercase_ascii_ids() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_owner(&connection); + + let overlong = "x".repeat(65); + for id in [ + "Uppercase", + "with space", + "con", + "com0", + "lpt9", + "unicode-é", + overlong.as_str(), + ] { + let result = sessions + .create_owned_session( + id, + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await; + assert!( + matches!(result, Err(AgentError::InvalidInput(_))), + "owned creation with id {id:?} must be rejected with InvalidInput, got {result:?}" + ); + assert_eq!( + stored_rows(&connection, id), + 0, + "nothing of {id:?} may be written" + ); + } + + sessions + .create_owned_session( + "valid-id_1", + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await + .unwrap(); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +#[tokio::test] +async fn owned_creation_rejects_case_variants_and_keeps_storage_error_for_byte_duplicates() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_owner(&connection); + seed_stored_session(&connection, "Legacy-1"); + seed_stored_session(&connection, "stored-1"); + + let variant = sessions + .create_owned_session( + "legacy-1", + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await; + assert!( + matches!(variant, Err(AgentError::InvalidInput(_))), + "an id differing only by case must be InvalidInput, got {variant:?}" + ); + // A byte-identical duplicate is only reachable under the admission rule + // when the stored id is itself conforming: the uppercase id above would + // already fail admission. The colliding write keeps the duplicate's + // Storage error; only the case variant is InvalidInput. + let duplicate = sessions + .create_owned_session( + "stored-1", + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await; + assert!( + matches!(duplicate, Err(AgentError::Storage(_))), + "a byte-identical duplicate must keep its Storage error, got {duplicate:?}" + ); + assert_eq!( + stored_rows(&connection, "legacy-1"), + 0, + "the refused variant writes nothing" + ); + assert_eq!( + connection + .query_row("SELECT count(*) FROM agent_sessions", [], |row| row + .get::<_, i64>(0)) + .unwrap(), + 2, + "the stored records are untouched" + ); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +#[tokio::test] +async fn fork_target_outside_the_admission_rule_or_in_case_collision_writes_nothing() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_stored_session(&connection, "Legacy-2"); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append(&store, key("source", "main"), vec![text(1, "source")]) + .await + .unwrap(); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + + for target in ["Uppercase", "con"] { + let result = sessions.fork_session("source", target, 1, &config).await; + assert!( + matches!(result, Err(AgentError::InvalidInput(_))), + "fork target {target:?} must be rejected with InvalidInput, got {result:?}" + ); + assert_eq!( + stored_rows(&connection, target), + 0, + "a refused fork target writes nothing" + ); + } + + let collision = sessions + .fork_session("source", "legacy-2", 1, &config) + .await; + assert!( + matches!(collision, Err(AgentError::InvalidInput(_))), + "a fork target differing only by case must be InvalidInput, got {collision:?}" + ); + assert_eq!( + stored_rows(&connection, "legacy-2"), + 0, + "the collision refusal writes nothing under the refused id" + ); + assert_eq!( + stored_rows(&connection, "Legacy-2"), + 1, + "the seeded uppercase session row is untouched" + ); + assert!( + stored_events(&connection, "legacy-2").is_empty(), + "no Timeline rows may be copied into the colliding id" + ); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// #2204's worst case: a fork whose target is byte-identical to a stored +/// Session. The copy's final insert cannot succeed, and the copy's cleanup +/// drops every row of the id — including the Session that already owned it, +/// before the fix. The refusal must happen before the first copy chunk, so +/// nothing is written and no cleanup runs. +#[tokio::test] +async fn fork_with_a_byte_identical_target_is_refused_without_touching_the_existing_session() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append(&store, key("source", "main"), vec![text(1, "source")]) + .await + .unwrap(); + store + .create_session("victim", &SessionConfig::default()) + .await + .unwrap(); + append(&store, key("victim", "main"), vec![text(1, "victim")]) + .await + .unwrap(); + + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + let result = sessions.fork_session("source", "victim", 1, &config).await; + assert!( + matches!(result, Err(AgentError::Storage(_))), + "a byte-identical fork target must keep its Storage error, got {result:?}" + ); + + let connection = Connection::open(&database.0).unwrap(); + assert!( + connection + .query_row( + "SELECT EXISTS(SELECT 1 FROM agent_sessions WHERE session_id='victim')", + [], + |row| row.get::<_, bool>(0) + ) + .unwrap(), + "the existing Session's row must survive the refused fork" + ); + assert_eq!( + stored_events(&connection, "victim").len(), + 1, + "the existing Session's Timeline rows must survive the refused fork" + ); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// Ids stored before the admission rule are neither migrated nor rewritten: +/// the raw store still writes them as given, an uppercase source forks into +/// a conforming target, and deletion removes it as before. This pins behavior +/// the change must not alter. +#[tokio::test] +async fn stored_uppercase_ids_remain_operable() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + store + .create_session("Legacy-9", &SessionConfig::default()) + .await + .unwrap(); + append( + &store, + key("Legacy-9", "main"), + vec![text(1, "first"), text(2, "second")], + ) + .await + .unwrap(); + + let config = sessions + .session_config_text("Legacy-9") + .await + .unwrap() + .unwrap(); + sessions + .fork_session("Legacy-9", "valid-fork", 2, &config) + .await + .unwrap(); + let connection = Connection::open(&database.0).unwrap(); + assert!( + !stored_events(&connection, "valid-fork").is_empty(), + "the uppercase source's rows are copied into the fork" + ); + + assert!(sessions.delete_session("Legacy-9").await.unwrap()); + assert!( + connection + .query_row( + "SELECT NOT EXISTS(SELECT 1 FROM agent_sessions WHERE session_id='Legacy-9')", + [], + |row| row.get::<_, bool>(0) + ) + .unwrap(), + "deletion removes the uppercase id as before" + ); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// The collision check is the indexed lookup the maintainer decision requires: +/// the query the write entries run resolves through the covering derived +/// index instead of scanning the table. +#[tokio::test] +async fn case_collision_check_uses_the_derived_index() { + let database = Database::new(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let connection = Connection::open(&database.0).unwrap(); + let plan: Vec = connection + .prepare( + "EXPLAIN QUERY PLAN SELECT session_id FROM agent_sessions \ + WHERE session_id = ?1 COLLATE NOCASE AND session_id <> ?1", + ) + .unwrap() + .query_map(["candidate"], |row| row.get::<_, String>(3)) + .unwrap() + .collect::>>() + .unwrap(); + assert!( + plan.iter() + .any(|step| step.contains("agent_sessions_session_id_nocase")), + "the collision check must use the covering index, plan: {plan:?}" + ); + + drop(connection); + db.close().await.unwrap(); +} diff --git a/docs/design/appserver/native-storage-format.md b/docs/design/appserver/native-storage-format.md index 5d34144b45..f3afede49e 100644 --- a/docs/design/appserver/native-storage-format.md +++ b/docs/design/appserver/native-storage-format.md @@ -245,14 +245,16 @@ valid in v48, and v16 request rows stay readable as written. (`(session_id, branch_id, kind, sequence) WHERE kind IN ('turn/start', 'input/message')`, [latest-turn 窗口 §5.1](session-history-window.md#51-the-derived-index))、 `timeline_policy_turns`(`(session_id, branch_id, kind, sequence, event_id) WHERE kind = 'turn/start'`, -已无读者,删除它要作为格式步骤)与事件查询的 +已无读者,删除它要作为格式步骤)、事件查询的 `timeline_events_by_kind`(`(session_id, branch_id, kind, sequence, event_id)`,按 kind -读取事件而不碰事件体,[ADR 019](../../adr/019-event-query.md) D4):读写打开在启动事务内用 -`CREATE INDEX IF NOT EXISTS` 创建或补建,只读导出只接受它们。它们不含数据,可从 -`timeline_events` 重新推导,读同一份事件不因它们有无而不同,因此不属于格式:启动门禁的 -精确结构比较忽略这些名字,格式标记不变(当前 v48);其余任何多余对象仍按原规则拒绝。代价是早于 +读取事件而不碰事件体,[ADR 019](../../adr/019-event-query.md) D4)与 +`agent_sessions_session_id_nocase`(`agent_sessions(session_id COLLATE NOCASE)`,#2204 +创建写入入口的大小写冲突检查走它做索引查找而不是扫表):读写打开在启动事务内用 +`CREATE INDEX IF NOT EXISTS` 创建或补建,只读导出只接受它们。它们不含数据,可从其 +基表重新推导,读同一份数据不因它们有无而不同,因此不属于格式:启动门禁的 +精确结构比较忽略这些名字,格式标记不变(当前 v53);其余任何多余对象仍按原规则拒绝。代价是早于 该变更的二进制不认识这些名字,会以 "unsupported SQLite schema … preserved" 拒绝已有该 -索引的库(行不变,新二进制可再次打开)。 +索引的库(行不变,原库保留,新二进制可再次打开)。 Storage versions are independent of RPC versions. Private MCP/Skill business documents do not belong in loader rows, events, diagnostics, Sessions or Timelines. From 9c13cf4a7013505df815f09c06c66c93acbffb84 Mon Sep 17 00:00:00 2001 From: huihui Date: Sat, 28 Nov 2026 06:12:01 +0800 Subject: [PATCH 02/16] fix(app-server): check fork id conflicts inside the first copy transaction and clean up only rows the fork still owns (#2204) A Session committed by another connection between the copy's first conflict check and its first write could be deleted by the failed copy's cleanup, which dropped every row of the target id. The first check now runs inside the first chunk transaction so the refusal rolls back before any write, and the cleanup deletes only while the id names no stored Session, re-checking inside every delete transaction; once a Session of the id exists the copy's rows stay as unreachable rows instead of the cleanup reaching the Session that owns the id. Regression tests inject the concurrent commit through INSERT triggers on the copy's own writes, deterministic in both the first-chunk window and the mid-copy window the final re-check covers: the fork keeps its Storage refusal, the winning Session's rows survive field by field, and a case-only variant still refuses with InvalidInput. --- crates/dim-app-server/src/storage/timeline.rs | 170 ++++++++---- .../tests/storage_flow/admission.rs | 243 ++++++++++++++++++ 2 files changed, 367 insertions(+), 46 deletions(-) diff --git a/crates/dim-app-server/src/storage/timeline.rs b/crates/dim-app-server/src/storage/timeline.rs index 049f66b53b..a2419fe05d 100644 --- a/crates/dim-app-server/src/storage/timeline.rs +++ b/crates/dim-app-server/src/storage/timeline.rs @@ -3147,10 +3147,12 @@ fn chunk(connection: &mut Connection, step: impl FnOnce(&Connection) -> Resul /// Copies a fork's rows in bounded transactions; the final transaction /// inserts the session row, so an interrupted copy leaves no Session. /// -/// A fork id that already names a stored Session — byte-identical or only by -/// case — is refused before the first chunk transaction (#2204): the refusal -/// writes nothing and runs no cleanup, so the cleanup's drop of every row of -/// the id can never reach the Session that already owned it. +/// A fork id that names a stored Session — byte-identical or only by case — +/// is refused inside the first chunk transaction, before its first write +/// (#2204): the refusal rolls that transaction back, so it writes nothing and +/// runs no cleanup. The cleanup of a copy refused later drops the id's rows +/// only while no Session of that exact id exists; one another connection +/// committed during the copy keeps the cleanup from deleting its rows. fn copy_fork( connection: &mut Connection, source: &str, @@ -3160,12 +3162,20 @@ fn copy_fork( arrays: &BTreeMap, config: &str, ) -> Result<()> { - reject_conflicting_id(connection, fork)?; let copied = copy_fork_rows(connection, source, fork, at, content, arrays, config); - if copied.is_err() - && let Err(cleanup) = drop_session(connection, fork) - { - tracing::error!(session_id = fork, error = %cleanup, "Incomplete fork rows were kept"); + if copied.is_err() { + match drop_fork_rows(connection, fork) { + Ok(true) => {} + Ok(false) => { + tracing::error!( + session_id = fork, + "Incomplete fork rows were kept: a Session of that id was committed during the copy" + ) + } + Err(cleanup) => { + tracing::error!(session_id = fork, error = %cleanup, "Incomplete fork rows were kept") + } + } } copied } @@ -3204,6 +3214,12 @@ fn copy_fork_rows( .map_err(error)?; let mut branches = Vec::new(); chunk(connection, |tx| { + // The first conflict check shares this transaction's write lock with + // the copy's first writes: a conflicting Session committed before the + // transaction started is seen here, and none can commit before the + // writes once the lock is held (#2204). A refusal rolls the chunk + // back, so the copy writes nothing. + reject_conflicting_id(tx, fork)?; branches = tx .prepare("SELECT branch_id, info FROM timeline_branches WHERE session_id=?1") .map_err(error)? @@ -3326,8 +3342,9 @@ fn copy_fork_rows( .pragma_update(None, "synchronous", "FULL") .map_err(error)?; chunk(connection, |tx| { - // The pre-check covered the copy's start; this re-check closes the - // race against an insertion committed while the chunks copied (#2204). + // The first chunk's check covered the copy's start; this re-check + // closes the race against an insertion committed while the chunks + // copied (#2204). reject_conflicting_id(tx, fork)?; // A fork is a new Session of the client that forked it, never its // source's origin (session classification §3.2). @@ -3413,43 +3430,45 @@ fn copy_fork_rows( }) } -/// Removes what makes a Session visible in one transaction, then its large -/// Timeline tables in bounded transactions. -fn drop_session(connection: &mut Connection, session: &str) -> Result { - connection - .pragma_update(None, "synchronous", "FULL") - .map_err(error)?; - let released = chunk(connection, |tx| { - let released = files::release(tx, session).map_err(error)?; +/// The rows that make a Session visible: its file and output owners, grants, +/// title, catalog, owner and session rows and its branch directories. +fn drop_visible_rows(tx: &Connection, session: &str) -> Result { + let released = files::release(tx, session).map_err(error)?; + tx.execute( + "UPDATE agent_sessions SET leader_session_id=NULL WHERE leader_session_id=?1 + AND CASE WHEN json_valid(config) THEN json_extract(config, '$.collaborationRole') END IS NOT 'member'", + [session], + ) + .map_err(error)?; + for table in [ + "session_output_owners", + "session_grants", + "session_worktrees", + "session_metadata", + "session_catalog", + "session_owners", + "timeline_branches", + "agent_sessions", + ] { tx.execute( - "UPDATE agent_sessions SET leader_session_id=NULL WHERE leader_session_id=?1 - AND CASE WHEN json_valid(config) THEN json_extract(config, '$.collaborationRole') END IS NOT 'member'", + &format!("DELETE FROM {table} WHERE session_id=?1"), [session], ) .map_err(error)?; - for table in [ - "session_output_owners", - "session_grants", - "session_worktrees", - "session_metadata", - "session_catalog", - "session_owners", - "timeline_branches", - "agent_sessions", - ] { - tx.execute( - &format!("DELETE FROM {table} WHERE session_id=?1"), - [session], - ) - .map_err(error)?; - } - Ok(released) - })?; - // The Session is invisible now; a lost delete chunk only leaves - // unreachable rows for a retry. - connection - .pragma_update(None, "synchronous", "NORMAL") - .map_err(error)?; + } + Ok(released) +} + +/// The large Timeline tables of a Session, in bounded transactions. `owned` +/// gates each transaction together with its delete: a copy cleanup passes a +/// check that the id still names no stored Session, so rows another +/// connection commits under the id are never deleted; a delete passes no +/// gate. +fn drop_timeline_rows( + connection: &mut Connection, + session: &str, + owned: impl Fn(&Connection) -> bool, +) -> Result> { for table in [ "timeline_output_ids", "timeline_member_roots", @@ -3464,7 +3483,10 @@ fn drop_session(connection: &mut Connection, session: &str) -> Result { "timeline_array_elements", ] { loop { - let deleted = chunk(connection, |tx| { + let Some(deleted) = chunk(connection, |tx| { + if !owned(tx) { + return Ok(None); + } tx.execute( &format!( "DELETE FROM {table} WHERE rowid IN \ @@ -3473,15 +3495,71 @@ fn drop_session(connection: &mut Connection, session: &str) -> Result { [session], ) .map_err(error) - })?; + .map(Some) + })? + else { + return Ok(None); + }; if deleted == 0 { break; } } } + Ok(Some(())) +} + +/// Removes what makes a Session visible in one transaction, then its large +/// Timeline tables in bounded transactions. +fn drop_session(connection: &mut Connection, session: &str) -> Result { + connection + .pragma_update(None, "synchronous", "FULL") + .map_err(error)?; + let released = chunk(connection, |tx| drop_visible_rows(tx, session))?; + // The Session is invisible now; a lost delete chunk only leaves + // unreachable rows for a retry. + connection + .pragma_update(None, "synchronous", "NORMAL") + .map_err(error)?; + drop_timeline_rows(connection, session, |_| true)?; Ok(released) } +/// The rows a failed fork copy committed, best effort. Every delete shares +/// its transaction with a check that the id still names no stored Session: +/// the copy is the only writer that ever wrote rows of the id without its +/// session row, so while that check holds the rows are provably the copy's +/// own. Once another connection has committed a Session of the id the rows +/// can no longer be told apart, so nothing more is deleted and the copy's +/// rows stay as unreachable rows of the id (#2204). Returns false when such +/// a Session stopped the cleanup. +fn drop_fork_rows(connection: &mut Connection, fork: &str) -> Result { + let unclaimed = |connection: &Connection, id: &str| -> Result { + connection + .query_row( + "SELECT NOT EXISTS(SELECT 1 FROM agent_sessions WHERE session_id=?1)", + [id], + |row| row.get(0), + ) + .map_err(error) + }; + connection + .pragma_update(None, "synchronous", "FULL") + .map_err(error)?; + if !chunk(connection, |tx| { + if !unclaimed(tx, fork)? { + return Ok(false); + } + drop_visible_rows(tx, fork)?; + Ok(true) + })? { + return Ok(false); + } + connection + .pragma_update(None, "synchronous", "NORMAL") + .map_err(error)?; + Ok(drop_timeline_rows(connection, fork, |tx| unclaimed(tx, fork).unwrap_or(false))?.is_some()) +} + /// The content rows the events of `source`'s `main` through `at` reference, /// parsed in bounded holds on read connections. async fn fork_references( diff --git a/crates/dim-app-server/tests/storage_flow/admission.rs b/crates/dim-app-server/tests/storage_flow/admission.rs index 12df720f63..9f6dc11290 100644 --- a/crates/dim-app-server/tests/storage_flow/admission.rs +++ b/crates/dim-app-server/tests/storage_flow/admission.rs @@ -490,3 +490,246 @@ async fn case_collision_check_uses_the_derived_index() { drop(connection); db.close().await.unwrap(); } + +/// A trigger that stands in for another connection committing a Session of +/// `winner` the moment the copy writes its first `into` row for `fork` — the +/// timing a concurrent creation would have. Its rows ride the copy's own +/// transaction, so the interleaving is deterministic: `branches` makes the +/// commit land with the copy's first chunk, `events` with a chunk after it. +/// `INSERT OR IGNORE` keeps the copies of a later row from failing the +/// statement once the commit already happened. +fn commit_winner_when_copy_writes(connection: &Connection, into: &str, fork: &str, winner: &str) { + connection + .execute_batch(&format!( + "CREATE TRIGGER concurrent_creation AFTER INSERT ON {into} + WHEN NEW.session_id = '{fork}' + BEGIN + INSERT OR IGNORE INTO agent_sessions (session_id, config, created_at_ms, origin) + VALUES ('{winner}', '{{\"cwd\":\"/winner\"}}', 1, 'client'); + INSERT OR IGNORE INTO session_catalog (session_id, updated_at_ms, preview, cwd) + VALUES ('{winner}', 1, 'winner-preview', '/winner'); + INSERT OR IGNORE INTO session_metadata (session_id, revision, title, title_source) + VALUES ('{winner}', 1, 'winner-title', 'manual'); + INSERT OR IGNORE INTO timeline_events (session_id, branch_id, sequence, last_sequence, kind, body, event_id) + VALUES ('{winner}', 'main', 99, 99, 'winner-kind', '{{\"winner\":true}}', 'winner-marker'); + END;" + )) + .unwrap(); +} + +/// The concurrent winner's own rows, asserted field by field: the copy's +/// cleanup must never reach a Session another connection committed. +fn assert_winner_intact(connection: &Connection, winner: &str) { + let row: Option<(String, String)> = connection + .query_row( + "SELECT config, origin FROM agent_sessions WHERE session_id=?1", + [winner], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .optional() + .unwrap(); + let (config, origin) = + row.unwrap_or_else(|| panic!("the winning Session {winner:?} lost its agent_sessions row")); + assert_eq!( + config, "{\"cwd\":\"/winner\"}", + "the winning Session's config was overwritten" + ); + assert_eq!( + origin, "client", + "the winning Session's origin was overwritten" + ); + let catalog: Option<(i64, Option, String)> = connection + .query_row( + "SELECT updated_at_ms, preview, cwd FROM session_catalog WHERE session_id=?1", + [winner], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + ) + .optional() + .unwrap(); + assert_eq!( + catalog, + Some((1, Some("winner-preview".to_owned()), "/winner".to_owned())), + "the winning Session's catalog row must survive unchanged" + ); + let metadata: Option<(i64, Option)> = connection + .query_row( + "SELECT revision, title FROM session_metadata WHERE session_id=?1", + [winner], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .optional() + .unwrap(); + assert_eq!( + metadata, + Some((1, Some("winner-title".to_owned()))), + "the winning Session's metadata row must survive unchanged" + ); + let marker: Option<(String, String)> = connection + .query_row( + "SELECT kind, body FROM timeline_events WHERE session_id=?1 AND branch_id='main' AND sequence=99", + [winner], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .optional() + .unwrap(); + assert_eq!( + marker, + Some(("winner-kind".to_owned(), "{\"winner\":true}".to_owned())), + "the winning Session's Timeline rows must survive the copy cleanup" + ); +} + +/// #2204: another connection commits the fork's target byte-identically while +/// the copy's first chunk writes. The fork is refused and the winning Session +/// keeps every row it committed; the cleanup may only remove rows the fork +/// itself wrote. +#[tokio::test] +async fn a_concurrent_creation_during_the_first_copy_write_is_refused_and_the_winner_survives() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append( + &store, + key("source", "main"), + vec![text(1, "first"), text(2, "second"), text(3, "third")], + ) + .await + .unwrap(); + let connection = Connection::open(&database.0).unwrap(); + commit_winner_when_copy_writes( + &connection, + "timeline_branches", + "fork-target", + "fork-target", + ); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + + let result = sessions + .fork_session("source", "fork-target", 3, &config) + .await; + assert!( + matches!(result, Err(AgentError::Storage(_))), + "a byte-identical concurrent creation must keep the fork's Storage refusal, got {result:?}" + ); + assert_winner_intact(&connection, "fork-target"); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// #2204: the concurrent creation commits after the copy's first chunks, so +/// only the final transaction's re-check can see it. The refusal must be the +/// re-check's, and the cleanup after it must still leave the winning Session +/// intact. +#[tokio::test] +async fn a_concurrent_creation_caught_by_the_final_recheck_keeps_the_winner_intact() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append( + &store, + key("source", "main"), + vec![text(1, "first"), text(2, "second"), text(3, "third")], + ) + .await + .unwrap(); + let connection = Connection::open(&database.0).unwrap(); + commit_winner_when_copy_writes(&connection, "timeline_events", "fork-target", "fork-target"); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + + let result = sessions + .fork_session("source", "fork-target", 3, &config) + .await; + assert!( + matches!(result, Err(AgentError::Storage(_))), + "a byte-identical concurrent creation must keep the fork's Storage refusal, got {result:?}" + ); + assert_winner_intact(&connection, "fork-target"); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// The final transaction's re-check tells a case-only variant apart from a +/// byte-identical duplicate: the concurrent creation commits `Fork-Target` +/// while the copy targets `fork-target`, so the refusal is InvalidInput and +/// the variant's rows stay untouched. +#[tokio::test] +async fn the_final_recheck_rejects_a_case_variant_with_invalid_input() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append( + &store, + key("source", "main"), + vec![text(1, "first"), text(2, "second"), text(3, "third")], + ) + .await + .unwrap(); + let connection = Connection::open(&database.0).unwrap(); + commit_winner_when_copy_writes(&connection, "timeline_events", "fork-target", "Fork-Target"); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + + let result = sessions + .fork_session("source", "fork-target", 3, &config) + .await; + assert!( + matches!(result, Err(AgentError::InvalidInput(_))), + "a concurrent creation differing only by case must be InvalidInput, got {result:?}" + ); + assert_winner_intact(&connection, "Fork-Target"); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} From a3b7694670f7ed41856fdfbac9ffcbf02a854557 Mon Sep 17 00:00:00 2001 From: huihui Date: Sat, 28 Nov 2026 06:50:43 +0800 Subject: [PATCH 03/16] fix(app-server): reject new Session ids sharing an output directory with a legacy one under filesystem identity rules (#2204) A retained legacy Session id can collide with a newly admitted lowercase id on a supported filesystem even when it differs byte-for-byte and under ASCII case folding: casefold volumes strip default-ignorable code points and fold the Unicode pairs (Kelvin sign, long s, sharp s, ligatures), and Windows trims trailing dots and spaces, reads a backslash or colon suffix as a path inside or a stream of the base name, maps the dotted and dotless i, and can serve a long name as its 8.3 short name, plain or hashed. The write entries now look up every stored id outside the admitted alphabet through the new covering partial derived index agent_sessions_session_id_non_ascii_word - inside the create_session write transaction, the fork copy's first chunk transaction and the final re-check, all before publishing anything - and refuse the candidate with InvalidInput when the union of the casefold and Windows rules shares the output directory, while byte-identical duplicates keep their Storage error. FORMAT stays 53; the index carries no data, and the format gate ignores it as it does the other derived indexes, so an older binary refuses a store that has it while the store itself is preserved. Deleting the legacy row unblocks the id it blocked, restoration and deletion of stored ids are unchanged, and dim-agent-runtime is untouched. --- crates/dim-app-server/src/storage/sqlite.rs | 14 +- crates/dim-app-server/src/storage/timeline.rs | 175 ++++++- crates/dim-app-server/tests/storage_flow.rs | 6 +- .../tests/storage_flow/admission.rs | 435 +++++++++++++++++- .../design/appserver/native-storage-format.md | 8 +- 5 files changed, 608 insertions(+), 30 deletions(-) diff --git a/crates/dim-app-server/src/storage/sqlite.rs b/crates/dim-app-server/src/storage/sqlite.rs index 4c70d3a777..4df351db1c 100644 --- a/crates/dim-app-server/src/storage/sqlite.rs +++ b/crates/dim-app-server/src/storage/sqlite.rs @@ -629,10 +629,12 @@ fn same_schema(actual: &[(String, String)], mut expected: Vec<(&str, String)>) - /// The read indexes the daemon creates at open: the latest-turn window's /// ([session-history-window §5.1](../../../../docs/design/appserver/session-history-window.md#51-the-derived-index)), /// the policy window's turn starts, the event query's by kind, which carries -/// the event id so a kind read needs no table body for it (ADR 019 D4), and the -/// case-insensitive Session id lookup the creation collision checks run (#2204). -/// They carry no data and no decode rule, so they are not part of the format: -/// `schema` and the format gate ignore them, and every open recreates them. +/// the event id so a kind read needs no table body for it (ADR 019 D4), the +/// case-insensitive Session id lookup the creation collision checks run, and +/// the stored ids outside the newly admitted alphabet, which the +/// output-directory conflict lookup reads (#2204). They carry no data and no +/// decode rule, so they are not part of the format: `schema` and the format +/// gate ignore them, and every open recreates them. const DERIVED_INDEXES: &[(&str, &str)] = &[ ( "timeline_history_anchors", @@ -650,6 +652,10 @@ const DERIVED_INDEXES: &[(&str, &str)] = &[ "agent_sessions_session_id_nocase", "CREATE INDEX IF NOT EXISTS agent_sessions_session_id_nocase ON agent_sessions(session_id COLLATE NOCASE)", ), + ( + "agent_sessions_session_id_non_ascii_word", + "CREATE INDEX IF NOT EXISTS agent_sessions_session_id_non_ascii_word ON agent_sessions(session_id) WHERE session_id GLOB '*[^0-9A-Za-z_-]*'", + ), ]; /// The schema objects of `connection`'s database that belong to the format, /// sorted by name. diff --git a/crates/dim-app-server/src/storage/timeline.rs b/crates/dim-app-server/src/storage/timeline.rs index a2419fe05d..41827031b7 100644 --- a/crates/dim-app-server/src/storage/timeline.rs +++ b/crates/dim-app-server/src/storage/timeline.rs @@ -2381,6 +2381,143 @@ fn case_conflicts(connection: &Connection, candidate: &str) -> Result Result> { + let mut rows = Vec::new(); + let mut statement = connection + .prepare_cached( + "SELECT session_id FROM agent_sessions WHERE session_id GLOB '*[^0-9A-Za-z_-]*'", + ) + .map_err(error)?; + for row in statement + .query_map([], |row| row.get::<_, String>(0)) + .map_err(error)? + { + rows.push(row.map_err(error)?); + } + Ok(rows) +} + +/// The identity of `stored` on a volume that folds case — APFS, HFS+ or a +/// Linux casefold directory — as one canonical key: lowercase, uppercase, +/// then ASCII-lowercase. Lowercase alone misses the pairs whose lowercase is +/// the same non-ASCII letter while their uppercase differs; uppercasing in +/// between maps every folding pair onto one key — ASCII case, the Kelvin +/// sign, the long s, ß/ẞ onto ss, the ligatures onto their expansion. The +/// second key strips the Unicode default-ignorable code points first, which a +/// casefold volume drops before comparing. The admitted lowercase ASCII +/// candidate is its own key, so comparison is bytewise. +fn casefold_keys(stored: &str) -> [String; 2] { + let fold = |text: &str| text.to_lowercase().to_uppercase().to_ascii_lowercase(); + let folded = fold(stored); + let stripped = fold( + &stored + .chars() + .filter(|c| !is_default_ignorable(*c)) + .collect::(), + ); + [folded, stripped] +} + +/// The Unicode default-ignorable code points a casefold volume strips from a +/// directory name before comparing it. Ranges per PropList.txt (Unicode +/// 15.1): the soft hyphen, combining grapheme joiner, Arabic and Mongolian +/// format characters, the zero-width and directional formatting characters, +/// the Hangul fillers, variation selectors, tag characters and the musical +/// format controls. +fn is_default_ignorable(c: char) -> bool { + matches!(c as u32, + 0x00AD | 0x034F | 0x061C | 0x115F..=0x1160 | 0x17B4..=0x17B5 | 0x180B..=0x180E + | 0x200B..=0x200F | 0x202A..=0x202E | 0x2060..=0x206F | 0x3164 + | 0xFE00..=0xFE0F | 0xFEFF | 0xFFA0 | 0xFFF0..=0xFFF8 + | 0x1BCA0..=0x1BCA3 | 0x1D173..=0x1D17A | 0xE0000..=0xE0FFF) +} + +/// `stored` lowercased under the Windows volume rules: ASCII letters fold, +/// and the dotted capital İ, the dotless ı, the long s and the Kelvin sign +/// map onto their ASCII pair. Windows neither expands ß nor strips ignorable +/// characters; those forms are covered by the casefold rule. +fn windows_lower(stored: &str) -> String { + stored + .chars() + .map(|c| match c { + 'A'..='Z' => c.to_ascii_lowercase(), + '\u{130}' | '\u{131}' => 'i', + '\u{17F}' => 's', + '\u{212A}' => 'k', + other => other, + }) + .collect() +} + +/// The name `stored` addresses on a Windows volume after its syntactic rules: +/// the segment before the first backslash, then before the first colon — what +/// a path inside the directory or one of its streams shares — with trailing +/// dots and spaces trimmed, under the Windows case mapping. +fn windows_name(stored: &str) -> String { + let backslash = stored.split('\\').next().unwrap_or(stored); + let colon = backslash.split(':').next().unwrap_or(backslash); + windows_lower(colon.trim_end_matches(['.', ' '])) +} + +/// Whether `stem` (the Windows form of a stored id, tilde and tail included) +/// can be the 8.3 short name a Windows volume serves `candidate` as: the +/// classic form truncates the long name at the stem, and the hashed form +/// keeps the long name's leading characters, replaces the middle with four +/// hexadecimal checksum digits and appends the tail — so a candidate starting +/// with what precedes those digits collides with it too. Only tails of one +/// digit from 1 upward are generated. +fn windows_8_3_collides(stem: &str, candidate: &str) -> bool { + let Some((stem, tail)) = stem.rsplit_once('~') else { + return false; + }; + if tail.len() != 1 || !matches!(tail.as_bytes()[0], b'1'..=b'9') { + return false; + } + if candidate.starts_with(stem) { + return true; + } + let letters: Vec = stem.chars().collect(); + letters.len() >= 5 + && letters[letters.len() - 4..] + .iter() + .all(|c| c.is_ascii_hexdigit()) + && candidate.starts_with(&letters[..letters.len() - 4].iter().collect::()) +} + +/// Whether a stored Session id can share its output directory with a newly +/// admitted id under the identity rules of a supported filesystem — a volume +/// folding case, or a Windows volume with its separators, trailing characters +/// and 8.3 short names. Both rule sets apply wherever the store runs, so a +/// store moving between platforms keeps its isolation (#2204): refusing too +/// much is safe, missing a collision is not. +fn shares_output_directory(stored: &str, candidate: &str) -> bool { + if casefold_keys(stored).iter().any(|key| key == candidate) { + return true; + } + let windows = windows_name(stored); + if windows == candidate { + return true; + } + candidate.len() > 8 && windows.len() <= 8 && windows_8_3_collides(&windows, candidate) +} + +/// A stored id that shares an output directory with `candidate` beyond ASCII +/// case folding, judged row by row under the filesystem identity rules +/// (#2204). +fn directory_conflict(connection: &Connection, candidate: &str) -> Result> { + for stored in non_ascii_word_conflicts(connection)? { + if shares_output_directory(&stored, candidate) { + return Ok(Some(stored)); + } + } + Ok(None) +} fn create_session( connection: &Connection, session: &str, @@ -2396,6 +2533,11 @@ fn create_session( "Session id {session} differs from a stored one only by case" ))); } + if let Some(stored) = directory_conflict(connection, session)? { + return Err(AgentError::InvalidInput(format!( + "Session id {session} would share an output directory with stored Session {stored}" + ))); + } let config = serde_json::to_string(config).map_err(error)?; connection .execute( @@ -3180,21 +3322,28 @@ fn copy_fork( copied } -/// Rejects `candidate` when a stored Session id equals it under the -/// case-insensitive collation: byte-identical keeps the duplicate's Storage -/// error, a case-only variant is InvalidInput (#2204). +/// Rejects `candidate` when a stored Session id collides with it: equals it +/// under the case-insensitive collation or shares its output directory under +/// a supported filesystem's identity rules. Byte-identical keeps the +/// duplicate's Storage error; a case-only variant and a directory-shape +/// collision are InvalidInput (#2204). fn reject_conflicting_id(connection: &Connection, candidate: &str) -> Result<()> { let conflicts = case_conflicts(connection, candidate)?; - if conflicts.is_empty() { - return Ok(()); - } - Err(if conflicts.iter().any(|stored| stored != candidate) { - AgentError::InvalidInput(format!( - "Session id {candidate} differs from a stored one only by case" - )) - } else { - error(format!("Session id {candidate} already exists")) - }) + if !conflicts.is_empty() { + return Err(if conflicts.iter().any(|stored| stored != candidate) { + AgentError::InvalidInput(format!( + "Session id {candidate} differs from a stored one only by case" + )) + } else { + error(format!("Session id {candidate} already exists")) + }); + } + if let Some(stored) = directory_conflict(connection, candidate)? { + return Err(AgentError::InvalidInput(format!( + "Session id {candidate} would share an output directory with stored Session {stored}" + ))); + } + Ok(()) } fn copy_fork_rows( diff --git a/crates/dim-app-server/tests/storage_flow.rs b/crates/dim-app-server/tests/storage_flow.rs index 62b09dd784..c32e35eece 100644 --- a/crates/dim-app-server/tests/storage_flow.rs +++ b/crates/dim-app-server/tests/storage_flow.rs @@ -689,7 +689,8 @@ fn schema(connection: &Connection) -> Vec { .prepare( "SELECT sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' \ AND name NOT IN ('timeline_history_anchors', 'timeline_events_by_kind', \ - 'timeline_policy_turns', 'agent_sessions_session_id_nocase') + 'timeline_policy_turns', 'agent_sessions_session_id_nocase', \ + 'agent_sessions_session_id_non_ascii_word') AND name NOT IN (SELECT name FROM pragma_table_list WHERE type='shadow' AND name LIKE 'timeline_text_fts_%')", ) .unwrap() @@ -8488,7 +8489,8 @@ async fn a_v41_store_upgrades_in_place_once_keeping_internal_launches() { indexed, [ "agent_sessions_by_leader", - "agent_sessions_session_id_nocase" + "agent_sessions_session_id_nocase", + "agent_sessions_session_id_non_ascii_word" ] ); for (session, expected) in [("s1", "client"), ("member", "internal")] { diff --git a/crates/dim-app-server/tests/storage_flow/admission.rs b/crates/dim-app-server/tests/storage_flow/admission.rs index 9f6dc11290..e76dca580d 100644 --- a/crates/dim-app-server/tests/storage_flow/admission.rs +++ b/crates/dim-app-server/tests/storage_flow/admission.rs @@ -2,13 +2,17 @@ //! `createOwnedSession` or a fork's target is lowercase ASCII — one to //! sixty-four characters of `[a-z0-9_-]`, and never a Windows reserved device //! name — and is rejected with InvalidInput before anything is written. The -//! store refuses a write whose id differs from a stored one only by case: -//! the case variant is InvalidInput, while a byte-identical duplicate keeps -//! its Storage error. A fork refused before its copy starts writes nothing -//! and drops nothing, so a target byte-identical to a stored Session cannot -//! delete that Session's rows. Ids already stored keep their bytes: -//! restoration reads them as written, and deletion plus use as a fork source -//! are unchanged. +//! store refuses a write whose id differs from a stored one only by case, +//! and a write whose id would share an output directory with a stored one +//! under a supported filesystem's identity rules — Unicode folding pairs, +//! default-ignorable code points, the Windows separators, trailing dots and +//! spaces and Unicode mappings, and the 8.3 short names. Both refusals are +//! InvalidInput, while a byte-identical duplicate keeps its Storage error. A +//! fork refused before its copy starts writes nothing and drops nothing, so +//! it cannot delete the rows of the Session it conflicted with. Ids already +//! stored keep their bytes: restoration reads them as written, deletion plus +//! use as a fork source are unchanged, and deleting the stored row unblocks +//! the id it conflicted with. use super::*; @@ -473,8 +477,7 @@ async fn case_collision_check_uses_the_derived_index() { let connection = Connection::open(&database.0).unwrap(); let plan: Vec = connection .prepare( - "EXPLAIN QUERY PLAN SELECT session_id FROM agent_sessions \ - WHERE session_id = ?1 COLLATE NOCASE AND session_id <> ?1", + "EXPLAIN QUERY PLAN SELECT session_id FROM agent_sessions WHERE session_id = ?1 COLLATE NOCASE", ) .unwrap() .query_map(["candidate"], |row| row.get::<_, String>(3)) @@ -491,6 +494,175 @@ async fn case_collision_check_uses_the_derived_index() { db.close().await.unwrap(); } +/// Legacy ids stored before the admission rule can share an output directory +/// with a newly admitted lowercase id under a supported filesystem's identity +/// rules even though they differ byte-for-byte and under ASCII case folding: +/// Unicode folding pairs (Kelvin sign, long s, ß/ẞ, ligatures), Unicode +/// default-ignorable code points (casefold volumes), and the Windows shapes — +/// backslash and alternate-stream separators, trailing dots and spaces, +/// Unicode mappings — plus the 8.3 short names, both plain and hashed. The +/// write entries must refuse such a candidate with InvalidInput before +/// anything is published, while the stored row keeps its bytes. +async fn assert_directory_shape_rejected(stored: &str, candidate: &str, why: &str) { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_owner(&connection); + seed_stored_session(&connection, stored); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append(&store, key("source", "main"), vec![text(1, "source")]) + .await + .unwrap(); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + + let created = sessions + .create_owned_session( + candidate, + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await; + assert!( + matches!(created, Err(AgentError::InvalidInput(_))), + "{why}: creating {candidate:?} while {stored:?} is stored must be InvalidInput, got {created:?}" + ); + let forked = sessions.fork_session("source", candidate, 1, &config).await; + assert!( + matches!(forked, Err(AgentError::InvalidInput(_))), + "{why}: forking into {candidate:?} while {stored:?} is stored must be InvalidInput, got {forked:?}" + ); + assert_eq!( + stored_rows(&connection, candidate), + 0, + "{why}: the refused candidate {candidate:?} writes nothing" + ); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// One regression per output-directory-sharing shape (stored, candidate). +macro_rules! directory_shape { + ($name:ident, $stored:expr, $candidate:expr, $why:expr) => { + #[tokio::test] + async fn $name() { + assert_directory_shape_rejected($stored, $candidate, $why).await; + } + }; +} + +directory_shape!( + kelvin_sign_folds_to_ascii_k, + "ab\u{212A}", + "abk", + "APFS/HFS+/Linux-casefold fold the Kelvin sign U+212A to k" +); +directory_shape!( + long_s_folds_to_ascii_s, + "ab\u{17F}", + "abs", + "the long s U+017F folds to s under both volume rules" +); +directory_shape!( + sharp_s_uppercases_to_ss, + "ab\u{DF}", + "abss", + "ß uppercases to SS, so a casefold volume equates it with ss" +); +directory_shape!( + uppercase_sharp_s_uppercases_to_ss, + "ab\u{1E9E}", + "abss", + "ẞ uppercases to SS, so a casefold volume equates it with ss" +); +directory_shape!( + ff_ligature_uppercases_to_ff, + "ab\u{FB00}", + "abff", + "the ff ligature uppercases to FF, so a casefold volume equates it with ff" +); +directory_shape!( + default_ignorable_is_stripped_before_folding, + "abc\u{AD}", + "abc", + "the soft hyphen U+00AD is a default-ignorable a casefold volume strips" +); +directory_shape!( + windows_backslash_prefix_shares_the_first_segment, + "abc\\def", + "abc", + "under Windows rules abc\\def names a path inside abc" +); +directory_shape!( + windows_index_allocation_stream_shares_the_base, + "abc::$INDEX_ALLOCATION", + "abc", + "under Windows rules abc::$INDEX_ALLOCATION is a stream of abc" +); +directory_shape!( + windows_alternate_stream_shares_the_base, + "abc:x", + "abc", + "under Windows rules abc:x is an alternate stream of abc" +); +directory_shape!( + windows_trailing_dot_is_trimmed, + "abc.", + "abc", + "under Windows rules a trailing dot is trimmed, so abc. is abc" +); +directory_shape!( + windows_trailing_space_is_trimmed, + "abc ", + "abc", + "under Windows rules a trailing space is trimmed, so abc␣ is abc" +); +directory_shape!( + windows_dotted_capital_i_maps_to_i, + "ab\u{130}", + "abi", + "under Windows rules the dotted capital İ maps onto i" +); +directory_shape!( + windows_dotless_i_maps_to_i, + "ab\u{131}", + "abi", + "under Windows rules the dotless ı maps onto i" +); +directory_shape!( + windows_8_3_short_name_aliasing, + "ab12cd~7", + "ab12cdxyz", + "an 8.3 volume may serve the long name ab12cdxyz as ab12cd~7" +); +directory_shape!( + windows_8_3_hashed_short_name_aliasing, + "ab12cd~7", + "abwxyztuv", + "an 8.3 volume may serve the long name abwxyztuv as the hashed ab12cd~7" +); + /// A trigger that stands in for another connection committing a Session of /// `winner` the moment the copy writes its first `into` row for `fork` — the /// timing a concurrent creation would have. Its rows ride the copy's own @@ -733,3 +905,248 @@ async fn the_final_recheck_rejects_a_case_variant_with_invalid_input() { db.close().await.unwrap(); root.shutdown().await.unwrap(); } + +/// The conflict lookup is per stored row, not a frozen key set: once the +/// legacy row is deleted, the id it blocked is admitted again, on both the +/// creation and the fork entry. +#[tokio::test] +async fn deleting_the_legacy_row_unblocks_the_shape_it_conflicted_with() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_owner(&connection); + seed_stored_session(&connection, "Legacy-1"); + seed_stored_session(&connection, "ab\u{212A}"); + + let blocked = sessions + .create_owned_session( + "legacy-1", + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await; + assert!( + matches!(blocked, Err(AgentError::InvalidInput(_))), + "the case variant is refused while the legacy row is stored, got {blocked:?}" + ); + let shaped = sessions + .create_owned_session( + "abk", + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await; + assert!( + matches!(shaped, Err(AgentError::InvalidInput(_))), + "the folding variant is refused while the legacy row is stored, got {shaped:?}" + ); + + assert!(sessions.delete_session("Legacy-1").await.unwrap()); + connection + .execute( + "DELETE FROM agent_sessions WHERE session_id='ab\u{212A}'", + [], + ) + .unwrap(); + + sessions + .create_owned_session( + "legacy-1", + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await + .unwrap(); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append(&store, key("source", "main"), vec![text(1, "source")]) + .await + .unwrap(); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + sessions + .fork_session("source", "abk", 1, &config) + .await + .unwrap(); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// #2204: the directory-shape lookup the write entries run must resolve +/// through the covering partial derived index — verbatim as the index defines +/// it — instead of scanning `agent_sessions`. +#[tokio::test] +async fn directory_shape_check_uses_the_derived_index() { + let database = Database::new(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let connection = Connection::open(&database.0).unwrap(); + let plan: Vec = connection + .prepare( + "EXPLAIN QUERY PLAN SELECT session_id FROM agent_sessions WHERE session_id GLOB '*[^0-9A-Za-z_-]*'", + ) + .unwrap() + .query_map([], |row| row.get::<_, String>(3)) + .unwrap() + .collect::>>() + .unwrap(); + assert!( + plan.iter() + .any(|step| { step.contains("agent_sessions_session_id_non_ascii_word") }), + "the directory-shape check must use the covering index, plan: {plan:?}" + ); + + drop(connection); + db.close().await.unwrap(); +} + +/// A write ledger for one fork target: every row the copy inserts or deletes +/// under the fork's id in the tables the copy touches is recorded, including +/// the cleanup's deletions. A fork refused before its first write must leave +/// the ledger empty — zero writes, zero cleanup. +fn ledger_fork_writes(connection: &Connection, fork: &str) { + connection + .execute_batch(&format!( + "CREATE TABLE copy_ledger (entry TEXT); + CREATE TRIGGER ledger_branches_insert AFTER INSERT ON timeline_branches + WHEN NEW.session_id = '{fork}' + BEGIN INSERT INTO copy_ledger VALUES ('timeline_branches'); END; + CREATE TRIGGER ledger_events_insert AFTER INSERT ON timeline_events + WHEN NEW.session_id = '{fork}' + BEGIN INSERT INTO copy_ledger VALUES ('timeline_events'); END; + CREATE TRIGGER ledger_content_insert AFTER INSERT ON timeline_content + WHEN NEW.session_id = '{fork}' + BEGIN INSERT INTO copy_ledger VALUES ('timeline_content'); END; + CREATE TRIGGER ledger_sessions_insert AFTER INSERT ON agent_sessions + WHEN NEW.session_id = '{fork}' + BEGIN INSERT INTO copy_ledger VALUES ('agent_sessions'); END; + CREATE TRIGGER ledger_branches_delete AFTER DELETE ON timeline_branches + WHEN OLD.session_id = '{fork}' + BEGIN INSERT INTO copy_ledger VALUES ('delete-timeline_branches'); END; + CREATE TRIGGER ledger_events_delete AFTER DELETE ON timeline_events + WHEN OLD.session_id = '{fork}' + BEGIN INSERT INTO copy_ledger VALUES ('delete-timeline_events'); END; + CREATE TRIGGER ledger_content_delete AFTER DELETE ON timeline_content + WHEN OLD.session_id = '{fork}' + BEGIN INSERT INTO copy_ledger VALUES ('delete-timeline_content'); END; + CREATE TRIGGER ledger_sessions_delete AFTER DELETE ON agent_sessions + WHEN OLD.session_id = '{fork}' + BEGIN INSERT INTO copy_ledger VALUES ('delete-agent_sessions'); END;" + )) + .unwrap(); +} + +fn ledger_entries(connection: &Connection) -> Vec { + connection + .prepare("SELECT entry FROM copy_ledger") + .unwrap() + .query_map([], |row| row.get::<_, String>(0)) + .unwrap() + .collect::>>() + .unwrap() +} + +/// A fork refused by a conflict that precedes the copy writes nothing and +/// runs no cleanup: the ledger proves not one row of the fork's id was ever +/// inserted or deleted, and the stored Session it conflicted with is +/// untouched. Shared by the case-collision and the directory-shape refusal. +async fn assert_refused_fork_never_writes(seed: &str, fork: &str, error: &str) { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append( + &store, + key("source", "main"), + vec![text(1, "first"), text(2, "second"), text(3, "third")], + ) + .await + .unwrap(); + let connection = Connection::open(&database.0).unwrap(); + seed_stored_session(&connection, seed); + ledger_fork_writes(&connection, fork); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + + let result = sessions.fork_session("source", fork, 3, &config).await; + match error { + "storage" => assert!( + matches!(result, Err(AgentError::Storage(_))), + "the refused fork must keep its Storage error, got {result:?}" + ), + _ => assert!( + matches!(result, Err(AgentError::InvalidInput(_))), + "the refused fork must be InvalidInput, got {result:?}" + ), + } + assert!( + ledger_entries(&connection).is_empty(), + "a fork refused before its first write may not write or delete a single row, ledger: {:?}", + ledger_entries(&connection) + ); + assert_eq!( + stored_rows(&connection, seed), + 1, + "the stored Session {seed:?} the fork conflicted with is untouched" + ); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// #2204 (decision Q2 c (1)): a stored Session differing from the fork target +/// only by case refuses the fork inside the first chunk transaction, before +/// its first write — zero inserts, zero cleanup. +#[tokio::test] +async fn a_fork_conflicting_by_case_is_refused_with_zero_writes_and_zero_cleanup() { + assert_refused_fork_never_writes("Fork-Case", "fork-case", "invalid").await; +} + +/// #2204: the same zero-write guarantee covers the directory-shape check in +/// the first chunk transaction — the conflict the NOCASE lookup cannot see. +#[tokio::test] +async fn a_fork_conflicting_by_directory_shape_is_refused_with_zero_writes_and_zero_cleanup() { + assert_refused_fork_never_writes("fork-shape\u{212A}", "fork-shapek", "invalid").await; +} diff --git a/docs/design/appserver/native-storage-format.md b/docs/design/appserver/native-storage-format.md index f3afede49e..6eaf213ac3 100644 --- a/docs/design/appserver/native-storage-format.md +++ b/docs/design/appserver/native-storage-format.md @@ -249,11 +249,15 @@ valid in v48, and v16 request rows stay readable as written. `timeline_events_by_kind`(`(session_id, branch_id, kind, sequence, event_id)`,按 kind 读取事件而不碰事件体,[ADR 019](../../adr/019-event-query.md) D4)与 `agent_sessions_session_id_nocase`(`agent_sessions(session_id COLLATE NOCASE)`,#2204 -创建写入入口的大小写冲突检查走它做索引查找而不是扫表):读写打开在启动事务内用 +创建写入入口的大小写冲突检查走它做索引查找而不是扫表)与 +`agent_sessions_session_id_non_ascii_word`(`agent_sessions(session_id) +WHERE session_id GLOB '*[^0-9A-Za-z_-]*'`,#2204 输出目录冲突检查按它逐个取出 +准入字母表之外的已存 id 再在 Rust 里按文件系统身份规则判断,常规库为空、不扫表): +读写打开在启动事务内用 `CREATE INDEX IF NOT EXISTS` 创建或补建,只读导出只接受它们。它们不含数据,可从其 基表重新推导,读同一份数据不因它们有无而不同,因此不属于格式:启动门禁的 精确结构比较忽略这些名字,格式标记不变(当前 v53);其余任何多余对象仍按原规则拒绝。代价是早于 -该变更的二进制不认识这些名字,会以 "unsupported SQLite schema … preserved" 拒绝已有该 +该变更的二进制不认识这些名字,会以 "unsupported SQLite schema … preserved" 拒绝已有这些 索引的库(行不变,原库保留,新二进制可再次打开)。 Storage versions are independent of RPC versions. Private MCP/Skill business documents do not belong in loader rows, events, diagnostics, Sessions or Timelines. From bab721455db3e37adeb9588988e6a844b80990bd Mon Sep 17 00:00:00 2001 From: huihui Date: Sat, 28 Nov 2026 08:17:49 +0800 Subject: [PATCH 04/16] fix(app-server): precedence and coverage fixes for legacy Session id isolation (#2204) Windows 8.3 short-name tails accept multi-digit ASCII sequences with a non-empty stem: a legacy id like abcde~12 is refused as colliding, while an empty stem like ~1 no longer blocks every long candidate. The default-ignorable ranges add U+180F per DerivedCoreProperties.txt, so a legacy id carrying it no longer shares a casefold directory silently. A byte-identical duplicate keeps its Storage error even when a case variant or a directory-shape collision is stored beside it; create_session now shares the one rejection helper instead of its own copy. The fork copy runs its cleanup only after its first chunk transaction committed, so a refusal ahead of the first write deletes nothing, and the ownership-check database error inside the cleanup propagates instead of being reported as a concurrent creation. resource-faces.md and the plugin.d.ts contract comment now state the id admission shape and the output-directory rule; deletion keeps its single path component check. --- crates/dim-app-server/src/storage/timeline.rs | 90 ++++--- .../tests/storage_flow/admission.rs | 239 ++++++++++++++++++ docs/design/resource-faces.md | 14 +- npm/plugin.d.ts | 2 +- 4 files changed, 301 insertions(+), 44 deletions(-) diff --git a/crates/dim-app-server/src/storage/timeline.rs b/crates/dim-app-server/src/storage/timeline.rs index 41827031b7..ed7eabf216 100644 --- a/crates/dim-app-server/src/storage/timeline.rs +++ b/crates/dim-app-server/src/storage/timeline.rs @@ -30,6 +30,7 @@ use rutis::host::{CtxHost, DynPlugin, Effect, Key, TypeKey}; use rutis_bridge::session::{HostDispatch, host_key}; use serde::{Deserialize, Serialize}; use std::{ + cell::Cell, collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque}, ops::RangeInclusive, panic::{AssertUnwindSafe, catch_unwind}, @@ -2425,14 +2426,15 @@ fn casefold_keys(stored: &str) -> [String; 2] { } /// The Unicode default-ignorable code points a casefold volume strips from a -/// directory name before comparing it. Ranges per PropList.txt (Unicode -/// 15.1): the soft hyphen, combining grapheme joiner, Arabic and Mongolian -/// format characters, the zero-width and directional formatting characters, -/// the Hangul fillers, variation selectors, tag characters and the musical -/// format controls. +/// directory name before comparing it. Ranges per the +/// Default_Ignorable_Code_Point property in DerivedCoreProperties.txt +/// (Unicode 15.1): the soft hyphen, combining grapheme joiner, Arabic and +/// Mongolian format characters, the zero-width and directional formatting +/// characters, the Hangul fillers, variation selectors, tag characters and +/// the musical format controls. fn is_default_ignorable(c: char) -> bool { matches!(c as u32, - 0x00AD | 0x034F | 0x061C | 0x115F..=0x1160 | 0x17B4..=0x17B5 | 0x180B..=0x180E + 0x00AD | 0x034F | 0x061C | 0x115F..=0x1160 | 0x17B4..=0x17B5 | 0x180B..=0x180F | 0x200B..=0x200F | 0x202A..=0x202E | 0x2060..=0x206F | 0x3164 | 0xFE00..=0xFE0F | 0xFEFF | 0xFFA0 | 0xFFF0..=0xFFF8 | 0x1BCA0..=0x1BCA3 | 0x1D173..=0x1D17A | 0xE0000..=0xE0FFF) @@ -2470,13 +2472,18 @@ fn windows_name(stored: &str) -> String { /// classic form truncates the long name at the stem, and the hashed form /// keeps the long name's leading characters, replaces the middle with four /// hexadecimal checksum digits and appends the tail — so a candidate starting -/// with what precedes those digits collides with it too. Only tails of one -/// digit from 1 upward are generated. +/// with what precedes those digits collides with it too. The tails generated +/// are ASCII digits whose first digit runs from 1 upward, growing to two and +/// more digits as the collisions of one stem accumulate; the outer length +/// rule already caps the whole short name at eight characters. fn windows_8_3_collides(stem: &str, candidate: &str) -> bool { let Some((stem, tail)) = stem.rsplit_once('~') else { return false; }; - if tail.len() != 1 || !matches!(tail.as_bytes()[0], b'1'..=b'9') { + if stem.is_empty() + || !matches!(tail.bytes().next(), Some(b'1'..=b'9')) + || !tail.bytes().all(|digit| digit.is_ascii_digit()) + { return false; } if candidate.starts_with(stem) { @@ -2525,19 +2532,7 @@ fn create_session( leader: Option<&str>, origin: SessionOrigin, ) -> Result<()> { - if case_conflicts(connection, session)? - .iter() - .any(|stored| stored != session) - { - return Err(AgentError::InvalidInput(format!( - "Session id {session} differs from a stored one only by case" - ))); - } - if let Some(stored) = directory_conflict(connection, session)? { - return Err(AgentError::InvalidInput(format!( - "Session id {session} would share an output directory with stored Session {stored}" - ))); - } + reject_conflicting_id(connection, session)?; let config = serde_json::to_string(config).map_err(error)?; connection .execute( @@ -3292,9 +3287,12 @@ fn chunk(connection: &mut Connection, step: impl FnOnce(&Connection) -> Resul /// A fork id that names a stored Session — byte-identical or only by case — /// is refused inside the first chunk transaction, before its first write /// (#2204): the refusal rolls that transaction back, so it writes nothing and -/// runs no cleanup. The cleanup of a copy refused later drops the id's rows -/// only while no Session of that exact id exists; one another connection -/// committed during the copy keeps the cleanup from deleting its rows. +/// no cleanup runs — a cleanup would only ever run against rows the copy +/// itself committed, and that transaction is the copy's only failure point +/// ahead of its first commit. The cleanup of a copy refused later drops the +/// id's rows only while no Session of that exact id exists; one another +/// connection committed during the copy keeps the cleanup from deleting its +/// rows. fn copy_fork( connection: &mut Connection, source: &str, @@ -3304,8 +3302,11 @@ fn copy_fork( arrays: &BTreeMap, config: &str, ) -> Result<()> { - let copied = copy_fork_rows(connection, source, fork, at, content, arrays, config); - if copied.is_err() { + let committed = Cell::new(false); + let copied = copy_fork_rows( + connection, source, fork, at, content, arrays, config, &committed, + ); + if copied.is_err() && committed.get() { match drop_fork_rows(connection, fork) { Ok(true) => {} Ok(false) => { @@ -3325,18 +3326,18 @@ fn copy_fork( /// Rejects `candidate` when a stored Session id collides with it: equals it /// under the case-insensitive collation or shares its output directory under /// a supported filesystem's identity rules. Byte-identical keeps the -/// duplicate's Storage error; a case-only variant and a directory-shape -/// collision are InvalidInput (#2204). +/// duplicate's Storage error even when a case variant or a directory-shape +/// collision is stored beside it (#2204); a case-only variant and a +/// directory-shape collision are InvalidInput. fn reject_conflicting_id(connection: &Connection, candidate: &str) -> Result<()> { let conflicts = case_conflicts(connection, candidate)?; + if conflicts.iter().any(|stored| stored == candidate) { + return Err(error(format!("Session id {candidate} already exists"))); + } if !conflicts.is_empty() { - return Err(if conflicts.iter().any(|stored| stored != candidate) { - AgentError::InvalidInput(format!( - "Session id {candidate} differs from a stored one only by case" - )) - } else { - error(format!("Session id {candidate} already exists")) - }); + return Err(AgentError::InvalidInput(format!( + "Session id {candidate} differs from a stored one only by case" + ))); } if let Some(stored) = directory_conflict(connection, candidate)? { return Err(AgentError::InvalidInput(format!( @@ -3346,6 +3347,13 @@ fn reject_conflicting_id(connection: &Connection, candidate: &str) -> Result<()> Ok(()) } +/// Copies the rows; `committed` flips the moment the first chunk transaction +/// commits, so the caller can tell rows it may clean up apart from a refusal +/// that rolled back before the first write. +#[expect( + clippy::too_many_arguments, + reason = "one parameter per piece of the copy plus its commit report" +)] fn copy_fork_rows( connection: &mut Connection, source: &str, @@ -3354,6 +3362,7 @@ fn copy_fork_rows( content: &[String], arrays: &BTreeMap, config: &str, + committed: &Cell, ) -> Result<()> { let cut = sql_sequence(at)?; // Intermediate chunks need no sync of their own: the final transaction @@ -3398,6 +3407,7 @@ fn copy_fork_rows( } Ok(()) })?; + committed.set(true); for (array, length) in arrays { let mut after = 0; while after < *length { @@ -3616,7 +3626,7 @@ fn drop_visible_rows(tx: &Connection, session: &str) -> Result { fn drop_timeline_rows( connection: &mut Connection, session: &str, - owned: impl Fn(&Connection) -> bool, + owned: impl Fn(&Connection) -> Result, ) -> Result> { for table in [ "timeline_output_ids", @@ -3633,7 +3643,7 @@ fn drop_timeline_rows( ] { loop { let Some(deleted) = chunk(connection, |tx| { - if !owned(tx) { + if !owned(tx)? { return Ok(None); } tx.execute( @@ -3669,7 +3679,7 @@ fn drop_session(connection: &mut Connection, session: &str) -> Result { connection .pragma_update(None, "synchronous", "NORMAL") .map_err(error)?; - drop_timeline_rows(connection, session, |_| true)?; + drop_timeline_rows(connection, session, |_| Ok(true))?; Ok(released) } @@ -3706,7 +3716,7 @@ fn drop_fork_rows(connection: &mut Connection, fork: &str) -> Result { connection .pragma_update(None, "synchronous", "NORMAL") .map_err(error)?; - Ok(drop_timeline_rows(connection, fork, |tx| unclaimed(tx, fork).unwrap_or(false))?.is_some()) + Ok(drop_timeline_rows(connection, fork, |tx| unclaimed(tx, fork))?.is_some()) } /// The content rows the events of `source`'s `main` through `at` reference, diff --git a/crates/dim-app-server/tests/storage_flow/admission.rs b/crates/dim-app-server/tests/storage_flow/admission.rs index e76dca580d..99eb5df2b0 100644 --- a/crates/dim-app-server/tests/storage_flow/admission.rs +++ b/crates/dim-app-server/tests/storage_flow/admission.rs @@ -1150,3 +1150,242 @@ async fn a_fork_conflicting_by_case_is_refused_with_zero_writes_and_zero_cleanup async fn a_fork_conflicting_by_directory_shape_is_refused_with_zero_writes_and_zero_cleanup() { assert_refused_fork_never_writes("fork-shape\u{212A}", "fork-shapek", "invalid").await; } + +directory_shape!( + windows_8_3_two_digit_tail_aliasing, + "abcde~12", + "abcdefghij", + "an 8.3 volume may serve the long name abcdefghij as abcde~12 once the stem's collisions accumulate" +); + +directory_shape!( + mongolian_free_variation_selector_four_is_stripped_before_folding, + "abc\u{180F}", + "abc", + "the Mongolian free variation selector four U+180F is a default-ignorable a casefold volume strips" +); + +/// A stored id whose 8.3 stem is empty — the volume never generates such a +/// short name — must not collide with any long candidate, including the +/// ordinary UUID-shaped creation ids. +#[tokio::test] +async fn an_empty_8_3_stem_blocks_no_long_candidate() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_owner(&connection); + seed_stored_session(&connection, "~1"); + + sessions + .create_owned_session( + "abcdef123456", + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await + .unwrap_or_else(|error| { + panic!("a long candidate must not collide with an empty 8.3 stem: {error:?}") + }); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append(&store, key("source", "main"), vec![text(1, "source")]) + .await + .unwrap(); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + sessions + .fork_session("source", "0f83c2da-4b18-4c61-9d1e-2a7b3c4d5e6f", 1, &config) + .await + .unwrap_or_else(|error| { + panic!("a UUID-shaped fork target must not collide with an empty 8.3 stem: {error:?}") + }); + assert_eq!( + stored_rows(&connection, "~1"), + 1, + "the stored row is untouched" + ); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// A store predating #2204 can hold a byte-identical duplicate and a +/// conflicting variant of the candidate at once. The duplicate's error takes +/// precedence on both write entries: it is the existing Session's protection, +/// while the variant's InvalidInput is only the admission refusal. +async fn assert_byte_identical_precedence(variant: &str, of: &str) { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_owner(&connection); + seed_stored_session(&connection, "abc"); + seed_stored_session(&connection, variant); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append(&store, key("source", "main"), vec![text(1, "source")]) + .await + .unwrap(); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + + let created = sessions + .create_owned_session( + "abc", + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await; + assert!( + matches!(created, Err(AgentError::Storage(_))), + "creating abc while abc and {variant} ({of}) are stored must keep the duplicate's Storage error, got {created:?}" + ); + let forked = sessions.fork_session("source", "abc", 1, &config).await; + assert!( + matches!(forked, Err(AgentError::Storage(_))), + "forking into abc while abc and {variant} ({of}) are stored must keep the duplicate's Storage error, got {forked:?}" + ); + assert_eq!( + connection + .query_row("SELECT count(*) FROM agent_sessions", [], |row| row + .get::<_, i64>(0)) + .unwrap(), + 3, + "abc, {variant} and the fork source stay stored, nothing else is written" + ); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// #2204 (decision Q2 c (2)): a legacy store holding `abc` beside its +/// uppercase variant reports the byte-identical duplicate as Storage, not the +/// variant's InvalidInput. +#[tokio::test] +async fn a_byte_identical_duplicate_beats_a_case_variant_on_both_write_entries() { + assert_byte_identical_precedence("ABC", "a case variant").await; +} + +/// #2204 (decision Q2 c (2)): the precedence also covers a variant that +/// collides only through the directory-shape rules, so creation must not +/// report InvalidInput for a duplicate the fork entry already reports as +/// Storage. +#[tokio::test] +async fn a_byte_identical_duplicate_beats_a_directory_shape_variant_on_both_write_entries() { + assert_byte_identical_precedence("abc.", "a directory-shape variant").await; +} + +/// #2204: a fork refused inside the first chunk transaction — before its copy +/// committed anything — runs no cleanup at all. Rows already present under +/// the fork's id, written around every validation the way an external writer +/// or a crashed earlier copy could leave them, must survive the refusal; the +/// ledger records neither an insert nor a delete. +#[tokio::test] +async fn a_fork_refused_before_its_first_write_deletes_no_preexisting_rows() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append( + &store, + key("source", "main"), + vec![text(1, "first"), text(2, "second"), text(3, "third")], + ) + .await + .unwrap(); + let connection = Connection::open(&database.0).unwrap(); + seed_stored_session(&connection, "Fork-Keep"); + // The row stands in for what an external writer or a crashed copy leaves + // under an id no Session owns: it cannot satisfy the branch foreign key, + // so it is written with the checks off, the way such rows exist. + connection + .execute_batch( + "PRAGMA foreign_keys = OFF; + INSERT INTO timeline_branches (session_id, branch_id, info, sequence) \ + VALUES ('fork-keep', 'main', '{\"id\":\"main\",\"parent\":null,\"branch_point\":null,\"create_anchor\":null}', 0); + PRAGMA foreign_keys = ON;", + ) + .unwrap(); + ledger_fork_writes(&connection, "fork-keep"); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + + let result = sessions + .fork_session("source", "fork-keep", 3, &config) + .await; + assert!( + matches!(result, Err(AgentError::InvalidInput(_))), + "the case-variant fork must be refused with InvalidInput, got {result:?}" + ); + assert_eq!( + connection + .query_row( + "SELECT count(*) FROM timeline_branches WHERE session_id='fork-keep'", + [], + |row| row.get::<_, i64>(0) + ) + .unwrap(), + 1, + "the rows already present under the fork's id must survive a refusal that wrote nothing" + ); + assert!( + ledger_entries(&connection).is_empty(), + "the refusal may not write or delete a single row, ledger: {:?}", + ledger_entries(&connection) + ); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index d85a031886..f956c7f54d 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -589,9 +589,17 @@ per-caller Session ownership or grant scoping. The lifecycle owner remains respo then initialize the fork under the source Agent/protocol. The repository copies the supplied text without applying live protocol exclusions or rebuilding the configuration. -`createOwnedSession`, `fork` and `delete` reject Session ids that are not a single normal path -component with `invalid`, before acquiring ownership or touching rows or output paths. These -checks are shared with the native Session admission/deletion boundary. +`createOwnedSession` and `fork` targets admit only lowercase ASCII Session ids — one to +sixty-four characters of `[a-z0-9_-]`, never a Windows reserved device name — rejecting any +other shape with `invalid` before acquiring ownership or touching rows or output paths. They +also reject with `invalid` an id that differs from a stored one only by case, and an id that +would share an output directory with a stored legacy id under a supported filesystem's +identity rules — Unicode folding pairs, default-ignorable code points, and the Windows +separators, trailing characters and 8.3 short names ([native storage +format](appserver/native-storage-format.md), #2204); a byte-identical duplicate keeps its +`storage` error. These creation checks are shared with the native Session admission boundary. +`delete` applies only the single normal path component check, so ids stored before the +admission rule stay deletable. Grant kind is `file` or `dir`, mode is `read` or `write`; adding read never downgrades an existing write grant. `language` is a ReplyLanguage code or null to clear it. diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index 141ab31283..73fcf45c19 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -694,7 +694,7 @@ export interface SqliteStorage extends Pick): Promise<{ databaseBytes: number; walBytes: number; reclaimableBytes: number }>; } -/** Process repository operations for trusted plugins; ids are not scoped to the caller. Create/fork/delete reject ids that are not one normal path component. */ +/** Process repository operations for trusted plugins; ids are not scoped to the caller. Create/fork admit only lowercase ASCII ids — one to sixty-four characters of `[a-z0-9_-]`, never a Windows reserved device name — and reject an id that differs from a stored one only by case or would share its output directory with a stored legacy id under a supported filesystem's identity rules; delete applies only the single normal path component check. */ export interface Store { query(request: { scope: TimelineReadScope; query: import('./branch-services.js').QuerySpec; page?: import('./branch-services.js').QueryPage | null }): Promise<{ result: import('./branch-services.js').QueryOutput; next: import('./branch-services.js').QueryCursor | null }>; /** Stored page: database sequence and closed=false; the lifecycle owner supplies live enrichment. */ From 0340e6f12955b468328111f0b4bd412f02b13e3a Mon Sep 17 00:00:00 2001 From: huihui Date: Sat, 28 Nov 2026 09:03:42 +0800 Subject: [PATCH 05/16] docs(app-server): read the v48 format summary as historical The summary below v37 called itself the current format at v48; the current format is v53, so state it as the v48 decision it describes. --- docs/design/appserver/native-storage-format.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/design/appserver/native-storage-format.md b/docs/design/appserver/native-storage-format.md index 6eaf213ac3..c259d6c98a 100644 --- a/docs/design/appserver/native-storage-format.md +++ b/docs/design/appserver/native-storage-format.md @@ -214,7 +214,7 @@ v36 的文本索引和事件编码合同继续适用。 后续提案:[状态读取索引与数组元素](#提案状态读取索引与数组元素)。数组元素编码采用独立新格式;owner 结果复用既有事件索引。 -The current native format is **v48**, with optional command and delegation task titles, conditional queued-input Steer candidates in withdrawal commands, directly addressed large-array elements, versioned unfinished-member indexes, property text-candidate indexes, a submission identity index, a Session's activity time following its own activity, worktree directory and Session usage records with the directory's last-used time, `prompt/changed` events naming their delivery inputs, source-owned `settings_documents`, +The v48 native format introduced optional command and delegation task titles, conditional queued-input Steer candidates in withdrawal commands, directly addressed large-array elements, versioned unfinished-member indexes, property text-candidate indexes, a submission identity index, a Session's activity time following its own activity, worktree directory and Session usage records with the directory's last-used time, `prompt/changed` events naming their delivery inputs, source-owned `settings_documents`, SessionStore's Session-file rows, its title metadata, request messages stored as lists of content-addressed nodes, extension event rows, Session configurations and Agent profiles that may omit their mount list, the two @@ -222,11 +222,11 @@ branch end events, the tool-effect and digest fields, and tool schemas that may omit `type`, the Session catalog projection, a configuration's System source, a model limit that only a declaration writes, a delegation's Agent owner and member leader, a Session's creation origin, Session file grants, command output -ownership and the two context reading switches on timeline events. Startup -requires the exact v48 SQL schema and a single +ownership and the two context reading switches on timeline events. The v48 +startup gate required the exact v48 SQL schema and a single format marker of 48 before writable PRAGMAs, or the exact v47, main v42–v46 and resume v42–v44 families, v41, v40, v39, v38, v37, v36, v35, v34, v33, v32, v31, v30, v29, v28, v27, v26, v25, v24, v23, v22, v21, v20, v19, v18, v17, v16, v15 or v13 schema with its own marker, -which the same startup transaction upgrades in place to v48 one step after +which the same startup transaction upgraded in place to v48 one step after another ([v48 task titles](#v48-task-titles), [v47 merged resume format](#v47合并-main-v46-与-resume-v44), [#1477 v46 reasoning count](#v46modelusage-携带推理-token-数), [#1451 v45 last-used time](#v45worktree-目录的最后使用时间), [v44 prompt changes](#v44提示变更携带其投递输入), [v43 conditional Steer](#v43-conditional-queued-input-steer), [v41 merged child tool-call and Timeline indexes](#v41合并-child-tool-call-与-timeline-索引格式), [#1421 v42 decision](#v42agent_sessions-接受-automation-来源), [v36 text candidates](#v36-property-text-candidates), [v35 submission index](#v35-submission-identity-index), [#1099 v34 decision](#1099-v34-格式决定), [#911 v33 decision](#911-v33-格式决定), [#605 v32 decision](#605-v32-格式决定), [#708 v31 decision](#708-v31-格式决定), [#557 v30 decision](#557-v30-格式决定), [ADR 013 v29 decision](#adr-013-v29-格式决定), [#717 v28 decision](#717-v28-格式决定), [#593 v27 decision](#593-v27-格式决定), [S5a v15 decision](#s5a-v15-格式决定), [S5b v16 decision](#s5b-v16-格式决定), [#193 v17 decision](#193-v17-格式决定), From 81f46c652fcac3b69b797ed645d2a3f012a6aa41 Mon Sep 17 00:00:00 2001 From: huihui Date: Sat, 28 Nov 2026 10:16:52 +0800 Subject: [PATCH 06/16] fix(app-server): admit caller-selected Session ids at the store's insertion boundary The storage creation the SqliteStorage.createSession and timelineStore.createSession faces dispatch to only checked collisions, so a caller-selected id bypassed the lowercase-ASCII shape rule and the Windows reserved-name exclusion every other creation entry applies before writing storage (#2204). Add the same check_new_session_id admission to the shared insertion helper, ahead of the collision check: shape refusals are InvalidInput before anything is written, a byte-identical duplicate keeps its Storage error, and case-variant plus directory-shape collisions stay InvalidInput. Restoration, migration and import write stored ids through their own statements and never reach this helper, so ids already stored stay readable, deletable and usable as fork sources unchanged. Document the id admission in the createSession face contract and the TimelineStore binding JSDoc. --- crates/dim-app-server/src/storage/timeline.rs | 1 + .../tests/storage_flow/admission.rs | 133 ++++++++++++++++-- docs/design/resource-faces.md | 16 ++- npm/plugin.d.ts | 3 +- 4 files changed, 137 insertions(+), 16 deletions(-) diff --git a/crates/dim-app-server/src/storage/timeline.rs b/crates/dim-app-server/src/storage/timeline.rs index ed7eabf216..7b122ab922 100644 --- a/crates/dim-app-server/src/storage/timeline.rs +++ b/crates/dim-app-server/src/storage/timeline.rs @@ -2532,6 +2532,7 @@ fn create_session( leader: Option<&str>, origin: SessionOrigin, ) -> Result<()> { + dim_agent_runtime::check_new_session_id(session)?; reject_conflicting_id(connection, session)?; let config = serde_json::to_string(config).map_err(error)?; connection diff --git a/crates/dim-app-server/tests/storage_flow/admission.rs b/crates/dim-app-server/tests/storage_flow/admission.rs index 99eb5df2b0..88f0969711 100644 --- a/crates/dim-app-server/tests/storage_flow/admission.rs +++ b/crates/dim-app-server/tests/storage_flow/admission.rs @@ -1,7 +1,9 @@ //! #2204: a new Session id admitted through `CreateSessionOptions::prepare`, -//! `createOwnedSession` or a fork's target is lowercase ASCII — one to -//! sixty-four characters of `[a-z0-9_-]`, and never a Windows reserved device -//! name — and is rejected with InvalidInput before anything is written. The +//! `createOwnedSession`, a fork's target or the low-level store creation the +//! `SqliteStorage.createSession` face dispatches to is lowercase ASCII — one +//! to sixty-four characters of `[a-z0-9_-]`, and never a Windows reserved +//! device name — and is rejected with InvalidInput before anything is +//! written. The //! store refuses a write whose id differs from a stored one only by case, //! and a write whose id would share an output directory with a stored one //! under a supported filesystem's identity rules — Unicode folding pairs, @@ -201,6 +203,108 @@ async fn owned_creation_admits_only_lowercase_ascii_ids() { root.shutdown().await.unwrap(); } +/// The low-level creation the `SqliteStorage.createSession` plugin face and +/// the `timelineStore.createSession` process face both dispatch to, and the +/// plain `Agent::create_session` writes through: a caller-selected id admits +/// the same shape rule as the entries above, at the store's shared insertion +/// boundary. Every refusal is InvalidInput before anything is written. +#[tokio::test] +async fn store_creation_admits_only_lowercase_ascii_ids() { + let database = Database::new(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + + let overlong = "x".repeat(65); + for id in [ + "Uppercase", + "with space", + "with/slash", + "con", + "com0", + "lpt9", + "unicode-é", + overlong.as_str(), + ] { + let result = store.create_session(id, &SessionConfig::default()).await; + assert!( + matches!(result, Err(AgentError::InvalidInput(_))), + "store creation with id {id:?} must be rejected with InvalidInput, got {result:?}" + ); + assert_eq!( + stored_rows(&connection, id), + 0, + "nothing of {id:?} may be written" + ); + } + + store + .create_session("valid-id_1", &SessionConfig::default()) + .await + .unwrap(); + assert_eq!( + stored_rows(&connection, "valid-id_1"), + 2, + "a conforming id writes its Session and root branch rows" + ); + + drop(connection); + store.close().await.unwrap(); + db.close().await.unwrap(); +} + +/// The shared insertion boundary keeps the collision semantics the creation +/// entries pin: a case-only variant of a stored id is InvalidInput, while a +/// byte-identical duplicate keeps its Storage error. +#[tokio::test] +async fn store_creation_rejects_case_variants_and_keeps_storage_error_for_byte_duplicates() { + let database = Database::new(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_stored_session(&connection, "Stored-9"); + + let variant = store + .create_session("stored-9", &SessionConfig::default()) + .await; + assert!( + matches!(variant, Err(AgentError::InvalidInput(_))), + "a case-only variant must be InvalidInput at the low-level creation, got {variant:?}" + ); + assert_eq!( + stored_rows(&connection, "stored-9"), + 0, + "nothing of the variant may be written" + ); + + store + .create_session("valid-id", &SessionConfig::default()) + .await + .unwrap(); + let duplicate = store + .create_session("valid-id", &SessionConfig::default()) + .await; + assert!( + matches!(duplicate, Err(AgentError::Storage(_))), + "a byte-identical duplicate must keep its Storage error, got {duplicate:?}" + ); + assert_eq!( + connection + .query_row( + "SELECT count(*) FROM agent_sessions WHERE session_id='valid-id'", + [], + |row| row.get::<_, i64>(0) + ) + .unwrap(), + 1, + "the stored row is neither duplicated nor overwritten" + ); + + drop(connection); + store.close().await.unwrap(); + db.close().await.unwrap(); +} + #[tokio::test] async fn owned_creation_rejects_case_variants_and_keeps_storage_error_for_byte_duplicates() { let database = Database::new(); @@ -407,9 +511,10 @@ async fn fork_with_a_byte_identical_target_is_refused_without_touching_the_exist } /// Ids stored before the admission rule are neither migrated nor rewritten: -/// the raw store still writes them as given, an uppercase source forks into -/// a conforming target, and deletion removes it as before. This pins behavior -/// the change must not alter. +/// restoration reads them as written, an uppercase source forks into +/// a conforming target, and deletion removes it as before. The rows are +/// seeded around the creation boundary the way a pre-#2204 daemon wrote them. +/// This pins behavior the change must not alter. #[tokio::test] async fn stored_uppercase_ids_remain_operable() { let database = Database::new(); @@ -421,9 +526,14 @@ async fn stored_uppercase_ids_remain_operable() { let db = SqliteStorage::open(database.0.clone()).unwrap(); let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); let store = SqliteTimelineStore::new(db.clone()); - store - .create_session("Legacy-9", &SessionConfig::default()) - .await + let connection = Connection::open(&database.0).unwrap(); + seed_stored_session(&connection, "Legacy-9"); + connection + .execute( + "INSERT INTO timeline_branches (session_id, branch_id, info, sequence) \ + VALUES ('Legacy-9', 'main', '{\"id\":\"main\"}', 0)", + [], + ) .unwrap(); append( &store, @@ -438,11 +548,14 @@ async fn stored_uppercase_ids_remain_operable() { .await .unwrap() .unwrap(); + assert!( + sessions.session_config("Legacy-9").await.unwrap().is_some(), + "restoration reads the uppercase id's configuration as written" + ); sessions .fork_session("Legacy-9", "valid-fork", 2, &config) .await .unwrap(); - let connection = Connection::open(&database.0).unwrap(); assert!( !stored_events(&connection, "valid-fork").is_empty(), "the uppercase source's rows are copied into the fork" diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index f956c7f54d..b59821d1c3 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -509,11 +509,17 @@ operation, without repeated remote probes. `trace` takes the same position and r and `saveSnapshot {sessionId,branchId,snapshot}` return `{}`. `sessionConfig {sessionId}` returns `{config}`. `latestSnapshot {sessionId,branchId,through,interpreter}` returns `{snapshot}`. These are storage lifecycle steps. `createSession` prepares the backend record; it does not -initialize or publish an Agent Session. `rollbackSession` undoes a successfully prepared creation -whose initialization failed, after its producers have stopped; it is not the general deletion -workflow. `releaseSession` drains accepted backend writes and releases their resources without -closing the Agent Session or its admission. App Server creation/deletion retain the repository -and lifecycle obligations in §5.2. +initialize or publish an Agent Session. Its id is caller-selected, so the native store's shared +insertion boundary applies the same admission as the creation entries in §5.2: one to sixty-four +characters of `[a-z0-9_-]`, never a Windows reserved device name, rejected with `invalid` before +anything is written, as is an id differing from a stored one only by case or sharing its output +directory with a stored legacy id; a byte-identical duplicate keeps its `storage` error. Ids +already stored are never re-validated: restoration reads them as written, and deletion plus use +as a fork source keep the single normal path component check (#2204). `rollbackSession` undoes a +successfully prepared creation whose initialization failed, after its producers have stopped; it +is not the general deletion workflow. `releaseSession` drains accepted backend writes and releases +their resources without closing the Agent Session or its admission. App Server creation/deletion +retain the repository and lifecycle obligations in §5.2. Snapshots retain their canonical fields (`sequence`, `event_id`, `interpreter`, `state`), optional acceleration semantics and owner validation. Domain errors preserve `{code,message}` using diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index 73fcf45c19..8932f56faa 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -760,7 +760,8 @@ export interface TimelineStore { /** Registration completes before return; observe later admissions, without replay of earlier batches. */ commits(request: { sessionId: string }, listener: (completion: TimelineStoreCompletion) => void | Promise): Promise<{ subscriptionId: string }>; closeCommits(request: { subscriptionId: string }): Promise<{}>; - /** Prepare the backend record; the lifecycle owner initializes and publishes the Agent Session. */ + /** Prepare the backend record; the lifecycle owner initializes and publishes the Agent Session. + * The id is caller-selected and admits the same rule as create/fork targets: one to sixty-four characters of `[a-z0-9_-]`, never a Windows reserved device name, rejected with `invalid` before anything is written, as is an id differing from a stored one only by case or sharing its output directory with a stored legacy id; a byte-identical duplicate rejects `storage`. Ids already stored stay readable, deletable and usable as fork sources unchanged. */ createSession(request: { sessionId: string; config: SessionConfig }): Promise<{}>; sessionConfig(request: { sessionId: string }): Promise<{ config: SessionConfig | null }>; /** Drain accepted storage writes; does not close the Agent Session or its admission. */ From 66aa7d75dd680e0086cde94aa5c30b7188479070 Mon Sep 17 00:00:00 2001 From: huihui Date: Sat, 28 Nov 2026 11:32:04 +0800 Subject: [PATCH 07/16] fix(app-server): resolve relative segments before comparing legacy Session output directories (#2204) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The directory check compared a legacy Session id's first literal component, but a Windows volume resolves . and .. segments before it accesses the directory, so a store moved from a platform with different path syntax could compare against a directory the id never lands in: x\..\abc and .\abc escaped the comparison while abc\..\def refused candidates it shares nothing with. The comparison now resolves the stored id against the output root the way the platform accessing it does — both separators, . and .. segments, trailing dots and spaces — and refuses a candidate only when the resolved directory is the candidate's own or inside it, which deletion follows recursively. Ids resolving onto the root itself, outside it, or sideways refuse nothing; a climb out of the root can still re-enter through the root's real components, which the comparison checks. Component equality keeps the casefold and Windows identity rules and the 8.3 short names, now in both directions. --- crates/dim-app-server/src/storage/timeline.rs | 226 ++++++++++++++---- .../tests/storage_flow/admission.rs | 149 +++++++++++- 2 files changed, 326 insertions(+), 49 deletions(-) diff --git a/crates/dim-app-server/src/storage/timeline.rs b/crates/dim-app-server/src/storage/timeline.rs index 7b122ab922..a62b22aebe 100644 --- a/crates/dim-app-server/src/storage/timeline.rs +++ b/crates/dim-app-server/src/storage/timeline.rs @@ -671,11 +671,19 @@ impl SqliteStorage { session: String, config: SessionConfig, ) -> Result<()> { + let database = self.path.clone(); self.run(move |connection| { let tx = connection .transaction_with_behavior(TransactionBehavior::Immediate) .map_err(error)?; - create_session(&tx, &session, &config, None, SessionOrigin::Unknown)?; + create_session( + &tx, + &database, + &session, + &config, + None, + SessionOrigin::Unknown, + )?; tx.commit().map_err(error) }) .await @@ -1761,13 +1769,14 @@ impl SessionStore { }, ) .transpose()?; + let database = self.timeline.db.path.clone(); self.timeline .db .run(move |connection| { let tx = connection .transaction_with_behavior(TransactionBehavior::Immediate) .map_err(error)?; - create_session(&tx, &session, &config, leader.as_deref(), origin)?; + create_session(&tx, &database, &session, &config, leader.as_deref(), origin)?; tx.execute( "INSERT INTO session_owners VALUES (?1, ?2, ?3)", params![session, agent, protocol_version], @@ -2404,25 +2413,21 @@ fn non_ascii_word_conflicts(connection: &Connection) -> Result> { Ok(rows) } -/// The identity of `stored` on a volume that folds case — APFS, HFS+ or a -/// Linux casefold directory — as one canonical key: lowercase, uppercase, -/// then ASCII-lowercase. Lowercase alone misses the pairs whose lowercase is -/// the same non-ASCII letter while their uppercase differs; uppercasing in -/// between maps every folding pair onto one key — ASCII case, the Kelvin -/// sign, the long s, ß/ẞ onto ss, the ligatures onto their expansion. The -/// second key strips the Unicode default-ignorable code points first, which a -/// casefold volume drops before comparing. The admitted lowercase ASCII -/// candidate is its own key, so comparison is bytewise. -fn casefold_keys(stored: &str) -> [String; 2] { - let fold = |text: &str| text.to_lowercase().to_uppercase().to_ascii_lowercase(); - let folded = fold(stored); - let stripped = fold( - &stored - .chars() - .filter(|c| !is_default_ignorable(*c)) - .collect::(), - ); - [folded, stripped] +/// The identity of `name` on a volume that folds case — APFS, HFS+ or a +/// Linux casefold directory — as one canonical key: the Unicode +/// default-ignorable code points stripped first, which a casefold volume +/// drops before comparing, then lowercase, uppercase, then ASCII-lowercase. +/// Lowercase alone misses the pairs whose lowercase is the same non-ASCII +/// letter while their uppercase differs; uppercasing in between maps every +/// folding pair onto one key — ASCII case, the Kelvin sign, the long s, ß/ẞ +/// onto ss, the ligatures onto their expansion. +fn casefold_name(name: &str) -> String { + name.chars() + .filter(|c| !is_default_ignorable(*c)) + .collect::() + .to_lowercase() + .to_uppercase() + .to_ascii_lowercase() } /// The Unicode default-ignorable code points a casefold volume strips from a @@ -2457,14 +2462,37 @@ fn windows_lower(stored: &str) -> String { .collect() } -/// The name `stored` addresses on a Windows volume after its syntactic rules: -/// the segment before the first backslash, then before the first colon — what -/// a path inside the directory or one of its streams shares — with trailing -/// dots and spaces trimmed, under the Windows case mapping. -fn windows_name(stored: &str) -> String { - let backslash = stored.split('\\').next().unwrap_or(stored); - let colon = backslash.split(':').next().unwrap_or(backslash); - windows_lower(colon.trim_end_matches(['.', ' '])) +/// Whether two path components can address the same entry on a Windows +/// volume: equal after the syntactic rules — the part before the first +/// colon, which the directory itself and every stream of it share, trailing +/// dots and spaces trimmed — under the Windows case mapping, or one the 8.3 +/// short name the volume can serve the other as. +fn windows_names_share(one: &str, other: &str) -> bool { + let windows_name = |name: &str| { + windows_lower( + name.split(':') + .next() + .unwrap_or(name) + .trim_end_matches(['.', ' ']), + ) + }; + let (one, other) = (windows_name(one), windows_name(other)); + one == other || windows_8_3_share(&one, &other) || windows_8_3_share(&other, &one) +} + +/// Whether `short` can be the 8.3 short name a Windows volume serves `long` +/// as, the directional half of [`windows_names_share`]: the classic form +/// truncates at the stem, so the name must exceed the eight characters the +/// volume caps the short form at. +fn windows_8_3_share(short: &str, long: &str) -> bool { + long.len() > 8 && short.len() <= 8 && windows_8_3_collides(short, long) +} + +/// Whether two path components can address the same entry under the identity +/// rules of a supported filesystem — a volume folding case, or a Windows +/// volume with its colon syntax, trailing characters and 8.3 short names. +fn components_share(one: &str, other: &str) -> bool { + casefold_name(one) == casefold_name(other) || windows_names_share(one, other) } /// Whether `stem` (the Windows form of a stored id, tilde and tail included) @@ -2497,29 +2525,121 @@ fn windows_8_3_collides(stem: &str, candidate: &str) -> bool { && candidate.starts_with(&letters[..letters.len() - 4].iter().collect::()) } +/// The normal components of `/command-output`, the root +/// every Session output directory is joined under (session files §3.1 and +/// the deletion layout in storage/files.rs). The joining form mirrors the +/// launcher's current working directory, which matters only for a relative +/// database path. +fn output_root_components(database: &Path) -> Vec { + let joined = std::env::current_dir() + .map(|cwd| cwd.join(database)) + .unwrap_or_else(|_| database.to_path_buf()); + let mut components: Vec = joined + .parent() + .map(|parent| { + parent + .components() + .filter_map(|part| match part { + Component::Normal(name) => Some(name.to_string_lossy().into_owned()), + _ => None, + }) + .collect() + }) + .unwrap_or_default(); + components.push(super::COMMAND_OUTPUT_DIRECTORY.into()); + components +} + +/// The components of `root.join(stored)` after the relative segments a +/// Windows volume resolves before it touches the directory (#2204): both +/// separators split, trailing dots and spaces trimmed, `.` dropped and `..` +/// consuming the deepest component left — and nothing once the root is +/// reached. `None` for a path the join replaces `root` with — rooted or +/// drive-anchored — which can never share the root's directory. The same +/// resolution runs on the POSIX separators a forward-slash id carries, so a +/// store moving between platforms keeps one comparison. +fn resolve_output_directory(root: &[String], stored: &str) -> Option> { + let text = if stored.len() >= 2 + && stored.as_bytes()[1] == b':' + && stored.as_bytes()[0].is_ascii_alphabetic() + { + &stored[2..] + } else { + stored + }; + if text.starts_with(['/', '\\']) { + return None; + } + let mut resolved: Vec = root.to_vec(); + for segment in text.split(['/', '\\']) { + if segment.is_empty() { + continue; + } + // `.` and `..` are relative before the trailing trim consumes them; + // one trimming to them is relative too: the exact segments resolve on + // every platform, and the trailing trim Windows applies to a name is + // ambiguous for them, so the relative reading — the one that resolves + // to a real directory — is the one that can collide. + if segment == "." { + continue; + } + if segment == ".." { + resolved.pop(); + continue; + } + let trimmed = segment.trim_end_matches(['.', ' ']); + if trimmed == "." { + continue; + } + if trimmed == ".." { + resolved.pop(); + continue; + } + resolved.push(trimmed.into()); + } + Some(resolved) +} + /// Whether a stored Session id can share its output directory with a newly /// admitted id under the identity rules of a supported filesystem — a volume /// folding case, or a Windows volume with its separators, trailing characters -/// and 8.3 short names. Both rule sets apply wherever the store runs, so a -/// store moving between platforms keeps its isolation (#2204): refusing too -/// much is safe, missing a collision is not. -fn shares_output_directory(stored: &str, candidate: &str) -> bool { - if casefold_keys(stored).iter().any(|key| key == candidate) { - return true; +/// and 8.3 short names — once the id is resolved against the output root the +/// way the platform accessing it does (#2204). The directories share when the +/// stored id's directory is the candidate's own or inside it, because writing +/// and deletion follow the directory recursively. An id resolving at or above +/// the root — `..` climbing out of it — and one whose path leaves the root +/// share nothing the candidate's directory covers, so they do not refuse. +/// Re-entering the root after a climb passes through the root's real +/// components, which the comparison of those components checks. +/// Both rule sets apply wherever the store runs, so a store moving between +/// platforms keeps its isolation: refusing too much is safe, missing a +/// collision is not. +fn shares_output_directory(root: &[String], stored: &str, candidate: &str) -> bool { + let Some(resolved) = resolve_output_directory(root, stored) else { + return false; + }; + if resolved.len() < root.len() + 1 { + return false; } - let windows = windows_name(stored); - if windows == candidate { - return true; + for (component, root_component) in resolved.iter().zip(root) { + if !components_share(component, root_component) { + return false; + } } - candidate.len() > 8 && windows.len() <= 8 && windows_8_3_collides(&windows, candidate) + components_share(&resolved[root.len()], candidate) } /// A stored id that shares an output directory with `candidate` beyond ASCII /// case folding, judged row by row under the filesystem identity rules /// (#2204). -fn directory_conflict(connection: &Connection, candidate: &str) -> Result> { +fn directory_conflict( + connection: &Connection, + database: &Path, + candidate: &str, +) -> Result> { + let root = output_root_components(database); for stored in non_ascii_word_conflicts(connection)? { - if shares_output_directory(&stored, candidate) { + if shares_output_directory(&root, &stored, candidate) { return Ok(Some(stored)); } } @@ -2527,13 +2647,14 @@ fn directory_conflict(connection: &Connection, candidate: &str) -> Result