Repository navigation
feat(session): workspace transcripts on driver ports with one-time legacy JSONL import #461
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
f3b6b9a
chore(session): remove legacy transcript migration code
senamakel a2cd858
refactor(session): move workspace port into its own module
senamakel dde3c7c
style(session): reformat legacy transcript marker code
senamakel 5669b82
feat(session): serve workspace transcripts through driver ports
senamakel e7f68b1
refactor(session): split legacy and port session types into modules
senamakel 7d77fb6
refactor(session): split workspace port into its own module
senamakel d9f83cf
refactor(session): move workspace port into its own module
senamakel 83754ee
refactor(session): move port types into a dedicated module
senamakel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
107 changes: 107 additions & 0 deletions
107
crates/tinyagents-session/src/legacy/transcripts_once.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| //! The one-time form of the classic JSONL transcript import. | ||
| //! | ||
| //! [`import_transcripts`] is already read-only, id-preserving and | ||
| //! only-if-absent, so running it again is harmless but rescans and re-parses | ||
| //! every file in `session_raw/`. A host that imports on every launch records a | ||
| //! marker document beside the session collections instead: once a pass has | ||
| //! read every file, later launches skip the scan and never touch the legacy | ||
| //! directory again. The legacy files themselves are never modified, renamed or | ||
| //! deleted. | ||
|
|
||
| use std::path::Path; | ||
|
|
||
| use serde_json::{Value, json}; | ||
| use tinystoragedrivers_core::{CollectionSpec, DocumentStore, ErrorKind, Precondition}; | ||
|
|
||
| use super::transcripts::{TranscriptImportReport, import_transcripts}; | ||
| use super::types::OnceOutcome; | ||
| use crate::port::DriverSessionStores; | ||
|
|
||
| /// Collection holding the import markers. | ||
| pub const MARKER_COLLECTION: &str = "session_import_markers"; | ||
| /// Id of the transcript-import marker document. | ||
| pub const TRANSCRIPT_MARKER_ID: &str = "session_raw_jsonl_v1"; | ||
|
|
||
| const LOG_PREFIX: &str = "[session_db:import:transcripts:once]"; | ||
|
|
||
| /// Imports `<workspace_dir>/session_raw/` into `agent_id`'s transcripts once. | ||
| /// | ||
| /// A marker document in the agent's scope records completion. A provider | ||
| /// without schema authority (`ValidateOnly`) cannot declare the marker | ||
| /// collection, so it runs the import every time (still idempotent). | ||
| /// | ||
| /// # Errors | ||
| /// | ||
| /// The destination refuses a read or write, or the raw directory cannot be | ||
| /// listed. No marker is written then, so a later call resumes the work. | ||
| pub fn import_transcripts_once( | ||
| provider: &DriverSessionStores, | ||
| agent_id: &str, | ||
| workspace_dir: &Path, | ||
| ) -> anyhow::Result<OnceOutcome> { | ||
| let stores = provider.try_for_agent(agent_id)?; | ||
| let (docs, may_declare) = provider.documents_for(agent_id)?; | ||
| if may_declare { | ||
| let docs = docs.clone(); | ||
| let marked = provider | ||
| .bridge() | ||
| .run(async move { marker_present(docs.as_ref()).await })??; | ||
| if marked { | ||
| tracing::debug!("{LOG_PREFIX} marker present; skipping scan agent_id={agent_id}"); | ||
| return Ok(OnceOutcome::AlreadyImported); | ||
| } | ||
| } | ||
| let report = import_transcripts(workspace_dir, stores.transcripts.as_ref())?; | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| let mut marked = false; | ||
| if may_declare && report.unreadable == 0 { | ||
| let docs = docs.clone(); | ||
| provider | ||
| .bridge() | ||
| .run(async move { write_marker(docs.as_ref(), &report).await })??; | ||
| marked = true; | ||
| } | ||
| tracing::info!( | ||
| "{LOG_PREFIX} agent_id={agent_id} imported={} already_present={} unreadable={} marked={marked}", | ||
| report.imported, | ||
| report.already_present, | ||
| report.unreadable | ||
| ); | ||
| Ok(OnceOutcome::Imported { report, marked }) | ||
| } | ||
|
|
||
| async fn marker_present( | ||
| docs: &dyn DocumentStore, | ||
| ) -> Result<bool, tinystoragedrivers_core::StorageError> { | ||
| docs.ensure_collection(&CollectionSpec::new(MARKER_COLLECTION)) | ||
| .await?; | ||
| Ok(docs | ||
| .get(MARKER_COLLECTION, TRANSCRIPT_MARKER_ID) | ||
| .await? | ||
| .is_some()) | ||
| } | ||
|
|
||
| async fn write_marker( | ||
| docs: &dyn DocumentStore, | ||
| report: &TranscriptImportReport, | ||
| ) -> Result<(), tinystoragedrivers_core::StorageError> { | ||
| let doc: Value = json!({ | ||
| "imported_at": chrono::Utc::now().to_rfc3339(), | ||
| "read": report.read, | ||
| "imported": report.imported, | ||
| "already_present": report.already_present, | ||
| "messages": report.messages, | ||
| }); | ||
| match docs | ||
| .put( | ||
| MARKER_COLLECTION, | ||
| TRANSCRIPT_MARKER_ID, | ||
| doc, | ||
| Precondition::Absent, | ||
| ) | ||
| .await | ||
| { | ||
| // A concurrent launch marked it first; the marker is idempotent. | ||
| Err(error) if error.kind() == ErrorKind::Conflict => Ok(()), | ||
| other => other.map(|_| ()), | ||
| } | ||
| } | ||
113 changes: 113 additions & 0 deletions
113
crates/tinyagents-session/src/legacy/transcripts_once_tests.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| use super::*; | ||
|
|
||
| // The one-time transcript import: marker, idempotence, untouched sources. | ||
| use crate::port::DriverSessionStores; | ||
| use crate::transcript::{TranscriptMessage, TranscriptMeta, write_transcript}; | ||
| use std::path::Path; | ||
| use std::sync::Arc; | ||
| use tinystoragedrivers_core::{MemoryStorage, StorageBackend}; | ||
|
|
||
| fn meta() -> TranscriptMeta { | ||
| TranscriptMeta { | ||
| session_id: None, | ||
| parent_session_id: None, | ||
| agent_name: "agent".into(), | ||
| agent_id: Some("agent-id".into()), | ||
| agent_type: Some("root".into()), | ||
| dispatcher: "native".into(), | ||
| provider: None, | ||
| model: None, | ||
| created: "2026-01-01T00:00:00Z".into(), | ||
| updated: "2026-01-01T00:00:00Z".into(), | ||
| turn_count: 1, | ||
| prefix_message_count: None, | ||
| input_tokens: 0, | ||
| output_tokens: 0, | ||
| cached_input_tokens: 0, | ||
| charged_amount_usd: 0.0, | ||
| thread_id: Some("thread-once".into()), | ||
| task_id: None, | ||
| } | ||
| } | ||
|
|
||
| fn provider() -> DriverSessionStores { | ||
| DriverSessionStores::new(Arc::new(MemoryStorage::new()) as Arc<dyn StorageBackend>).unwrap() | ||
| } | ||
|
|
||
| fn write(workspace: &Path, stem: &str, text: &str) -> std::path::PathBuf { | ||
| let raw = workspace.join("session_raw"); | ||
| std::fs::create_dir_all(&raw).unwrap(); | ||
| let path = raw.join(format!("{stem}.jsonl")); | ||
| write_transcript( | ||
| &path, | ||
| &[ | ||
| TranscriptMessage::user(text), | ||
| TranscriptMessage::assistant("ok"), | ||
| ], | ||
| &meta(), | ||
| None, | ||
| ) | ||
| .unwrap(); | ||
| path | ||
| } | ||
|
|
||
| #[test] | ||
| fn a_second_launch_skips_the_legacy_scan_and_never_touches_the_files() { | ||
| let dir = tempfile::tempdir().unwrap(); | ||
| let path = write(dir.path(), "1700000000_agent", "hello"); | ||
| let before = std::fs::read(&path).unwrap(); | ||
| let provider = provider(); | ||
|
|
||
| let first = import_transcripts_once(&provider, "agent", dir.path()).unwrap(); | ||
| let OnceOutcome::Imported { report, marked } = first else { | ||
| panic!("first launch imports"); | ||
| }; | ||
| assert_eq!((report.imported, report.already_present), (1, 0)); | ||
| assert!(marked); | ||
|
|
||
| // A file an old binary drops in after the marker is not picked up: the | ||
| // import is one-time. | ||
| write(dir.path(), "1700000001_agent", "late"); | ||
| let second = import_transcripts_once(&provider, "agent", dir.path()).unwrap(); | ||
| assert_eq!(second, OnceOutcome::AlreadyImported); | ||
| let stores = provider.try_for_agent("agent").unwrap(); | ||
| let late = stores | ||
| .transcripts | ||
| .open_stem("1700000001_agent", meta()) | ||
| .unwrap(); | ||
| assert!(late.read_session().unwrap().is_none()); | ||
|
|
||
| assert_eq!(std::fs::read(&path).unwrap(), before, "source untouched"); | ||
| } | ||
|
|
||
| #[test] | ||
| fn an_unreadable_file_leaves_the_import_unmarked_so_it_is_retried() { | ||
| let dir = tempfile::tempdir().unwrap(); | ||
| write(dir.path(), "good", "hi"); | ||
| std::fs::write(dir.path().join("session_raw").join("bad.jsonl"), "").unwrap(); | ||
| let provider = provider(); | ||
|
|
||
| let first = import_transcripts_once(&provider, "agent", dir.path()).unwrap(); | ||
| let OnceOutcome::Imported { report, marked } = first else { | ||
| panic!("imports"); | ||
| }; | ||
| assert_eq!(report.unreadable, 1); | ||
| assert!(!marked); | ||
|
|
||
| // Retry is idempotent: the good transcript is already there. | ||
| let again = import_transcripts_once(&provider, "agent", dir.path()).unwrap(); | ||
| let OnceOutcome::Imported { report, .. } = again else { | ||
| panic!("retries"); | ||
| }; | ||
| assert_eq!((report.imported, report.already_present), (0, 1)); | ||
| } | ||
|
|
||
| #[test] | ||
| fn markers_are_per_agent_scope() { | ||
| let dir = tempfile::tempdir().unwrap(); | ||
| write(dir.path(), "s", "x"); | ||
| let provider = provider(); | ||
| import_transcripts_once(&provider, "a", dir.path()).unwrap(); | ||
| let other = import_transcripts_once(&provider, "b", dir.path()).unwrap(); | ||
| assert!(matches!(other, OnceOutcome::Imported { marked: true, .. })); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| //! Result types of the legacy imports. | ||
|
|
||
| use super::transcripts::TranscriptImportReport; | ||
|
|
||
| /// How a one-time import ended. | ||
| #[derive(Debug, Clone, PartialEq)] | ||
| pub enum OnceOutcome { | ||
| /// A marker from an earlier launch says the import already ran. | ||
| AlreadyImported, | ||
| /// This pass ran. `marked` is false when some file did not parse, so the | ||
| /// next launch tries again instead of treating the import as complete. | ||
| Imported { | ||
| /// What the pass did. | ||
| report: TranscriptImportReport, | ||
| /// Whether the completion marker was written. | ||
| marked: bool, | ||
| }, | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.