Allow callers to supply Goose session IDs (#13098)
Co-authored-by: James Dumay <james@generalinference.xyz>
This commit is contained in:
@@ -35,6 +35,16 @@ pub const DB_NAME: &str = "sessions.db";
|
||||
const MILLISECOND_TIMESTAMP_THRESHOLD: i64 = 10_000_000_000;
|
||||
const SESSION_COUNT_BATCH_SIZE: usize = 900;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum SessionCreationError {
|
||||
#[error("session ID already exists: {id}")]
|
||||
AlreadyExists {
|
||||
id: String,
|
||||
#[source]
|
||||
source: sqlx::Error,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(
|
||||
Debug,
|
||||
Clone,
|
||||
@@ -457,7 +467,20 @@ impl SessionManager {
|
||||
goose_mode: GooseMode,
|
||||
) -> Result<Session> {
|
||||
self.storage
|
||||
.create_session(working_dir, name, session_type, goose_mode)
|
||||
.create_session(None, working_dir, name, session_type, goose_mode)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn create_session_with_id(
|
||||
&self,
|
||||
id: &str,
|
||||
working_dir: PathBuf,
|
||||
name: String,
|
||||
session_type: SessionType,
|
||||
goose_mode: GooseMode,
|
||||
) -> Result<Session> {
|
||||
self.storage
|
||||
.create_session(Some(id), working_dir, name, session_type, goose_mode)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -1757,11 +1780,29 @@ impl SessionStorage {
|
||||
|
||||
async fn create_session(
|
||||
&self,
|
||||
id: Option<&str>,
|
||||
working_dir: PathBuf,
|
||||
name: String,
|
||||
session_type: SessionType,
|
||||
goose_mode: GooseMode,
|
||||
) -> Result<Session> {
|
||||
if let Some(id) = id {
|
||||
anyhow::ensure!(
|
||||
!id.is_empty()
|
||||
&& id.len() <= 128
|
||||
&& id
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-'),
|
||||
"session ID must be 1-128 ASCII letters, digits, underscores, or hyphens"
|
||||
);
|
||||
let bytes = id.as_bytes();
|
||||
anyhow::ensure!(
|
||||
!(bytes.len() >= 19
|
||||
&& bytes[..8].iter().all(u8::is_ascii_digit)
|
||||
&& bytes[9..19].iter().all(u8::is_ascii_digit)),
|
||||
"session ID date-prefixed numeric suffix must be fewer than 10 digits"
|
||||
);
|
||||
}
|
||||
let pool = self.pool().await?;
|
||||
let mut tx = pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
|
||||
@@ -1770,11 +1811,11 @@ impl SessionStorage {
|
||||
r#"
|
||||
INSERT INTO sessions (id, name, user_set_name, session_type, working_dir, extension_data, goose_mode)
|
||||
VALUES (
|
||||
? || '_' || CAST(COALESCE((
|
||||
COALESCE(?, ? || '_' || CAST(COALESCE((
|
||||
SELECT MAX(CAST(SUBSTR(id, 10) AS INTEGER))
|
||||
FROM sessions
|
||||
WHERE id LIKE ? || '_%'
|
||||
), 0) + 1 AS TEXT),
|
||||
), 0) + 1 AS TEXT)),
|
||||
?,
|
||||
FALSE,
|
||||
?,
|
||||
@@ -1785,6 +1826,7 @@ impl SessionStorage {
|
||||
RETURNING *
|
||||
"#,
|
||||
)
|
||||
.bind(id)
|
||||
.bind(&today)
|
||||
.bind(&today)
|
||||
.bind(&name)
|
||||
@@ -1792,7 +1834,17 @@ impl SessionStorage {
|
||||
.bind(&*working_dir.to_string_lossy())
|
||||
.bind(goose_mode.to_string())
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
.await
|
||||
.map_err(|error| match (id, &error) {
|
||||
(Some(id), sqlx::Error::Database(db_error)) if db_error.is_unique_violation() => {
|
||||
SessionCreationError::AlreadyExists {
|
||||
id: id.to_string(),
|
||||
source: error,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
_ => anyhow::Error::from(error),
|
||||
})?;
|
||||
|
||||
tx.commit().await?;
|
||||
#[cfg(feature = "telemetry")]
|
||||
@@ -2730,6 +2782,7 @@ impl SessionStorage {
|
||||
|
||||
let session = self
|
||||
.create_session(
|
||||
None,
|
||||
import.working_dir.clone(),
|
||||
import.name.clone(),
|
||||
session_type_override.unwrap_or(import.session_type),
|
||||
@@ -2774,6 +2827,7 @@ impl SessionStorage {
|
||||
|
||||
let new_session = self
|
||||
.create_session(
|
||||
None,
|
||||
original_session.working_dir.clone(),
|
||||
new_name,
|
||||
original_session.session_type,
|
||||
@@ -4516,6 +4570,133 @@ mod tests {
|
||||
assert!(page.next_cursor.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_caller_supplied_session_id() {
|
||||
let temp_dir = TempDir::new().unwrap();
|
||||
let sm = SessionManager::new(temp_dir.path().to_path_buf());
|
||||
let id = "ses_rotten-canary-32";
|
||||
let session = sm
|
||||
.create_session_with_id(
|
||||
id,
|
||||
PathBuf::from("/tmp/custom-session"),
|
||||
"Custom session".to_string(),
|
||||
SessionType::User,
|
||||
GooseMode::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(session.id, id);
|
||||
|
||||
sm.add_message(
|
||||
id,
|
||||
&Message {
|
||||
id: None,
|
||||
role: Role::User,
|
||||
created: chrono::Utc::now().timestamp_millis(),
|
||||
content: vec![MessageContent::text("hello world")],
|
||||
metadata: Default::default(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(sm.get_session(id, true).await.unwrap().message_count, 1);
|
||||
assert!(sm.list_sessions().await.unwrap().iter().any(|s| s.id == id));
|
||||
|
||||
let collision = sm
|
||||
.create_session_with_id(
|
||||
id,
|
||||
PathBuf::from("/tmp/other-session"),
|
||||
"Collision".to_string(),
|
||||
SessionType::User,
|
||||
GooseMode::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
collision.downcast_ref::<SessionCreationError>(),
|
||||
Some(SessionCreationError::AlreadyExists { id: existing_id, .. }) if existing_id == id
|
||||
));
|
||||
assert_eq!(
|
||||
sm.get_session(id, false).await.unwrap().name,
|
||||
"Custom session"
|
||||
);
|
||||
|
||||
let generated = sm
|
||||
.create_session(
|
||||
PathBuf::from("/tmp/generated-session"),
|
||||
"Generated session".to_string(),
|
||||
SessionType::User,
|
||||
GooseMode::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_ne!(generated.id, id);
|
||||
assert!(generated
|
||||
.id
|
||||
.starts_with(&chrono::Utc::now().format("%Y%m%d_").to_string()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_caller_supplied_session_id_rejects_invalid_values() {
|
||||
let temp_dir = TempDir::new().unwrap();
|
||||
let sm = SessionManager::new(temp_dir.path().to_path_buf());
|
||||
let oversized_suffix = format!("{}_9223372036854775807", Utc::now().format("%Y%m%d"));
|
||||
let trailing_text = format!("{oversized_suffix}x");
|
||||
let alternate_separator = format!("{}X9223372036854775807", Utc::now().format("%Y%m%d"));
|
||||
for id in [
|
||||
"",
|
||||
"../session",
|
||||
"a b",
|
||||
"a/b",
|
||||
&oversized_suffix,
|
||||
&trailing_text,
|
||||
&alternate_separator,
|
||||
] {
|
||||
assert!(sm
|
||||
.create_session_with_id(
|
||||
id,
|
||||
PathBuf::from("/tmp/custom-session"),
|
||||
"Invalid".to_string(),
|
||||
SessionType::User,
|
||||
GooseMode::default(),
|
||||
)
|
||||
.await
|
||||
.is_err());
|
||||
}
|
||||
assert!(sm.list_sessions().await.unwrap().is_empty());
|
||||
|
||||
assert!(sm
|
||||
.storage
|
||||
.create_session(
|
||||
Some("../direct-storage"),
|
||||
PathBuf::from("/tmp/custom-session"),
|
||||
"Invalid".to_string(),
|
||||
SessionType::User,
|
||||
GooseMode::default(),
|
||||
)
|
||||
.await
|
||||
.is_err());
|
||||
let first = sm
|
||||
.create_session(
|
||||
PathBuf::from("/tmp/generated-session"),
|
||||
"Generated".to_string(),
|
||||
SessionType::User,
|
||||
GooseMode::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let second = sm
|
||||
.create_session(
|
||||
PathBuf::from("/tmp/generated-session"),
|
||||
"Generated".to_string(),
|
||||
SessionType::User,
|
||||
GooseMode::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_ne!(first.id, second.id);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_concurrent_session_creation() {
|
||||
let temp_dir = TempDir::new().unwrap();
|
||||
|
||||
Reference in New Issue
Block a user