feat(webui): read a task's log through the State Store and let it be downloaded

The dashboard's attempt-log panel answered every read with "task logging is
optional and was not enabled for this run". That message was false: logging is
wired unconditionally in the daemon, and the log files exist. The dashboard
process simply had no reader -- composition left TaskLogs absent because no
contract carried it -- so the handler saw a nil registry and reported the
disabled shape, which the page rendered as a claim about configuration.

internal/logging now answers whether an attempt has a log at all: Tail sets
Result.Found, so "this attempt has no log" is a value rather than an empty
list indistinguishable from a read that never happened. Its registry gains
TaskLog (a decoded page) and TaskLogContent (the file verbatim, streamed,
because a log is unbounded input), and an absent reader reports
ErrTaskLogsUnavailable rather than an empty page -- a process that cannot read
logs must not implicate the attempt.

Those two answers travel the State Store contract as storecontract.TaskLogStore
(ReadTaskLog, StreamTaskLogContent) and are rehydrated on the client by
(Unavailable, canonical message), so archie-ui composes the reader from its own
store client instead of opening another process's files. The daemon's registry
is wired as the server-side reader in the State Store process only.

On top of that read, GET /api/tasks/{id}/logs/download serves the attempt's log
as a Content-Disposition attachment named task-<id>-attempt-<n>.log, and the
panel offers it. The JSON route keeps its shape and gains found, so the page
states the attempt has no log instead of blaming a setting.

Task log files stay owned by their directory's owner: archiving still removes a
task's log directory, and that removal is the daemon's, not the dashboard's.
This commit is contained in:
sam committed 2026-09-17 12:12:43 +00:00
1 parent 781358c862
commit 21d8250cde
19 files changed
+1266 -83

No files matched your search

@@ -14,6 +14,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/logging"
)
// Client is the single remote adapter wrapping one StateStoreServiceClient,
@@ -36,6 +37,7 @@ func (c *Client) Close() error { return nil }
var (
_ task.Store = (*Client)(nil)
_ storecontract.TaskStore = (*Client)(nil)
_ storecontract.TaskLogStore = (*Client)(nil)
_ storecontract.CaptureStore = (*Client)(nil)
_ storecontract.MappingStore = (*Client)(nil)
_ storecontract.BindingStore = (*Client)(nil)
@@ -417,6 +419,58 @@ func (c *Client) EnqueueBindingTask(ctx context.Context, owner, repo, title, bod
return taskValue(r.Task), nil
}
// Task log
// TaskLog reads one task attempt's decoded log over the wire. found=false with
// a nil error is the attempt-has-no-log answer; a process with no reader at
// all comes back as an unavailable error, not as an empty page, so a caller
// can tell the two apart.
func (c *Client) TaskLog(ctx context.Context, taskID int64, attempt int, q logging.Query) (logging.TaskLogPage, error) {
r, err := c.client.ReadTaskLog(ctx, taskLogRequestProto(taskID, attempt, q))
if err != nil {
return logging.TaskLogPage{}, unmapError(err)
}
if !r.Found {
return logging.TaskLogPage{
Entries: []logging.Entry{},
Components: []string{},
}, nil
}
return logging.TaskLogPage{
Entries: mapValues(r.Entries, taskLogEntryValue),
Truncated: r.Truncated,
File: r.File,
Found: true,
Components: r.Components,
}, nil
}
// TaskLogContent streams one attempt's log verbatim into w, for a download.
// found is false, with a nil error, when the attempt has no log file.
func (c *Client) TaskLogContent(ctx context.Context, taskID int64, attempt int, w io.Writer) (bool, error) {
stream, err := c.client.StreamTaskLogContent(ctx, &pb.StreamTaskLogContentRequest{TaskId: taskID, Attempt: int64(attempt)})
if err != nil {
return false, unmapError(err)
}
found := false
for {
r, err := stream.Recv()
if errors.Is(err, io.EOF) {
return found, nil
}
if err != nil {
return found, unmapError(err)
}
found = found || r.Found
if len(r.Chunk) == 0 {
continue
}
if _, err := w.Write(r.Chunk); err != nil {
return found, err
}
}
}
func derefTasks(in []*pb.Task) []task.Task {
if in == nil {
return nil
@@ -31,13 +31,31 @@ type contract interface {
store.ConfigSnapshotStore
}
// taskLogContract is the task-log read group, driven separately because it is
// not a *store.Store surface: the reader is internal/logging's own registry,
// which owns the log format, so the local side of this contract is a registry
// rather than a store.
type taskLogContract interface {
store.TaskLogStore
}
func remoteContract(t *testing.T, local *store.Store) contract {
t.Helper()
return remoteTaskStore(t, local, nil)
}
// remoteTaskStore serves local behind a bufconn listener with a task-log
// reader attached, and returns a client for it. The reader is a parameter
// because the log files are internal/logging's, not the store's: this contract
// fronts a reader rather than a table.
func remoteTaskStore(t *testing.T, local *store.Store, logs store.TaskLogStore) *Client {
t.Helper()
listener := bufconn.Listen(1 << 20)
server := grpc.NewServer()
RegisterServer(server, Deps{
Tasks: local, Captures: local, Mappings: local, Bindings: local,
BindingDispatcher: local, BindingTaskCreator: local, ConfigSnapshots: local,
TaskLogs: logs,
})
go func() { _ = server.Serve(listener) }()
t.Cleanup(func() { server.Stop(); _ = listener.Close() })
+135 -1
View File
@@ -5,7 +5,9 @@
package staterpc
import (
"bytes"
"context"
"errors"
"log/slog"
"time"
@@ -17,6 +19,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/logging"
)
// Unavailable-capability errors, mirroring gatewayrpc's missing-session-store
@@ -30,10 +33,23 @@ var (
errBindingUnavailable = status.Error(codes.Unavailable, "binding store unavailable")
errBindingDispatchUnavailable = status.Error(codes.Unavailable, "binding dispatcher unavailable")
errBindingTaskCreatorUnavailable = status.Error(codes.Unavailable, "binding task creator unavailable")
// errTaskLogsUnavailable is the "this process cannot read task logs at
// all" answer, and it is deliberately distinct from a found=false read
// result: only the first is a deployment matter. A dashboard that receives
// this reports that the log cannot be read here; it must never turn it
// into "task logging was not enabled for this run", which is what the
// absent-handle path used to do.
errTaskLogsUnavailable = status.Error(codes.Unavailable, msgTaskLogsUnavailable)
)
func timeSeconds(s int64) time.Duration { return time.Duration(s) * time.Second }
// taskLogChunkBytes bounds one streamed message. A log file rotates at
// logging.DefaultMaxSizeMB, well past gRPC's 4MiB unary cap, so the download
// is served in pieces (the same reason StreamCaptures superseded ListCaptures)
// and the pieces must be small enough to carry.
const taskLogChunkBytes = 256 << 10
// Deps groups the store surfaces the StateStore service fronts. TaskStore is
// required; the rest are optional (nil disables that group's RPCs, returning
// codes.Unavailable) exactly as their daemon-side consumers already treat a
@@ -47,7 +63,14 @@ type Deps struct {
Bindings storecontract.BindingStore
BindingDispatcher storecontract.BindingDispatcher
BindingTaskCreator storecontract.BindingTaskCreator
Log *slog.Logger
// TaskLogs reads one task attempt's persisted log out of the state
// directory this process owns. Optional, and nil is the honest default for
// a store service that shares no state directory with the daemon:
// ReadTaskLog then answers codes.Unavailable, which the dashboard reports
// as "this process cannot read logs" rather than as "this attempt has no
// log". Conflating those two is the bug this contract exists to fix.
TaskLogs storecontract.TaskLogStore
Log *slog.Logger
}
type server struct {
@@ -565,6 +588,117 @@ func (s *server) EnqueueBindingTask(ctx context.Context, r *pb.EnqueueBindingTas
return &pb.EnqueueBindingTaskResponse{Task: taskProto(t)}, nil
}
// Task log
func (s *server) taskLogs() (storecontract.TaskLogStore, error) {
if s.deps.TaskLogs == nil {
return nil, errTaskLogsUnavailable
}
return s.deps.TaskLogs, nil
}
func (s *server) ReadTaskLog(ctx context.Context, r *pb.ReadTaskLogRequest) (*pb.ReadTaskLogResponse, error) {
logs, err := s.taskLogs()
if err != nil {
return nil, err
}
page, err := logs.TaskLog(ctx, r.TaskId, int(r.Attempt), taskLogQueryValue(r))
if err != nil {
// A store that cannot read its own state directory keeps its own
// identity: this is unavailability, not a missing log, and a caller
// has to be able to tell them apart.
if errors.Is(err, logging.ErrTaskLogsUnavailable) {
return nil, errTaskLogsUnavailable
}
return nil, s.logErr("ReadTaskLog", err)
}
if !page.Found {
return &pb.ReadTaskLogResponse{Attempt: r.Attempt}, nil
}
return &pb.ReadTaskLogResponse{
Entries: mapValues(page.Entries, taskLogEntryProto),
Truncated: page.Truncated,
Attempt: r.Attempt,
Found: true,
Components: page.Components,
File: page.File,
}, nil
}
// StreamTaskLogContent sends one attempt's log verbatim, one chunk per
// message, for a download. A single reply reports found=false with no chunks:
// the attempt has no log file, which is a normal state rather than a failure.
func (s *server) StreamTaskLogContent(r *pb.StreamTaskLogContentRequest, stream pb.StateStoreService_StreamTaskLogContentServer) error {
logs, err := s.taskLogs()
if err != nil {
return err
}
// The chunking the client sees is owned by the reader that writes into
// this buffer, so the wire never holds a whole log to re-slice it.
buf := &chunkWriter{stream: stream, attempt: r.Attempt}
found, err := logs.TaskLogContent(stream.Context(), r.TaskId, int(r.Attempt), buf)
if err != nil {
if errors.Is(err, logging.ErrTaskLogsUnavailable) {
return errTaskLogsUnavailable
}
return s.logErr("StreamTaskLogContent", err)
}
if err := buf.flush(); err != nil {
return err
}
// A found log with no bytes still reports found: an attempt whose file is
// empty did produce a log, and found is what tells the download it may
// write an empty file rather than answer 404.
if found && buf.sent {
return nil
}
return stream.Send(&pb.StreamTaskLogContentResponse{Attempt: r.Attempt, Found: found})
}
// chunkWriter packs everything a log reader writes into stream-sized messages
// on its way through. It exists so the read can be one io.CopyBuffer of the
// file into this writer: the reader keeps its own chunk size, and the bytes
// are never all held at once.
type chunkWriter struct {
stream pb.StateStoreService_StreamTaskLogContentServer
attempt int64
pending []byte
// sent records whether any chunk reached the client, which is how the
// caller tells "the file was empty" from "the file was read".
sent bool
}
func (w *chunkWriter) Write(p []byte) (int, error) {
w.pending = append(w.pending, p...)
for len(w.pending) >= taskLogChunkBytes {
if err := w.emit(w.pending[:taskLogChunkBytes]); err != nil {
return 0, err
}
w.pending = w.pending[taskLogChunkBytes:]
}
return len(p), nil
}
func (w *chunkWriter) emit(chunk []byte) error {
w.sent = true
// The slice is copied into the message: the reader's buffer is reused
// across writes and must not be aliased by a message in flight.
return w.stream.Send(&pb.StreamTaskLogContentResponse{
Chunk: bytes.Clone(chunk),
Attempt: w.attempt,
Found: true,
})
}
func (w *chunkWriter) flush() error {
if len(w.pending) == 0 {
return nil
}
chunk := w.pending
w.pending = nil
return w.emit(chunk)
}
func mappingProtoPtr(m *mapping.Mapping) *pb.Mapping {
if m == nil {
return nil
@@ -0,0 +1,200 @@
package staterpc
import (
"bytes"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/logging"
"github.com/samcharles93/archie-core/internal/store"
)
// TestTaskLogContract drives the task-log read group through both adapters,
// matching the §11 conformance requirement the rest of this package already
// satisfies: the same battery runs against the local reader (a
// *logging.TaskRegistry over this process's own state directory) and against
// the remote *Client.
//
// The two answers this pins as DIFFERENT are the point of the contract. A
// process with no reader reports unavailability; an attempt with no log file
// reports found=false with no error. A caller that cannot tell those apart
// tells an operator task logging is switched off when it is not.
func TestTaskLogContract(t *testing.T) {
for _, mode := range []string{"local", "grpc"} {
t.Run(mode, func(t *testing.T) {
ctx := t.Context()
baseDir := filepath.Join(t.TempDir(), "logs", "tasks")
reader := logging.NewTaskRegistry(baseDir, logging.NewFeed(10), logging.TaskSinkOptions{})
const taskID = 7
if err := reader.Open(taskID, 0); err != nil {
t.Fatalf("open sink: %v", err)
}
reader.Write(taskID, logging.Entry{Level: "INFO", Message: "starting", Fields: map[string]any{"component": "daemon"}})
reader.Write(taskID, logging.Entry{Level: "ERROR", Message: "gate failed", Fields: map[string]any{"component": "gate"}})
if err := reader.Close(taskID); err != nil {
t.Fatalf("close sink: %v", err)
}
var c taskLogContract = reader
if mode == "grpc" {
c = remoteTaskStore(t, store.OpenTest(t), reader)
}
t.Run("a page carries the decoded entries and their fields", func(t *testing.T) {
page, err := c.TaskLog(ctx, taskID, 0, logging.Query{})
if err != nil {
t.Fatalf("TaskLog: %v", err)
}
if !page.Found {
t.Fatal("Found = false for an attempt whose log exists")
}
if len(page.Entries) != 2 {
t.Fatalf("entries = %d, want 2", len(page.Entries))
}
if page.Entries[1].Message != "gate failed" || page.Entries[1].Level != "ERROR" {
t.Errorf("entry = %+v, want the ERROR line the sink wrote", page.Entries[1])
}
if got, _ := page.Entries[0].Fields["component"].(string); got != "daemon" {
t.Errorf("fields = %+v, want the structured component to survive the hop", page.Entries[0].Fields)
}
if !strings.HasSuffix(page.File, "attempt-0.jsonl") {
t.Errorf("file = %q, want the attempt's own path", page.File)
}
})
t.Run("filters and the limit cross the wire", func(t *testing.T) {
page, err := c.TaskLog(ctx, taskID, 0, logging.Query{Levels: []string{"ERROR"}})
if err != nil {
t.Fatalf("TaskLog: %v", err)
}
if len(page.Entries) != 1 || page.Entries[0].Message != "gate failed" {
t.Fatalf("level filter = %+v, want just the ERROR line", page.Entries)
}
page, err = c.TaskLog(ctx, taskID, 0, logging.Query{Component: "daemon"})
if err != nil {
t.Fatalf("TaskLog: %v", err)
}
if len(page.Entries) != 1 || page.Entries[0].Message != "starting" {
t.Fatalf("component filter = %+v, want just the daemon line", page.Entries)
}
page, err = c.TaskLog(ctx, taskID, 0, logging.Query{Contains: "gate"})
if err != nil {
t.Fatalf("TaskLog: %v", err)
}
if len(page.Entries) != 1 || page.Entries[0].Message != "gate failed" {
t.Fatalf("contains filter = %+v, want just the gate line", page.Entries)
}
page, err = c.TaskLog(ctx, taskID, 0, logging.Query{Limit: 1})
if err != nil {
t.Fatalf("TaskLog: %v", err)
}
if len(page.Entries) != 1 || !page.Truncated {
t.Fatalf("limit = 1 gave %d entries (truncated %v), want one and a truncated marker", len(page.Entries), page.Truncated)
}
})
t.Run("components list what the log actually contains", func(t *testing.T) {
page, err := c.TaskLog(ctx, taskID, 0, logging.Query{})
if err != nil {
t.Fatalf("TaskLog: %v", err)
}
if len(page.Components) != 2 || page.Components[0] != "daemon" || page.Components[1] != "gate" {
t.Fatalf("components = %v, want the sorted distinct set", page.Components)
}
})
t.Run("an attempt with no log is found=false, not an error", func(t *testing.T) {
page, err := c.TaskLog(ctx, taskID, 99, logging.Query{})
if err != nil {
t.Fatalf("TaskLog for a missing attempt = %v, want no error", err)
}
if page.Found {
t.Error("Found = true for an attempt with no log file")
}
if len(page.Entries) != 0 {
t.Errorf("entries = %+v, want none", page.Entries)
}
})
t.Run("content is the file verbatim, and found is false when there is none", func(t *testing.T) {
var buf bytes.Buffer
found, err := c.TaskLogContent(ctx, taskID, 0, &buf)
if err != nil {
t.Fatalf("TaskLogContent: %v", err)
}
if !found {
t.Fatal("found = false for an attempt whose log exists")
}
body := buf.String()
if !strings.Contains(body, "gate failed") || !strings.Contains(body, "starting") {
t.Fatalf("content = %q, want the raw log lines", body)
}
// Byte-for-byte: the contract transports the log, it does not
// re-encode it. Every line must still parse as the package's
// own JSONL.
for line := range strings.Lines(strings.TrimSpace(body)) {
if _, ok := loggingTailDecodes(t, line); !ok {
t.Fatalf("line %q does not decode as the logging package's own format", line)
}
}
buf.Reset()
found, err = c.TaskLogContent(ctx, taskID, 99, &buf)
if err != nil {
t.Fatalf("TaskLogContent for a missing attempt = %v, want no error", err)
}
if found || buf.Len() != 0 {
t.Errorf("found = %v with %d bytes, want false and nothing", found, buf.Len())
}
})
})
}
}
// TestTaskLogContractWithoutAReaderIsUnavailable pins the other half of the
// distinction, and the one the dashboard's misleading message came from: a
// service with no task-log reader at all must say UNAVAILABLE rather than
// answer an empty page. An empty page is indistinguishable from an attempt
// that has no log, and the dashboard rendered that as "task logging is
// optional and was not enabled for this run".
func TestTaskLogContractWithoutAReaderIsUnavailable(t *testing.T) {
local := store.OpenTest(t)
// remoteContract leaves Deps.TaskLogs nil, which is what a store service
// sharing no state directory with the daemon looks like.
c := remoteContract(t, local)
logs, ok := c.(taskLogContract)
if !ok {
t.Fatalf("remote client does not carry the task-log contract (%T)", c)
}
if _, err := logs.TaskLog(t.Context(), 1, 0, logging.Query{}); !errors.Is(err, logging.ErrTaskLogsUnavailable) {
t.Errorf("TaskLog without a reader = %v, want ErrTaskLogsUnavailable; an empty page here is what the dashboard read as \"logging was not enabled\"", err)
}
var buf bytes.Buffer
if _, err := logs.TaskLogContent(t.Context(), 1, 0, &buf); !errors.Is(err, logging.ErrTaskLogsUnavailable) {
t.Errorf("TaskLogContent without a reader = %v, want ErrTaskLogsUnavailable", err)
}
}
// loggingTailDecodes reports whether one line is a record the logging package
// can decode, using that package's own reader rather than a second opinion
// about its format.
func loggingTailDecodes(t *testing.T, line string) (logging.Entry, bool) {
t.Helper()
path := filepath.Join(t.TempDir(), "one.jsonl")
if err := os.WriteFile(path, []byte(line+"\n"), 0o600); err != nil {
t.Fatalf("write temp log: %v", err)
}
res, err := logging.Tail(path, logging.Query{})
if err != nil {
t.Fatalf("Tail: %v", err)
}
if len(res.Entries) != 1 {
return logging.Entry{}, false
}
return res.Entries[0], true
}
+74 -1
View File
@@ -17,6 +17,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/logging"
)
func timestamp(t time.Time) *timestamppb.Timestamp {
@@ -245,6 +246,12 @@ const (
msgBindingTransition = "binding transition rejected"
msgAlreadyDispatched = "already dispatched"
msgInternal = "state store: internal error"
// msgTaskLogsUnavailable is the public phrase for "this service has no
// task-log reader". It is a wire contract like the sentinels above: the
// client rehydrates logging.ErrTaskLogsUnavailable from (Unavailable, this
// message), and a caller depends on that to tell "this process cannot read
// logs" from "this attempt has no log".
msgTaskLogsUnavailable = "task log reader unavailable"
)
// mapError converts a store sentinel error into a structured gRPC status
@@ -301,6 +308,12 @@ func mapError(err error) error {
// *status.Error whose code is DeadlineExceeded or Canceled, so we rehydrate
// those back to the standard context sentinels -- otherwise the consumer
// would (wrongly) park a task that was merely interrupted.
//
// Unavailable carries one message this package owns: the absent task-log
// reader. It is rehydrated for the same reason the error sentinels are --
// the dashboard's whole bug was rendering "this process cannot read logs" as
// "the attempt has no log", and only the typed error makes that distinction
// available to a caller.
func unmapError(err error) error {
if err == nil {
return nil
@@ -314,6 +327,19 @@ func unmapError(err error) error {
return context.Canceled
case codes.DeadlineExceeded:
return context.DeadlineExceeded
}
if sentinel := sentinelForStatus(st); sentinel != nil {
return sentinel
}
return fmt.Errorf("state store: %s: %w", st.Message(), err)
}
// sentinelForStatus maps a status to the store or logging sentinel it stands
// for, matched on (code, exact canonical message) -- those message constants
// are part of the wire contract (§4). A code whose message is not one this
// package defines returns nil, so the caller falls back to the wrapped form.
func sentinelForStatus(st *status.Status) error {
switch st.Code() {
case codes.FailedPrecondition:
switch st.Message() {
case msgStaleTransition:
@@ -334,8 +360,12 @@ func unmapError(err error) error {
if st.Message() == msgAlreadyDispatched {
return storecontract.ErrAlreadyDispatched
}
case codes.Unavailable:
if st.Message() == msgTaskLogsUnavailable {
return logging.ErrTaskLogsUnavailable
}
}
return fmt.Errorf("state store: %s: %w", st.Message(), err)
return nil
}
// configSnapshotProto and configSnapshotValue carry the dashboard's
@@ -359,3 +389,46 @@ func configSnapshotValue(snapshot *pb.ConfigSnapshot) storecontract.ConfigSnapsh
PublishedAt: timeValue(snapshot.PublishedAt),
}
}
// taskLogEntryProto and taskLogEntryValue mirror internal/logging.Entry, whose
// Fields map crosses as a JSON object string exactly as events.Event.Data does
// (see eventDataJSON above). The logging package owns that format end to end;
// this is a transport of it, not a second definition.
func taskLogEntryProto(e logging.Entry) *pb.TaskLogEntry {
return &pb.TaskLogEntry{
Id: e.ID, Time: timestamp(e.Time), Level: e.Level, Msg: e.Message,
FieldsJson: eventDataJSON(e.Fields),
}
}
func taskLogEntryValue(e *pb.TaskLogEntry) logging.Entry {
if e == nil {
return logging.Entry{}
}
return logging.Entry{
ID: e.Id, Time: timeValue(e.Time), Level: e.Level, Message: e.Msg,
Fields: eventDataValue(e.FieldsJson),
}
}
// taskLogRequestProto is the client half of the ReadTaskLog mapping and
// taskLogQueryValue the server half: the whole logging.Query crosses, not a
// subset of it, so a filter cannot silently stop working at the boundary.
func taskLogRequestProto(taskID int64, attempt int, q logging.Query) *pb.ReadTaskLogRequest {
return &pb.ReadTaskLogRequest{
TaskId: taskID, Attempt: int64(attempt), Limit: int64(q.Limit),
Levels: q.Levels, Component: q.Component, Contains: q.Contains,
Since: timestamp(q.Since), Until: timestamp(q.Until),
}
}
func taskLogQueryValue(r *pb.ReadTaskLogRequest) logging.Query {
return logging.Query{
Levels: r.Levels,
Component: r.Component,
Contains: r.Contains,
Limit: int(r.Limit),
Since: timeValue(r.Since),
Until: timeValue(r.Until),
}
}