mirror of
https://github.com/pchuan98/codex.git
synced 2026-07-01 00:31:56 +08:00
7a3eec6fdb
## Why This continues the compile-time cleanup from #16630. `SessionTask` implementations are monomorphized, but `Session` stores the task behind a `dyn` boundary so it can drive and abort heterogenous turn tasks uniformly. That means we can move the `#[async_trait]` expansion off the implementation trait, keep a small boxed adapter only at the storage boundary, and preserve the existing task lifecycle semantics while reducing the amount of generated async-trait glue in `codex-core`. One measurement caveat showed up while exploring this: a warm incremental benchmark based on `touch core/src/tasks/mod.rs && cargo check -p codex-core --lib` was basically flat, but that was the wrong benchmark for this change. Using package-clean `codex-core` rebuilds, like #16630, shows the real win. Relevant pre-change code: - [`SessionTask` with `#[async_trait]`](https://github.com/openai/codex/blob/3c7f013f9735e67796c70d95f75f436b7f97e3ec/codex-rs/core/src/tasks/mod.rs#L129-L182) - [`RunningTask` storing `Arc<dyn SessionTask>`](https://github.com/openai/codex/blob/3c7f013f9735e67796c70d95f75f436b7f97e3ec/codex-rs/core/src/state/turn.rs#L69-L77) ## What changed - Switched `SessionTask::{run, abort}` to native RPITIT futures with explicit `Send` bounds. - Added a private `AnySessionTask` adapter that boxes those futures only at the `Arc<dyn ...>` storage boundary. - Updated `RunningTask` to store `Arc<dyn AnySessionTask>` and removed `#[async_trait]` from the concrete task impls plus test-only `SessionTask` impls. ## Timing Benchmarked package-clean `codex-core` rebuilds with dependencies left warm: ```shell cargo check -p codex-core --lib >/dev/null cargo clean -p codex-core >/dev/null /usr/bin/time -p cargo +nightly rustc -p codex-core --lib -- \ -Z time-passes \ -Z time-passes-format=json >/dev/null ``` | revision | rustc `total` | process `real` | `generate_crate_metadata` | `MIR_borrow_checking` | `monomorphization_collector_graph_walk` | | --- | ---: | ---: | ---: | ---: | ---: | | parent `3c7f013f9735` | 67.21s | 67.71s | 24.61s | 23.43s | 22.43s | | this PR `2cafd783ac22` | 35.08s | 35.60s | 8.01s | 7.25s | 7.15s | | delta | -47.8% | -47.4% | -67.5% | -69.1% | -68.1% | For completeness, the warm touched-file benchmark stayed flat (`1.96s` parent vs `1.97s` this PR), which is why that benchmark should not be used to evaluate this refactor. ## Verification - Ran `cargo test -p codex-core`; this change compiled and task-related tests passed before hitting the same unrelated 5 `config::tests::*guardian*` failures already present on the parent stack.
130 lines
4.1 KiB
Rust
130 lines
4.1 KiB
Rust
use std::sync::Arc;
|
|
|
|
use crate::codex::TurnContext;
|
|
use crate::state::TaskKind;
|
|
use crate::tasks::SessionTask;
|
|
use crate::tasks::SessionTaskContext;
|
|
use codex_git_utils::RestoreGhostCommitOptions;
|
|
use codex_git_utils::restore_ghost_commit_with_options;
|
|
use codex_protocol::models::ResponseItem;
|
|
use codex_protocol::protocol::EventMsg;
|
|
use codex_protocol::protocol::UndoCompletedEvent;
|
|
use codex_protocol::protocol::UndoStartedEvent;
|
|
use codex_protocol::user_input::UserInput;
|
|
use tokio_util::sync::CancellationToken;
|
|
use tracing::error;
|
|
use tracing::info;
|
|
use tracing::warn;
|
|
|
|
pub(crate) struct UndoTask;
|
|
|
|
impl UndoTask {
|
|
pub(crate) fn new() -> Self {
|
|
Self
|
|
}
|
|
}
|
|
|
|
impl SessionTask for UndoTask {
|
|
fn kind(&self) -> TaskKind {
|
|
TaskKind::Regular
|
|
}
|
|
|
|
fn span_name(&self) -> &'static str {
|
|
"session_task.undo"
|
|
}
|
|
|
|
async fn run(
|
|
self: Arc<Self>,
|
|
session: Arc<SessionTaskContext>,
|
|
ctx: Arc<TurnContext>,
|
|
_input: Vec<UserInput>,
|
|
cancellation_token: CancellationToken,
|
|
) -> Option<String> {
|
|
session
|
|
.session
|
|
.services
|
|
.session_telemetry
|
|
.counter("codex.task.undo", /*inc*/ 1, &[]);
|
|
let sess = session.clone_session();
|
|
sess.send_event(
|
|
ctx.as_ref(),
|
|
EventMsg::UndoStarted(UndoStartedEvent {
|
|
message: Some("Undo in progress...".to_string()),
|
|
}),
|
|
)
|
|
.await;
|
|
|
|
if cancellation_token.is_cancelled() {
|
|
sess.send_event(
|
|
ctx.as_ref(),
|
|
EventMsg::UndoCompleted(UndoCompletedEvent {
|
|
success: false,
|
|
message: Some("Undo cancelled.".to_string()),
|
|
}),
|
|
)
|
|
.await;
|
|
return None;
|
|
}
|
|
|
|
let history = sess.clone_history().await;
|
|
let mut items = history.raw_items().to_vec();
|
|
let mut completed = UndoCompletedEvent {
|
|
success: false,
|
|
message: None,
|
|
};
|
|
|
|
let Some((idx, ghost_commit)) =
|
|
items
|
|
.iter()
|
|
.enumerate()
|
|
.rev()
|
|
.find_map(|(idx, item)| match item {
|
|
ResponseItem::GhostSnapshot { ghost_commit } => {
|
|
Some((idx, ghost_commit.clone()))
|
|
}
|
|
_ => None,
|
|
})
|
|
else {
|
|
completed.message = Some("No ghost snapshot available to undo.".to_string());
|
|
sess.send_event(ctx.as_ref(), EventMsg::UndoCompleted(completed))
|
|
.await;
|
|
return None;
|
|
};
|
|
|
|
let commit_id = ghost_commit.id().to_string();
|
|
let repo_path = ctx.cwd.clone();
|
|
let ghost_snapshot = ctx.ghost_snapshot.clone();
|
|
let restore_result = tokio::task::spawn_blocking(move || {
|
|
let options = RestoreGhostCommitOptions::new(&repo_path).ghost_snapshot(ghost_snapshot);
|
|
restore_ghost_commit_with_options(&options, &ghost_commit)
|
|
})
|
|
.await;
|
|
|
|
match restore_result {
|
|
Ok(Ok(())) => {
|
|
items.remove(idx);
|
|
let reference_context_item = sess.reference_context_item().await;
|
|
sess.replace_history(items, reference_context_item).await;
|
|
let short_id: String = commit_id.chars().take(7).collect();
|
|
info!(commit_id = commit_id, "Undo restored ghost snapshot");
|
|
completed.success = true;
|
|
completed.message = Some(format!("Undo restored snapshot {short_id}."));
|
|
}
|
|
Ok(Err(err)) => {
|
|
let message = format!("Failed to restore snapshot {commit_id}: {err}");
|
|
warn!("{message}");
|
|
completed.message = Some(message);
|
|
}
|
|
Err(err) => {
|
|
let message = format!("Failed to restore snapshot {commit_id}: {err}");
|
|
error!("{message}");
|
|
completed.message = Some(message);
|
|
}
|
|
}
|
|
|
|
sess.send_event(ctx.as_ref(), EventMsg::UndoCompleted(completed))
|
|
.await;
|
|
None
|
|
}
|
|
}
|