Refactor analysis file names

The versioning of analysis input and document files
(`analysis_input_v{N}.json`, `document_v{N}.md`) has been removed. All
analysis inputs will now use `analysis_input.json` and generated
documents will use `document.md`.

This simplifies file management, as there's no longer a need to track
and manage multiple versions of these files within a case directory. The
analysis worker will now overwrite the existing `document.md` if it
exists, ensuring that the latest analysis result is always present. The
`version` field has also been removed from `AnalyzeJob` and
`AnalysisInput`.
This commit is contained in:
2026-04-16 01:56:55 +02:00
parent 928c0659c1
commit 8c6b2eeaa4
9 changed files with 111 additions and 281 deletions
+12 -13
View File
@@ -8,14 +8,18 @@ pub mod prompt;
pub mod recovery; pub mod recovery;
pub mod worker; pub mod worker;
/// A single request to analyze a case. Payload is tiny (path + u32), so the /// Single-document-per-case filenames. A re-analysis overwrites the
/// channel is unbounded — persistence lives in `analysis_input_v{N}.json` on /// document in place (handler deletes it first; worker writes the fresh one).
pub const DOCUMENT_FILE: &str = "document.md";
pub const ANALYSIS_INPUT_FILE: &str = "analysis_input.json";
/// A single request to analyze a case. Payload is tiny (a path), so the
/// channel is unbounded — persistence lives in `analysis_input.json` on
/// disk, not in the queue. Recovery re-enqueues any inputs the server may /// disk, not in the queue. Recovery re-enqueues any inputs the server may
/// have held at crash time. /// have held at crash time.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct AnalyzeJob { pub struct AnalyzeJob {
pub case_dir: PathBuf, pub case_dir: PathBuf,
pub version: u32,
} }
pub type AnalyzeSender = mpsc::UnboundedSender<AnalyzeJob>; pub type AnalyzeSender = mpsc::UnboundedSender<AnalyzeJob>;
@@ -25,19 +29,14 @@ pub fn channel() -> (AnalyzeSender, AnalyzeReceiver) {
mpsc::unbounded_channel() mpsc::unbounded_channel()
} }
/// Persistent input for a single analysis run. Written by the close-case /// Persistent input for a single analysis run. Written by the analyze
/// handler, consumed by the analyze worker, and left on disk indefinitely as /// handler, consumed by the analyze worker, removed after a successful
/// an audit trail of what was sent to the LLM. /// document write.
///
/// Timestamps are stored as ISO-8601 strings (lexicographic order matches
/// chronological order, so string comparison is sufficient for the
/// "Nachtrag" detection the UI needs later).
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct AnalysisInput { pub struct AnalysisInput {
pub version: u32,
/// Latest filesystem mtime (server clock) of any `.m4a` in the case at /// Latest filesystem mtime (server clock) of any `.m4a` in the case at
/// the moment the close button was clicked. Used later to detect late /// the moment the analyze button was clicked. Carried through for
/// arrivals that should trigger a re-analysis prompt. /// diagnostics / future "Nachtrag" detection.
pub last_recording_mtime: String, pub last_recording_mtime: String,
pub recordings: Vec<RecordingInput>, pub recordings: Vec<RecordingInput>,
} }
-1
View File
@@ -34,7 +34,6 @@ mod tests {
fn mk(input: Vec<(&str, &str)>) -> AnalysisInput { fn mk(input: Vec<(&str, &str)>) -> AnalysisInput {
AnalysisInput { AnalysisInput {
version: 1,
last_recording_mtime: "2026-04-15T10:47:00Z".into(), last_recording_mtime: "2026-04-15T10:47:00Z".into(),
recordings: input recordings: input
.into_iter() .into_iter()
+17 -61
View File
@@ -2,7 +2,7 @@ use std::path::Path;
use tracing::{info, warn}; use tracing::{info, warn};
use super::{AnalyzeJob, AnalyzeSender}; use super::{AnalyzeJob, AnalyzeSender, ANALYSIS_INPUT_FILE, DOCUMENT_FILE};
/// Walk `data_path/*/` and enqueue every pending analysis for every user. /// Walk `data_path/*/` and enqueue every pending analysis for every user.
/// Intended to run once at startup; the same primitive backs the per-user /// Intended to run once at startup; the same primitive backs the per-user
@@ -18,10 +18,8 @@ pub async fn scan_and_enqueue(data_path: &Path, tx: &AnalyzeSender) {
info!(count = total, "Analyze recovery scan finished"); info!(count = total, "Analyze recovery scan finished");
} }
/// Scan a single `<user_root>/<case>/analysis_input_v*.json` set and enqueue /// Scan a user's case dirs and enqueue any case that has an
/// every input whose `document_v{N}.md` is missing. Returns the number sent. /// `analysis_input.json` but no `document.md`. Returns the number sent.
/// Channel send is synchronous on the unbounded channel — only fails if the
/// worker is gone, which is a programming error.
pub async fn enqueue_pending_for_user(user_root: &Path, tx: &AnalyzeSender) -> usize { pub async fn enqueue_pending_for_user(user_root: &Path, tx: &AnalyzeSender) -> usize {
let Ok(mut cases) = tokio::fs::read_dir(user_root).await else { let Ok(mut cases) = tokio::fs::read_dir(user_root).await else {
return 0; return 0;
@@ -32,64 +30,22 @@ pub async fn enqueue_pending_for_user(user_root: &Path, tx: &AnalyzeSender) -> u
if !case_dir.is_dir() || crate::paths::is_deleted(&case_dir).await { if !case_dir.is_dir() || crate::paths::is_deleted(&case_dir).await {
continue; continue;
} }
let Ok(mut files) = tokio::fs::read_dir(&case_dir).await else { if !case_dir.join(ANALYSIS_INPUT_FILE).exists() {
continue; continue;
};
while let Ok(Some(file)) = files.next_entry().await {
let path = file.path();
let Some(name) = path.file_name().and_then(|s| s.to_str()) else {
continue;
};
let Some(version) = parse_input_version(name) else {
continue;
};
if case_dir.join(format!("document_v{version}.md")).exists() {
continue;
}
if tx
.send(AnalyzeJob {
case_dir: case_dir.clone(),
version,
})
.is_err()
{
warn!(case = %case_dir.display(), "recovery send failed (worker gone)");
return sent;
}
sent += 1;
} }
if case_dir.join(DOCUMENT_FILE).exists() {
continue;
}
if tx
.send(AnalyzeJob {
case_dir: case_dir.clone(),
})
.is_err()
{
warn!(case = %case_dir.display(), "recovery send failed (worker gone)");
return sent;
}
sent += 1;
} }
sent sent
} }
/// Parse `analysis_input_v{N}.json` and return `N` (as u32) if the pattern
/// matches exactly. Rejects malformed names, leading zeros, and overflow.
fn parse_input_version(filename: &str) -> Option<u32> {
let rest = filename.strip_prefix("analysis_input_v")?;
let num = rest.strip_suffix(".json")?;
if num.is_empty() || (num.starts_with('0') && num.len() > 1) {
return None;
}
num.parse::<u32>().ok()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_valid_names() {
assert_eq!(parse_input_version("analysis_input_v1.json"), Some(1));
assert_eq!(parse_input_version("analysis_input_v42.json"), Some(42));
}
#[test]
fn rejects_invalid_names() {
assert_eq!(parse_input_version("analysis_input_v.json"), None);
assert_eq!(parse_input_version("analysis_input_v01.json"), None);
assert_eq!(parse_input_version("analysis_input_vx.json"), None);
assert_eq!(parse_input_version("document_v1.md"), None);
assert_eq!(parse_input_version("analysis_input_v1.txt"), None);
assert_eq!(parse_input_version(""), None);
}
}
+6 -9
View File
@@ -5,7 +5,7 @@ use std::time::Duration;
use tokio::io::AsyncWriteExt; use tokio::io::AsyncWriteExt;
use tracing::{error, info, warn}; use tracing::{error, info, warn};
use super::{llm, prompt, AnalysisInput, AnalyzeReceiver}; use super::{llm, prompt, AnalysisInput, AnalyzeReceiver, ANALYSIS_INPUT_FILE, DOCUMENT_FILE};
use crate::config::Config; use crate::config::Config;
use crate::{BusyGuard, WorkerBusy}; use crate::{BusyGuard, WorkerBusy};
@@ -23,7 +23,7 @@ pub async fn run(
while let Some(job) = rx.recv().await { while let Some(job) = rx.recv().await {
let _guard = BusyGuard::new(worker_busy.clone()); let _guard = BusyGuard::new(worker_busy.clone());
process(&job.case_dir, job.version, &config, &client, timeout).await; process(&job.case_dir, &config, &client, timeout).await;
} }
warn!("Analyze worker stopped (channel closed)"); warn!("Analyze worker stopped (channel closed)");
@@ -31,13 +31,12 @@ pub async fn run(
async fn process( async fn process(
case_dir: &Path, case_dir: &Path,
version: u32,
config: &Config, config: &Config,
client: &reqwest::Client, client: &reqwest::Client,
timeout: Duration, timeout: Duration,
) { ) {
let input_path = case_dir.join(format!("analysis_input_v{version}.json")); let input_path = case_dir.join(ANALYSIS_INPUT_FILE);
let document_path = case_dir.join(format!("document_v{version}.md")); let document_path = case_dir.join(DOCUMENT_FILE);
// If the document already exists, the job is obsolete (e.g. recovery // If the document already exists, the job is obsolete (e.g. recovery
// re-enqueued a finished case during a race). Skip silently. // re-enqueued a finished case during a race). Skip silently.
@@ -69,7 +68,7 @@ async fn process(
if let Err(e) = tokio::fs::remove_file(&input_path).await { if let Err(e) = tokio::fs::remove_file(&input_path).await {
warn!(path = %input_path.display(), error = %e, "removing analysis input failed"); warn!(path = %input_path.display(), error = %e, "removing analysis input failed");
} }
info!(case = %case_dir.display(), version, "analysis done (stub, no recordings)"); info!(case = %case_dir.display(), "analysis done (stub, no recordings)");
return; return;
} }
@@ -77,7 +76,6 @@ async fn process(
let total_chars = user_content.chars().count(); let total_chars = user_content.chars().count();
info!( info!(
case = %case_dir.display(), case = %case_dir.display(),
version,
recording_count = input.recordings.len(), recording_count = input.recordings.len(),
total_chars, total_chars,
"sending to llm" "sending to llm"
@@ -106,7 +104,7 @@ async fn process(
Err(e) => { Err(e) => {
// Do not log the response body — LlmError::Display is already // Do not log the response body — LlmError::Display is already
// redacted, but reinforce the rule here for future readers. // redacted, but reinforce the rule here for future readers.
error!(case = %case_dir.display(), version, error = %e, "llm call failed"); error!(case = %case_dir.display(), error = %e, "llm call failed");
return; return;
} }
}; };
@@ -125,7 +123,6 @@ async fn process(
info!( info!(
case = %case_dir.display(), case = %case_dir.display(),
version,
bytes = document.len(), bytes = document.len(),
"analysis done" "analysis done"
); );
+16 -9
View File
@@ -8,12 +8,12 @@ use time::format_description::well_known::Rfc3339;
use time::OffsetDateTime; use time::OffsetDateTime;
use tracing::{info, warn}; use tracing::{info, warn};
use crate::analyze::{AnalyzeJob, AnalyzeSender}; use crate::analyze::{AnalyzeJob, AnalyzeSender, ANALYSIS_INPUT_FILE, DOCUMENT_FILE};
use crate::auth::AuthenticatedWebUser; use crate::auth::AuthenticatedWebUser;
use crate::config::Config; use crate::config::Config;
use crate::error::AppError; use crate::error::AppError;
use crate::paths::{write_delete_marker, DeleteMarker}; use crate::paths::{write_delete_marker, DeleteMarker};
use crate::routes::case_actions::{build_analysis_input, find_latest_document, write_input_create_new}; use crate::routes::case_actions::{build_analysis_input, write_input_create_new};
use crate::routes::user_web::locate_case; use crate::routes::user_web::locate_case;
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
@@ -72,11 +72,19 @@ async fn bulk_analyze(
skipped += 1; skipped += 1;
continue; continue;
}; };
let version = find_latest_document(&case_dir) // Same order as the single-case handler: drop old document first so
.await // the UI doesn't keep showing "ausgewertet" during re-analysis.
.map(|(v, _)| v + 1) let document_path = case_dir.join(DOCUMENT_FILE);
.unwrap_or(1); match tokio::fs::remove_file(&document_path).await {
let input = match build_analysis_input(&case_dir, version).await { Ok(_) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => {
warn!(slug = %slug, case_id = %case_id, error = %e, "bulk-analyze: remove old document failed");
skipped += 1;
continue;
}
}
let input = match build_analysis_input(&case_dir).await {
Ok(i) => i, Ok(i) => i,
Err(_) => { Err(_) => {
warn!(slug = %slug, case_id = %case_id, "bulk-analyze: build_analysis_input failed"); warn!(slug = %slug, case_id = %case_id, "bulk-analyze: build_analysis_input failed");
@@ -84,7 +92,7 @@ async fn bulk_analyze(
continue; continue;
} }
}; };
let input_path = case_dir.join(format!("analysis_input_v{version}.json")); let input_path = case_dir.join(ANALYSIS_INPUT_FILE);
if write_input_create_new(&input_path, &input).await.is_err() { if write_input_create_new(&input_path, &input).await.is_err() {
warn!(slug = %slug, case_id = %case_id, "bulk-analyze: write input failed"); warn!(slug = %slug, case_id = %case_id, "bulk-analyze: write input failed");
skipped += 1; skipped += 1;
@@ -93,7 +101,6 @@ async fn bulk_analyze(
if analyze_tx if analyze_tx
.send(AnalyzeJob { .send(AnalyzeJob {
case_dir: case_dir.clone(), case_dir: case_dir.clone(),
version,
}) })
.is_err() .is_err()
{ {
+21 -66
View File
@@ -10,7 +10,9 @@ use time::OffsetDateTime;
use tokio::io::AsyncWriteExt; use tokio::io::AsyncWriteExt;
use tracing::{info, warn}; use tracing::{info, warn};
use crate::analyze::{AnalysisInput, AnalyzeJob, AnalyzeSender, RecordingInput}; use crate::analyze::{
AnalysisInput, AnalyzeJob, AnalyzeSender, RecordingInput, ANALYSIS_INPUT_FILE, DOCUMENT_FILE,
};
use crate::auth::AuthenticatedWebUser; use crate::auth::AuthenticatedWebUser;
use crate::config::Config; use crate::config::Config;
use crate::error::AppError; use crate::error::AppError;
@@ -21,7 +23,6 @@ use crate::routes::user_web::locate_case;
#[template(path = "document.html")] #[template(path = "document.html")]
struct DocumentTemplate { struct DocumentTemplate {
case_id: String, case_id: String,
version: u32,
content: String, content: String,
} }
@@ -56,13 +57,18 @@ pub async fn handle_analyze_case(
} }
}; };
let version = find_latest_document(&case_dir) // Re-analyze: delete the existing document first so the UI stops showing
.await // the stale "ausgewertet" state while the worker re-computes. Ignore
.map(|(v, _)| v + 1) // NotFound (first-time analysis path).
.unwrap_or(1); let document_path = case_dir.join(DOCUMENT_FILE);
match tokio::fs::remove_file(&document_path).await {
Ok(_) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(AppError::Internal(format!("remove old document: {e}"))),
}
let input = build_analysis_input(&case_dir, version).await?; let input = build_analysis_input(&case_dir).await?;
let input_path = case_dir.join(format!("analysis_input_v{version}.json")); let input_path = case_dir.join(ANALYSIS_INPUT_FILE);
write_input_create_new(&input_path, &input).await?; write_input_create_new(&input_path, &input).await?;
// Unbounded send: only fails if the worker has gone away (programmer error // Unbounded send: only fails if the worker has gone away (programmer error
@@ -71,7 +77,6 @@ pub async fn handle_analyze_case(
if analyze_tx if analyze_tx
.send(AnalyzeJob { .send(AnalyzeJob {
case_dir: case_dir.clone(), case_dir: case_dir.clone(),
version,
}) })
.is_err() .is_err()
{ {
@@ -81,7 +86,6 @@ pub async fn handle_analyze_case(
info!( info!(
slug = %user.slug, slug = %user.slug,
case_id = %case_id, case_id = %case_id,
version,
recordings = input.recordings.len(), recordings = input.recordings.len(),
"analyze requested; analysis enqueued" "analyze requested; analysis enqueued"
); );
@@ -110,29 +114,22 @@ pub async fn handle_document_view(
} }
}; };
let (version, content) = find_latest_document(&case_dir) let content = read_document(&case_dir)
.await .await
.ok_or_else(|| AppError::NotFound("Noch kein Dokument erzeugt".into()))?; .ok_or_else(|| AppError::NotFound("Noch kein Dokument erzeugt".into()))?;
DocumentTemplate { DocumentTemplate { case_id, content }
case_id,
version,
content,
}
.render() .render()
.map(Html) .map(Html)
.map_err(|e| AppError::Internal(format!("Template render failed: {e}"))) .map_err(|e| AppError::Internal(format!("Template render failed: {e}")))
} }
/// Build an `AnalysisInput` for the given case directory at the given version. /// Build an `AnalysisInput` for the given case directory.
/// Collects all `.m4a` (excluding `.m4a.failed`), reads the matching /// Collects all `.m4a` (excluding `.m4a.failed`), reads the matching
/// `.transcript.txt` for each, skips blank transcripts, and computes /// `.transcript.txt` for each, skips blank transcripts, and computes
/// `last_recording_mtime` as the max mtime over ALL `.m4a` (including blank /// `last_recording_mtime` as the max mtime over ALL `.m4a` (including blank
/// ones — a late blank addendum still counts as activity). /// ones — a late blank addendum still counts as activity).
pub(crate) async fn build_analysis_input( pub(crate) async fn build_analysis_input(case_dir: &Path) -> Result<AnalysisInput, AppError> {
case_dir: &Path,
version: u32,
) -> Result<AnalysisInput, AppError> {
let m4as = collect_m4as(case_dir).await?; let m4as = collect_m4as(case_dir).await?;
if m4as.is_empty() { if m4as.is_empty() {
return Err(AppError::BadRequest("Keine Aufnahmen im Fall".into())); return Err(AppError::BadRequest("Keine Aufnahmen im Fall".into()));
@@ -170,7 +167,6 @@ pub(crate) async fn build_analysis_input(
.map_err(|e| AppError::Internal(format!("format mtime: {e}")))?; .map_err(|e| AppError::Internal(format!("format mtime: {e}")))?;
Ok(AnalysisInput { Ok(AnalysisInput {
version,
last_recording_mtime, last_recording_mtime,
recordings, recordings,
}) })
@@ -242,36 +238,9 @@ fn filename_stem_to_recorded_at(stem: &str) -> String {
} }
} }
/// Scan `case_dir` for `document_v{N}.md`, pick the highest N, return its /// Read `case_dir/document.md`. Returns `None` if no document exists.
/// content together with N. Returns `None` if no document exists. pub(crate) async fn read_document(case_dir: &Path) -> Option<String> {
pub(crate) async fn find_latest_document(case_dir: &Path) -> Option<(u32, String)> { tokio::fs::read_to_string(case_dir.join(DOCUMENT_FILE)).await.ok()
let mut highest: Option<u32> = None;
let mut entries = tokio::fs::read_dir(case_dir).await.ok()?;
while let Ok(Some(entry)) = entries.next_entry().await {
let name = entry.file_name();
let Some(name_str) = name.to_str() else { continue };
let Some(version) = parse_document_version(name_str) else {
continue;
};
highest = match highest {
Some(h) if h >= version => Some(h),
_ => Some(version),
};
}
let v = highest?;
let content = tokio::fs::read_to_string(case_dir.join(format!("document_v{v}.md")))
.await
.ok()?;
Some((v, content))
}
fn parse_document_version(filename: &str) -> Option<u32> {
let rest = filename.strip_prefix("document_v")?;
let num = rest.strip_suffix(".md")?;
if num.is_empty() || (num.starts_with('0') && num.len() > 1) {
return None;
}
num.parse::<u32>().ok()
} }
/// POST /web/cases/{case_id}/delete /// POST /web/cases/{case_id}/delete
@@ -437,18 +406,4 @@ mod tests {
); );
} }
#[test]
fn parses_valid_document_names() {
assert_eq!(parse_document_version("document_v1.md"), Some(1));
assert_eq!(parse_document_version("document_v42.md"), Some(42));
}
#[test]
fn rejects_invalid_document_names() {
assert_eq!(parse_document_version("document_v01.md"), None);
assert_eq!(parse_document_version("document_v.md"), None);
assert_eq!(parse_document_version("document_vx.md"), None);
assert_eq!(parse_document_version("analysis_input_v1.json"), None);
assert_eq!(parse_document_version(""), None);
}
} }
+10 -30
View File
@@ -9,7 +9,7 @@ use tracing::{info, warn};
use time::{format_description::well_known::Rfc3339, Date, OffsetDateTime, UtcOffset}; use time::{format_description::well_known::Rfc3339, Date, OffsetDateTime, UtcOffset};
use crate::analyze::{recovery as analyze_recovery, AnalyzeSender}; use crate::analyze::{recovery as analyze_recovery, AnalyzeSender, ANALYSIS_INPUT_FILE, DOCUMENT_FILE};
use crate::auth::AuthenticatedWebUser; use crate::auth::AuthenticatedWebUser;
use crate::config::Config; use crate::config::Config;
use crate::error::AppError; use crate::error::AppError;
@@ -173,39 +173,19 @@ async fn compute_flags(
} }
} }
/// True iff the case directory contains at least one `analysis_input_v*.json`. /// True iff `analysis_input.json` exists. The worker removes it after a
/// The worker removes the input after successful document write, so existence /// successful document write, so existence implies a pending or in-flight job.
/// implies a pending or in-flight analyze job.
pub(crate) async fn any_analysis_input_exists(case_dir: &Path) -> bool { pub(crate) async fn any_analysis_input_exists(case_dir: &Path) -> bool {
let mut entries = match tokio::fs::read_dir(case_dir).await { tokio::fs::try_exists(case_dir.join(ANALYSIS_INPUT_FILE))
Ok(r) => r, .await
Err(_) => return false, .unwrap_or(false)
};
while let Ok(Some(entry)) = entries.next_entry().await {
let name = entry.file_name();
let Some(name_str) = name.to_str() else { continue };
if name_str.starts_with("analysis_input_v") && name_str.ends_with(".json") {
return true;
}
}
false
} }
/// True iff the case directory contains at least one `document_v{N}.md`. /// True iff `document.md` exists.
/// We don't care about N here — any version means "Ausgewertet" for the UI.
pub(crate) async fn any_document_exists(case_dir: &Path) -> bool { pub(crate) async fn any_document_exists(case_dir: &Path) -> bool {
let mut entries = match tokio::fs::read_dir(case_dir).await { tokio::fs::try_exists(case_dir.join(DOCUMENT_FILE))
Ok(r) => r, .await
Err(_) => return false, .unwrap_or(false)
};
while let Ok(Some(entry)) = entries.next_entry().await {
let name = entry.file_name();
let Some(name_str) = name.to_str() else { continue };
if name_str.starts_with("document_v") && name_str.ends_with(".md") {
return true;
}
}
false
} }
/// Self-heal: if a worker is idle but orphans exist on disk for this user, /// Self-heal: if a worker is idle but orphans exist on disk for this user,
+2 -2
View File
@@ -2,7 +2,7 @@
<html lang="de"> <html lang="de">
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<title>Doctate — Dokument v{{ version }}</title> <title>Doctate — Dokument</title>
<style> <style>
body { font-family: sans-serif; max-width: 900px; margin: 2em auto; padding: 0 1em; } body { font-family: sans-serif; max-width: 900px; margin: 2em auto; padding: 0 1em; }
header { display: flex; justify-content: space-between; align-items: center; } header { display: flex; justify-content: space-between; align-items: center; }
@@ -20,7 +20,7 @@ pre { white-space: pre-wrap; font-family: serif; font-size: 1.05em; line-height:
<div><a class="back-button" href="/web/cases">&larr; Alle Fälle</a></div> <div><a class="back-button" href="/web/cases">&larr; Alle Fälle</a></div>
<form method="post" action="/web/logout"><button type="submit">Logout</button></form> <form method="post" action="/web/logout"><button type="submit">Logout</button></form>
</header> </header>
<h1>Dokument v{{ version }}</h1> <h1>Dokument</h1>
<div class="meta">{{ case_id }}</div> <div class="meta">{{ case_id }}</div>
<div class="toolbar"> <div class="toolbar">
<button id="copy-btn" type="button" class="copy-btn" hidden>In Zwischenablage</button> <button id="copy-btn" type="button" class="copy-btn" hidden>In Zwischenablage</button>
+27 -90
View File
@@ -235,15 +235,14 @@ async fn analyze_case_happy_path_writes_input_and_redirects() {
assert_eq!(resp.status(), StatusCode::SEE_OTHER); assert_eq!(resp.status(), StatusCode::SEE_OTHER);
assert_eq!( assert_eq!(
resp.headers().get(header::LOCATION).unwrap().to_str().unwrap(), resp.headers().get(header::LOCATION).unwrap().to_str().unwrap(),
format!("/web/cases/{case_id}") "/web/cases"
); );
let input_path = case_dir.join("analysis_input_v1.json"); let input_path = case_dir.join("analysis_input.json");
assert!(input_path.exists(), "analysis_input_v1.json missing"); assert!(input_path.exists(), "analysis_input.json missing");
let raw = std::fs::read_to_string(&input_path).unwrap(); let raw = std::fs::read_to_string(&input_path).unwrap();
let parsed: Value = serde_json::from_str(&raw).unwrap(); let parsed: Value = serde_json::from_str(&raw).unwrap();
assert_eq!(parsed["version"], 1);
let recs = parsed["recordings"].as_array().unwrap(); let recs = parsed["recordings"].as_array().unwrap();
assert_eq!(recs.len(), 2); assert_eq!(recs.len(), 2);
assert_eq!(recs[0]["recorded_at"], "2026-04-15T10:00:00Z"); assert_eq!(recs[0]["recorded_at"], "2026-04-15T10:00:00Z");
@@ -284,7 +283,7 @@ async fn analyze_case_skips_blank_transcript_from_recordings() {
let resp = app.oneshot(analyze_request(case_id, &cookie)).await.unwrap(); let resp = app.oneshot(analyze_request(case_id, &cookie)).await.unwrap();
assert_eq!(resp.status(), StatusCode::SEE_OTHER); assert_eq!(resp.status(), StatusCode::SEE_OTHER);
let raw = std::fs::read_to_string(case_dir.join("analysis_input_v1.json")).unwrap(); let raw = std::fs::read_to_string(case_dir.join("analysis_input.json")).unwrap();
let parsed: Value = serde_json::from_str(&raw).unwrap(); let parsed: Value = serde_json::from_str(&raw).unwrap();
let recs = parsed["recordings"].as_array().unwrap(); let recs = parsed["recordings"].as_array().unwrap();
assert_eq!(recs.len(), 2, "blank transcript must be filtered out"); assert_eq!(recs.len(), 2, "blank transcript must be filtered out");
@@ -301,14 +300,13 @@ async fn analyze_worker_writes_document_via_wiremock() {
std::fs::create_dir_all(&case_dir).unwrap(); std::fs::create_dir_all(&case_dir).unwrap();
let input = json!({ let input = json!({
"version": 1,
"last_recording_mtime": "2026-04-15T10:00:00Z", "last_recording_mtime": "2026-04-15T10:00:00Z",
"recordings": [ "recordings": [
{ "recorded_at": "2026-04-15T10:00:00Z", "text": "Patient mit Knie." } { "recorded_at": "2026-04-15T10:00:00Z", "text": "Patient mit Knie." }
] ]
}); });
std::fs::write( std::fs::write(
case_dir.join("analysis_input_v1.json"), case_dir.join("analysis_input.json"),
serde_json::to_vec_pretty(&input).unwrap(), serde_json::to_vec_pretty(&input).unwrap(),
) )
.unwrap(); .unwrap();
@@ -332,16 +330,15 @@ async fn analyze_worker_writes_document_via_wiremock() {
tx.send(analyze::AnalyzeJob { tx.send(analyze::AnalyzeJob {
case_dir: case_dir.clone(), case_dir: case_dir.clone(),
version: 1,
}) })
.unwrap(); .unwrap();
// Poll for the document (worker is in a separate task). // Poll for the document (worker is in a separate task).
let document_path = case_dir.join("document_v1.md"); let document_path = case_dir.join("document.md");
let deadline = std::time::Instant::now() + Duration::from_secs(5); let deadline = std::time::Instant::now() + Duration::from_secs(5);
while !document_path.exists() { while !document_path.exists() {
if std::time::Instant::now() > deadline { if std::time::Instant::now() > deadline {
panic!("document_v1.md not written within 5s"); panic!("document.md not written within 5s");
} }
tokio::time::sleep(Duration::from_millis(20)).await; tokio::time::sleep(Duration::from_millis(20)).await;
} }
@@ -365,13 +362,12 @@ async fn recovery_enqueues_pending_analysis() {
let tmp = unique_tmp("r1"); let tmp = unique_tmp("r1");
let case_dir = tmp.join("dr_a/11111111-1111-1111-1111-111111111111"); let case_dir = tmp.join("dr_a/11111111-1111-1111-1111-111111111111");
std::fs::create_dir_all(&case_dir).unwrap(); std::fs::create_dir_all(&case_dir).unwrap();
std::fs::write(case_dir.join("analysis_input_v1.json"), "{}").unwrap(); std::fs::write(case_dir.join("analysis_input.json"), "{}").unwrap();
let (tx, mut rx) = analyze::channel(); let (tx, mut rx) = analyze::channel();
analyze::recovery::scan_and_enqueue(&tmp, &tx).await; analyze::recovery::scan_and_enqueue(&tmp, &tx).await;
let job = rx.try_recv().expect("expected one job"); let job = rx.try_recv().expect("expected one job");
assert_eq!(job.version, 1);
assert_eq!(job.case_dir, case_dir); assert_eq!(job.case_dir, case_dir);
assert!(rx.try_recv().is_err(), "no further jobs expected"); assert!(rx.try_recv().is_err(), "no further jobs expected");
} }
@@ -381,8 +377,8 @@ async fn recovery_skips_completed_analysis() {
let tmp = unique_tmp("r2"); let tmp = unique_tmp("r2");
let case_dir = tmp.join("dr_a/11111111-1111-1111-1111-111111111111"); let case_dir = tmp.join("dr_a/11111111-1111-1111-1111-111111111111");
std::fs::create_dir_all(&case_dir).unwrap(); std::fs::create_dir_all(&case_dir).unwrap();
std::fs::write(case_dir.join("analysis_input_v1.json"), "{}").unwrap(); std::fs::write(case_dir.join("analysis_input.json"), "{}").unwrap();
std::fs::write(case_dir.join("document_v1.md"), "done").unwrap(); std::fs::write(case_dir.join("document.md"), "done").unwrap();
let (tx, mut rx) = analyze::channel(); let (tx, mut rx) = analyze::channel();
analyze::recovery::scan_and_enqueue(&tmp, &tx).await; analyze::recovery::scan_and_enqueue(&tmp, &tx).await;
@@ -395,12 +391,11 @@ async fn recovery_skips_completed_analysis() {
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
#[tokio::test] #[tokio::test]
async fn document_view_picks_highest_version() { async fn document_view_reads_document() {
let config = config_with_llm(unique_tmp("dv"), "http://unused".into()); let config = config_with_llm(unique_tmp("dv"), "http://unused".into());
let case_id = "11111111-1111-1111-1111-111111111111"; let case_id = "11111111-1111-1111-1111-111111111111";
let case_dir = seed_case(&config.data_path, "dr_a", case_id); let case_dir = seed_case(&config.data_path, "dr_a", case_id);
std::fs::write(case_dir.join("document_v1.md"), "alte Version").unwrap(); std::fs::write(case_dir.join("document.md"), "der Inhalt").unwrap();
std::fs::write(case_dir.join("document_v2.md"), "neue Version v2").unwrap();
let app = doctate_server::create_router(config); let app = doctate_server::create_router(config);
let cookie = login(app.clone(), "dr_a").await; let cookie = login(app.clone(), "dr_a").await;
@@ -418,9 +413,8 @@ async fn document_view_picks_highest_version() {
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
let body = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap(); let body = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
let body_str = String::from_utf8(body.to_vec()).unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap();
assert!(body_str.contains("neue Version v2"), "expected v2 content"); assert!(body_str.contains("der Inhalt"), "expected content in body");
assert!(!body_str.contains("alte Version"), "v1 must not leak"); assert!(body_str.contains("Dokument"));
assert!(body_str.contains("Dokument v2"));
} }
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
@@ -428,11 +422,11 @@ async fn document_view_picks_highest_version() {
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
#[tokio::test] #[tokio::test]
async fn analyze_writes_v2_when_document_exists() { async fn analyze_deletes_old_document_and_writes_fresh_input() {
let config = config_with_llm(unique_tmp("rn-5"), "http://unused".into()); let config = config_with_llm(unique_tmp("rn-5"), "http://unused".into());
let case_id = "11111111-1111-1111-1111-111111111111"; let case_id = "11111111-1111-1111-1111-111111111111";
let case_dir = seed_case(&config.data_path, "dr_a", case_id); let case_dir = seed_case(&config.data_path, "dr_a", case_id);
std::fs::write(case_dir.join("document_v1.md"), "altes Dokument").unwrap(); std::fs::write(case_dir.join("document.md"), "altes Dokument").unwrap();
seed_recording(&case_dir, "10-00-00", Some("erste Aufnahme")); seed_recording(&case_dir, "10-00-00", Some("erste Aufnahme"));
seed_recording(&case_dir, "10-05-00", Some("zweite Aufnahme")); seed_recording(&case_dir, "10-05-00", Some("zweite Aufnahme"));
@@ -442,74 +436,17 @@ async fn analyze_writes_v2_when_document_exists() {
let resp = app.oneshot(analyze_request(case_id, &cookie)).await.unwrap(); let resp = app.oneshot(analyze_request(case_id, &cookie)).await.unwrap();
assert_eq!(resp.status(), StatusCode::SEE_OTHER); assert_eq!(resp.status(), StatusCode::SEE_OTHER);
let input_path = case_dir.join("analysis_input_v2.json"); assert!(
assert!(input_path.exists(), "analysis_input_v2.json missing"); !case_dir.join("document.md").exists(),
let parsed: Value = serde_json::from_str(&std::fs::read_to_string(&input_path).unwrap()).unwrap(); "old document must be deleted before re-analysis"
assert_eq!(parsed["version"], 2);
assert_eq!(parsed["recordings"].as_array().unwrap().len(), 2);
assert!(case_dir.join("document_v1.md").exists());
}
#[tokio::test]
async fn analyze_v2_worker_writes_document_v2_via_wiremock() {
let tmp = unique_tmp("rn-w");
let case_dir = tmp.join("dr_a/11111111-1111-1111-1111-111111111111");
std::fs::create_dir_all(&case_dir).unwrap();
std::fs::write(case_dir.join("document_v1.md"), "alte Version").unwrap();
let input = json!({
"version": 2,
"last_recording_mtime": "2026-04-15T10:00:00Z",
"recordings": [
{ "recorded_at": "2026-04-15T10:00:00Z", "text": "Patient." }
]
});
std::fs::write(
case_dir.join("analysis_input_v2.json"),
serde_json::to_vec_pretty(&input).unwrap(),
)
.unwrap();
let mock = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/v1/chat/completions"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"choices": [{ "message": { "content": "neue Fassung" } }]
})))
.mount(&mock)
.await;
let config = config_with_llm(tmp.clone(), mock.uri());
let (tx, rx) = analyze::channel();
let busy = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let handle = tokio::spawn(analyze::worker::run(rx, config, reqwest::Client::new(), busy));
tx.send(analyze::AnalyzeJob {
case_dir: case_dir.clone(),
version: 2,
})
.unwrap();
let doc_v2 = case_dir.join("document_v2.md");
let deadline = std::time::Instant::now() + Duration::from_secs(5);
while !doc_v2.exists() {
if std::time::Instant::now() > deadline {
panic!("document_v2.md not written within 5s");
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
let content = std::fs::read_to_string(&doc_v2).unwrap();
assert!(content.contains("neue Fassung"));
assert_eq!(
std::fs::read_to_string(case_dir.join("document_v1.md")).unwrap(),
"alte Version"
); );
let input_path = case_dir.join("analysis_input.json");
drop(tx); assert!(input_path.exists(), "analysis_input.json missing");
let _ = tokio::time::timeout(Duration::from_secs(2), handle).await; let parsed: Value = serde_json::from_str(&std::fs::read_to_string(&input_path).unwrap()).unwrap();
assert_eq!(parsed["recordings"].as_array().unwrap().len(), 2);
} }
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
// Soft-delete + Undo // Soft-delete + Undo
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
@@ -664,8 +601,8 @@ async fn bulk_analyze_processes_each_selected_case() {
.unwrap(); .unwrap();
assert_eq!(resp.status(), StatusCode::SEE_OTHER); assert_eq!(resp.status(), StatusCode::SEE_OTHER);
assert!(dir_a.join("analysis_input_v1.json").exists()); assert!(dir_a.join("analysis_input.json").exists());
assert!(dir_b.join("analysis_input_v1.json").exists()); assert!(dir_b.join("analysis_input.json").exists());
} }
#[tokio::test] #[tokio::test]
@@ -673,7 +610,7 @@ async fn recovery_skips_deleted_cases() {
let tmp = unique_tmp("rec-del"); let tmp = unique_tmp("rec-del");
let case_dir = tmp.join("dr_a/11111111-1111-1111-1111-111111111111"); let case_dir = tmp.join("dr_a/11111111-1111-1111-1111-111111111111");
std::fs::create_dir_all(&case_dir).unwrap(); std::fs::create_dir_all(&case_dir).unwrap();
std::fs::write(case_dir.join("analysis_input_v1.json"), "{}").unwrap(); std::fs::write(case_dir.join("analysis_input.json"), "{}").unwrap();
std::fs::write( std::fs::write(
case_dir.join(".deleted"), case_dir.join(".deleted"),
r#"{"batch":"00000000-0000-0000-0000-000000000000","deleted_at":"2026-04-15T10:00:00Z"}"#, r#"{"batch":"00000000-0000-0000-0000-000000000000","deleted_at":"2026-04-15T10:00:00Z"}"#,