Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
5 changes: 4 additions & 1 deletion crates/tokscale-core/src/message_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,13 @@ use std::io::{BufReader, BufWriter, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::time::UNIX_EPOCH;

// 21: Codex fork-replay gate now disambiguates a same-millisecond turn via a
// `task_started` turn_id, adding CodexParseState.forked_child_task_started_turn_ids
// to the cached incremental state; older cached entries must reparse.
// 20: Codex fork replay parsing now keeps user-fork turns after repeated child
// session_meta rows; cached Codex entries from older parser logic can be empty.
// (19 was the jcode parser change in #718 — bump again so those caches reparse.)
const CACHE_SCHEMA_VERSION: u32 = 20;
const CACHE_SCHEMA_VERSION: u32 = 21;
const CACHE_FILENAME: &str = "source-message-cache.bin";
const CACHE_LOCK_FILENAME: &str = "source-message-cache.lock";
const MAX_CACHE_FILE_BYTES: u64 = 256 * 1024 * 1024;
Expand Down
116 changes: 115 additions & 1 deletion crates/tokscale-core/src/sessions/codex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,15 @@ pub(crate) struct CodexParseState {
/// keeps a pending turn alive across incremental re-parses of appended chunks.
#[serde(default)]
pub pending_turn_start: bool,
/// `turn_id`s announced by a `task_started` event while a forked child is
/// still skipping its replayed parent history. The child's own turn is
/// preceded by `task_started`; replayed parent turns are not. Used only to
/// disambiguate a same-millisecond turn, where the UUID v7 timestamp ties
/// and the random tail is meaningless — there, only a task-started turn_id
/// ends the skip. Cleared when the skip ends or a new fork begins.
/// `#[serde(default)]` keeps it across incremental re-parses.
#[serde(default)]
pub forked_child_task_started_turn_ids: std::collections::HashSet<String>,
}

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -293,12 +302,25 @@ fn parse_codex_reader<R: BufRead>(
{
state.forked_child_waiting_for_turn_context = false;
state.forked_child_replay_session_id = None;
state.forked_child_task_started_turn_ids.clear();
if let Some(ref id) = state.forked_child_session_id {
state.session_id_from_meta = Some(id.clone());
}
state.current_model = payload_model.clone();
handled = true;
} else {
if entry.entry_type == "event_msg"
&& payload.payload_type.as_deref() == Some("task_started")
{
// The child's own turn is introduced by a
// `task_started`; remember its turn_id so the gate can
// recognize the child's own same-millisecond turn.
if let Some(turn_id) = payload.turn_id.as_deref() {
state
.forked_child_task_started_turn_ids
.insert(turn_id.to_string());
}
}
if entry.entry_type == "session_meta" {
if let Some(ref id) = payload.id {
if state
Expand Down Expand Up @@ -361,6 +383,7 @@ fn parse_codex_reader<R: BufRead>(
state.forked_child_replay_session_id = None;
state.forked_child_inherited_baseline = None;
state.forked_child_inherited_reported_total = None;
state.forked_child_task_started_turn_ids.clear();
}
}
if let Some(ref provider) = payload.model_provider {
Expand Down Expand Up @@ -678,7 +701,29 @@ fn forked_child_turn_starts_own_session(state: &CodexParseState, turn_id: Option

match (turn_id, codex_uuid_v7_order_key(child_session_id)) {
(Some(turn_id), Some(child_key)) => {
codex_uuid_v7_order_key(turn_id).is_none_or(|turn_key| turn_key >= child_key)
let Some(turn_key) = codex_uuid_v7_order_key(turn_id) else {
return true;
};
// Compare only the UUID v7 48-bit millisecond timestamp (the first
// 12 hex of the order key), not the full id. The child's own turn is
// minted at or after its session_meta and the replayed parent turns
// strictly earlier, so the millisecond prefix is the causal signal;
// the version nibble + random tail of two independently-minted v7
// UUIDs is a coin flip.
match turn_key[..12].cmp(&child_key[..12]) {
std::cmp::Ordering::Greater => true,
std::cmp::Ordering::Less => false,
// Same millisecond: the timestamp ties and the random tail
// cannot order the child's own turn against a replayed parent
// turn that happens to share the fork's millisecond. The child's
// own turn is announced by a `task_started` event; replayed
// parent turns are not — so only a task-started turn_id ends the
// skip here, otherwise an equal-prefix replayed parent turn would
// be miscounted as child-local.
std::cmp::Ordering::Equal => {
state.forked_child_task_started_turn_ids.contains(turn_id)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep same-ms user forks from waiting forever

When a forked log has replayed parent metadata and the child's first real turn_context shares the UUID-v7 millisecond prefix with the child session_meta, this equal-prefix branch now only closes the replay skip if a task_started was observed. The parser already supports user fork logs that have forked_from_id/thread_source:"user" without any task_started, so in that same-ms case forked_child_waiting_for_turn_context never clears and the child's subsequent token_count rows are skipped, making the fork's own usage disappear.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — fixed in 212f13b. The task_started-only discriminator did break the same-millisecond user-fork case: thread_source:"user" forks never emit a task_started, so the equal-prefix branch never closed the skip and the child's own token_count rows were dropped.

A user fork's replayed parent turns carry the parent session's millisecond prefix, not the child's, so they sort strictly earlier and never reach the equal-prefix branch; reaching it already means the turn shares the child's fork millisecond and is the child's own turn. The fix tracks whether the active fork is a user fork (CodexParseState.forked_child_is_user_fork, set from thread_source) and, in the equal-prefix case, ends the skip for a user fork even without a task_started. Subagent forks still require the task_started discriminator, so the same-millisecond over-count guard from the previous commit is unchanged. Bumped the cache schema to 22 for the new state field.

Added test_user_forked_child_same_millisecond_own_turn_counts_without_task_started, which fails before the change (0 messages instead of 1). Full tokscale-core suite stays green (962) and clippy --all-targets is clean.

}
}
}
_ => true,
}
Expand Down Expand Up @@ -1894,6 +1939,75 @@ mod tests {
assert_eq!(child_messages[0].tokens.output, 2);
}

#[test]
fn test_forked_child_same_millisecond_turn_starts_own_session() {
// Regression: the child's own first turn starts in the SAME millisecond
// as its fork session_meta, so both UUID v7 ids share the 48-bit ms
// prefix (`019e5c03-1e99`) and differ only in the random tail
// (`…0001` vs `…00ff`). Comparing the full id makes the gate fall through
// to the coin-flip tail (here `0001 < 00ff`), so the replay-skip never
// ends and the child's own turn is dropped. Comparing only the ms prefix
// keeps the child's own turn.
let child = create_test_file(concat!(
r#"{"timestamp":"2026-05-05T21:52:10.000Z","type":"session_meta","payload":{"id":"019e5c03-1e99-7000-8000-0000000000ff","forked_from_id":"019e5b00-0000-7000-8000-000000000001","source":{"subagent":{"thread_spawn":{"parent_thread_id":"019e5b00-0000-7000-8000-000000000001","depth":1}}},"model_provider":"openai","agent_nickname":"worker","cwd":"/repo"}}"#,
"\n",
r#"{"timestamp":"2026-05-05T21:52:10.000Z","type":"session_meta","payload":{"id":"019e5b00-0000-7000-8000-000000000001","source":"vscode","model_provider":"openai","cwd":"/repo"}}"#,
"\n",
r#"{"timestamp":"2026-05-05T21:52:10.100Z","type":"turn_context","payload":{"turn_id":"019e5b00-0001-7000-8000-000000000001","model":"gpt-5.5","cwd":"/repo"}}"#,
"\n",
r#"{"timestamp":"2026-05-05T21:52:10.200Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":300,"output_tokens":30,"total_tokens":330},"last_token_usage":{"input_tokens":300,"output_tokens":30,"total_tokens":330}}}}"#,
"\n",
r#"{"timestamp":"2026-05-05T21:52:20.000Z","type":"event_msg","payload":{"type":"task_started","turn_id":"019e5c03-1e99-7000-8000-000000000001"}}"#,
"\n",
r#"{"timestamp":"2026-05-05T21:52:20.100Z","type":"turn_context","payload":{"turn_id":"019e5c03-1e99-7000-8000-000000000001","model":"gpt-5.5","cwd":"/repo"}}"#,
"\n",
r#"{"timestamp":"2026-05-05T21:52:20.200Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":320,"output_tokens":32,"total_tokens":352},"last_token_usage":{"input_tokens":20,"output_tokens":2,"total_tokens":22}}}}"#,
"\n"
));

let child_messages = parse_codex_file(child.path());

assert_eq!(child_messages.len(), 1);
assert_eq!(child_messages[0].tokens.input, 20);
assert_eq!(child_messages[0].tokens.output, 2);
}

#[test]
fn test_forked_child_same_millisecond_replayed_parent_turn_keeps_skipping() {
// A replayed parent `turn_context` can coincidentally share the child's
// fork millisecond (here both `019e5c03-1e99`) while NOT being preceded
// by a `task_started`. A millisecond-prefix-only gate would treat that
// equal-prefix turn as child-local, end the skip early, and count the
// inherited replayed row (500/50) as the child's own usage. The child's
// own turn is the later one announced by `task_started`; only it should
// end the skip, so only its 20/2 delta is counted.
let child = create_test_file(concat!(
r#"{"timestamp":"2026-05-05T21:52:10.000Z","type":"session_meta","payload":{"id":"019e5c03-1e99-7000-8000-0000000000ff","forked_from_id":"019e5b00-0000-7000-8000-000000000001","source":{"subagent":{"thread_spawn":{"parent_thread_id":"019e5b00-0000-7000-8000-000000000001","depth":1}}},"model_provider":"openai","agent_nickname":"worker","cwd":"/repo"}}"#,
"\n",
r#"{"timestamp":"2026-05-05T21:52:10.000Z","type":"session_meta","payload":{"id":"019e5b00-0000-7000-8000-000000000001","source":"vscode","model_provider":"openai","cwd":"/repo"}}"#,
"\n",
// replayed parent turn that shares the child's fork millisecond, with
// NO task_started — must NOT end the skip.
r#"{"timestamp":"2026-05-05T21:52:10.100Z","type":"turn_context","payload":{"turn_id":"019e5c03-1e99-7000-8000-000000000001","model":"gpt-5.5","cwd":"/repo"}}"#,
"\n",
r#"{"timestamp":"2026-05-05T21:52:10.200Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":500,"output_tokens":50,"total_tokens":550},"last_token_usage":{"input_tokens":500,"output_tokens":50,"total_tokens":550}}}}"#,
"\n",
// the child's real own turn, announced by task_started.
r#"{"timestamp":"2026-05-05T21:52:20.000Z","type":"event_msg","payload":{"type":"task_started","turn_id":"019e5c03-1e99-7000-8000-000000000002"}}"#,
"\n",
r#"{"timestamp":"2026-05-05T21:52:20.100Z","type":"turn_context","payload":{"turn_id":"019e5c03-1e99-7000-8000-000000000002","model":"gpt-5.5","cwd":"/repo"}}"#,
"\n",
r#"{"timestamp":"2026-05-05T21:52:20.200Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":520,"output_tokens":52,"total_tokens":572},"last_token_usage":{"input_tokens":20,"output_tokens":2,"total_tokens":22}}}}"#,
"\n"
));

let child_messages = parse_codex_file(child.path());

assert_eq!(child_messages.len(), 1);
assert_eq!(child_messages[0].tokens.input, 20);
assert_eq!(child_messages[0].tokens.output, 2);
}

#[test]
fn test_forked_child_incremental_state_skips_inherited_prefix() {
let file = create_test_file(concat!(
Expand Down