Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 101 additions & 0 deletions internal/cmd/runner/logging_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nit] TestInstallLogging can fail for an unrelated reason if controller-runtime's global logger was already claimed

Problem: controller-runtime's SetLogger is first-write-wins. If anything in this test process calls logf.Log / log.FromContext(context.Background()) more than 30s after package init without SetLogger having run, eventuallyFulfillRoot (controller-runtime pkg/log/log.go:54-70) installs a NullLogSink permanently. installLogging then becomes a no-op for the global and the three logf.Log assertions at lines 78-80 fail with no hint why. Not triggered today (package has no TestMain, runs in a few seconds), but it grows with the suite.
Verify: optional. Add a throwaway test in a file that sorts before logging_test.go that sleeps 31s and then calls logf.Log.Info(...); run it together with TestInstallLogging. controller-runtime prints "log.SetLogger(...) was never called" and TestInstallLogging fails. The reviewer reproduced this with go test -overlay.
Fix: add a TestMain in internal/cmd/runner that calls installLogging(installedHandler) once before m.Run(), and keep the assertions in the test (reset installedOutput first). Alternative: leave as is and add a comment here naming the dependency. Either is acceptable; low priority.
Test: go test -race -count=2 -run 'TestInstallLogging|TestNewRootContext' ./internal/cmd/runner/ must still pass.


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.
func TestNewRootContext_FromContextReachesHandler(t *testing.T) {
var buf bytes.Buffer
ctx, cancel := newRootContext(slog.NewTextHandler(&buf, nil))

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)
}
25 changes: 23 additions & 2 deletions internal/cmd/runner/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -254,7 +255,7 @@ func main() {
deplogs.Silence()

logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelInfo}))
slog.SetDefault(logger)
installLogging(logger.Handler())

// run() owns its own context + manual SIGTERM/SIGINT handling (see below),
// so the root command uses Execute() rather than ExecuteContext() — the
Expand Down Expand Up @@ -326,6 +327,26 @@ func newCommand() *cobra.Command {
return cmd
}

// 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 {
hostname := cfg.hostname
ns := cfg.agentSessionNamespace
Expand Down Expand Up @@ -383,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(context.Background())
rootCtx, cancel := newRootContext(slog.Default().Handler())
defer cancel()

// loopRef is stored once the runner Loop is fully constructed (below). The
Expand Down
Loading