feat: store large paste inputs as artifacts

This commit is contained in:
2026-09-01 17:26:58 +09:00
parent 5cc78d63c6
commit 04e296a4ef
21 changed files with 1164 additions and 23 deletions
+1
View File
@@ -10,6 +10,7 @@ base64.workspace = true
agen = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
sha2.workspace = true
uuid = { workspace = true, features = ["v7", "serde"] }
thiserror = { workspace = true }
protocol = { workspace = true }
+123 -1
View File
@@ -16,9 +16,11 @@
//! enumerable by the picker.
use crate::event_trace::TraceEntry;
use crate::paste_artifact::{read_from_dir, write_to_dir};
use crate::segment_log::LogEntry;
use crate::store::{Store, StoreError};
use crate::{SegmentId, SessionId};
use crate::{PasteArtifactLimits, SegmentId, SessionId};
use protocol::PasteArtifactRef;
use std::fs;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
@@ -109,6 +111,16 @@ impl FsStore {
.join(format!("{segment_id}.trace.jsonl"))
}
fn paste_artifact_dir(&self, session_id: SessionId) -> PathBuf {
self.session_dir(session_id).join("artifacts").join("paste")
}
#[cfg(test)]
fn paste_artifact_path(&self, session_id: SessionId, artifact_id: &str) -> PathBuf {
self.paste_artifact_dir(session_id)
.join(format!("{artifact_id}.json"))
}
fn append_line(&self, path: &Path, line: &str) -> Result<(), StoreError> {
let _guard = self
.append_lock
@@ -350,6 +362,33 @@ impl Store for FsStore {
Ok(complete.lines().filter(|l| !l.trim().is_empty()).count())
}
fn write_paste_artifact(
&self,
session_id: SessionId,
source_entry_id: &str,
content: &str,
limits: PasteArtifactLimits,
) -> Result<PasteArtifactRef, StoreError> {
let _guard = self
.append_lock
.lock()
.map_err(|_| std::io::Error::other("session store append lock was poisoned"))?;
write_to_dir(
&self.paste_artifact_dir(session_id),
source_entry_id,
content,
limits,
)
}
fn read_paste_artifact(
&self,
session_id: SessionId,
artifact_id: &str,
) -> Result<(PasteArtifactRef, String), StoreError> {
read_from_dir(&self.paste_artifact_dir(session_id), artifact_id)
}
fn append_trace(
&self,
session_id: SessionId,
@@ -398,4 +437,87 @@ mod tests {
store.create_segment(session_id, segment_id, &[]).unwrap();
assert!(store.session_modified_at(session_id).unwrap().is_some());
}
#[test]
fn paste_artifacts_are_atomic_integrity_checked_and_session_scoped() {
let tmp = tempfile::TempDir::new().unwrap();
let store = FsStore::new(tmp.path()).unwrap();
let owner = new_session_id();
let other = new_session_id();
let content = "αβγ\nsecond line\n";
let reference = store
.write_paste_artifact(owner, "entry-1", content, PasteArtifactLimits::default())
.unwrap();
assert_eq!(reference.byte_len, content.len() as u64);
assert_eq!(reference.char_count, content.chars().count() as u64);
assert_eq!(reference.source_entry_id, "entry-1");
assert_eq!(
store
.read_paste_artifact(owner, &reference.artifact_id)
.unwrap()
.1,
content
);
assert!(matches!(
store.read_paste_artifact(other, &reference.artifact_id),
Err(StoreError::PasteArtifactNotFound(_))
));
assert!(
self::fs::read_dir(store.paste_artifact_dir(owner))
.unwrap()
.all(|entry| !entry
.unwrap()
.file_name()
.to_string_lossy()
.ends_with(".tmp"))
);
let very_large = "z".repeat(1024 * 1024);
let very_large_ref = store
.write_paste_artifact(
owner,
"entry-2",
&very_large,
PasteArtifactLimits::default(),
)
.unwrap();
assert_eq!(
store
.read_paste_artifact(owner, &very_large_ref.artifact_id)
.unwrap()
.1,
very_large
);
}
#[test]
fn paste_artifact_limits_and_corruption_fail_closed() {
let tmp = tempfile::TempDir::new().unwrap();
let store = FsStore::new(tmp.path()).unwrap();
let session_id = new_session_id();
let limits = PasteArtifactLimits {
max_artifact_bytes: 5,
max_session_bytes: 8,
};
let first = store
.write_paste_artifact(session_id, "entry-1", "1234", limits)
.unwrap();
assert!(matches!(
store.write_paste_artifact(session_id, "entry-2", "56789", limits),
Err(StoreError::PasteArtifactLimit(_))
));
assert!(matches!(
store.write_paste_artifact(session_id, "entry-2", "5678", limits),
Ok(_)
));
std::fs::write(
store.paste_artifact_path(session_id, &first.artifact_id),
b"{}",
)
.unwrap();
assert!(matches!(
store.read_paste_artifact(session_id, &first.artifact_id),
Err(StoreError::Serde(_)) | Err(StoreError::PasteArtifactIntegrity(_))
));
}
}
+2
View File
@@ -35,6 +35,7 @@ pub mod fs_store;
pub mod history;
mod legacy_session_log;
pub mod logged_item;
mod paste_artifact;
pub mod public_snapshot;
pub mod segment;
pub mod segment_log;
@@ -53,6 +54,7 @@ pub use history::{
LoggedWorkerSubject,
};
pub use logged_item::{LoggedContentPart, LoggedItem, LoggedRole, from_logged, to_logged};
pub use paste_artifact::PasteArtifactLimits;
pub use segment::{
SegmentStartState, append_entry, append_system_item, classify_logged_history_entry,
create_compacted_segment, create_segment, create_segment_with_ids, ensure_head_or_fork, fork,
+156
View File
@@ -0,0 +1,156 @@
//! Session-owned storage for large pasted-input artifacts.
use std::fs;
use std::io::Write as _;
use std::path::Path;
use protocol::PasteArtifactRef;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::StoreError;
/// Bounded storage policy applied before a large paste becomes durable input.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PasteArtifactLimits {
pub max_artifact_bytes: u64,
pub max_session_bytes: u64,
}
impl Default for PasteArtifactLimits {
fn default() -> Self {
Self {
max_artifact_bytes: 8 * 1024 * 1024,
max_session_bytes: 64 * 1024 * 1024,
}
}
}
/// Integrity-bearing on-disk record. The body and metadata are committed in one
/// atomic file replacement so readers never observe a half-written artifact.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct StoredPasteArtifact {
pub reference: PasteArtifactRef,
pub content: String,
}
pub(crate) fn write_to_dir(
artifact_dir: &Path,
source_entry_id: &str,
content: &str,
limits: PasteArtifactLimits,
) -> Result<PasteArtifactRef, StoreError> {
let byte_len = content.len() as u64;
if byte_len > limits.max_artifact_bytes {
return Err(StoreError::PasteArtifactLimit(format!(
"artifact has {byte_len} bytes; maximum is {}",
limits.max_artifact_bytes
)));
}
fs::create_dir_all(artifact_dir)?;
let mut aggregate = 0_u64;
for entry in fs::read_dir(artifact_dir)? {
let path = entry?.path();
if path.extension().and_then(|value| value.to_str()) != Some("json") {
continue;
}
let stored: StoredPasteArtifact = serde_json::from_slice(&fs::read(&path)?)?;
verify(&stored, &stored.reference.artifact_id)?;
aggregate = aggregate
.checked_add(stored.reference.byte_len)
.ok_or_else(|| {
StoreError::PasteArtifactLimit("session aggregate size overflow".to_string())
})?;
}
let projected = aggregate.checked_add(byte_len).ok_or_else(|| {
StoreError::PasteArtifactLimit("session aggregate size overflow".to_string())
})?;
if projected > limits.max_session_bytes {
return Err(StoreError::PasteArtifactLimit(format!(
"session artifacts would use {projected} bytes; maximum is {}",
limits.max_session_bytes
)));
}
let artifact_id = uuid::Uuid::now_v7().to_string();
let reference = PasteArtifactRef {
artifact_id: artifact_id.clone(),
byte_len,
char_count: content.chars().count() as u64,
line_count: line_count(content),
sha256: sha256_hex(content),
source_entry_id: source_entry_id.to_string(),
};
let bytes = serde_json::to_vec(&StoredPasteArtifact {
reference: reference.clone(),
content: content.to_string(),
})?;
let target = artifact_dir.join(format!("{artifact_id}.json"));
let temporary = artifact_dir.join(format!(".{artifact_id}.tmp"));
let mut file = fs::OpenOptions::new()
.create_new(true)
.write(true)
.open(&temporary)?;
if let Err(error) = file.write_all(&bytes).and_then(|_| file.sync_all()) {
let _ = fs::remove_file(&temporary);
return Err(error.into());
}
if let Err(error) = fs::rename(&temporary, &target) {
let _ = fs::remove_file(&temporary);
return Err(error.into());
}
if let Ok(directory) = fs::File::open(artifact_dir) {
directory.sync_all()?;
}
Ok(reference)
}
pub(crate) fn read_from_dir(
artifact_dir: &Path,
artifact_id: &str,
) -> Result<(PasteArtifactRef, String), StoreError> {
let parsed = uuid::Uuid::parse_str(artifact_id)
.map_err(|_| StoreError::PasteArtifactNotFound(artifact_id.to_string()))?;
if parsed.to_string() != artifact_id {
return Err(StoreError::PasteArtifactNotFound(artifact_id.to_string()));
}
let path = artifact_dir.join(format!("{artifact_id}.json"));
let bytes = match fs::read(path) {
Ok(bytes) => bytes,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return Err(StoreError::PasteArtifactNotFound(artifact_id.to_string()));
}
Err(error) => return Err(error.into()),
};
let stored: StoredPasteArtifact = serde_json::from_slice(&bytes)?;
verify(&stored, artifact_id)?;
Ok((stored.reference, stored.content))
}
fn verify(stored: &StoredPasteArtifact, artifact_id: &str) -> Result<(), StoreError> {
let actual_digest = sha256_hex(&stored.content);
if stored.reference.artifact_id != artifact_id
|| stored.reference.byte_len != stored.content.len() as u64
|| stored.reference.char_count != stored.content.chars().count() as u64
|| stored.reference.line_count != line_count(&stored.content)
|| stored.reference.sha256 != actual_digest
{
return Err(StoreError::PasteArtifactIntegrity(artifact_id.to_string()));
}
Ok(())
}
fn sha256_hex(content: &str) -> String {
Sha256::digest(content.as_bytes())
.iter()
.map(|byte| format!("{byte:02x}"))
.collect()
}
fn line_count(content: &str) -> u64 {
if content.is_empty() {
0
} else {
content.lines().count().max(1) as u64
}
}
+34 -1
View File
@@ -13,7 +13,8 @@
use crate::event_trace::TraceEntry;
use crate::segment_log::LogEntry;
use crate::{SegmentId, SessionId};
use crate::{PasteArtifactLimits, SegmentId, SessionId};
use protocol::PasteArtifactRef;
/// Errors from the persistence store.
#[derive(Debug, thiserror::Error)]
@@ -29,6 +30,18 @@ pub enum StoreError {
#[error("log corrupted at line {line}: {message}")]
Corrupt { line: usize, message: String },
#[error("paste artifact storage is unavailable")]
PasteArtifactUnsupported,
#[error("paste artifact not found: {0}")]
PasteArtifactNotFound(String),
#[error("paste artifact integrity check failed: {0}")]
PasteArtifactIntegrity(String),
#[error("paste artifact size limit exceeded: {0}")]
PasteArtifactLimit(String),
}
/// Sync persistence backend for segment logs.
@@ -117,6 +130,26 @@ pub trait Store: Send + Sync {
segment_id: SegmentId,
) -> Result<usize, StoreError>;
/// Store a large paste before its reference is committed to history.
fn write_paste_artifact(
&self,
_session_id: SessionId,
_source_entry_id: &str,
_content: &str,
_limits: PasteArtifactLimits,
) -> Result<PasteArtifactRef, StoreError> {
Err(StoreError::PasteArtifactUnsupported)
}
/// Read and verify one artifact owned by `session_id`.
fn read_paste_artifact(
&self,
_session_id: SessionId,
_artifact_id: &str,
) -> Result<(PasteArtifactRef, String), StoreError> {
Err(StoreError::PasteArtifactUnsupported)
}
/// Append a trace entry to the debug event trace file.
fn append_trace(
&self,
@@ -608,6 +608,24 @@ where
) -> Result<usize, crate::StoreError> {
self.session_store.read_entry_count(session_id, segment_id)
}
fn write_paste_artifact(
&self,
session_id: SessionId,
source_entry_id: &str,
content: &str,
limits: crate::PasteArtifactLimits,
) -> Result<protocol::PasteArtifactRef, crate::StoreError> {
self.session_store
.write_paste_artifact(session_id, source_entry_id, content, limits)
}
fn read_paste_artifact(
&self,
session_id: SessionId,
artifact_id: &str,
) -> Result<(protocol::PasteArtifactRef, String), crate::StoreError> {
self.session_store
.read_paste_artifact(session_id, artifact_id)
}
fn append_trace(
&self,
session_id: SessionId,
@@ -10,9 +10,11 @@
//! every later operation must use that same ID.
use crate::event_trace::TraceEntry;
use crate::paste_artifact::{read_from_dir, write_to_dir};
use crate::segment_log::LogEntry;
use crate::store::{Store, StoreError};
use crate::{SegmentId, SessionId};
use crate::{PasteArtifactLimits, SegmentId, SessionId};
use protocol::PasteArtifactRef;
use serde::{Deserialize, Serialize};
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Seek, SeekFrom, Write};
@@ -25,6 +27,7 @@ const PREVIOUS_SESSION_SCHEMA_VERSION: u32 = 2;
const LEGACY_SESSION_SCHEMA_VERSION: u32 = 1;
const SESSION_FILE: &str = "session.json";
const SEGMENTS_DIR: &str = "segments";
const PASTE_ARTIFACTS_DIR: &str = "artifacts/paste";
#[derive(Clone)]
pub struct WorkerSessionStore {
@@ -317,6 +320,35 @@ impl Store for WorkerSessionStore {
.count())
}
fn write_paste_artifact(
&self,
session_id: SessionId,
source_entry_id: &str,
content: &str,
limits: PasteArtifactLimits,
) -> Result<PasteArtifactRef, StoreError> {
self.ensure_session(session_id, true)?;
let _guard = self
.append_lock
.lock()
.map_err(|_| std::io::Error::other("Worker Session append lock was poisoned"))?;
write_to_dir(
&self.root.join(PASTE_ARTIFACTS_DIR),
source_entry_id,
content,
limits,
)
}
fn read_paste_artifact(
&self,
session_id: SessionId,
artifact_id: &str,
) -> Result<(PasteArtifactRef, String), StoreError> {
self.ensure_session(session_id, false)?;
read_from_dir(&self.root.join(PASTE_ARTIFACTS_DIR), artifact_id)
}
fn append_trace(
&self,
session_id: SessionId,
@@ -601,6 +633,45 @@ mod tests {
assert_eq!(store.list_sessions().unwrap(), vec![session_id]);
}
#[test]
fn worker_session_store_keeps_paste_artifacts_inside_retention_root() {
let root = tempfile::tempdir().unwrap();
let store = WorkerSessionStore::new(root.path().join("session")).unwrap();
let session_id = new_session_id();
store
.create_segment(session_id, new_segment_id(), &[])
.unwrap();
let content = "large paste body\n終端\n";
let reference = store
.write_paste_artifact(
session_id,
"entry-1",
content,
PasteArtifactLimits::default(),
)
.unwrap();
assert!(
root.path()
.join(format!(
"session/{PASTE_ARTIFACTS_DIR}/{}.json",
reference.artifact_id
))
.is_file()
);
assert_eq!(
store
.read_paste_artifact(session_id, &reference.artifact_id)
.unwrap()
.1,
content
);
assert!(matches!(
store.read_paste_artifact(new_session_id(), &reference.artifact_id),
Err(StoreError::Corrupt { .. })
));
}
#[test]
fn schema_v1_logs_are_rewritten_and_promoted_to_v3() {
let root = tempfile::tempdir().unwrap();