carlos / platform Public

activator: exec tee's journal copy takes the lossy journal queue

teeStd wrote the journal copy of an exec child's stdout and stderr
synchronously to the agent's own streams, so a stalled journald blocked
the child's output drain and its Wait. Each stream is now an execTee:
the tenant sink's line writer exactly as before, and the journal copy,
cut into lines, through the agent's bounded, lossy journal queue that
the gVisor log listener has used since F9, held to the same per-source
journal line cap. ReadFrom gives the tee its stream's end, so the last
journal line is flushed and the cap's drop count reported then.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 55ec7490f7507f5c488953f8276d5135362011d2 parent 4799995
3 files changed, +309 −8
  • internal/activator/backend_exec.go +13 −8
  • internal/activator/exectee.go +99 −0
  • internal/activator/exectee_test.go +197 −0
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index 27baefe08..9a38476c0 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -213,9 +213,10 @@ type ExecBackend struct {
// falls back to Tier (tests, and every flag-off spawn).
TierOf func(rt registry.Route, version string) cgroup.Limit
// Logs, when non-nil, gets each instance and seed child's stdout/stderr
- // teed in line-wise for `carlos logs` (spec §5) — journald keeps every
- // byte it got before. Nil (tests, a box without the shipping loop)
- // spawns exactly as before: fd passthrough, no pipes.
+ // teed in line-wise for `carlos logs` (spec §5). journald gets the
+ // same lines through the agent's journal queue, bounded and lossy, as
+ // the log listeners' (teeStd). Nil (tests, a box without the shipping
+ // loop) spawns exactly as before: fd passthrough, no pipes.
Logs EventSink
// Timers, when non-nil, mounts the scheduled-work verbs on each spawned
// instance's control socket so an app can set and clear its own one-shot
@@ -589,9 +590,12 @@ const execLogLineMax = 8 << 10
// long as some stray grandchild lived, and Stop would hang on p.done.
var execDrainGrace = 5 * time.Second
-// teeStd wires cmd's stdout/stderr: straight to the agent's own streams
-// (journald under systemd) exactly as before, PLUS — only when b.Logs is
-// set — a line-splitting tee into the log sink tagged as rt's app output.
+// teeStd wires cmd's stdout/stderr. With b.Logs unset, straight to the
+// agent's own streams (journald under systemd), the fds passed through.
+// With it set, each stream is an execTee: a line-splitting tee into the
+// log sink tagged as rt's app output, as before, and the journal copy
+// through the agent's bounded, lossy journal queue, so a stalled journald
+// never blocks the child's drain (gvisor follow-ups).
func (b *ExecBackend) teeStd(cmd *exec.Cmd, rt registry.Route) {
if b.Logs == nil {
cmd.Stdout = os.Stdout
@@ -600,8 +604,9 @@ func (b *ExecBackend) teeStd(cmd *exec.Cmd, rt registry.Route) {
}
acct, app := release.RouteAccount(rt), rt.App
emit := func(line string) { b.Logs.App(acct, app, rt.Host, line) }
- cmd.Stdout = io.MultiWriter(os.Stdout, applog.NewLineWriter(execLogLineMax, emit))
- cmd.Stderr = io.MultiWriter(os.Stderr, applog.NewLineWriter(execLogLineMax, emit))
+ child := newExecJournalCopy(rt.Host)
+ cmd.Stdout = newExecTee(child, emit)
+ cmd.Stderr = newExecTee(child, emit)
cmd.WaitDelay = execDrainGrace
}
diff --git a/internal/activator/exectee.go b/internal/activator/exectee.go
new file mode 100644
index 000000000..6b94fa543
--- /dev/null
+++ b/internal/activator/exectee.go
@@ -0,0 +1,99 @@
+package activator
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "time"
+
+ "github.com/carlosframework/platform/internal/applog"
+)
+
+// execTee is one stream, stdout or stderr, of an exec child whose output
+// is teed (teeStd with Logs set). Every byte goes to the tenant's line
+// writer, exactly as before. The journal copy no longer writes the
+// agent's stdout itself: it goes, cut into lines, through the agent's
+// journal queue (logJournal), the bounded and lossy path the gVisor log
+// listener takes since F9 (gvisor follow-ups). A stalled journald
+// therefore holds up neither this child's drain nor its Wait, nor any
+// other child's output.
+//
+// Write never fails and never waits on the journal, so os/exec's copy
+// keeps the child's pipe drained. os/exec copies through io.Copy, which
+// calls ReadFrom when the destination has one: that is how the tee
+// learns its stream has ended, and only then is the journal copy's last
+// line flushed and the child's dropped count reported.
+type execTee struct {
+ tenant *applog.LineWriter
+ journal *applog.LineWriter
+ child *execJournalCopy
+}
+
+func (t *execTee) Write(p []byte) (int, error) {
+ _, _ = t.journal.Write(p)
+ _, _ = t.tenant.Write(p)
+ return len(p), nil
+}
+
+// ReadFrom copies r into the tee until it ends, then closes the journal
+// copy's stream. It returns r's error, if not EOF.
+func (t *execTee) ReadFrom(r io.Reader) (n int64, err error) {
+ defer t.end()
+ buf := make([]byte, 32<<10)
+ for {
+ m, rerr := r.Read(buf)
+ if m > 0 {
+ t.Write(buf[:m])
+ n += int64(m)
+ }
+ if rerr != nil {
+ if errors.Is(rerr, io.EOF) {
+ return n, nil
+ }
+ return n, rerr
+ }
+ }
+}
+
+// end flushes the journal copy's last line and reports what the child's
+// journal line cap dropped so far. The tenant's writer keeps its tail, as
+// it always has.
+func (t *execTee) end() {
+ t.journal.Close()
+ if n := t.child.cap.flush(); n > 0 {
+ t.child.report(n)
+ }
+}
+
+// execJournalCopy is one exec child's lines into the agent's journal,
+// shared by its two streams and held to one line cap, as one log
+// listener's are (logListener.journalLine): a flooding child cannot take
+// the agent's whole journal budget from the others.
+type execJournalCopy struct {
+ journal *logJournal
+ label string
+ cap lineCap
+}
+
+func newExecJournalCopy(label string) *execJournalCopy {
+ return &execJournalCopy{journal: agentJournal(), label: label, cap: newLineCap(logJournalLinesPerMin, logJournalLineBurst, time.Now)}
+}
+
+func (c *execJournalCopy) line(line string) {
+ ok, report := c.cap.admit(len(line) + 1)
+ if report > 0 {
+ c.report(report)
+ }
+ if ok {
+ c.journal.putLine(line)
+ }
+}
+
+// report is the agent-only line logListener.reportJournal writes.
+func (c *execJournalCopy) report(n int64) {
+ c.journal.putNotice(fmt.Sprintf("%s: dropped %d byte(s) of app output (journal line cap)", c.label, n))
+}
+
+func newExecTee(child *execJournalCopy, emit func(string)) *execTee {
+ return &execTee{tenant: applog.NewLineWriter(execLogLineMax, emit), journal: applog.NewLineWriter(execLogLineMax, child.line), child: child}
+}
diff --git a/internal/activator/exectee_test.go b/internal/activator/exectee_test.go
new file mode 100644
index 000000000..8b45961fd
--- /dev/null
+++ b/internal/activator/exectee_test.go
@@ -0,0 +1,197 @@
+package activator
+
+import (
+ "bufio"
+ "io"
+ "os"
+ "os/exec"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+// teeSink is an EventSink that several tee goroutines may call at once.
+type teeSink struct {
+ mu sync.Mutex
+ lines map[string][]string // host -> app lines
+ events []string
+}
+
+func (s *teeSink) App(acct, app, host, line string) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.lines == nil {
+ s.lines = map[string][]string{}
+ }
+ s.lines[host] = append(s.lines[host], line)
+}
+
+func (s *teeSink) Event(acct, app, host, level, msg string) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.events = append(s.events, host+": "+msg)
+}
+
+func (s *teeSink) of(host string) []string {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return append([]string(nil), s.lines[host]...)
+}
+
+// execTeeFloodLines is the flood child's stdout: three bursts of the
+// journal queue's bound, in 1 KiB lines.
+const execTeeFloodLines = 3 * logJournalMax / 1024
+
+// TestExecTeeChild is the exec children of the tee tests, run from this
+// test binary; it does nothing in a normal run.
+func TestExecTeeChild(t *testing.T) {
+ switch os.Getenv("CARLOS_EXEC_TEE_CHILD") {
+ case "":
+ t.Skip("the tee tests' child")
+ case "flood":
+ w := bufio.NewWriterSize(os.Stdout, 64<<10)
+ line := "flood" + strings.Repeat("x", 1018) + "\n"
+ for range execTeeFloodLines {
+ w.WriteString(line)
+ }
+ w.Flush()
+ os.Stderr.WriteString("flood-err\n")
+ case "line":
+ os.Stdout.WriteString("b-line\n")
+ case "partial":
+ os.Stdout.WriteString("whole\nno newline at exit")
+ }
+ os.Exit(0)
+}
+
+func execTeeChild(t *testing.T, mode string) *exec.Cmd {
+ t.Helper()
+ cmd := exec.Command(os.Args[0], "-test.run=^TestExecTeeChild$", "-test.count=1")
+ cmd.Env = append(os.Environ(), "CARLOS_EXEC_TEE_CHILD="+mode)
+ return cmd
+}
+
+// stallAgentStreams makes the agent's own stdout and stderr, and its
+// journal queue's writer, a journal that has stopped reading: a pipe
+// nobody reads, and journal, which blocks every write. The test's
+// cleanups put both back.
+func stallAgentStreams(t *testing.T, journal *stallWriter) {
+ t.Helper()
+ r, w, err := os.Pipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ stdout, stderr, agent := os.Stdout, os.Stderr, agentJournal
+ j := newLogJournal(journal, logJournalMax)
+ os.Stdout, os.Stderr = w, w
+ agentJournal = func() *logJournal { return j }
+ t.Cleanup(func() {
+ os.Stdout, os.Stderr, agentJournal = stdout, stderr, agent
+ journal.unstall()
+ j.stop()
+ // A writer still blocked on the pipe gets EPIPE.
+ r.Close()
+ w.Close()
+ })
+}
+
+// A journal that stops reading (journald stalled, the agent's stdout pipe
+// full) must not stop the agent draining an exec child's flood, must not
+// hold back another child's tenant lines, and must not keep Wait from
+// returning: the exec tee's journal copy takes the listener's bounded,
+// lossy queue (gvisor follow-ups). The tenant sink gets every line, as
+// it always has.
+func TestExecTeeStalledJournalBlocksNoDrainNoTenantNoWait(t *testing.T) {
+ journal := newStallWriter()
+ stallAgentStreams(t, journal)
+ sink := &teeSink{}
+ b := &ExecBackend{Logs: sink}
+
+ flood := execTeeChild(t, "flood")
+ b.teeStd(flood, testRoute("flood.example.com"))
+ if err := flood.Start(); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { flood.Process.Kill() })
+ waited := make(chan error, 1)
+ returnsWithin(t, "Wait of the flooding child", 20*time.Second, func() { waited <- flood.Wait() })
+ if err := <-waited; err != nil {
+ t.Fatalf("flooding child: %v", err)
+ }
+ select {
+ case <-journal.entered:
+ default:
+ t.Fatal("nothing reached the journal: the stall was never in the way")
+ }
+
+ second := execTeeChild(t, "line")
+ b.teeStd(second, testRoute("second.example.com"))
+ if err := second.Start(); err != nil {
+ t.Fatal(err)
+ }
+ waited = make(chan error, 1)
+ returnsWithin(t, "Wait of the second child", 20*time.Second, func() { waited <- second.Wait() })
+ if err := <-waited; err != nil {
+ t.Fatalf("second child: %v", err)
+ }
+ if got := sink.of("second.example.com"); len(got) != 1 || got[0] != "b-line" {
+ t.Fatalf("second child's tenant lines: %q", got)
+ }
+ got := sink.of("flood.example.com")
+ if len(got) != execTeeFloodLines+1 || !slices.Contains(got, "flood-err") {
+ t.Fatalf("flooding child's tenant got %d lines, want every one of %d", len(got), execTeeFloodLines+1)
+ }
+}
+
+// The journal copy is whole lines, each child held to the listener's
+// journal line cap with its drop counted once its streams end, and the
+// last line flushed even without a newline; the tenant sink is as it
+// always was: complete lines, an unterminated tail left out.
+func TestExecTeeJournalCopyIsCappedLinesPerChild(t *testing.T) {
+ out := &stallWriter{release: make(chan struct{}), entered: make(chan struct{}, 1)}
+ out.unstall()
+ agent := agentJournal
+ j := newLogJournal(out, 64<<20)
+ agentJournal = func() *logJournal { return j }
+ t.Cleanup(func() { agentJournal = agent; j.stop() })
+ sink := &teeSink{}
+ b := &ExecBackend{Logs: sink}
+
+ for _, mode := range []string{"partial", "flood"} {
+ cmd := execTeeChild(t, mode)
+ b.teeStd(cmd, testRoute(mode+".example.com"))
+ if err := cmd.Run(); err != nil {
+ t.Fatalf("%s child: %v", mode, err)
+ }
+ }
+ waitFor(t, "the journal copy", func() bool {
+ return strings.Contains(out.String(), "no newline at exit\n") && strings.Contains(out.String(), "flood.example.com: dropped")
+ })
+ lines := strings.Split(strings.TrimSuffix(out.String(), "\n"), "\n")
+ floods := 0
+ for _, line := range lines {
+ if strings.HasPrefix(line, "flood") && !strings.Contains(line, "dropped") {
+ floods++
+ }
+ }
+ // The burst, and what the cap refilled while the flood ran.
+ if floods < logJournalLineBurst || floods >= execTeeFloodLines/2 {
+ t.Errorf("journal got %d flood lines, want the per-child burst %d and little more", floods, logJournalLineBurst)
+ }
+ if !strings.Contains(out.String(), "flood.example.com: dropped ") || !strings.Contains(out.String(), " byte(s) of app output (journal line cap)\n") {
+ t.Errorf("no journal line cap notice for the flooding child in %d lines", len(lines))
+ }
+ if got := sink.of("partial.example.com"); len(got) != 1 || got[0] != "whole" {
+ t.Errorf("tenant lines %q: the tenant sink keeps only complete lines, as before", got)
+ }
+ if got := sink.of("flood.example.com"); len(got) != execTeeFloodLines+1 {
+ t.Errorf("tenant got %d flood lines, want all %d", len(got), execTeeFloodLines+1)
+ }
+ for _, e := range sink.events {
+ t.Errorf("tenant event %q: the journal cap is the journal's alone", e)
+ }
+}
+
+var _ io.Writer = (*stallWriter)(nil)