Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion crates/openhuman-core/src/agent/session_host/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,11 @@ impl TranscriptCodec<OpenHumanRunContext> for OpenHumanTranscriptCodec {
// the new generation's first row. An ordinary turn keeps the row that
// holds them, so this does nothing there. Out-of-band compaction
// (`compact_bound_history`) and an in-turn one both come through here.
crate::agent::tinyagents::discovery::carry_forward(&prior, &mut reconciled.rows);
crate::agent::tinyagents::discovery::carry_forward(
&prior,
&mut reconciled.rows,
sidecar.discovery_record.as_ref(),
);
// Likewise the history-replay options (result expiry, reasoning replay).
if let Some(options) = &sidecar.replay_record {
options.record_on(&mut reconciled.rows, &reconciled.fresh);
Expand Down
157 changes: 157 additions & 0 deletions crates/openhuman-core/src/agent/session_host/codec_adoption_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,7 @@ fn the_codec_records_replay_options_on_the_first_new_row_only_once() {
tool_result_max_age_turns: Some(6),
tool_result_exempt_tools: vec!["tool_search".into()],
replay_reasoning: ReasoningReplay::CurrentTurn,
keep_recent_tokens: None,
};
let context = OpenHumanRunContext::new();
context.session_sidecar.lock().unwrap().replay_record = Some(wanted.clone());
Expand Down Expand Up @@ -408,3 +409,159 @@ fn replay_pin_survives_compaction() {
.unwrap();
assert_eq!(ReplayOptions::recorded_in(&rows), None);
}

fn turn_options(context: OpenHumanRunContext) -> TranscriptTurnOptions<OpenHumanRunContext> {
TranscriptTurnOptions {
request_id: Some("turn".into()),
thread_id: None,
stream: false,
resume: ResumeMode::Never,
context,
}
}

/// A host that forces new discovery options onto a thread records them on a
/// later row. A compaction that keeps the system row (and the older pin on it)
/// but folds that later row away must not hand the thread back to the older
/// pin.
#[test]
fn a_forced_discovery_pin_survives_compaction_that_folds_its_row_but_keeps_an_older_pin() {
use crate::agent::tinyagents::discovery::DiscoveryOptions;

let first = DiscoveryOptions {
collapse_search_results: true,
..DiscoveryOptions::TODAY
};
let forced = DiscoveryOptions {
compact_search_results: true,
..DiscoveryOptions::TODAY
};
let started = OpenHumanRunContext::new();
started.session_sidecar.lock().unwrap().discovery_record = Some(first);
let one = vec![
Message::system("prompt"),
Message::user("one"),
Message::assistant("first answer"),
];
let prior = OpenHumanTranscriptCodec
.reconcile(&[], &[], &one, &turn_options(started))
.unwrap();

// The host forces new options on the second turn: recorded on its user row.
let forcing = OpenHumanRunContext::new();
forcing.session_sidecar.lock().unwrap().discovery_record = Some(forced);
let mut two = one.clone();
two.push(Message::user("two"));
two.push(Message::assistant("second answer"));
let prior = OpenHumanTranscriptCodec
.reconcile(&prior, &one, &two, &turn_options(forcing))
.unwrap();
assert_eq!(DiscoveryOptions::recorded_in(&prior), Some(forced));

// The compaction keeps the system row, so the older pin survives on it,
// and folds the forced row into a summary.
let compacted = vec![
Message::system("prompt"),
Message::user("summary of the first two turns"),
Message::assistant("second answer"),
];
let rows = OpenHumanTranscriptCodec
.reconcile(
&prior,
&two,
&compacted,
&turn_options(OpenHumanRunContext::new()),
)
.unwrap();
assert_eq!(
DiscoveryOptions::recorded_in(&rows),
Some(forced),
"the thread keeps the options it was last forced onto"
);
assert_eq!(
rows[0], prior[0],
"the retained system row is not rewritten"
);
}

/// Forcing options on the turn that also compacts: the fresh rows come before
/// a retained row that still carries the old pin, which would win on every
/// later turn.
#[test]
fn a_forced_discovery_pin_beats_an_older_pin_on_a_row_the_compaction_retained() {
use crate::agent::tinyagents::discovery::DiscoveryOptions;

let older = DiscoveryOptions {
collapse_search_results: true,
..DiscoveryOptions::TODAY
};
let forced = DiscoveryOptions {
compact_search_results: true,
..DiscoveryOptions::TODAY
};
let history = vec![
Message::system("prompt"),
Message::user("one"),
Message::assistant("first answer"),
Message::user("two"),
Message::assistant("second answer"),
];
let mut prior = OpenHumanTranscriptCodec
.reconcile(
&[],
&[],
&history,
&turn_options(OpenHumanRunContext::new()),
)
.unwrap();
assert!(older.record_on(&mut prior, &[false, false, false, true, false]));

let forcing = OpenHumanRunContext::new();
forcing.session_sidecar.lock().unwrap().discovery_record = Some(forced);
let compacted = vec![
Message::system("prompt with a fresh memory block"),
Message::user("summary of the first turn"),
history[3].clone(),
history[4].clone(),
];
let rows = OpenHumanTranscriptCodec
.reconcile(&prior, &history, &compacted, &turn_options(forcing))
.unwrap();
assert_eq!(DiscoveryOptions::recorded_in(&rows), Some(forced));
assert_eq!(rows[2], prior[3], "the retained row is not rewritten");
}

/// A retry of an interrupted message can reach the codec before the model has
/// answered, so the turn has no fresh row. Forcing options then has nowhere to
/// be recorded, and the codec must not rewrite a stored row to make room: the
/// commit would stop extending the thread and open a new generation.
#[test]
fn a_forced_discovery_pin_never_rewrites_a_stored_row_when_the_turn_has_no_fresh_row() {
use crate::agent::tinyagents::discovery::DiscoveryOptions;

let started = DiscoveryOptions {
collapse_search_results: true,
..DiscoveryOptions::TODAY
};
let forced = DiscoveryOptions {
compact_search_results: true,
..DiscoveryOptions::TODAY
};
let first = OpenHumanRunContext::new();
first.session_sidecar.lock().unwrap().discovery_record = Some(started);
let history = vec![
Message::system("prompt"),
Message::user("one"),
Message::assistant("first answer"),
];
let prior = OpenHumanTranscriptCodec
.reconcile(&[], &[], &history, &turn_options(first))
.unwrap();

let forcing = OpenHumanRunContext::new();
forcing.session_sidecar.lock().unwrap().discovery_record = Some(forced);
let rows = OpenHumanTranscriptCodec
.reconcile(&prior, &history, &history, &turn_options(forcing))
.unwrap();
assert_eq!(rows, prior, "no stored row is touched");
}
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,41 @@ fn a_thread_created_with_todays_behaviour_records_nothing_and_stays_that_way() {
);
});
}

/// A thread whose durable history was imported has rows but no frozen prefix
/// and no recorded options: it ran before they existed, so it keeps today's
/// behaviour whatever the config says now, like any other unrecorded thread.
#[test]
fn a_thread_with_imported_history_and_no_record_keeps_todays_behaviour() {
use tinyagents_session::transcript::TranscriptMessage;

run_async(async {
// No TinySecurity module runs in a unit test, so the screen would hold the input.
let _off = crate::security::switch::off_for_this_thread();
let root = tempfile::tempdir().expect("tempdir");
let thread = thread_id("imported-unpinned");
let next = model(vec![ModelResponse::assistant("ok")], true);
let mut host = build_host_with_config(
root.path(),
next,
true,
&thread,
agent_config(no_promotion()),
);
let imported = [
TranscriptMessage::user("legacy question"),
TranscriptMessage::assistant("legacy answer"),
];
assert!(host.adopt_imported_history(&imported).expect("adopt"));
host.turn("hello").await.expect("turn");
let session = host.session.clone().expect("bound session");
let records: usize = store_tree(root.path(), &thread, &session)
.values()
.map(|stored| stored.to_string().matches(DISCOVERY_METADATA_KEY).count())
.sum();
assert_eq!(
records, 0,
"the config of today must not be adopted by a thread that predates the pin"
);
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,9 @@ impl SessionDriver<OpenHumanRunContext> for OpenHumanSessionDriver {
crate::agent::tinyagents::host::run_context::SessionRunOptions::of(
&request.run_context.config,
);
// The close and the required-output repair run after the loop, outside
// the harness's request builder, so they apply the same options.
let replay = run_context.session_run_options.clone();
let cancellation = request.run_context.cancellation.clone();
// Boxing avoids worker-stack overflow in debug builds.
let turn = Box::pin(async move {
Expand Down Expand Up @@ -249,6 +252,7 @@ impl SessionDriver<OpenHumanRunContext> for OpenHumanSessionDriver {
&outcome,
close_by.map(|at| at.saturating_duration_since(Instant::now())),
supplemental_trace.as_ref(),
&replay,
) => close,
};
let mut output = close
Expand Down Expand Up @@ -319,6 +323,7 @@ impl SessionDriver<OpenHumanRunContext> for OpenHumanSessionDriver {
outcome.model_calls.saturating_add(1) as u32,
&mut repair_usage,
supplemental_trace.as_ref(),
&replay,
);
tokio::pin!(repair);
tokio::select! {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ use tinyagents_harness::middleware::wrap_harness_instruction;

use crate::agent::{
session_host::{product_copy, stop_policy},
tinyagents::{SupplementalTrace, TinyagentsTurnOutcome, TurnModelSource},
tinyagents::{
host::run_context::SessionRunOptions, SupplementalTrace, TinyagentsTurnOutcome,
TurnModelSource,
},
};
use tinyagents_harness::turn_policy::AGENT_TURN_MAX_OUTPUT_TOKENS;
use tinyinference_llm::usage::BilledUsage;
Expand Down Expand Up @@ -293,10 +296,12 @@ pub(super) async fn repair_required_output(
iteration: u32,
usage: &mut RepairUsage,
trace: Option<&Arc<SupplementalTrace>>,
replay: &SessionRunOptions,
) -> Option<String> {
use tinyagents_harness::config as required;

let prompt_history: Vec<tinyinference_llm::message::Message> = history
let prompt_history: Vec<tinyinference_llm::message::Message> = replay
.replayed(history)
.iter()
.filter_map(message_to_native_chat_message)
.map(|message| crate::agent::tinyagents::chat_message_to_message(&message))
Expand Down Expand Up @@ -407,6 +412,7 @@ pub(super) async fn close_if_needed(
outcome: &TinyagentsTurnOutcome,
budget: Option<std::time::Duration>,
trace: Option<&Arc<SupplementalTrace>>,
replay: &SessionRunOptions,
) -> Option<GroundedClose> {
let needs_cap_close = outcome.hit_cap && !outcome.wrap_up_injected;
let needs_final_close = outcome.text.trim().is_empty()
Expand All @@ -422,7 +428,8 @@ pub(super) async fn close_if_needed(
let records = product_copy::close_results(&outcome.tool_outcomes);
let rendered = product_copy::render_close_results(&records, 16_000);
let instruction = close_instruction(outcome, needs_cap_close, &rendered);
let history: Vec<tinyinference_llm::message::Message> = base_history
let history: Vec<tinyinference_llm::message::Message> = replay
.replayed(base_history)
.iter()
.filter_map(message_to_native_chat_message)
.map(|message| crate::agent::tinyagents::chat_message_to_message(&message))
Expand Down
Loading
Loading