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