Skip to main content

magi/
chat_worker.rs

1//! Independent conversation execution, publication fencing and restart recovery.
2//!
3//! These workers belong to persisted conversations. They retain their executable,
4//! turn lease and submission reservation across web and scheduler restarts.
5use crate::{
6    config::Config,
7    talk::{self, Talk, Talks},
8};
9use anyhow::{Context, Result, bail};
10
11/// Run the talk's turns under `lease` until no draft is owed.
12///
13/// Other starters that found the lease held queued drafts and left them to
14/// us, so drain until nothing is left (as the web's drain loop does). A failed
15/// turn is kept and reported at the end, not returned at once: drafts accepted
16/// meanwhile are still owed an answer.
17pub async fn drain_turns(
18    talks: &Talks,
19    talk_id: &str,
20    mut lease: talk::TurnLease,
21    cfg: &Config,
22) -> Result<()> {
23    let mut talk = talks.get(talk_id)?;
24    let mut failed = None;
25    loop {
26        while let Some(text) = talk::drain(&mut talk, talks)? {
27            if let Err(e) = talk::respond(&lease, &mut talk, talks, cfg, &text).await {
28                failed.get_or_insert(e);
29            }
30            if !lease.beat()? {
31                bail!("the turn lease for chat {} was lost", talk.short());
32            }
33        }
34        // A draft queued after the last drain, before the lease is gone, was
35        // left to us by a starter that found the lease held. Release first,
36        // then look again: whoever queues later either sees no lease (and
37        // starts its own turn) or is seen by this re-check.
38        drop(lease);
39        talk = talks.get(&talk.id)?;
40        let owed = talk.status.open()
41            && (!talk.pending.is_empty() || !talk.pending_attachments.is_empty());
42        if !owed {
43            break;
44        }
45        // Somebody else took the lease meanwhile: they drain it.
46        let Some(again) = talks.claim_turn(&talk.id)? else {
47            break;
48        };
49        lease = again;
50    }
51    if let Some(e) = failed {
52        return Err(e);
53    }
54    Ok(())
55}
56
57/// Try the short cross-process draft-publication fence for one talk.
58pub fn try_publication_guard(talks: &Talks, talk_id: &str) -> Result<Option<crate::worker::Lease>> {
59    crate::worker::try_lease(talks.home(), &format!("chat-publication:{talk_id}"))
60}
61
62/// Serialize queue/record -> worker acknowledgement against a drainer's
63/// generation scan + promotion. Never hold this fence across an agent call.
64///
65/// Lock order deliberately differs: a drainer owns TurnLease then waits here;
66/// ingress owns publication but only *tries* TurnLease and queues when busy.
67/// Ingress must never wait for TurnLease while holding publication.
68pub async fn publication_guard(talks: &Talks, talk_id: &str) -> Result<crate::worker::Lease> {
69    loop {
70        if let Some(guard) = try_publication_guard(talks, talk_id)? {
71            return Ok(guard);
72        }
73        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
74    }
75}
76
77/// Reserve and launch a detached drainer for an explicitly submitted draft.
78///
79/// Every submission has its own durable reservation. A shared key would lose
80/// arrivals between the previous drainer's last read and its job settlement.
81/// The talk's existing turn lease, not the job key, serializes CLI sessions.
82pub async fn spawn_turn(talks: &Talks, talk_id: &str) -> Result<crate::worker::Job> {
83    spawn_turn_with_source(talks, talk_id, false, None).await
84}
85
86/// Continue an operator turn already persisted by the HTTP admission path.
87/// Reserve this job before releasing the caller's turn lease.
88pub async fn spawn_recorded_turn(
89    talks: &Talks,
90    talk_id: &str,
91    turn: usize,
92) -> Result<crate::worker::Job> {
93    spawn_turn_with_source(talks, talk_id, false, Some(turn)).await
94}
95
96pub(crate) async fn spawn_notice_turn(talks: &Talks, talk_id: &str) -> Result<crate::worker::Job> {
97    spawn_turn_with_source(talks, talk_id, true, None).await
98}
99
100async fn spawn_turn_with_source(
101    talks: &Talks,
102    talk_id: &str,
103    automatic: bool,
104    recorded_turn: Option<usize>,
105) -> Result<crate::worker::Job> {
106    let talk = talks.get(talk_id)?;
107    let recorded = recorded_turn
108        .map(|index| {
109            talk.turns
110                .get(index)
111                .context("recorded chat admission disappeared")
112        })
113        .transpose()?;
114    let key = format!(
115        "chat:{}:{}",
116        talk.id,
117        crate::rng::SplitMix64::new(crate::rng::entropy()).uuid_v4()
118    );
119    let result = crate::worker::spawn(
120        talks.home(),
121        "chat",
122        &key,
123        serde_json::json!({
124            "talk": &talk.id, "automatic": automatic, "recorded_turn": recorded_turn,
125        }),
126    )
127    .await;
128    match result {
129        Err(error) if recorded.is_some() && crate::worker::not_started(&error) => {
130            let index = recorded_turn.expect("recorded snapshot");
131            match talk::restore_recorded_draft(
132                talks, &talk.id, index, recorded.expect("recorded snapshot"),
133            ) {
134                Ok(true) => Err(error.context(
135                    "the agent never started; your send is saved as a draft — use Resume draft",
136                )),
137                Ok(false) => Err(error.context(
138                    "the agent never started, but the transcript changed before draft restoration; the recorded send was retained",
139                )),
140                Err(restore) => Err(error.context(format!(
141                    "the agent never started and its recorded send was retained; draft restoration failed: {restore:#}",
142                ))),
143            }
144        }
145        other => other,
146    }
147}
148
149/// Includes startup reservations, before the child acquires the turn lease.
150pub fn turn_worker_active(talks: &Talks, talk_id: &str) -> bool {
151    match crate::worker::active(talks.home()) {
152        Ok(jobs) => jobs.iter().any(|job| {
153            job.kind == "chat"
154                && job
155                    .payload
156                    .get("talk")
157                    .and_then(serde_json::Value::as_str)
158                    .is_none_or(|id| id == talk_id)
159        }),
160        // An unreadable reservation is not evidence that a previous worker
161        // stopped. Hold admission until its ownership can be inspected.
162        Err(error) => {
163            tracing::warn!("cannot inspect chat workers: {error:#}");
164            true
165        }
166    }
167}
168
169/// Task-authored transcript posts do not answer a submitted owner turn.
170fn recorded_answered(talk: &Talk, index: usize) -> bool {
171    index
172        .checked_add(1)
173        .and_then(|next| talk.turns.get(next..))
174        .is_some_and(|turns| {
175            turns.iter().enumerate().any(|(offset, turn)| {
176                turn.who == talk::Who::Agent
177                    && turn.posted_by.is_none()
178                    && !talk
179                        .standing_actions
180                        .iter()
181                        .any(|audit| audit.turn == index + 1 + offset)
182            })
183        })
184}
185
186/// Hidden worker entry point. The original talk/session and cross-process
187/// lease stay authoritative even when an older worker is still responding.
188pub async fn run_turn_worker(home: &std::path::Path, payload: serde_json::Value) -> Result<()> {
189    let id = payload
190        .get("talk")
191        .and_then(serde_json::Value::as_str)
192        .context("chat worker has no talk id")?;
193    let automatic = payload
194        .get("automatic")
195        .and_then(serde_json::Value::as_bool)
196        .unwrap_or(false);
197    let recorded_turn = payload
198        .get("recorded_turn")
199        .and_then(serde_json::Value::as_u64)
200        .map(usize::try_from)
201        .transpose()?;
202    let talks = Talks::at(home.join("talks"));
203    if let Some(wake) = payload.get("goal_wake") {
204        let goal = wake
205            .get("id")
206            .and_then(serde_json::Value::as_str)
207            .context("goal wake has no goal id")?;
208        let generation = wake
209            .get("generation")
210            .and_then(serde_json::Value::as_u64)
211            .context("goal wake has no generation")?;
212        return crate::chat_goal_runtime::run_wake(&talks, id, goal, generation).await;
213    }
214    if let Some(request) = payload
215        .get("external_request")
216        .and_then(serde_json::Value::as_str)
217    {
218        return talk::external::run_worker(&talks, id, request).await;
219    }
220    let current = crate::worker::current_job(home)?;
221    loop {
222        let talk = talks.get(id)?;
223        if !talk.status.open()
224            || (recorded_turn.is_none()
225                && talk.pending.is_empty()
226                && talk.pending_attachments.is_empty())
227        {
228            return Ok(());
229        }
230        if automatic && !crate::chat_notify::pending_is_only_notices(&talk) {
231            return Ok(());
232        }
233        if let Some(lease) = talks.claim_turn(id)? {
234            let publication = publication_guard(&talks, id).await?;
235            // Reload the draft after ownership is acquired: a notice must not
236            // turn an unsent operator draft into an automatic submission.
237            if automatic && !crate::chat_notify::pending_is_only_notices(&talks.get(id)?) {
238                return Ok(());
239            }
240            let mut fresh = talks.get(id)?;
241            let active = crate::worker::active(home)?;
242            if recorded_turn.is_none() && current.as_ref().is_some_and(|current| {
243                active.iter().any(|job| {
244                    job.kind == "chat" && job.id != current.id
245                        && job.generation != current.generation
246                        && job.payload.get("talk").and_then(serde_json::Value::as_str) == Some(id)
247                        && job.payload.get("recorded_turn").and_then(serde_json::Value::as_u64).is_none()
248                        && (!job.payload.get("automatic").and_then(serde_json::Value::as_bool).unwrap_or(false)
249                            || crate::chat_notify::pending_is_only_notices(&fresh))
250                        // Sequence zero belongs to pre-ordering records. In
251                        // that case relinquish rather than infer from time.
252                        && job.sequence > 0
253                        && (current.sequence == 0 || job.sequence > current.sequence)
254                })
255            }) {
256                return Ok(());
257            }
258            if recorded_turn.is_none()
259                && active.iter().any(|job| {
260                    if job.kind != "chat"
261                        || job.payload.get("talk").and_then(serde_json::Value::as_str) != Some(id)
262                    {
263                        return false;
264                    }
265                    if let Some(request) = job
266                        .payload
267                        .get("external_request")
268                        .and_then(serde_json::Value::as_str)
269                    {
270                        return fresh.external_requests.iter().any(|record| {
271                            record.request == request
272                                && matches!(record.status.as_str(), "accepted" | "started")
273                        });
274                    }
275                    let Some(index) = job
276                        .payload
277                        .get("recorded_turn")
278                        .and_then(serde_json::Value::as_u64)
279                        .and_then(|index| usize::try_from(index).ok())
280                    else {
281                        return false;
282                    };
283                    fresh
284                        .turns
285                        .get(index)
286                        .is_some_and(|turn| turn.who == talk::Who::Operator)
287                        && !recorded_answered(&fresh, index)
288                })
289            {
290                // Submitted input is already in the transcript, but its
291                // owner or external worker may not have acquired the lease.
292                // Queued follow-ups must not overtake either during startup.
293                drop(publication);
294                drop(lease);
295                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
296                continue;
297            }
298            let (cfg, _) = Config::discover(&fresh.repo, None)?;
299            let text = if let Some(index) = recorded_turn {
300                let turn = fresh
301                    .turns
302                    .get(index)
303                    .context("recorded chat turn disappeared")?;
304                anyhow::ensure!(
305                    turn.who == talk::Who::Operator,
306                    "recorded turn is not operator input"
307                );
308                if recorded_answered(&fresh, index) {
309                    return Ok(());
310                }
311                turn.body.clone()
312            } else {
313                let Some(text) = talk::drain(&mut fresh, &talks)? else {
314                    return Ok(());
315                };
316                text
317            };
318            drop(publication);
319            // Exactly one invocation per job. A submission accepted by the
320            // successor UI already owns a successor-generation reservation;
321            // never pull it into this old worker after the current reply.
322            if automatic && cfg.talk.standing_authorization {
323                return crate::chat_goal::with_source(
324                    crate::chat_goal::Source::Automatic,
325                    talk::respond(&lease, &mut fresh, &talks, &cfg, &text),
326                )
327                .await;
328            }
329            return talk::respond(&lease, &mut fresh, &talks, &cfg, &text).await;
330        }
331        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
332    }
333}
334
335#[cfg(test)]
336mod tests {
337    use super::*;
338    use crate::config::{AgentKind, AgentSpec};
339    use std::collections::BTreeMap;
340
341    #[test]
342    fn unreadable_worker_ownership_never_looks_idle() {
343        let (_home, talks, talk) = talks();
344        std::fs::write(talks.home().join("workers"), "not a directory")
345            .expect("make reservation inspection fail");
346        assert!(crate::worker::active(talks.home()).is_err());
347        assert!(turn_worker_active(&talks, &talk.id));
348    }
349
350    #[test]
351    fn a_task_post_does_not_answer_an_admitted_owner_send() {
352        let (_home, talks, mut talk) = talks();
353        talk::record(&mut talk, &talks, "owner send", Vec::new()).expect("owner turn");
354        let index = talk.turns.len() - 1;
355        talk::post(&talks, &talk.id, "unrelated task report", "task-seat").expect("task post");
356        let mut fresh = talks.get(&talk.id).expect("persisted transcript");
357        assert!(!recorded_answered(&fresh, index));
358        let mut response = fresh.turns.last().expect("post").clone();
359        response.posted_by = None;
360        response.body = "actual persona response".to_owned();
361        fresh.turns.push(response);
362        assert!(recorded_answered(&fresh, index));
363    }
364
365    #[tokio::test]
366    async fn publication_waiting_drainer_does_not_block_busy_queue_admission() {
367        let (_home, talks, mut talk) = talks();
368        let ingress = publication_guard(&talks, &talk.id)
369            .await
370            .expect("ingress publication");
371        let turn = talks
372            .claim_turn(&talk.id)
373            .expect("turn claim")
374            .expect("drainer turn");
375        let id = talk.id.clone();
376        let waiting = publication_guard(&talks, &id);
377        tokio::pin!(waiting);
378        std::future::poll_fn(|cx| {
379            assert!(
380                waiting.as_mut().poll(cx).is_pending(),
381                "worker waits for publication"
382            );
383            std::task::Poll::Ready(())
384        })
385        .await;
386        assert!(
387            talks
388                .claim_turn(&talk.id)
389                .expect("nonblocking ingress claim")
390                .is_none()
391        );
392        talk::queue(&mut talk, &talks, "accepted while busy", Vec::new())
393            .expect("queue without owning turn");
394        assert_eq!(
395            talks.get(&talk.id).expect("durable pending").pending,
396            "accepted while busy"
397        );
398        drop(ingress);
399        let publication = tokio::time::timeout(std::time::Duration::from_secs(5), waiting)
400            .await
401            .expect("publication fence released")
402            .expect("drainer publication");
403        assert_eq!(
404            talk::drain(&mut talk, &talks).expect("drain").as_deref(),
405            Some("accepted while busy")
406        );
407        drop(publication);
408        assert!(
409            try_publication_guard(&talks, &talk.id)
410                .expect("released fence")
411                .is_some()
412        );
413        drop(turn);
414    }
415
416    #[tokio::test]
417    async fn queued_owner_worker_releases_the_turn_until_external_input_is_answered() {
418        for status in ["accepted", "started"] {
419            let (_home, talks, mut talk) = talks();
420            talk::record(&mut talk, &talks, "external input", Vec::new()).expect("input");
421            talk.turns[0].sender = Some(talk::Sender::External);
422            talk.turns[0].messages.clear();
423            talk.external_requests.push(talk::external::Request {
424                request: "external-first".to_owned(),
425                sender: "external-fixture".to_owned(),
426                text: "external input".to_owned(),
427                input_turn: 0,
428                reply_turn: None,
429                status: status.to_owned(),
430                worker: None,
431                error: None,
432            });
433            talks.put(&mut talk).expect("admitted external input");
434            talk::post(&talks, &talk.id, "unrelated task post", "task-seat").expect("post");
435            talk::queue(&mut talk, &talks, "later owner input", Vec::new()).expect("queue");
436
437            let reserve = |id: &str, payload: serde_json::Value| {
438                let dir = talks.home().join("workers/jobs").join(id);
439                std::fs::create_dir_all(&dir).expect("reservation directory");
440                let lease = crate::worker::execution_lease_for_test(&dir.join("live.lock"));
441                let job = crate::worker::Job {
442                    id: id.to_owned(),
443                    sequence: 1,
444                    kind: "chat".to_owned(),
445                    key: id.to_owned(),
446                    payload,
447                    generation: "fixture-generation".to_owned(),
448                    version: None,
449                    status: crate::worker::Status::Running,
450                    result: None,
451                    pid: None,
452                    created_at: 0,
453                    finished_at: None,
454                };
455                std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).expect("job"))
456                    .expect("persist reservation");
457                lease
458            };
459            // Keep test-host worker identity local if verification inherited it.
460            // No environment mutation or access to the operator's worker store.
461            let _current = std::env::var("MAGI_WORKER_ID")
462                .ok()
463                .map(|id| reserve(&id, serde_json::json!({"talk": talk.id})));
464            let external_id = crate::rng::SplitMix64::new(crate::rng::entropy()).uuid_v4();
465            let _external = reserve(
466                &external_id,
467                serde_json::json!({"talk": talk.id, "external_request": "external-first"}),
468            );
469
470            // If the ordering fence regresses, fail before any backend can run.
471            std::fs::write(talk.repo.join("magi.toml"), "invalid = [")
472                .expect("invalid owner config");
473
474            // The owner worker wins TurnLease while the external worker has
475            // not acquired it yet. Poll the real drainer through that boundary.
476            let work = run_turn_worker(talks.home(), serde_json::json!({"talk": talk.id}));
477            tokio::pin!(work);
478            std::future::poll_fn(|cx| {
479                assert!(
480                    work.as_mut().poll(cx).is_pending(),
481                    "queued owner must wait"
482                );
483                std::task::Poll::Ready(())
484            })
485            .await;
486            let fresh = talks.get(&talk.id).expect("retained input");
487            assert_eq!(fresh.pending, "later owner input");
488            assert_eq!(
489                fresh.turns.len(),
490                2,
491                "no owner turn or response was appended"
492            );
493            assert!(
494                talks.claim_turn(&talk.id).expect("turn claim").is_some(),
495                "waiting owner worker must yield the lease to the external worker"
496            );
497            assert!(
498                try_publication_guard(&talks, &talk.id)
499                    .expect("publication claim")
500                    .is_some(),
501                "waiting owner worker must also yield publication"
502            );
503            let mut fresh = fresh;
504            let mut response = fresh.turns[1].clone();
505            response.sender = Some(talk::Sender::Persona);
506            response.posted_by = None;
507            response.body = "external response".to_owned();
508            fresh.external_requests[0].reply_turn = Some(fresh.turns.len());
509            fresh.external_requests[0].status = "replied".to_owned();
510            fresh.turns.push(response);
511            talks.put(&mut fresh).expect("external completion");
512            tokio::time::timeout(std::time::Duration::from_secs(5), work.as_mut())
513                .await
514                .expect("owner worker proceeds after the external reply")
515                .expect_err("invalid config stops execution before invoking any backend");
516        }
517    }
518
519    #[tokio::test]
520    async fn a_pinning_failure_restores_the_recorded_send_for_manual_resume() {
521        let (_home, talks, mut talk) = talks();
522        let _publication = publication_guard(&talks, &talk.id)
523            .await
524            .expect("publication");
525        let _turn = talks
526            .claim_turn(&talk.id)
527            .expect("turn")
528            .expect("free turn");
529        talk::record(&mut talk, &talks, "keep this accepted send", Vec::new()).expect("record");
530        let workers = talks.home().join("workers");
531        std::fs::create_dir_all(&workers).expect("worker directory");
532        std::fs::write(workers.join("generations"), "block executable publication")
533            .expect("controlled pre-reservation failure");
534        let error = spawn_recorded_turn(&talks, &talk.id, talk.turns.len() - 1)
535            .await
536            .expect_err("pinning must fail");
537        assert!(crate::worker::not_started(&error));
538        assert!(error.to_string().contains("saved as a draft"));
539        let mut recovered = talks.get(&talk.id).expect("recovered draft");
540        assert!(
541            recovered.turns.is_empty(),
542            "no unanswered transcript orphan"
543        );
544        assert_eq!(recovered.pending, "keep this accepted send");
545        assert!(
546            crate::chat_notify::talks_to_start(&talks).is_empty(),
547            "recovery does not become an automatic retry"
548        );
549        assert_eq!(
550            talk::drain(&mut recovered, &talks)
551                .expect("manual resume")
552                .as_deref(),
553            Some("keep this accepted send")
554        );
555    }
556
557    #[test]
558    fn restoring_an_unstarted_send_retains_reply_attachments_and_later_drafts() {
559        let (_home, talks, mut talk) = talks();
560        talk::post(&talks, &talk.id, "original reply source", "source-task").expect("source");
561        let attachment = talk::Attachment {
562            id: "image".to_owned(),
563            name: "photo.png".to_owned(),
564            mime: "image/png".to_owned(),
565            bytes: 12,
566        };
567        talk::record_reply(
568            &mut talk,
569            &talks,
570            "  preserve formatting\n\nowner send",
571            vec![attachment.clone()],
572            Some(talk::ReplyTarget {
573                turn: 0,
574                message: 0,
575            }),
576        )
577        .expect("record reply");
578        let index = talk.turns.len() - 1;
579        let recorded = talk.turns[index].clone();
580        talk::post(&talks, &talk.id, "unrelated concurrent post", "later-task").expect("post");
581        talk::queue(&mut talk, &talks, "later draft", Vec::new()).expect("later draft");
582        assert!(talk::restore_recorded_draft(&talks, &talk.id, index, &recorded).expect("restore"));
583        let mut recovered = talks.get(&talk.id).expect("recovered");
584        assert_eq!(recovered.turns.len(), 2, "task posts are retained");
585        assert_eq!(recovered.pending_messages[0], recorded.messages[0]);
586        assert_eq!(recovered.pending_messages[1].body, "later draft");
587        assert_eq!(recovered.pending_attachments, vec![attachment]);
588        assert_eq!(
589            recovered.pending,
590            "  preserve formatting\n\nowner send\n\nlater draft"
591        );
592        assert!(
593            !talk::restore_recorded_draft(&talks, &talk.id, index, &recorded).expect("idempotent")
594        );
595        talk::drain(&mut recovered, &talks)
596            .expect("manual resume")
597            .expect("draft");
598        assert_eq!(
599            recovered.turns.last().expect("resumed").messages[0],
600            recorded.messages[0]
601        );
602    }
603
604    #[test]
605    fn a_started_response_is_never_rolled_back_into_a_draft() {
606        let (_home, talks, mut talk) = talks();
607        talk::record(&mut talk, &talks, "owner send", Vec::new()).expect("record");
608        let recorded = talk.turns[0].clone();
609        let mut response = recorded.clone();
610        response.who = talk::Who::Agent;
611        response.sender = None;
612        response.body = "already answered".to_owned();
613        talk.turns.push(response);
614        talks.put(&mut talk).expect("response");
615        assert!(
616            !talk::restore_recorded_draft(&talks, &talk.id, 0, &recorded).expect("refuse rollback")
617        );
618        let fresh = talks.get(&talk.id).expect("unchanged");
619        assert_eq!(fresh.turns.len(), 2);
620        assert!(fresh.pending.is_empty());
621    }
622
623    fn talks() -> (tempfile::TempDir, Talks, Talk) {
624        let tmp = tempfile::tempdir().expect("tempdir");
625        let store = Talks::at(tmp.path().join("talks"));
626        let cfg = Config {
627            agents: vec![AgentSpec {
628                id: "mock".to_owned(),
629                kind: AgentKind::Command,
630                model: None,
631                command: vec!["true".to_owned()],
632                extra_args: Vec::new(),
633                env: BTreeMap::new(),
634                prompt_delivery: None,
635                max_turn_secs: None,
636            }],
637            ..Config::default()
638        };
639        let talk = talk::begin(&store, &cfg, tmp.path().to_path_buf(), Some("mock")).expect("talk");
640        (tmp, store, talk)
641    }
642}