From d8d5cba1ddb8d45664f4deda0bcfe5384a18d519 Mon Sep 17 00:00:00 2001 From: Joseph Schorr Date: Thu, 5 Nov 2026 15:43:11 -0500 Subject: [PATCH 1/2] runner: route controller-runtime logging to the runner's log The runner never installed a controller-runtime logger, so every log.FromContext call in runner-side code was discarded - including the respond_to_user path's report that a fallback notice failed to publish. Install it globally and carry it on the root context, since a dependency can claim the global first. --- internal/cmd/runner/logging_test.go | 24 ++++++++++++++++++++++++ internal/cmd/runner/main.go | 18 +++++++++++++++++- 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 internal/cmd/runner/logging_test.go diff --git a/internal/cmd/runner/logging_test.go b/internal/cmd/runner/logging_test.go new file mode 100644 index 00000000..3f3b6d43 --- /dev/null +++ b/internal/cmd/runner/logging_test.go @@ -0,0 +1,24 @@ +package main + +import ( + "bytes" + "log/slog" + "testing" + + "github.com/stretchr/testify/assert" + logf "sigs.k8s.io/controller-runtime/pkg/log" +) + +// log.FromContext is how respond_to_user, the dispatch loop and authz slot +// promotion log. Before loggingContext existed those lines went nowhere. +func TestLoggingContext_FromContextReachesSlogDefault(t *testing.T) { + var buf bytes.Buffer + prev := slog.Default() + slog.SetDefault(slog.New(slog.NewTextHandler(&buf, nil))) + t.Cleanup(func() { slog.SetDefault(prev) }) + + logf.FromContext(loggingContext()).Info("fallback notice publish failed", "session", "ns/demo-agent") + + assert.Contains(t, buf.String(), "fallback notice publish failed") + assert.Contains(t, buf.String(), "session=ns/demo-agent") +} diff --git a/internal/cmd/runner/main.go b/internal/cmd/runner/main.go index 479589f3..8dd02009 100644 --- a/internal/cmd/runner/main.go +++ b/internal/cmd/runner/main.go @@ -32,6 +32,7 @@ import ( "k8s.io/utils/clock" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" + logf "sigs.k8s.io/controller-runtime/pkg/log" "github.com/authzed/openagentprimitives/pkg/agent/derivevalidator" "github.com/authzed/openagentprimitives/pkg/agent/llm" @@ -255,6 +256,13 @@ func main() { logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelInfo})) slog.SetDefault(logger) + // Route controller-runtime's logger through the same handler. Without it, + // every log.FromContext call in runner-side code (respond_to_user's + // fallback-notice failures, the dispatch loop, authz slot promotion) is + // discarded. SetLogger is first-write-wins and a transitive init() can + // claim it first (see internal/cmd/channelsd), so run() also carries the + // logger on rootCtx, which log.FromContext prefers. + ctrl.SetLogger(logr.FromSlogHandler(logger.Handler())) // run() owns its own context + manual SIGTERM/SIGINT handling (see below), // so the root command uses Execute() rather than ExecuteContext() — the @@ -326,6 +334,14 @@ func newCommand() *cobra.Command { return cmd } +// loggingContext returns a background context carrying a logr view of the +// default slog handler, so log.FromContext in runner-side code writes to the +// runner's stderr even when controller-runtime's global logger was claimed by a +// dependency before main ran. +func loggingContext() context.Context { + return logf.IntoContext(context.Background(), logr.FromSlogHandler(slog.Default().Handler())) +} + func run(cfg *config) error { hostname := cfg.hostname ns := cfg.agentSessionNamespace @@ -383,7 +399,7 @@ func run(cfg *config) error { // SIGTERM handling. The signal-consuming goroutine is started below, once // the signing memory + session scope exist, so it can record an explicit // Stopped lifecycle transition before cancelling the loop. - rootCtx, cancel := context.WithCancel(context.Background()) + rootCtx, cancel := context.WithCancel(loggingContext()) defer cancel() // loopRef is stored once the runner Loop is fully constructed (below). The From 90270bacf92d2d5d9fb71b9532f5bfb77a947d0a Mon Sep 17 00:00:00 2001 From: Joseph Schorr Date: Thu, 12 Nov 2026 15:33:08 -0500 Subject: [PATCH 2/2] runner: extract the logging wiring into tested helpers Address review: installLogging and newRootContext are now what main() and run() call, so the tests exercise the real wiring rather than a lookalike. The test restores the stdlib log output slog.SetDefault redirects, and the comments no longer cite an init() race that does not occur in this binary. --- internal/cmd/runner/logging_test.go | 89 +++++++++++++++++++++++++++-- internal/cmd/runner/main.go | 35 +++++++----- 2 files changed, 103 insertions(+), 21 deletions(-) diff --git a/internal/cmd/runner/logging_test.go b/internal/cmd/runner/logging_test.go index 3f3b6d43..64dcff1d 100644 --- a/internal/cmd/runner/logging_test.go +++ b/internal/cmd/runner/logging_test.go @@ -2,23 +2,100 @@ package main import ( "bytes" + "context" + "errors" + "log" "log/slog" + "sync" "testing" "github.com/stretchr/testify/assert" logf "sigs.k8s.io/controller-runtime/pkg/log" ) +// lockedBuffer is a bytes.Buffer safe for the concurrent writes a process-wide +// log destination can receive. +type lockedBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *lockedBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *lockedBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +func (b *lockedBuffer) Reset() { + b.mu.Lock() + defer b.mu.Unlock() + b.buf.Reset() +} + +// installedOutput backs installedHandler. controller-runtime's SetLogger is +// first-write-wins and cannot be undone, so the handler installLogging is +// tested with must be the same one on every run in this process (-count=2 +// included); only its buffer is reset. +var ( + installedOutput = &lockedBuffer{} + installedHandler = slog.NewTextHandler(installedOutput, nil) +) + +// These tests cover the two helpers main() and run() call. They cannot prove +// that main() calls installLogging or that run() builds its root context with +// newRootContext — neither is reachable from a unit test. + +// Not parallel: installLogging mutates slog's default logger, the stdlib log +// package's output, and controller-runtime's global logger. +func TestInstallLogging(t *testing.T) { + prevWriter, prevFlags := log.Writer(), log.Flags() + + t.Run("slog default and controller-runtime's global logger reach the handler", func(t *testing.T) { + prevDefault := slog.Default() + t.Cleanup(func() { + slog.SetDefault(prevDefault) + // SetDefault with a non-default handler also redirects the stdlib + // log package; restoring the previous default does not undo that. + log.SetOutput(prevWriter) + log.SetFlags(prevFlags) + }) + installedOutput.Reset() + + installLogging(installedHandler) + + slog.Info("via slog default") + logf.Log.Info("fallback notice publish failed", "session", "ns/demo-agent") + logf.Log.Error(errors.New("bus closed"), "publish errored") + + out := installedOutput.String() + assert.Contains(t, out, "via slog default") + assert.Contains(t, out, "fallback notice publish failed") + assert.Contains(t, out, "session=ns/demo-agent") + assert.Contains(t, out, `level=ERROR msg="publish errored" err="bus closed"`) + }) + + assert.Same(t, prevWriter, log.Writer(), "stdlib log output restored after cleanup") + assert.Equal(t, prevFlags, log.Flags(), "stdlib log flags restored after cleanup") +} + // log.FromContext is how respond_to_user, the dispatch loop and authz slot -// promotion log. Before loggingContext existed those lines went nowhere. -func TestLoggingContext_FromContextReachesSlogDefault(t *testing.T) { +// promotion log. +func TestNewRootContext_FromContextReachesHandler(t *testing.T) { var buf bytes.Buffer - prev := slog.Default() - slog.SetDefault(slog.New(slog.NewTextHandler(&buf, nil))) - t.Cleanup(func() { slog.SetDefault(prev) }) + ctx, cancel := newRootContext(slog.NewTextHandler(&buf, nil)) - logf.FromContext(loggingContext()).Info("fallback notice publish failed", "session", "ns/demo-agent") + logf.FromContext(ctx).Info("fallback notice publish failed", "session", "ns/demo-agent") assert.Contains(t, buf.String(), "fallback notice publish failed") assert.Contains(t, buf.String(), "session=ns/demo-agent") + + assert.NoError(t, ctx.Err()) + cancel() + assert.ErrorIs(t, ctx.Err(), context.Canceled) } diff --git a/internal/cmd/runner/main.go b/internal/cmd/runner/main.go index 8dd02009..21e7d151 100644 --- a/internal/cmd/runner/main.go +++ b/internal/cmd/runner/main.go @@ -255,14 +255,7 @@ func main() { deplogs.Silence() logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelInfo})) - slog.SetDefault(logger) - // Route controller-runtime's logger through the same handler. Without it, - // every log.FromContext call in runner-side code (respond_to_user's - // fallback-notice failures, the dispatch loop, authz slot promotion) is - // discarded. SetLogger is first-write-wins and a transitive init() can - // claim it first (see internal/cmd/channelsd), so run() also carries the - // logger on rootCtx, which log.FromContext prefers. - ctrl.SetLogger(logr.FromSlogHandler(logger.Handler())) + installLogging(logger.Handler()) // run() owns its own context + manual SIGTERM/SIGINT handling (see below), // so the root command uses Execute() rather than ExecuteContext() — the @@ -334,12 +327,24 @@ func newCommand() *cobra.Command { return cmd } -// loggingContext returns a background context carrying a logr view of the -// default slog handler, so log.FromContext in runner-side code writes to the -// runner's stderr even when controller-runtime's global logger was claimed by a -// dependency before main ran. -func loggingContext() context.Context { - return logf.IntoContext(context.Background(), logr.FromSlogHandler(slog.Default().Handler())) +// installLogging makes h the destination for both slog's default logger and +// controller-runtime's global logger. Without the second half, every +// log.FromContext call in runner-side code (respond_to_user's fallback-notice +// failures, the dispatch loop, authz slot promotion) on a context that carries +// no logger of its own is discarded. +func installLogging(h slog.Handler) { + slog.SetDefault(slog.New(h)) + ctrl.SetLogger(logr.FromSlogHandler(h)) +} + +// newRootContext returns run()'s cancellable root context, carrying a logr view +// of h. log.FromContext prefers a context's own logger over the global one +// installLogging sets, so this is defence in depth: nothing in this binary is +// known to claim controller-runtime's first-write-wins global ahead of main, +// but the lines routed here are error reports, and a context-carried logger +// keeps them reaching stderr even if a dependency someday does. +func newRootContext(h slog.Handler) (context.Context, context.CancelFunc) { + return context.WithCancel(logf.IntoContext(context.Background(), logr.FromSlogHandler(h))) } func run(cfg *config) error { @@ -399,7 +404,7 @@ func run(cfg *config) error { // SIGTERM handling. The signal-consuming goroutine is started below, once // the signing memory + session scope exist, so it can record an explicit // Stopped lifecycle transition before cancelling the loop. - rootCtx, cancel := context.WithCancel(loggingContext()) + rootCtx, cancel := newRootContext(slog.Default().Handler()) defer cancel() // loopRef is stored once the runner Loop is fully constructed (below). The