diff --git a/README.md b/README.md index d2059af..755884b 100644 --- a/README.md +++ b/README.md @@ -136,6 +136,13 @@ does not cancel the job automatically, so the example explicitly calls `job.cancel()`. `manager.shutdown()` disconnects without cancelling jobs. Callbacks support `log`, `status`, and `heartbeat` and are attached before execution. +Failure status messages start with `[ERROR]: `. If the worker can report the +failure, it includes up to the last 8 KiB of workload stderr under +`stderr (tail):` when stderr is available. Status callbacks receive the full +message, and the exception raised by `job.wait()` includes the failure detail +and stderr tail. If the worker dies before it can report, the manager can +report the failure from Slurm's job record. + `manager.listen("log", callback)` registers a callback for **all current and future jobs**, even when called before the first submission. Pass the returned IDs to `manager.unlisten(callback_ids)` to stop listening. Use `job.listen()` or pass diff --git a/slurm_manager/job_tracker.py b/slurm_manager/job_tracker.py index 10272b1..c23182f 100644 --- a/slurm_manager/job_tracker.py +++ b/slurm_manager/job_tracker.py @@ -191,12 +191,14 @@ class JobTracker: same cleanup path as an explicit error. """ info = message.status.split(":", 1) + if info[0] == "[ERROR]": + info[0] = JobStatus.ERROR.value try: status = JobStatus(info[0]) except ValueError: logger.warning("Received unknown job status '%s' for job %s", info[0], future.name) detail = f"Received unknown job status '{info[0]}' from message: {message.model_dump()}" - message = StatusMessage(status=f"error:{detail}", metadata=message.metadata.copy()) + message = StatusMessage(status=f"[ERROR]: {detail}", metadata=message.metadata.copy()) status = JobStatus.ERROR info = [status.value, detail] @@ -205,7 +207,7 @@ class JobTracker: return topic = TopicInfo(future._job_id).event callbacks = list(self._subscriptions_by_topic.get(topic, {}).values()) - exc_info = info[1] if len(info) > 1 else None + exc_info = info[1].lstrip(" ") if len(info) > 1 else None future._update_status(status, exc_info) # Queue notifications before cleanup or concurrent shutdown can discard them. # User code runs on the executor, never on this thread under the state lock. @@ -439,7 +441,7 @@ class JobTracker: if future is not None and not future.done() and not skip_event_callback: self.apply_status( StatusMessage( - status=f"error:Removal requested by user; timestamp {datetime.now().isoformat()}", + status=f"[ERROR]: Removal requested by user; timestamp {datetime.now().isoformat()}", metadata={ "msg_received": datetime.now().isoformat(), "job_id": future._job_id, diff --git a/slurm_manager/slurm_manager.py b/slurm_manager/slurm_manager.py index 7e55f7e..1251961 100644 --- a/slurm_manager/slurm_manager.py +++ b/slurm_manager/slurm_manager.py @@ -310,7 +310,7 @@ class SlurmManager(Generic[_JobOptionsT]): except (SlurmRestError, ValueError): logger.error("Could not cancel held job %s", slurm_job_id) self._job_tracker.apply_status( - StatusMessage(status=f"error:Submission setup failed: {exc}"), job_future + StatusMessage(status=f"[ERROR]: Submission setup failed: {exc}"), job_future ) raise with self._submitted_futures_lock: @@ -653,5 +653,5 @@ class SlurmManager(Generic[_JobOptionsT]): # A partial accounting record is not proof of failure. return else: - status = f"error:Slurm state {state}, exit code {exit_code}" + status = f"[ERROR]: Slurm state {state}, exit code {exit_code}" self._job_tracker.apply_status(StatusMessage(status=status), future) diff --git a/test/test_job_tracker.py b/test/test_job_tracker.py index 11f3314..7817e57 100644 --- a/test/test_job_tracker.py +++ b/test/test_job_tracker.py @@ -70,7 +70,15 @@ def test_scheduler_check_skips_a_job_removed_after_snapshot(tracker): assert tracker.begin_scheduler_check("unknown") is None -@pytest.mark.parametrize("status", ["finished", "cancelled", "error:workload failed", "unknown"]) +@pytest.mark.parametrize( + "status", + [ + "finished", + "cancelled", + "[ERROR]: workload exited with code 7\nstderr (tail):\nInput file not found\n", + "unknown", + ], +) def test_synthesized_terminal_status_notifies_listeners_once(tracker, status): future = JobFuture("first", manager=mock.Mock(spec=SlurmManager), slurm_job_id="123") tracker.track(future) @@ -89,8 +97,19 @@ def test_synthesized_terminal_status_notifies_listeners_once(tracker, status): assert len(received) == 1 assert received[0].metadata["job_id"] == "first" assert received[0].metadata["slurm_job_id"] == "123" - assert received[0].status == status or received[0].status.startswith("error:") + if status == "unknown": + assert received[0].status.startswith("[ERROR]: Received unknown job status 'unknown'") + else: + assert received[0].status == status assert future.done() + if status.startswith("[ERROR]: "): + with pytest.raises(Exception) as exc_info: + future.wait() + assert str(exc_info.value) == ( + "Job-123 failed with status error. Exception info: workload exited with code 7\n" + "stderr (tail):\n" + "Input file not found\n" + ) def test_redis_status_is_dispatched_once_and_shutdown_drains_it(tracker): @@ -118,7 +137,7 @@ def test_removing_tracking_reports_failure_to_status_listeners(tracker): tracker.shutdown(timeout=3) assert len(received) == 1 - assert received[0].status.startswith("error:Removal requested by user") + assert received[0].status.startswith("[ERROR]: Removal requested by user") assert tracker.get_future("first") is None assert tracker._sub_client.registered_topics == set() diff --git a/worker/internal/worker/worker.go b/worker/internal/worker/worker.go index 56c9757..d7de4d4 100644 --- a/worker/internal/worker/worker.go +++ b/worker/internal/worker/worker.go @@ -177,7 +177,10 @@ func Run(ctx context.Context, config Config, payload Payload, publisher Publishe }() stdout := &lineWriter{local: config.Stdout, stream: "stdout", publish: publish, onError: cancelWork} - stderr := &lineWriter{local: config.Stderr, stream: "stderr", publish: publish, onError: cancelWork} + stderr := &lineWriter{ + local: config.Stderr, stream: "stderr", publish: publish, onError: cancelWork, + tail: make([]byte, 0, 8*1024), + } shellArgs := []string{"-c", shellSetup, "bec-slurm-worker", activation} if config.RunCommand { shellArgs = append(shellArgs, "-c", payload.Script, "bec-slurm-worker") @@ -229,17 +232,26 @@ func Run(ctx context.Context, config Config, payload Payload, publisher Publishe if errors.As(runError, &exitError) && exitError.ExitCode() > 0 { code = exitError.ExitCode() } - status = fmt.Sprintf("error:workload exited with code %d", code) + status = fmt.Sprintf("[ERROR]: workload exited with code %d", code) } outputError := errors.Join(stdout.err, stderr.err) if outputError != nil { - code, status = 1, "error:Slurm output write failed" + code, status = 1, "[ERROR]: Slurm output write failed" } publishLock.Lock() failure := publishError publishLock.Unlock() if failure != nil { - code, status = 1, "error:Redis feedback failed" + code, status = 1, "[ERROR]: Redis feedback failed" + } + if strings.HasPrefix(status, "[ERROR]:") && len(stderr.tail) > 0 { + tail := stderr.tail + for len(tail) > 0 && !utf8.RuneStart(tail[0]) { + tail = tail[1:] + } + if len(tail) > 0 { + status += "\nstderr (tail):\n" + string(tail) + } } terminalError := publish("status", map[string]any{"status": status}) if failure != nil { @@ -301,6 +313,7 @@ type lineWriter struct { local io.Writer stream string buffer []byte + tail []byte // Optional bounded tail for failure status messages. publish func(string, map[string]any) error onError func() err error @@ -312,6 +325,12 @@ func (w *lineWriter) Write(data []byte) (int, error) { if w.err != nil { return 0, w.err } + if limit := cap(w.tail); limit > 0 { + recent := data[max(0, len(data)-limit):] + drop := max(0, len(w.tail)+len(recent)-limit) + w.tail = w.tail[:copy(w.tail, w.tail[drop:])] + w.tail = append(w.tail, recent...) + } written, err := w.local.Write(data) if err == nil && written != len(data) { err = io.ErrShortWrite diff --git a/worker/internal/worker/worker_test.go b/worker/internal/worker/worker_test.go index b8f46cd..67f6267 100644 --- a/worker/internal/worker/worker_test.go +++ b/worker/internal/worker/worker_test.go @@ -93,7 +93,7 @@ func TestScriptsOutputAndCleanup(t *testing.T) { if code == 0 && status != "finished" { t.Fatal(status) } - if code != 0 && !strings.HasPrefix(status, "error:") { + if code != 0 && !strings.HasPrefix(status, "[ERROR]:") { t.Fatal(status) } }) @@ -116,7 +116,7 @@ exit 7`, if code != 7 || err == nil || out.String() != "from activation" { t.Fatalf("exit=%d err=%v stdout=%q stderr=%q", code, err, out.String(), errout.String()) } - if status := lastStatus(t, publisher); !strings.HasPrefix(status, "error:") { + if status := lastStatus(t, publisher); !strings.HasPrefix(status, "[ERROR]:") { t.Fatalf("status=%q", status) } } @@ -187,10 +187,24 @@ func TestActivationFailureIsReported(t *testing.T) { if code != 9 || out.Len() != 0 { t.Fatalf("%d %s", code, out.String()) } - if lastStatus(t, p) != "error:workload exited with code 9" { + if lastStatus(t, p) != "[ERROR]: workload exited with code 9" { t.Fatal("wrong status") } } +func TestWorkloadFailureIncludesBoundedStderr(t *testing.T) { + var out, errout bytes.Buffer + p := &fakePublisher{} + code, _ := Run(context.Background(), config(&out, &errout), Payload{ + Script: "printf 'stdout only\\n'; printf 'old stderr\\n%9000s\\nlast error' '' >&2; exit 7\n", + }, p) + if code != 7 || !strings.HasPrefix(errout.String(), "old stderr\n") { + t.Fatalf("exit=%d or missing archived stderr", code) + } + want := "[ERROR]: workload exited with code 7\nstderr (tail):\n" + errout.String()[errout.Len()-8*1024:] + if lastStatus(t, p) != want { + t.Fatal("failure status did not include the last 8 KiB of stderr") + } +} func TestInitialRedisFailureDoesNotRunWorkload(t *testing.T) { marker := filepath.Join(t.TempDir(), "executed") var out, errout bytes.Buffer @@ -214,7 +228,7 @@ func TestLogFailureStopsWorkload(t *testing.T) { if time.Since(start) > 3*time.Second { t.Fatal("workload continued after feedback failed") } - if lastStatus(t, p) != "error:Redis feedback failed" { + if lastStatus(t, p) != "[ERROR]: Redis feedback failed" { t.Fatal("wrong status") } } @@ -339,7 +353,7 @@ func TestRedisFailureSkipsRemainingBufferedPublications(t *testing.T) { if attempts != 1 { t.Fatalf("made %d network publications after feedback failed", attempts) } - if lastStatus(t, &publisher.fakePublisher) != "error:Redis feedback failed" { + if lastStatus(t, &publisher.fakePublisher) != "[ERROR]: Redis feedback failed" { t.Fatal("missing terminal failure") } } @@ -364,7 +378,7 @@ func TestArchiveWriteFailuresFailTheJob(t *testing.T) { if code != 1 || !errors.Is(err, expected) { t.Fatalf("code=%d err=%v", code, err) } - if lastStatus(t, publisher) != "error:Slurm output write failed" { + if lastStatus(t, publisher) != "[ERROR]: Slurm output write failed" { t.Fatal("archive failure reported as success") } })