From 365c4ae7cedc2e88b60d541dff5d823c2fe4826a Mon Sep 17 00:00:00 2001 From: Valeriy Selitskiy <239034+iamwavecut@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:31:00 +0100 Subject: [PATCH] Stop rejecting code and choruses as repeated phrases The phrase check dropped operators and scanned code, so a calculator and a song with a chorus failed on every model, and the job retry budget replayed the rejection five times. Code spans are now masked, operators stay tokens, and a repeated phrase is rejected only when it fills most of the prose. A step that every model answers with a loop fails without a requeue, and routing events record the rejection kind. --- .../openplotva-app/src/dialog_jobs/retry.rs | 15 +- .../openplotva-app/src/dialog_jobs/tests.rs | 62 +++++ crates/openplotva-app/src/dialog_runtime.rs | 212 +++++++++++++++++- .../openplotva-app/src/dialog_turn/session.rs | 5 + crates/openplotva-app/src/routed_attempts.rs | 52 ++++- crates/openplotva-dialog/src/lib.rs | 169 ++++++++++++-- 6 files changed, 479 insertions(+), 36 deletions(-) diff --git a/crates/openplotva-app/src/dialog_jobs/retry.rs b/crates/openplotva-app/src/dialog_jobs/retry.rs index 52b0a634..a1b828cb 100644 --- a/crates/openplotva-app/src/dialog_jobs/retry.rs +++ b/crates/openplotva-app/src/dialog_jobs/retry.rs @@ -49,6 +49,8 @@ pub(crate) struct RetryableDialogProviderFailure<'a> { pub max_attempts: i32, pub now: OffsetDateTime, pub budget_deadline: OffsetDateTime, + /// Every routed model already failed this step the same way, so a requeue would replay it. + pub requeue_futile: bool, } /// Decide retry vs terminal for one retryable failure. Appends the retry job @@ -71,7 +73,8 @@ where let target_queue = retryable_dialog_job_target_queue(failure.queue_name); let attempts_exhausted = attempt >= max_attempts; let budget_exhausted = failure.now >= failure.budget_deadline; - let exhausted = attempts_exhausted || budget_exhausted; + let futile = failure.requeue_futile && !attempts_exhausted && !budget_exhausted; + let exhausted = attempts_exhausted || budget_exhausted || futile; let stage = if exhausted { LLM_JOB_RETRY_EXHAUSTED_STAGE } else { @@ -87,7 +90,10 @@ where failure.error, ); if exhausted { - event.message = if budget_exhausted && !attempts_exhausted { + event.message = if futile { + "every routed model's answer was rejected; a requeue would replay the rejection" + .to_owned() + } else if budget_exhausted && !attempts_exhausted { "retryable LLM provider error exhausted the turn budget".to_owned() } else { "retryable LLM provider error exhausted job attempts".to_owned() @@ -119,7 +125,9 @@ where max_attempts, )); } - let reason = if budget_exhausted && !attempts_exhausted { + let reason = if futile { + "output_rejected_by_every_target" + } else if budget_exhausted && !attempts_exhausted { "budget_exhausted" } else { failure.codes.exhausted @@ -232,6 +240,7 @@ fn dialog_retry_exhausted_routing_event( "last_retryable_reason": failure.reason.as_str(), "provider": provider, "target_queue": target_queue, + "rejected_by_every_target": failure.requeue_futile, }), } } diff --git a/crates/openplotva-app/src/dialog_jobs/tests.rs b/crates/openplotva-app/src/dialog_jobs/tests.rs index bda40e47..38f421c2 100644 --- a/crates/openplotva-app/src/dialog_jobs/tests.rs +++ b/crates/openplotva-app/src/dialog_jobs/tests.rs @@ -1880,6 +1880,7 @@ async fn retry_handler_exhausts_on_budget_deadline_despite_remaining_attempts() max_attempts: 5, now: now + TimeDuration::seconds(130), budget_deadline: now + TimeDuration::seconds(120), + requeue_futile: false, }, &mut report, ) @@ -1909,6 +1910,67 @@ async fn retry_handler_exhausts_on_budget_deadline_despite_remaining_attempts() Ok(()) } +#[tokio::test] +async fn retry_handler_fails_without_requeue_when_every_target_rejected_the_answer() +-> Result<(), Box> { + let now = OffsetDateTime::from_unix_timestamp(1_779_193_800)?; + let queue = InMemoryTaskQueue::new(); + let job_id = queue.assign( + DIALOG_AIFARM_QUEUE_NAME, + new_dialog_job_at(dialog_params("hello"), now), + ); + let item = queue + .dequeue_dialog_job(DIALOG_AIFARM_QUEUE_NAME) + .await? + .expect("work item"); + let params = dialog_params("hello"); + let mut report = DialogJobWorkerReport::default(); + let error = "every routed model's answer was rejected: pathological final text"; + + let resolution = handle_retryable_dialog_provider_error( + &queue, + &item, + ¶ms, + None, + RetryableDialogProviderFailure { + queue_name: DIALOG_AIFARM_QUEUE_NAME, + provider_name: "aifarm", + reason: FailureReason::ModelOutputRejected, + codes: PROVIDER_ERROR_RETRY_CODES, + error, + max_attempts: 5, + now, + budget_deadline: now + TimeDuration::seconds(120), + requeue_futile: true, + }, + &mut report, + ) + .await; + + assert!(report.retry_exhausted); + assert_eq!(report.retry_attempt, Some(1)); + assert_eq!( + resolution.outcome, + crate::dialog_turn::TurnOutcome::TerminalFailed { + reason: "output_rejected_by_every_target", + error: error.to_owned(), + user_signal: crate::dialog_turn::UserSignalPlan::React, + } + ); + assert_eq!( + resolution.disposition, + crate::dialog_turn::JobDisposition::Fail(error.to_owned()) + ); + let record = queue.record(job_id).expect("job record"); + let event = record.events.last().expect("retry event"); + assert_eq!(event.stage, LLM_JOB_RETRY_EXHAUSTED_STAGE); + assert_eq!( + event.message, + "every routed model's answer was rejected; a requeue would replay the rejection" + ); + Ok(()) +} + #[tokio::test] async fn event_append_failure_does_not_leave_job_processing() -> Result<(), Box> { let now = OffsetDateTime::from_unix_timestamp(1_779_193_800)?; diff --git a/crates/openplotva-app/src/dialog_runtime.rs b/crates/openplotva-app/src/dialog_runtime.rs index 96bca601..c8f5d71c 100644 --- a/crates/openplotva-app/src/dialog_runtime.rs +++ b/crates/openplotva-app/src/dialog_runtime.rs @@ -1,7 +1,9 @@ //! App-level dialog provider construction. use std::{ - collections::HashMap, + collections::{HashMap, HashSet}, + error::Error, + fmt, sync::{Arc, Mutex}, }; @@ -201,9 +203,11 @@ impl ChatStepProvider for RouterChatProvider { // Feedback for a re-sample, kept per model: the note tells the model that // rejected sample what was wrong with it, and means nothing to a different one. let rejected: Arc>> = Arc::new(Mutex::new(None)); + let tally: Arc> = Arc::default(); + let attempt_tally = Arc::clone(&tally); let result = self .walker - .run( + .run_described( RoutedRequestContext { workflow_key: DIALOG_WORKFLOW_KEY.to_owned(), queue_name: Some("dialog".to_owned()), @@ -223,6 +227,10 @@ impl ChatStepProvider for RouterChatProvider { let resolved = factory.resolve(&attempt); let mut step_request = request_for_attempts.clone(); let rejected = Arc::clone(&rejected); + let tally = Arc::clone(&attempt_tally); + if let Ok(mut tally) = tally.lock() { + tally.attempts += 1; + } if let Some(verdict) = rejected.lock().ok().and_then(|last| match last.as_ref() { Some((model_id, verdict)) if *model_id == attempt.model_id => { @@ -295,12 +303,17 @@ impl ChatStepProvider for RouterChatProvider { Err(error) => { if retryable_reason(error.as_ref()) == Some(FailureReason::ModelOutputRejected) - && let Ok(mut last) = rejected.lock() { - *last = Some(( - attempt_model_id, - rejection_verdict_for(error.as_ref()).to_owned(), - )); + let verdict = rejection_verdict_for(error.as_ref()); + if let Ok(mut last) = rejected.lock() { + *last = Some((attempt_model_id, verdict.to_owned())); + } + if verdict == PATHOLOGICAL_VERDICT + && let Ok(mut tally) = tally.lock() + { + tally.pathological_models.insert(attempt_model_id); + tally.pathological += 1; + } } Err(error) } @@ -308,11 +321,22 @@ impl ChatStepProvider for RouterChatProvider { } }, |error| retryable_reason(error.as_ref()), + |error| rejection_detail(error.as_ref()), ) .await; match result { Ok(output) => Ok(output), - Err(RoutedAttemptRunError::Attempt(error)) => Err(error), + Err(RoutedAttemptRunError::Attempt(error)) => { + if tally + .lock() + .is_ok_and(|tally| tally.rejected_by_every_target()) + { + let error: ChatProviderError = + Box::new(OutputRejectedByEveryTarget { source: error }); + return Err(error); + } + Err(error) + } Err(RoutedAttemptRunError::Routing(error)) => { let error: ChatProviderError = Box::new(error); Err(error) @@ -322,6 +346,79 @@ impl ChatStepProvider for RouterChatProvider { } } +const PATHOLOGICAL_VERDICT: &str = "pathological"; + +/// The attempts of one routed dialog step, and which of them the loop guard rejected. +#[derive(Default)] +struct RejectionTally { + attempts: usize, + pathological: usize, + pathological_models: HashSet, +} + +impl RejectionTally { + /// Every attempt, across at least two models, wrote text the loop guard rejected: the + /// turn itself draws the loop, so a requeue would replay the same rejection. + fn rejected_by_every_target(&self) -> bool { + self.attempts > 0 + && self.pathological == self.attempts + && self.pathological_models.len() >= 2 + } +} + +/// Every routed model answered the dialog step with text the loop guard rejected. +#[derive(Debug)] +pub struct OutputRejectedByEveryTarget { + source: ChatProviderError, +} + +impl fmt::Display for OutputRejectedByEveryTarget { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "every routed model's answer was rejected: {}", + self.source + ) + } +} + +impl Error for OutputRejectedByEveryTarget { + fn source(&self) -> Option<&(dyn Error + 'static)> { + Some(self.source.as_ref()) + } +} + +/// Whether a requeue of this dialog step would replay the same rejection. +#[must_use] +pub fn is_output_rejected_by_every_target(error: &(dyn Error + 'static)) -> bool { + error + .downcast_ref::() + .is_some() + || error + .source() + .is_some_and(is_output_rejected_by_every_target) +} + +/// What the validators found wrong with a rejected sample, for its routing event. +fn rejection_detail(error: &(dyn Error + 'static)) -> Option { + if retryable_reason(error) != Some(FailureReason::ModelOutputRejected) { + return None; + } + let verdict = rejection_verdict_for(error); + let kind = (verdict == PATHOLOGICAL_VERDICT) + .then(|| error.to_string()) + .and_then(|message| { + message + .rsplit_once(": ") + .map(|(_, kind)| kind.trim().to_owned()) + }) + .filter(|kind| !kind.is_empty()); + Some(match kind { + Some(kind) => format!("{verdict}: {kind}"), + None => verdict.to_owned(), + }) +} + /// Build the dialog executor from the shared routing policy. pub fn router_dialog_provider( config: &AppConfig, @@ -978,6 +1075,105 @@ mod tests { ); } + fn two_model_dialog_snapshot() -> RoutingSnapshot { + let mut snapshot = routed_dialog_snapshot(); + snapshot.workflows[0].retry_max_hops = 3; + let mut fallback_model = snapshot.models[0].clone(); + fallback_model.id = 11; + fallback_model.model_name = "db/fallback".to_owned(); + snapshot.models.push(fallback_model); + let mut fallback = snapshot.assignments[0].clone(); + fallback.id = 101; + fallback.role = "fallback".to_owned(); + fallback.provider_model_id = 11; + fallback.fallback_order = Some(0); + snapshot.assignments.push(fallback); + snapshot + } + + async fn run_two_model_step( + results: Vec>, + ) -> ( + ChatProviderError, + Vec, + ) { + let default_provider = Arc::new(SequencedProvider::new("unused", vec![])); + let routed_provider: DialogProviderHandle = + Arc::new(SequencedProvider::new("aifarm", results)); + let mut clients = HashMap::new(); + clients.insert("aifarm".to_owned(), routed_provider); + let reporter = crate::runtime_routing::RoutingEventReporter::new( + crate::runtime_routing::RoutingEventBuffer::new(16), + None, + None, + ); + let provider = router_provider_for_test( + two_model_dialog_snapshot(), + default_provider, + clients, + reporter.clone(), + ); + let error = provider + .as_chat_step() + .expect("step seam") + .run_chat_step(default_step_request()) + .await + .expect_err("every attempt fails"); + (error, reporter.buffer().routing_events(16)) + } + + fn pathological(reason: &str) -> Result { + Err(Box::new( + openplotva_llm::aifarm::AifarmDialogError::FinalAnswerPathological(reason.to_owned()), + )) + } + + #[tokio::test] + async fn pathological_answers_from_every_model_mark_the_requeue_futile() { + let (error, events) = run_two_model_step(vec![ + pathological("repeated phrase"), + pathological("repeated phrase"), + ]) + .await; + + assert!(is_output_rejected_by_every_target(error.as_ref())); + assert_eq!( + retryable_reason(error.as_ref()), + Some(FailureReason::ModelOutputRejected), + "the marker keeps the retry classification of the rejection it wraps" + ); + let rejections = events + .iter() + .filter(|event| event.event_type == "attempt_failed") + .map(|event| event.detail["rejection"].clone()) + .collect::>(); + assert_eq!(rejections, vec![json!("pathological: repeated phrase"); 2]); + } + + #[tokio::test] + async fn a_failure_of_another_kind_keeps_the_requeue() { + let unavailable: ChatProviderError = Box::new(ProviderError::new( + "aifarm", + FailureReason::ProviderUnavailable, + "status 503", + )); + let (error, events) = + run_two_model_step(vec![pathological("repeated phrase"), Err(unavailable)]).await; + + assert!(!is_output_rejected_by_every_target(error.as_ref())); + let mut rejections = events + .iter() + .filter(|event| event.event_type == "attempt_failed") + .map(|event| event.detail.get("rejection").cloned()) + .collect::>(); + rejections.sort_by_key(Option::is_some); + assert_eq!( + rejections, + vec![None, Some(json!("pathological: repeated phrase"))], + "only rejected outputs carry a rejection kind" + ); + } + #[tokio::test] async fn router_chat_provider_honors_turn_deadline_task_local() { let default_provider = Arc::new(SequencedProvider::new("unused", vec![])); diff --git a/crates/openplotva-app/src/dialog_turn/session.rs b/crates/openplotva-app/src/dialog_turn/session.rs index e5b698f8..c2926006 100644 --- a/crates/openplotva-app/src/dialog_turn/session.rs +++ b/crates/openplotva-app/src/dialog_turn/session.rs @@ -755,6 +755,8 @@ where let retryable_reason = openplotva_llm::retry::retryable_reason(error.as_ref()); let retry_provider = openplotva_llm::retry::provider_name(error.as_ref()).to_owned(); + let requeue_futile = + crate::dialog_runtime::is_output_rejected_by_every_target(error.as_ref()); let error = error.to_string(); if let Some(reason) = retryable_reason { if sent.any() @@ -800,6 +802,7 @@ where max_attempts: ctx.max_llm_job_attempts.max(1), now: failure_now, budget_deadline: budget.deadline(), + requeue_futile, }, report, ) @@ -898,6 +901,7 @@ where }, now: failure_now, budget_deadline: budget.deadline(), + requeue_futile: false, }, report, ) @@ -1070,6 +1074,7 @@ where max_attempts: ctx.max_llm_job_attempts.max(1), now: failure_now, budget_deadline: budget.deadline(), + requeue_futile: false, }, report, ) diff --git a/crates/openplotva-app/src/routed_attempts.rs b/crates/openplotva-app/src/routed_attempts.rs index 2291d72f..185f629d 100644 --- a/crates/openplotva-app/src/routed_attempts.rs +++ b/crates/openplotva-app/src/routed_attempts.rs @@ -224,16 +224,36 @@ impl RoutedAttemptWalker { } pub async fn run( + &self, + context: RoutedRequestContext, + execute: F, + retryable: Retry, + ) -> Result> + where + E: std::fmt::Debug + Send + Sync + 'static, + F: FnMut(RoutedAttempt) -> Fut + Send, + Fut: Future> + Send, + Retry: Fn(&E) -> Option + Send, + { + self.run_described(context, execute, retryable, |_: &E| None) + .await + } + + /// [`Self::run`], plus `describe`: what was wrong with a failed attempt, recorded as + /// `rejection` in its `attempt_failed` or `model_output_retry` event. + pub async fn run_described( &self, context: RoutedRequestContext, mut execute: F, retryable: Retry, + describe: Describe, ) -> Result> where E: std::fmt::Debug + Send + Sync + 'static, F: FnMut(RoutedAttempt) -> Fut + Send, Fut: Future> + Send, Retry: Fn(&E) -> Option + Send, + Describe: Fn(&E) -> Option + Send, { let table = self.handle.snapshot(); let Some(route) = table.resolve(&context.workflow_key, context.vip) else { @@ -538,6 +558,14 @@ impl RoutedAttemptWalker { model_output_retry += 1; failed_attempts += 1; last_reason = Some(reason.as_str().to_owned()); + let detail = with_rejection( + json!({ + "retry": model_output_retry, + "limit": self.model_output_retries, + "retryable_reason": reason.as_str(), + }), + describe(&error), + ); last_error = Some(error); self.record_event(routing_event_with_severity( "model_output_retry", @@ -546,11 +574,7 @@ impl RoutedAttemptWalker { Some(attempt.provider), Some(attempt.model), "model output rejected; re-sampling the same model", - json!({ - "retry": model_output_retry, - "limit": self.model_output_retries, - "retryable_reason": reason.as_str(), - }), + detail, )); continue; } @@ -575,10 +599,13 @@ impl RoutedAttemptWalker { Some(attempt.provider), Some(attempt.model), "routed provider attempt failed", - json!({ - "attempt": failed_attempts + 1, - "retryable_reason": reason.as_str(), - }), + with_rejection( + json!({ + "attempt": failed_attempts + 1, + "retryable_reason": reason.as_str(), + }), + describe(&error), + ), )); if reason == FailureReason::CapacityUnavailable && let Some(cooldown) = provider_capacity_cooldown( @@ -726,6 +753,13 @@ impl RoutedAttemptWalker { } } +fn with_rejection(mut detail: Value, rejection: Option) -> Value { + if let (Some(rejection), Some(object)) = (rejection, detail.as_object_mut()) { + object.insert("rejection".to_owned(), json!(rejection)); + } + detail +} + fn all_attempts_exhausted_detail( context: &RoutedRequestContext, failed_attempts: usize, diff --git a/crates/openplotva-dialog/src/lib.rs b/crates/openplotva-dialog/src/lib.rs index df92e3a8..e0a04dc9 100644 --- a/crates/openplotva-dialog/src/lib.rs +++ b/crates/openplotva-dialog/src/lib.rs @@ -2335,28 +2335,110 @@ pub fn pathological_final_answer_reason(value: &str) -> Option { if has_adjacent_repeated_block(¶graphs) { return Some("repeated block".to_owned()); } - let mut repeated_segments = std::collections::HashMap::::new(); - let repetition_text = strip_html_tags_for_repetition(&strip_http_urls_for_repetition(value)); - for segment in repetition_text.split(['\n', '.', '!', '?']) { - let words = segment - .split(|ch: char| !ch.is_alphanumeric()) - .filter(|word| !word.is_empty()) - .map(str::to_lowercase) - .collect::>(); - if words.len() < 2 { + has_looping_phrase(value).then(|| "repeated phrase".to_owned()) +} + +const MIN_REPEATED_PHRASE_OCCURRENCES: usize = 3; +/// Share of the prose, in percent, that one run of back-to-back copies must cover. +const MIN_ADJACENT_PHRASE_SHARE_PERCENT: usize = 50; +/// Share of the prose, in percent, that all phrases seen three or more times must cover. +/// A chorus spread across verses stays under it; a model stuck in a sentence cycle does not. +const MIN_SPREAD_PHRASE_SHARE_PERCENT: usize = 80; + +/// A phrase segment: its normalized text when it is long enough to compare, and its weight +/// in characters of normalized text. +struct PhraseSegment { + key: Option, + weight: usize, +} + +fn phrase_segments(value: &str) -> Vec { + // Code repeats lines by nature (`return None`, `}`), so only the prose is checked. + let prose = leak_guard::mask_code_spans(value); + let prose = strip_html_tags_for_repetition(&strip_http_urls_for_repetition(&prose)); + prose + .split(['\n', '.', '!', '?']) + .filter_map(|segment| { + let tokens = phrase_tokens(segment); + if tokens.is_empty() { + return None; + } + let words = tokens + .iter() + .filter(|token| token.chars().any(char::is_alphanumeric)) + .count(); + let normalized = tokens.join(" "); + let weight = normalized.chars().count(); + let key = (words >= 2 && weight >= 8).then_some(normalized); + Some(PhraseSegment { key, weight }) + }) + .collect() +} + +/// Lowercased words plus operator symbols, so `a + b` and `a - b` stay different phrases. +fn phrase_tokens(segment: &str) -> Vec { + let mut tokens = Vec::new(); + let mut word = String::new(); + for ch in segment.chars() { + if ch.is_alphanumeric() { + word.extend(ch.to_lowercase()); continue; } - let normalized = words.join(" "); - if normalized.chars().count() < 8 { + if !word.is_empty() { + tokens.push(std::mem::take(&mut word)); + } + if matches!( + ch, + '+' | '-' | '*' | '/' | '=' | '<' | '>' | '%' | '^' | '&' | '|' | '~' + ) { + tokens.push(ch.to_string()); + } + } + if !word.is_empty() { + tokens.push(word); + } + tokens +} + +/// Whether one phrase repeats enough to read as a sampling loop: back-to-back copies that +/// fill half the prose, or phrases seen three or more times that fill most of it. +fn has_looping_phrase(value: &str) -> bool { + let segments = phrase_segments(value); + let total = segments.iter().map(|segment| segment.weight).sum::(); + if total == 0 { + return false; + } + let covers = |weight: usize, percent: usize| weight * 100 >= total * percent; + + let mut run_key: Option<&str> = None; + let mut run_len = 0; + let mut occurrences = std::collections::HashMap::<&str, (usize, usize)>::new(); + for segment in &segments { + let Some(key) = segment.key.as_deref() else { + run_key = None; + run_len = 0; continue; + }; + if run_key == Some(key) { + run_len += 1; + } else { + run_key = Some(key); + run_len = 1; } - let count = repeated_segments.entry(normalized).or_default(); - *count += 1; - if *count >= 3 { - return Some("repeated phrase".to_owned()); + if run_len >= MIN_REPEATED_PHRASE_OCCURRENCES + && covers(run_len * segment.weight, MIN_ADJACENT_PHRASE_SHARE_PERCENT) + { + return true; } + let entry = occurrences.entry(key).or_insert((0, segment.weight)); + entry.0 += 1; } - None + let repeated = occurrences + .values() + .filter(|(count, _)| *count >= MIN_REPEATED_PHRASE_OCCURRENCES) + .map(|(count, weight)| count * weight) + .sum::(); + covers(repeated, MIN_SPREAD_PHRASE_SHARE_PERCENT) } #[derive(Clone, Debug, Eq, PartialEq)] @@ -6102,6 +6184,61 @@ mod tests { ); } + #[test] + fn finalize_dialog_reply_keeps_code_whose_lines_differ_by_operator() { + let functions = "def add(a, b):\n return a + b\n\ndef sub(a, b):\n return a - b\n\ndef mul(a, b):\n return a * b\n\ndef div(a, b):\n return a / b"; + for raw in [ + format!( + "Вот простой калькулятор:\n
{functions}\n
" + ), + format!("Вот простой калькулятор:\n```python\n{functions}\n```"), + format!("Вот простой калькулятор:\n\n{functions}"), + ] { + assert_eq!( + finalize_dialog_reply(&raw), + DialogReplyOutcome::Reply(raw.clone()), + "{raw}" + ); + } + } + + #[test] + fn finalize_dialog_reply_keeps_song_chorus_repeated_across_verses() { + let raw = "[Verse 1]\nНочь опять зовёт меня\nЯ иду туда, где ты\n\n[Chorus]\nМы горим до утра\nМы горим до утра\n\n[Verse 2]\nГород спит, а мы не спим\nСердце бьётся в такт\n\n[Chorus]\nМы горим до утра\nМы горим до утра\n\n[Outro]\nМы горим до утра"; + + assert_eq!( + finalize_dialog_reply(raw), + DialogReplyOutcome::Reply(raw.to_owned()) + ); + } + + #[test] + fn finalize_dialog_reply_keeps_long_reply_with_short_repeated_tail() { + let raw = "Собрала для тебя короткий план на неделю. В понедельник начни с лёгкой пробежки и растяжки. Во вторник сделай силовую тренировку на ноги и корпус. В среду отдыхай и гуляй не меньше часа. В четверг повтори силовую, но добавь подтягивания. В пятницу снова пробежка, чуть длиннее первой. На выходных отдыхай. Удачи! Удачи тебе! Удачи тебе! Удачи тебе!"; + + assert_eq!( + finalize_dialog_reply(raw), + DialogReplyOutcome::Reply(raw.to_owned()) + ); + } + + #[test] + fn finalize_dialog_reply_rejects_sentence_loops() { + for raw in [ + "Я не знаю. Я не знаю. Я не знаю. Я не знаю. Я не знаю.", + "Хороший вопрос. Я подумаю над ним. Хороший вопрос. Я подумаю над ним. Хороший вопрос. Я подумаю над ним. Хороший вопрос. Я подумаю над ним.", + "Вот код:\n
print(1)
\nЭто всё, что я могу. Это всё, что я могу. Это всё, что я могу.", + ] { + assert_eq!( + finalize_dialog_reply(raw), + DialogReplyOutcome::Suppressed(DialogReplySuppression::Pathological( + "repeated phrase".to_owned() + )), + "{raw}" + ); + } + } + #[test] fn finalize_dialog_reply_rejects_excessive_paragraph_count() { let raw = (0..257)