diff --git a/internal/daemon/agn.go b/internal/daemon/agn.go index 6f73fde..52f12d8 100644 --- a/internal/daemon/agn.go +++ b/internal/daemon/agn.go @@ -10,6 +10,7 @@ import ( "github.com/agynio/agynd-cli/internal/platform" "github.com/agynio/agynd-cli/internal/subscriber" "github.com/agynio/agynd-cli/internal/tracing" + "github.com/agynio/agynd-cli/internal/tracingproxy" ) func newAgnDaemon(ctx context.Context, cfg config.Config, version string) (*Daemon, error) { @@ -64,38 +65,57 @@ func newAgnDaemon(ctx context.Context, cfg config.Config, version string) (*Daem return nil, err } + // agn reports its own turns rather than keeping a transcript to read back, + // so its spans arrive over OTLP and need something listening for them. The + // hook the other CLIs use never runs here, and the daemon exports only the + // invocation message -- without this the model call is never exported. + tracingProxy, err := tracingproxy.Start(ctx, tracingproxy.Config{ + TracingAddress: cfg.TracingAddress, + ThreadID: cfg.ThreadID, + WorkloadID: cfg.WorkloadID, + }) + if err != nil { + _ = tracingExporter.Close() + _ = setup.gatewayConn.Close() + return nil, err + } + agnClient, err := agnsdk.Start(ctx, agnsdk.Options{ BinaryPath: cfg.AgentBinary, Env: []string{ "PATH=" + agentPathValue(), "AGN_CONFIG_PATH=" + configPath, - // agn reports its own turns rather than having a transcript read - // back, so it is handed the same trace the hook is given for the - // other CLIs. Without it agn rooted its spans itself, and the - // message and the model call it caused landed in separate traces. + // Its own listener rather than whatever the workload was handed: + // the proxy stamps the thread and workload onto what it forwards. + "OTEL_EXPORTER_OTLP_ENDPOINT=http://" + tracingProxy.Address(), + // Handed the same trace the hook is given for the other CLIs. + // Without it agn rooted its spans itself, and the message and the + // model call it caused landed in separate traces. traceparentEnv + "=" + traceparentFor(cfg.WorkloadID), }, }) if err != nil { + tracingProxy.Close() _ = tracingExporter.Close() _ = setup.gatewayConn.Close() return nil, err } return &Daemon{ - cfg: cfg, - sdk: SDKAgn, - gatewayConn: setup.gatewayConn, - threads: setup.threads, - agents: setup.agents, - agentInbox: setup.agentInbox, - runners: setup.runners, - subscriber: subscriber.New(setup.notifications, cfg.ThreadID), - consumer: platform.NewInboxConsumer(setup.agentInbox, pageSize, pageTimeout), - agn: agnClient, - agent: setup.agent, - tracing: tracingExporter, - mcpReady: true, + cfg: cfg, + sdk: SDKAgn, + gatewayConn: setup.gatewayConn, + threads: setup.threads, + agents: setup.agents, + agentInbox: setup.agentInbox, + runners: setup.runners, + subscriber: subscriber.New(setup.notifications, cfg.ThreadID), + consumer: platform.NewInboxConsumer(setup.agentInbox, pageSize, pageTimeout), + agn: agnClient, + agent: setup.agent, + tracing: tracingExporter, + tracingProxy: tracingProxy, + mcpReady: true, }, nil } diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 186a7d4..42f4de9 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -25,6 +25,7 @@ import ( "github.com/agynio/agynd-cli/internal/platform" "github.com/agynio/agynd-cli/internal/subscriber" "github.com/agynio/agynd-cli/internal/tracing" + "github.com/agynio/agynd-cli/internal/tracingproxy" claude "github.com/agynio/claude-sdk-go" codex "github.com/agynio/codex-sdk-go" "github.com/google/uuid" @@ -98,6 +99,7 @@ type Daemon struct { claude claudeClient agent *agentsv1.Agent tracing *tracing.Exporter + tracingProxy *tracingproxy.Proxy claudeReadyMu sync.Mutex claudeReady bool mcpReadyMu sync.Mutex @@ -481,6 +483,9 @@ func (d *Daemon) Close() { if d.tracing != nil { _ = d.tracing.Close() } + if d.tracingProxy != nil { + d.tracingProxy.Close() + } if d.gatewayConn != nil { _ = d.gatewayConn.Close() } diff --git a/internal/tracingproxy/proxy.go b/internal/tracingproxy/proxy.go new file mode 100644 index 0000000..9da9935 --- /dev/null +++ b/internal/tracingproxy/proxy.go @@ -0,0 +1,381 @@ +package tracingproxy + +import ( + "context" + "errors" + "fmt" + "io" + "log" + "net" + "net/http" + "strings" + "sync" + "time" + + collectorlogsv1 "go.opentelemetry.io/proto/otlp/collector/logs/v1" + collectortracev1 "go.opentelemetry.io/proto/otlp/collector/trace/v1" + commonv1 "go.opentelemetry.io/proto/otlp/common/v1" + logsv1 "go.opentelemetry.io/proto/otlp/logs/v1" + resourcev1 "go.opentelemetry.io/proto/otlp/resource/v1" + tracev1 "go.opentelemetry.io/proto/otlp/trace/v1" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" +) + +const ( + DefaultListenAddress = "127.0.0.1:4317" + ListenAddress = DefaultListenAddress + threadIDAttributeKey = "agyn.thread.id" + messageIDAttributeKey = "agyn.thread.message.id" + workloadIDAttributeKey = "agyn.workload.id" + maxHTTPExportBytes = 32 << 20 + maxLoggedValueBytes = 400 +) + +type Config struct { + TracingAddress string + ListenAddress string + ThreadID string + WorkloadID string +} + +type Proxy struct { + collectortracev1.UnimplementedTraceServiceServer + + server *grpc.Server + httpServer *http.Server + upstream collectortracev1.TraceServiceClient + conn *grpc.ClientConn + address string + httpAddress string + workloadID string + // An instance serves many threads, so the thread is per-message and set + // from the consumer goroutine while Export runs on gRPC's. + threadMu sync.RWMutex + threadID string + messageMu sync.RWMutex + messageID string + // Usage counts arrive on a later event than the call they belong to, so the + // call is held until they do and re-emitted with them. + llmCallMu sync.Mutex + llmCalls map[string]*pendingLLMCall + // The message a conversation is answering, so its calls hang off it. + messageSpans map[string]*tracev1.Span +} + +func Start(ctx context.Context, cfg Config) (*Proxy, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + conn, err := grpc.NewClient(cfg.TracingAddress, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + return nil, fmt.Errorf("dial tracing address: %w", err) + } + server := grpc.NewServer() + proxy := &Proxy{ + server: server, + upstream: collectortracev1.NewTraceServiceClient(conn), + conn: conn, + threadID: cfg.ThreadID, + workloadID: cfg.WorkloadID, + } + collectortracev1.RegisterTraceServiceServer(server, proxy) + + listenAddress := cfg.ListenAddress + if listenAddress == "" { + listenAddress = DefaultListenAddress + } + listener, err := net.Listen("tcp", listenAddress) + if err != nil { + _ = conn.Close() + return nil, fmt.Errorf("listen on %s: %w", listenAddress, err) + } + proxy.address = listener.Addr().String() + + go func() { + if err := server.Serve(listener); err != nil && !errors.Is(err, grpc.ErrServerStopped) { + log.Printf("tracing proxy stopped: %v", err) + } + }() + + // The same exporter over OTLP/HTTP, on its own port. Codex cannot use the + // gRPC one -- its otlp-grpc exporter fails to build at all, against any + // address -- and the console and any other OTLP client still can, so this + // serves both rather than replacing one with the other. + httpListener, err := net.Listen("tcp", httpListenAddress(listenAddress)) + if err != nil { + server.Stop() + _ = conn.Close() + return nil, fmt.Errorf("listen for OTLP/HTTP: %w", err) + } + proxy.httpAddress = httpListener.Addr().String() + mux := http.NewServeMux() + mux.HandleFunc("POST /v1/traces", proxy.serveHTTPTraces) + mux.HandleFunc("POST /v1/logs", proxy.serveHTTPLogs) + proxy.httpServer = &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second} + go func() { + if err := proxy.httpServer.Serve(httpListener); err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Printf("tracing proxy OTLP/HTTP stopped: %v", err) + } + }() + + return proxy, nil +} + +// httpListenAddress keeps the OTLP/HTTP listener on the same host as the gRPC +// one and lets the kernel choose its port, so the two never collide. +func httpListenAddress(grpcAddress string) string { + host, _, err := net.SplitHostPort(grpcAddress) + if err != nil || host == "" { + return "127.0.0.1:0" + } + return net.JoinHostPort(host, "0") +} + +// serveHTTPTraces accepts the binary protobuf encoding, which is what the OTLP +// specification defaults to and the only one codex emits. +func (p *Proxy) serveHTTPTraces(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxHTTPExportBytes)) + if err != nil { + http.Error(w, "read body", http.StatusBadRequest) + return + } + request := &collectortracev1.ExportTraceServiceRequest{} + if err := proto.Unmarshal(body, request); err != nil { + http.Error(w, "decode OTLP request", http.StatusBadRequest) + return + } + response, err := p.Export(r.Context(), request) + if err != nil { + http.Error(w, "export traces", http.StatusBadGateway) + return + } + encoded, err := proto.Marshal(response) + if err != nil { + http.Error(w, "encode OTLP response", http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/x-protobuf") + _, _ = w.Write(encoded) +} + +// serveHTTPLogs takes the signal codex ships its structured events on -- the +// prompt, the model call, the usage counts -- and translates them into spans, +// because the tracing service stores traces and nothing else. +func (p *Proxy) serveHTTPLogs(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxHTTPExportBytes)) + if err != nil { + http.Error(w, "read body", http.StatusBadRequest) + return + } + request := &collectorlogsv1.ExportLogsServiceRequest{} + if err := proto.Unmarshal(body, request); err != nil { + http.Error(w, "decode OTLP request", http.StatusBadRequest) + return + } + if spans := p.semanticSpans(request); len(spans) > 0 { + export := &collectortracev1.ExportTraceServiceRequest{ + ResourceSpans: []*tracev1.ResourceSpans{{ + ScopeSpans: []*tracev1.ScopeSpans{{ + Scope: &commonv1.InstrumentationScope{Name: semanticScopeName}, + Spans: spans, + }}, + }}, + } + // Export, not the upstream directly: the thread, message and workload + // this run belongs to are injected there, and without them a span is + // unreachable from the run view. + if _, err := p.Export(r.Context(), export); err != nil { + log.Printf("tracing proxy: export translated log spans: %v", err) + } + } + encoded, err := proto.Marshal(&collectorlogsv1.ExportLogsServiceResponse{}) + if err != nil { + http.Error(w, "encode OTLP response", http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/x-protobuf") + _, _ = w.Write(encoded) +} + +// logUntranslatedRecord reports an event no span was built from, so a codex +// release that adds one -- tool calls above all -- surfaces here rather than +// being dropped in silence. The SSE deltas are the one deliberate omission: +// they fire per chunk and carry nothing but a duration. +func logUntranslatedRecord(record *logsv1.LogRecord, name string) { + attrs := make([]string, 0, len(record.Attributes)) + for _, attr := range record.Attributes { + attrs = append(attrs, attr.Key+"="+truncateValue(attr.Value)) + } + log.Printf("otlp log: untranslated event=%s attrs={%s}", name, strings.Join(attrs, " ")) +} + +func truncateValue(value *commonv1.AnyValue) string { + if value == nil { + return "" + } + rendered := strings.ReplaceAll(value.String(), "\n", "\\n") + if len(rendered) > maxLoggedValueBytes { + return rendered[:maxLoggedValueBytes] + "..." + } + return rendered +} + +func (p *Proxy) Address() string { + return p.address +} + +// HTTPAddress is the OTLP/HTTP collector root; callers append the signal path. +func (p *Proxy) HTTPAddress() string { + return p.httpAddress +} + +func (p *Proxy) Export(ctx context.Context, req *collectortracev1.ExportTraceServiceRequest) (*collectortracev1.ExportTraceServiceResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "trace export request missing") + } + if threadID := p.threadIDValue(); threadID != "" { + injectThreadID(req, threadID) + } + if p.workloadID != "" { + injectWorkloadID(req, p.workloadID) + } + if messageID := p.messageIDValue(); messageID != "" { + injectMessageID(req, messageID) + } + return p.upstream.Export(ctx, req) +} + +func (p *Proxy) SetThreadID(threadID string) { + p.threadMu.Lock() + p.threadID = threadID + p.threadMu.Unlock() +} + +func (p *Proxy) threadIDValue() string { + p.threadMu.RLock() + defer p.threadMu.RUnlock() + return p.threadID +} + +func (p *Proxy) SetMessageID(messageID string) { + p.messageMu.Lock() + p.messageID = messageID + p.messageMu.Unlock() +} + +func (p *Proxy) ClearMessageID() { + p.messageMu.Lock() + p.messageID = "" + p.messageMu.Unlock() +} + +func (p *Proxy) messageIDValue() string { + p.messageMu.RLock() + defer p.messageMu.RUnlock() + return p.messageID +} + +func (p *Proxy) Close() { + done := make(chan struct{}) + go func() { + p.server.GracefulStop() + close(done) + }() + select { + case <-done: + case <-time.After(5 * time.Second): + p.server.Stop() + } + if p.httpServer != nil { + shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + _ = p.httpServer.Shutdown(shutdownCtx) + cancel() + } + _ = p.conn.Close() +} + +func injectThreadID(req *collectortracev1.ExportTraceServiceRequest, threadID string) { + for _, spans := range req.ResourceSpans { + if spans == nil { + continue + } + resource := spans.Resource + if resource == nil { + resource = &resourcev1.Resource{} + spans.Resource = resource + } + upsertAttribute(resource, threadIDAttributeKey, threadID) + } +} + +func injectWorkloadID(req *collectortracev1.ExportTraceServiceRequest, workloadID string) { + for _, spans := range req.ResourceSpans { + if spans == nil { + continue + } + resource := spans.Resource + if resource == nil { + resource = &resourcev1.Resource{} + spans.Resource = resource + } + upsertAttribute(resource, workloadIDAttributeKey, workloadID) + } +} + +func injectMessageID(req *collectortracev1.ExportTraceServiceRequest, messageID string) { + for _, spans := range req.ResourceSpans { + if spans == nil { + continue + } + resource := spans.Resource + if resource == nil { + resource = &resourcev1.Resource{} + spans.Resource = resource + } + upsertAttribute(resource, messageIDAttributeKey, messageID) + for _, scopeSpans := range spans.GetScopeSpans() { + for _, span := range scopeSpans.GetSpans() { + upsertSpanAttribute(span, messageIDAttributeKey, messageID) + } + } + } +} + +func upsertSpanAttribute(span *tracev1.Span, key, value string) { + if span == nil { + return + } + attributeValue := &commonv1.AnyValue{ + Value: &commonv1.AnyValue_StringValue{StringValue: value}, + } + for _, attribute := range span.Attributes { + if attribute != nil && attribute.Key == key { + attribute.Value = attributeValue + return + } + } + span.Attributes = append(span.Attributes, &commonv1.KeyValue{ + Key: key, + Value: attributeValue, + }) +} + +func upsertAttribute(resource *resourcev1.Resource, key, value string) { + attributeValue := &commonv1.AnyValue{ + Value: &commonv1.AnyValue_StringValue{StringValue: value}, + } + for _, attribute := range resource.Attributes { + if attribute != nil && attribute.Key == key { + attribute.Value = attributeValue + return + } + } + resource.Attributes = append(resource.Attributes, &commonv1.KeyValue{ + Key: key, + Value: attributeValue, + }) +} diff --git a/internal/tracingproxy/proxy_test.go b/internal/tracingproxy/proxy_test.go new file mode 100644 index 0000000..418a54e --- /dev/null +++ b/internal/tracingproxy/proxy_test.go @@ -0,0 +1,543 @@ +package tracingproxy + +import ( + "bytes" + "context" + "net" + "net/http" + "strings" + "testing" + "time" + + collectortracev1 "go.opentelemetry.io/proto/otlp/collector/trace/v1" + commonv1 "go.opentelemetry.io/proto/otlp/common/v1" + resourcev1 "go.opentelemetry.io/proto/otlp/resource/v1" + tracev1 "go.opentelemetry.io/proto/otlp/trace/v1" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/protobuf/proto" +) + +type captureTraceServer struct { + collectortracev1.UnimplementedTraceServiceServer + requests chan *collectortracev1.ExportTraceServiceRequest +} + +func (s *captureTraceServer) Export(ctx context.Context, req *collectortracev1.ExportTraceServiceRequest) (*collectortracev1.ExportTraceServiceResponse, error) { + s.requests <- req + return &collectortracev1.ExportTraceServiceResponse{}, nil +} + +func TestInjectThreadID(t *testing.T) { + req := &collectortracev1.ExportTraceServiceRequest{ + ResourceSpans: []*tracev1.ResourceSpans{ + { + Resource: &resourcev1.Resource{ + Attributes: []*commonv1.KeyValue{ + {Key: "existing", Value: stringValue("keep")}, + }, + }, + }, + }, + } + + injectThreadID(req, "thread-1") + + resource := req.ResourceSpans[0].Resource + if value, ok := findAttribute(resource, "existing"); !ok || value.GetStringValue() != "keep" { + t.Fatalf("expected existing attribute preserved, got %v", value) + } + if value, ok := findAttribute(resource, threadIDAttributeKey); !ok || value.GetStringValue() != "thread-1" { + t.Fatalf("expected thread id injected, got %v", value) + } + if len(resource.Attributes) != 2 { + t.Fatalf("expected 2 attributes, got %d", len(resource.Attributes)) + } +} + +func TestInjectWorkloadID(t *testing.T) { + req := &collectortracev1.ExportTraceServiceRequest{ + ResourceSpans: []*tracev1.ResourceSpans{ + { + Resource: &resourcev1.Resource{ + Attributes: []*commonv1.KeyValue{ + {Key: "existing", Value: stringValue("keep")}, + }, + }, + }, + }, + } + + injectWorkloadID(req, "workload-1") + + resource := req.ResourceSpans[0].Resource + if value, ok := findAttribute(resource, "existing"); !ok || value.GetStringValue() != "keep" { + t.Fatalf("expected existing attribute preserved, got %v", value) + } + if value, ok := findAttribute(resource, workloadIDAttributeKey); !ok || value.GetStringValue() != "workload-1" { + t.Fatalf("expected workload id injected, got %v", value) + } + if len(resource.Attributes) != 2 { + t.Fatalf("expected 2 attributes, got %d", len(resource.Attributes)) + } +} + +func TestInjectMessageID(t *testing.T) { + req := &collectortracev1.ExportTraceServiceRequest{ + ResourceSpans: []*tracev1.ResourceSpans{ + { + Resource: &resourcev1.Resource{ + Attributes: []*commonv1.KeyValue{ + {Key: "existing", Value: stringValue("keep")}, + }, + }, + ScopeSpans: []*tracev1.ScopeSpans{ + { + Spans: []*tracev1.Span{ + { + Attributes: []*commonv1.KeyValue{{Key: "span.existing", Value: stringValue("keep")}}, + }, + }, + }, + }, + }, + }, + } + + injectMessageID(req, "message-1") + + resource := req.ResourceSpans[0].Resource + if value, ok := findAttribute(resource, "existing"); !ok || value.GetStringValue() != "keep" { + t.Fatalf("expected existing attribute preserved, got %v", value) + } + if value, ok := findAttribute(resource, messageIDAttributeKey); !ok || value.GetStringValue() != "message-1" { + t.Fatalf("expected message id injected, got %v", value) + } + span := req.ResourceSpans[0].ScopeSpans[0].Spans[0] + if value, ok := findSpanAttribute(span, "span.existing"); !ok || value.GetStringValue() != "keep" { + t.Fatalf("expected existing span attribute preserved, got %v", value) + } + if value, ok := findSpanAttribute(span, messageIDAttributeKey); !ok || value.GetStringValue() != "message-1" { + t.Fatalf("expected span message id injected, got %v", value) + } + if len(resource.Attributes) != 2 { + t.Fatalf("expected 2 attributes, got %d", len(resource.Attributes)) + } + if len(span.Attributes) != 2 { + t.Fatalf("expected 2 span attributes, got %d", len(span.Attributes)) + } +} + +func TestInjectThreadIDOverwritesExisting(t *testing.T) { + req := &collectortracev1.ExportTraceServiceRequest{ + ResourceSpans: []*tracev1.ResourceSpans{ + { + Resource: &resourcev1.Resource{ + Attributes: []*commonv1.KeyValue{ + {Key: threadIDAttributeKey, Value: stringValue("old")}, + }, + }, + }, + }, + } + + injectThreadID(req, "new") + + resource := req.ResourceSpans[0].Resource + if len(resource.Attributes) != 1 { + t.Fatalf("expected 1 attribute, got %d", len(resource.Attributes)) + } + value, ok := findAttribute(resource, threadIDAttributeKey) + if !ok || value.GetStringValue() != "new" { + t.Fatalf("expected updated thread id, got %v", value) + } +} + +func TestInjectThreadIDNilResource(t *testing.T) { + req := &collectortracev1.ExportTraceServiceRequest{ + ResourceSpans: []*tracev1.ResourceSpans{{}}, + } + + injectThreadID(req, "thread-2") + + resource := req.ResourceSpans[0].Resource + if resource == nil { + t.Fatal("expected resource to be created") + } + value, ok := findAttribute(resource, threadIDAttributeKey) + if !ok || value.GetStringValue() != "thread-2" { + t.Fatalf("expected injected thread id, got %v", value) + } +} + +func TestInjectThreadIDMultipleResourceSpans(t *testing.T) { + req := &collectortracev1.ExportTraceServiceRequest{ + ResourceSpans: []*tracev1.ResourceSpans{ + {Resource: &resourcev1.Resource{}}, + {Resource: &resourcev1.Resource{}}, + }, + } + + injectThreadID(req, "thread-3") + + for i, span := range req.ResourceSpans { + value, ok := findAttribute(span.Resource, threadIDAttributeKey) + if !ok || value.GetStringValue() != "thread-3" { + t.Fatalf("resource span %d missing thread id", i) + } + } +} + +func TestProxyForwardsToUpstream(t *testing.T) { + server, listener, requests := startCaptureServer(t) + defer server.Stop() + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + + proxy, err := Start(ctx, Config{TracingAddress: listener.Addr().String(), ListenAddress: "127.0.0.1:0", ThreadID: "thread-4", WorkloadID: "workload-4"}) + if err != nil { + t.Fatalf("start proxy: %v", err) + } + defer proxy.Close() + proxy.SetMessageID("message-4") + + conn, err := grpc.NewClient(proxy.Address(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("dial proxy: %v", err) + } + defer conn.Close() + + client := collectortracev1.NewTraceServiceClient(conn) + resp, err := client.Export(ctx, &collectortracev1.ExportTraceServiceRequest{ + ResourceSpans: []*tracev1.ResourceSpans{ + {Resource: &resourcev1.Resource{}}, + }, + }) + if err != nil { + t.Fatalf("export via proxy: %v", err) + } + if resp == nil { + t.Fatal("expected export response") + } + + forwarded := awaitRequest(t, requests) + value, ok := findAttribute(forwarded.ResourceSpans[0].Resource, threadIDAttributeKey) + if !ok || value.GetStringValue() != "thread-4" { + t.Fatalf("expected forwarded request to include thread id, got %v", value) + } + value, ok = findAttribute(forwarded.ResourceSpans[0].Resource, workloadIDAttributeKey) + if !ok || value.GetStringValue() != "workload-4" { + t.Fatalf("expected forwarded request to include workload id, got %v", value) + } + value, ok = findAttribute(forwarded.ResourceSpans[0].Resource, messageIDAttributeKey) + if !ok || value.GetStringValue() != "message-4" { + t.Fatalf("expected forwarded request to include message id, got %v", value) + } +} + +func TestProxyKeepsMessageIDForDelayedExports(t *testing.T) { + server, listener, requests := startCaptureServer(t) + defer server.Stop() + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + + proxy, err := Start(ctx, Config{TracingAddress: listener.Addr().String(), ListenAddress: "127.0.0.1:0", ThreadID: "thread-5"}) + if err != nil { + t.Fatalf("start proxy: %v", err) + } + defer proxy.Close() + + conn, err := grpc.NewClient(proxy.Address(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("dial proxy: %v", err) + } + defer conn.Close() + + client := collectortracev1.NewTraceServiceClient(conn) + proxy.SetMessageID("message-5") + _, err = client.Export(ctx, &collectortracev1.ExportTraceServiceRequest{ + ResourceSpans: []*tracev1.ResourceSpans{{Resource: &resourcev1.Resource{}}}, + }) + if err != nil { + t.Fatalf("export via proxy: %v", err) + } + forwarded := awaitRequest(t, requests) + if value, ok := findAttribute(forwarded.ResourceSpans[0].Resource, messageIDAttributeKey); !ok || value.GetStringValue() != "message-5" { + t.Fatalf("expected forwarded request to include message id, got %v", value) + } + + time.Sleep(25 * time.Millisecond) + _, err = client.Export(ctx, &collectortracev1.ExportTraceServiceRequest{ + ResourceSpans: []*tracev1.ResourceSpans{{Resource: &resourcev1.Resource{}}}, + }) + if err != nil { + t.Fatalf("export via proxy: %v", err) + } + forwarded = awaitRequest(t, requests) + if value, ok := findAttribute(forwarded.ResourceSpans[0].Resource, messageIDAttributeKey); !ok || value.GetStringValue() != "message-5" { + t.Fatalf("expected delayed export to include message id, got %v", value) + } +} + +func TestProxyNextMessageOverwritesMessageID(t *testing.T) { + server, listener, requests := startCaptureServer(t) + defer server.Stop() + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + + proxy, err := Start(ctx, Config{TracingAddress: listener.Addr().String(), ListenAddress: "127.0.0.1:0", ThreadID: "thread-6"}) + if err != nil { + t.Fatalf("start proxy: %v", err) + } + defer proxy.Close() + + conn, err := grpc.NewClient(proxy.Address(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("dial proxy: %v", err) + } + defer conn.Close() + + client := collectortracev1.NewTraceServiceClient(conn) + proxy.SetMessageID("message-6a") + _, err = client.Export(ctx, &collectortracev1.ExportTraceServiceRequest{ + ResourceSpans: []*tracev1.ResourceSpans{{Resource: &resourcev1.Resource{}}}, + }) + if err != nil { + t.Fatalf("export via proxy: %v", err) + } + forwarded := awaitRequest(t, requests) + if value, ok := findAttribute(forwarded.ResourceSpans[0].Resource, messageIDAttributeKey); !ok || value.GetStringValue() != "message-6a" { + t.Fatalf("expected forwarded request to include first message id, got %v", value) + } + + proxy.SetMessageID("message-6b") + _, err = client.Export(ctx, &collectortracev1.ExportTraceServiceRequest{ + ResourceSpans: []*tracev1.ResourceSpans{{Resource: &resourcev1.Resource{}}}, + }) + if err != nil { + t.Fatalf("export via proxy: %v", err) + } + forwarded = awaitRequest(t, requests) + if value, ok := findAttribute(forwarded.ResourceSpans[0].Resource, messageIDAttributeKey); !ok || value.GetStringValue() != "message-6b" { + t.Fatalf("expected forwarded request to include updated message id, got %v", value) + } +} + +// An instance serves many threads, so the proxy starts without one and is told +// which thread each message belongs to as it is handled. +func TestProxySetThreadIDPerMessage(t *testing.T) { + server, listener, requests := startCaptureServer(t) + defer server.Stop() + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + + proxy, err := Start(ctx, Config{TracingAddress: listener.Addr().String(), ListenAddress: "127.0.0.1:0", ThreadID: ""}) + if err != nil { + t.Fatalf("start proxy: %v", err) + } + defer proxy.Close() + + conn, err := grpc.NewClient(proxy.Address(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("dial proxy: %v", err) + } + defer conn.Close() + + client := collectortracev1.NewTraceServiceClient(conn) + for _, threadID := range []string{"thread-a", "thread-b"} { + proxy.SetThreadID(threadID) + if _, err := client.Export(ctx, &collectortracev1.ExportTraceServiceRequest{ + ResourceSpans: []*tracev1.ResourceSpans{{Resource: &resourcev1.Resource{}}}, + }); err != nil { + t.Fatalf("export via proxy: %v", err) + } + forwarded := awaitRequest(t, requests) + if value, ok := findAttribute(forwarded.ResourceSpans[0].Resource, threadIDAttributeKey); !ok || value.GetStringValue() != threadID { + t.Fatalf("expected forwarded request to carry thread %q, got %v", threadID, value) + } + } +} + +func TestProxyNoThreadIDPassthrough(t *testing.T) { + server, listener, requests := startCaptureServer(t) + defer server.Stop() + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + + proxy, err := Start(ctx, Config{TracingAddress: listener.Addr().String(), ListenAddress: "127.0.0.1:0", ThreadID: ""}) + if err != nil { + t.Fatalf("start proxy: %v", err) + } + defer proxy.Close() + + conn, err := grpc.NewClient(proxy.Address(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("dial proxy: %v", err) + } + defer conn.Close() + + client := collectortracev1.NewTraceServiceClient(conn) + _, err = client.Export(ctx, &collectortracev1.ExportTraceServiceRequest{ + ResourceSpans: []*tracev1.ResourceSpans{ + {Resource: &resourcev1.Resource{Attributes: []*commonv1.KeyValue{{Key: "existing", Value: stringValue("keep")}}}}, + }, + }) + if err != nil { + t.Fatalf("export via proxy: %v", err) + } + + forwarded := awaitRequest(t, requests) + if _, ok := findAttribute(forwarded.ResourceSpans[0].Resource, threadIDAttributeKey); ok { + t.Fatal("expected no thread id injected") + } + if _, ok := findAttribute(forwarded.ResourceSpans[0].Resource, workloadIDAttributeKey); ok { + t.Fatal("expected no workload id injected") + } + value, ok := findAttribute(forwarded.ResourceSpans[0].Resource, "existing") + if !ok || value.GetStringValue() != "keep" { + t.Fatalf("expected passthrough attribute, got %v", value) + } +} + +func startCaptureServer(t *testing.T) (*grpc.Server, net.Listener, chan *collectortracev1.ExportTraceServiceRequest) { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + server := grpc.NewServer() + requests := make(chan *collectortracev1.ExportTraceServiceRequest, 1) + collectortracev1.RegisterTraceServiceServer(server, &captureTraceServer{requests: requests}) + go func() { + _ = server.Serve(listener) + }() + return server, listener, requests +} + +func awaitRequest(t *testing.T, requests <-chan *collectortracev1.ExportTraceServiceRequest) *collectortracev1.ExportTraceServiceRequest { + t.Helper() + select { + case req := <-requests: + return req + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for forwarded request") + return nil + } +} + +func stringValue(value string) *commonv1.AnyValue { + return &commonv1.AnyValue{ + Value: &commonv1.AnyValue_StringValue{StringValue: value}, + } +} + +func findAttribute(resource *resourcev1.Resource, key string) (*commonv1.AnyValue, bool) { + if resource == nil { + return nil, false + } + for _, attribute := range resource.Attributes { + if attribute != nil && attribute.Key == key { + return attribute.Value, true + } + } + return nil, false +} + +func findSpanAttribute(span *tracev1.Span, key string) (*commonv1.AnyValue, bool) { + if span == nil { + return nil, false + } + for _, attribute := range span.Attributes { + if attribute != nil && attribute.Key == key { + return attribute.Value, true + } + } + return nil, false +} + +// Codex exports over OTLP/HTTP because its gRPC exporter will not build, so the +// proxy has to accept that encoding as well and enrich it identically -- a +// forwarder that only spoke gRPC left codex unable to start at all. +func TestProxyForwardsOTLPOverHTTP(t *testing.T) { + server, listener, requests := startCaptureServer(t) + defer server.Stop() + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + proxy, err := Start(ctx, Config{TracingAddress: listener.Addr().String(), ListenAddress: "127.0.0.1:0", ThreadID: "thread-http", WorkloadID: "workload-http"}) + if err != nil { + t.Fatalf("start proxy: %v", err) + } + defer proxy.Close() + proxy.SetMessageID("message-http") + + if proxy.HTTPAddress() == "" || proxy.HTTPAddress() == proxy.Address() { + t.Fatalf("expected a distinct OTLP/HTTP address, got %q and %q", proxy.HTTPAddress(), proxy.Address()) + } + + body, err := proto.Marshal(&collectortracev1.ExportTraceServiceRequest{ + ResourceSpans: []*tracev1.ResourceSpans{{Resource: &resourcev1.Resource{}}}, + }) + if err != nil { + t.Fatalf("marshal request: %v", err) + } + request, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://"+proxy.HTTPAddress()+"/v1/traces", bytes.NewReader(body)) + if err != nil { + t.Fatalf("build request: %v", err) + } + request.Header.Set("Content-Type", "application/x-protobuf") + response, err := http.DefaultClient.Do(request) + if err != nil { + t.Fatalf("post traces: %v", err) + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + t.Fatalf("expected 200, got %d", response.StatusCode) + } + + forwarded := awaitRequest(t, requests) + for key, want := range map[string]string{ + threadIDAttributeKey: "thread-http", + workloadIDAttributeKey: "workload-http", + messageIDAttributeKey: "message-http", + } { + value, ok := findAttribute(forwarded.ResourceSpans[0].Resource, key) + if !ok || value.GetStringValue() != want { + t.Fatalf("expected %s=%s, got %v", key, want, value) + } + } +} + +// A body that is not an OTLP request is the client's error, not the upstream's. +func TestProxyRejectsMalformedHTTPBody(t *testing.T) { + server, listener, _ := startCaptureServer(t) + defer server.Stop() + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + proxy, err := Start(ctx, Config{TracingAddress: listener.Addr().String(), ListenAddress: "127.0.0.1:0"}) + if err != nil { + t.Fatalf("start proxy: %v", err) + } + defer proxy.Close() + + request, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://"+proxy.HTTPAddress()+"/v1/traces", strings.NewReader("not protobuf at all")) + if err != nil { + t.Fatalf("build request: %v", err) + } + response, err := http.DefaultClient.Do(request) + if err != nil { + t.Fatalf("post traces: %v", err) + } + defer response.Body.Close() + if response.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400, got %d", response.StatusCode) + } +} diff --git a/internal/tracingproxy/semantic.go b/internal/tracingproxy/semantic.go new file mode 100644 index 0000000..6ccf846 --- /dev/null +++ b/internal/tracingproxy/semantic.go @@ -0,0 +1,333 @@ +package tracingproxy + +import ( + "crypto/rand" + "crypto/sha256" + "strconv" + "strings" + "time" + + collectorlogsv1 "go.opentelemetry.io/proto/otlp/collector/logs/v1" + commonv1 "go.opentelemetry.io/proto/otlp/common/v1" + logsv1 "go.opentelemetry.io/proto/otlp/logs/v1" + tracev1 "go.opentelemetry.io/proto/otlp/trace/v1" +) + +// Codex ships its structured events on the OTLP log signal, which nothing here +// stores: the tracing service speaks traces alone. These are the events worth +// keeping, translated into the span vocabulary the run view already renders. +const ( + eventUserPrompt = "codex.user_prompt" + eventAPIRequest = "codex.api_request" + eventSSE = "codex.sse_event" + + spanInvocationMessage = "invocation.message" + spanLLMCall = "llm.call" + + // Names the spans this proxy synthesised, as distinct from the ones codex + // exported itself. + semanticScopeName = "agynd.codex.semantic" + + sseResponseCompleted = "response.completed" +) + +type logAttrs map[string]*commonv1.AnyValue + +func attrsOf(record *logsv1.LogRecord) logAttrs { + attrs := make(logAttrs, len(record.Attributes)) + for _, attr := range record.Attributes { + attrs[attr.Key] = attr.Value + } + return attrs +} + +func (a logAttrs) str(key string) string { + value, ok := a[key] + if !ok || value == nil { + return "" + } + switch v := value.Value.(type) { + case *commonv1.AnyValue_StringValue: + return v.StringValue + case *commonv1.AnyValue_IntValue: + return strconv.FormatInt(v.IntValue, 10) + case *commonv1.AnyValue_BoolValue: + return strconv.FormatBool(v.BoolValue) + } + return "" +} + +// Codex is inconsistent about whether a count is an int or a decimal string -- +// input_token_count arrives as a string while cached_token_count is an int -- +// so both spellings are read. +func (a logAttrs) int(key string) (int64, bool) { + value, ok := a[key] + if !ok || value == nil { + return 0, false + } + switch v := value.Value.(type) { + case *commonv1.AnyValue_IntValue: + return v.IntValue, true + case *commonv1.AnyValue_StringValue: + parsed, err := strconv.ParseInt(strings.TrimSpace(v.StringValue), 10, 64) + if err != nil { + return 0, false + } + return parsed, true + } + return 0, false +} + +func (a logAttrs) eventTime(fallback uint64) uint64 { + raw := a.str("event.timestamp") + if raw == "" { + return fallback + } + parsed, err := time.Parse(time.RFC3339Nano, raw) + if err != nil { + return fallback + } + return uint64(parsed.UnixNano()) +} + +func stringAttr(key, value string) *commonv1.KeyValue { + return &commonv1.KeyValue{ + Key: key, + Value: &commonv1.AnyValue{Value: &commonv1.AnyValue_StringValue{StringValue: value}}, + } +} + +func intAttr(key string, value int64) *commonv1.KeyValue { + return &commonv1.KeyValue{ + Key: key, + Value: &commonv1.AnyValue{Value: &commonv1.AnyValue_IntValue{IntValue: value}}, + } +} + +// traceIDForMessage keeps every span of one message in one trace. Codex opens a +// fresh trace per JSON-RPC call, so its own ids scatter a single turn across +// dozens; the message is the unit the run view shows. +func traceIDForMessage(seed string) []byte { + sum := sha256.Sum256([]byte("agyn.trace." + seed)) + return sum[:16] +} + +func newSpanID() []byte { + id := make([]byte, 8) + if _, err := rand.Read(id); err != nil { + // A collision only merges two spans in the upsert; refusing to emit + // loses the event outright, so a time-derived id is the better failure. + now := uint64(time.Now().UnixNano()) + for i := range id { + id[i] = byte(now >> (8 * i)) + } + } + return id +} + +// pendingLLMCall is held so the usage counts, which arrive on a later event than +// the request itself, can be written onto the same span. Ingest upserts on +// (trace_id, span_id) and replaces the attributes wholesale, so the span is +// re-emitted complete rather than patched. +type pendingLLMCall struct { + span *tracev1.Span +} + +// semanticSpans translates one OTLP log export into the spans the run view +// renders. Records it has no mapping for are dropped rather than passed +// through: the raw event is already in the container log, and a span per SSE +// delta is the noise this is meant to remove. +func (p *Proxy) semanticSpans(request *collectorlogsv1.ExportLogsServiceRequest) []*tracev1.Span { + var spans []*tracev1.Span + for _, resourceLogs := range request.GetResourceLogs() { + for _, scopeLogs := range resourceLogs.GetScopeLogs() { + for _, record := range scopeLogs.GetLogRecords() { + attrs := attrsOf(record) + span := p.spanForRecord(record, attrs) + if span != nil { + spans = append(spans, span) + continue + } + if name := attrs.str("event.name"); name != "" && name != eventSSE { + logUntranslatedRecord(record, name) + } + } + } + } + return spans +} + +func (p *Proxy) spanForRecord(record *logsv1.LogRecord, attrs logAttrs) *tracev1.Span { + switch attrs.str("event.name") { + case eventUserPrompt: + return p.messageSpan(record, attrs) + case eventAPIRequest: + return p.llmCallSpan(record, attrs) + case eventSSE: + if attrs.str("event.kind") != sseResponseCompleted { + return nil + } + return p.llmCallUsageSpan(attrs) + } + return nil +} + +// traceSeed prefers the message the daemon is processing, so a turn's spans +// group the way the run view reads them, and falls back to codex's own +// conversation when no message is set -- a sandbox has no message at all. +func (p *Proxy) traceSeed(attrs logAttrs) string { + if messageID := p.messageIDValue(); messageID != "" { + return messageID + } + return attrs.str("conversation.id") +} + +func (p *Proxy) messageSpan(record *logsv1.LogRecord, attrs logAttrs) *tracev1.Span { + at := attrs.eventTime(record.GetTimeUnixNano()) + span := &tracev1.Span{ + TraceId: traceIDForMessage(p.traceSeed(attrs)), + SpanId: newSpanID(), + Name: spanInvocationMessage, + Kind: tracev1.Span_SPAN_KIND_INTERNAL, + StartTimeUnixNano: at, + EndTimeUnixNano: at, + Attributes: []*commonv1.KeyValue{ + stringAttr("agyn.message.role", "user"), + stringAttr("agyn.message.text", attrs.str("prompt")), + }, + Status: &tracev1.Status{Code: tracev1.Status_STATUS_CODE_OK}, + } + if length, ok := attrs.int("prompt_length"); ok { + span.Attributes = append(span.Attributes, intAttr("agyn.message.length", length)) + } + p.rememberMessage(attrs.str("conversation.id"), span) + return span +} + +func (p *Proxy) llmCallSpan(record *logsv1.LogRecord, attrs logAttrs) *tracev1.Span { + end := attrs.eventTime(record.GetTimeUnixNano()) + start := end + if duration, ok := attrs.int("duration_ms"); ok && duration > 0 { + start = end - uint64(duration)*uint64(time.Millisecond) + } + // The call belongs to the message being answered, so it hangs off it: the + // run view then reads in the order things happened rather than trusting a + // start this proxy derives by subtracting a duration codex reports. + parent := p.messageSpanFor(attrs.str("conversation.id")) + var parentID []byte + if parent != nil { + parentID = parent.SpanId + if start < parent.StartTimeUnixNano { + start = parent.StartTimeUnixNano + } + } + span := &tracev1.Span{ + TraceId: traceIDForMessage(p.traceSeed(attrs)), + SpanId: newSpanID(), + ParentSpanId: parentID, + Name: spanLLMCall, + Kind: tracev1.Span_SPAN_KIND_CLIENT, + StartTimeUnixNano: start, + EndTimeUnixNano: end, + Attributes: []*commonv1.KeyValue{ + stringAttr("gen_ai.system", attrs.str("provider_name")), + stringAttr("gen_ai.request.model", attrs.str("model")), + stringAttr("agyn.llm.endpoint", attrs.str("endpoint")), + }, + Status: &tracev1.Status{Code: tracev1.Status_STATUS_CODE_OK}, + } + if status, ok := attrs.int("http.response.status_code"); ok { + span.Attributes = append(span.Attributes, intAttr("http.response.status_code", status)) + if status >= 400 { + span.Status = &tracev1.Status{Code: tracev1.Status_STATUS_CODE_ERROR} + } + } + if attempt, ok := attrs.int("attempt"); ok { + span.Attributes = append(span.Attributes, intAttr("agyn.llm.attempt", attempt)) + } + if message := attrs.str("error.message"); message != "" { + span.Status = &tracev1.Status{Code: tracev1.Status_STATUS_CODE_ERROR, Message: message} + } + p.rememberLLMCall(attrs.str("conversation.id"), span) + return span +} + +// llmCallUsageSpan re-emits the call this usage belongs to. Without the +// remembered span there is nothing to attach to -- usage alone is not a call -- +// so the record is dropped. +func (p *Proxy) llmCallUsageSpan(attrs logAttrs) *tracev1.Span { + usage := []struct { + source string + key string + }{ + {"input_token_count", "gen_ai.usage.input_tokens"}, + {"output_token_count", "gen_ai.usage.output_tokens"}, + {"cached_token_count", "gen_ai.usage.cache_read.input_tokens"}, + {"reasoning_token_count", "agyn.usage.reasoning_tokens"}, + } + counted := make([]*commonv1.KeyValue, 0, len(usage)) + for _, entry := range usage { + if value, ok := attrs.int(entry.source); ok { + counted = append(counted, intAttr(entry.key, value)) + } + } + // Codex completes a response twice: once to end the stream, and again + // carrying the counts. Taking the call on the first would spend it on the + // record that has nothing to add and leave the counts nowhere to land. + if len(counted) == 0 { + return nil + } + pending := p.takeLLMCall(attrs.str("conversation.id")) + if pending == nil { + return nil + } + pending.span.Attributes = append(pending.span.Attributes, counted...) + return pending.span +} + +func (p *Proxy) rememberMessage(conversationID string, span *tracev1.Span) { + if conversationID == "" { + return + } + p.llmCallMu.Lock() + defer p.llmCallMu.Unlock() + if p.messageSpans == nil { + p.messageSpans = make(map[string]*tracev1.Span, 1) + } + p.messageSpans[conversationID] = span +} + +func (p *Proxy) messageSpanFor(conversationID string) *tracev1.Span { + if conversationID == "" { + return nil + } + p.llmCallMu.Lock() + defer p.llmCallMu.Unlock() + return p.messageSpans[conversationID] +} + +func (p *Proxy) rememberLLMCall(conversationID string, span *tracev1.Span) { + if conversationID == "" { + return + } + p.llmCallMu.Lock() + defer p.llmCallMu.Unlock() + if p.llmCalls == nil { + p.llmCalls = make(map[string]*pendingLLMCall, 1) + } + p.llmCalls[conversationID] = &pendingLLMCall{span: span} +} + +func (p *Proxy) takeLLMCall(conversationID string) *pendingLLMCall { + if conversationID == "" { + return nil + } + p.llmCallMu.Lock() + defer p.llmCallMu.Unlock() + pending, ok := p.llmCalls[conversationID] + if !ok { + return nil + } + delete(p.llmCalls, conversationID) + return pending +} diff --git a/internal/tracingproxy/semantic_test.go b/internal/tracingproxy/semantic_test.go new file mode 100644 index 0000000..b2a0b21 --- /dev/null +++ b/internal/tracingproxy/semantic_test.go @@ -0,0 +1,233 @@ +package tracingproxy + +import ( + "testing" + + collectorlogsv1 "go.opentelemetry.io/proto/otlp/collector/logs/v1" + commonv1 "go.opentelemetry.io/proto/otlp/common/v1" + logsv1 "go.opentelemetry.io/proto/otlp/logs/v1" + tracev1 "go.opentelemetry.io/proto/otlp/trace/v1" +) + +func logRecord(attrs ...*commonv1.KeyValue) *logsv1.LogRecord { + return &logsv1.LogRecord{Attributes: attrs} +} + +func logExport(records ...*logsv1.LogRecord) *collectorlogsv1.ExportLogsServiceRequest { + return &collectorlogsv1.ExportLogsServiceRequest{ + ResourceLogs: []*logsv1.ResourceLogs{{ + ScopeLogs: []*logsv1.ScopeLogs{{LogRecords: records}}, + }}, + } +} + +func spanAttr(t *testing.T, span *tracev1.Span, key string) *commonv1.AnyValue { + t.Helper() + for _, attr := range span.Attributes { + if attr.Key == key { + return attr.Value + } + } + return nil +} + +func requireStringAttr(t *testing.T, span *tracev1.Span, key, want string) { + t.Helper() + value := spanAttr(t, span, key) + if value == nil { + t.Fatalf("expected attribute %q on %s", key, span.Name) + } + if got := value.GetStringValue(); got != want { + t.Fatalf("expected %s=%q, got %q", key, want, got) + } +} + +func requireIntAttr(t *testing.T, span *tracev1.Span, key string, want int64) { + t.Helper() + value := spanAttr(t, span, key) + if value == nil { + t.Fatalf("expected attribute %q on %s", key, span.Name) + } + if got := value.GetIntValue(); got != want { + t.Fatalf("expected %s=%d, got %d", key, want, got) + } +} + +func TestSemanticSpansTranslatesUserPrompt(t *testing.T) { + proxy := &Proxy{} + spans := proxy.semanticSpans(logExport(logRecord( + stringAttr("event.name", eventUserPrompt), + stringAttr("prompt", "hello"), + stringAttr("prompt_length", "67"), + stringAttr("conversation.id", "conv-1"), + stringAttr("event.timestamp", "2026-08-09T00:48:22.310Z"), + ))) + + if len(spans) != 1 { + t.Fatalf("expected 1 span, got %d", len(spans)) + } + if spans[0].Name != spanInvocationMessage { + t.Fatalf("expected %s, got %s", spanInvocationMessage, spans[0].Name) + } + requireStringAttr(t, spans[0], "agyn.message.text", "hello") + requireStringAttr(t, spans[0], "agyn.message.role", "user") + // prompt_length arrives as a decimal string, not an int. + requireIntAttr(t, spans[0], "agyn.message.length", 67) + if spans[0].StartTimeUnixNano == 0 { + t.Fatal("expected the event timestamp to be parsed") + } +} + +func TestSemanticSpansTranslatesAPIRequest(t *testing.T) { + proxy := &Proxy{} + spans := proxy.semanticSpans(logExport(logRecord( + stringAttr("event.name", eventAPIRequest), + stringAttr("provider_name", "Agyn LLM"), + stringAttr("model", "gpt-5.5"), + stringAttr("endpoint", "/responses"), + intAttr("http.response.status_code", 200), + stringAttr("duration_ms", "1551"), + intAttr("attempt", 0), + stringAttr("conversation.id", "conv-1"), + stringAttr("event.timestamp", "2026-08-09T00:48:23.889Z"), + ))) + + if len(spans) != 1 || spans[0].Name != spanLLMCall { + t.Fatalf("expected one %s span, got %#v", spanLLMCall, spans) + } + requireStringAttr(t, spans[0], "gen_ai.request.model", "gpt-5.5") + requireStringAttr(t, spans[0], "gen_ai.system", "Agyn LLM") + requireIntAttr(t, spans[0], "http.response.status_code", 200) + // duration_ms is a string; the span still has to span the call. + if spans[0].EndTimeUnixNano-spans[0].StartTimeUnixNano != 1551*1_000_000 { + t.Fatalf("expected a 1551ms span, got %d ns", spans[0].EndTimeUnixNano-spans[0].StartTimeUnixNano) + } + if spans[0].Status.GetCode() != tracev1.Status_STATUS_CODE_OK { + t.Fatalf("expected a 200 to be OK, got %v", spans[0].Status.GetCode()) + } +} + +// The counts arrive on a later event than the call, so the call is re-emitted +// with the same ids and ingest upserts it. +func TestSemanticSpansAttachesUsageToTheCall(t *testing.T) { + proxy := &Proxy{} + call := proxy.semanticSpans(logExport(logRecord( + stringAttr("event.name", eventAPIRequest), + stringAttr("model", "gpt-5.5"), + stringAttr("conversation.id", "conv-1"), + stringAttr("event.timestamp", "2026-08-09T00:48:23.889Z"), + ))) + if len(call) != 1 { + t.Fatalf("expected the call span, got %d", len(call)) + } + + // Codex completes the response twice; only the second carries counts, and + // the first must not spend the pending call. + if empty := proxy.semanticSpans(logExport(logRecord( + stringAttr("event.name", eventSSE), + stringAttr("event.kind", sseResponseCompleted), + stringAttr("conversation.id", "conv-1"), + ))); len(empty) != 0 { + t.Fatalf("expected a completion with no counts to emit nothing, got %d", len(empty)) + } + + usage := proxy.semanticSpans(logExport(logRecord( + stringAttr("event.name", eventSSE), + stringAttr("event.kind", sseResponseCompleted), + stringAttr("input_token_count", "8607"), + stringAttr("output_token_count", "11"), + intAttr("cached_token_count", 0), + intAttr("reasoning_token_count", 0), + stringAttr("conversation.id", "conv-1"), + ))) + if len(usage) != 1 { + t.Fatalf("expected the call re-emitted with usage, got %d", len(usage)) + } + if string(usage[0].SpanId) != string(call[0].SpanId) { + t.Fatal("expected usage to land on the same span the call was emitted as") + } + requireIntAttr(t, usage[0], "gen_ai.usage.input_tokens", 8607) + requireIntAttr(t, usage[0], "gen_ai.usage.output_tokens", 11) + requireIntAttr(t, usage[0], "gen_ai.usage.cache_read.input_tokens", 0) +} + +func TestSemanticSpansDropsSSEDeltasAndUnpairedUsage(t *testing.T) { + proxy := &Proxy{} + spans := proxy.semanticSpans(logExport( + logRecord( + stringAttr("event.name", eventSSE), + stringAttr("event.kind", "response.output_text.delta"), + stringAttr("conversation.id", "conv-1"), + ), + // Usage with no call before it describes nothing on its own. + logRecord( + stringAttr("event.name", eventSSE), + stringAttr("event.kind", sseResponseCompleted), + stringAttr("input_token_count", "10"), + stringAttr("conversation.id", "conv-unknown"), + ), + )) + if len(spans) != 0 { + t.Fatalf("expected no spans, got %#v", spans) + } +} + +// A turn is one trace, whatever codex does with its own trace ids. +func TestSemanticSpansGroupSpansByMessage(t *testing.T) { + proxy := &Proxy{} + proxy.SetMessageID("message-1") + spans := proxy.semanticSpans(logExport( + logRecord( + stringAttr("event.name", eventUserPrompt), + stringAttr("prompt", "hello"), + stringAttr("conversation.id", "conv-1"), + ), + logRecord( + stringAttr("event.name", eventAPIRequest), + stringAttr("model", "gpt-5.5"), + stringAttr("conversation.id", "conv-2"), + ), + )) + if len(spans) != 2 { + t.Fatalf("expected 2 spans, got %d", len(spans)) + } + if string(spans[0].TraceId) != string(spans[1].TraceId) { + t.Fatal("expected both spans in the message's trace, despite different conversations") + } + if len(spans[0].TraceId) != 16 || len(spans[0].SpanId) != 8 { + t.Fatalf("expected OTLP id widths, got trace=%d span=%d", len(spans[0].TraceId), len(spans[0].SpanId)) + } +} + +// The call answers the message, so it hangs off it rather than relying on a +// start derived by subtracting codex's reported duration. +func TestSemanticSpansParentTheCallToItsMessage(t *testing.T) { + proxy := &Proxy{} + message := proxy.semanticSpans(logExport(logRecord( + stringAttr("event.name", eventUserPrompt), + stringAttr("prompt", "hello"), + stringAttr("conversation.id", "conv-1"), + stringAttr("event.timestamp", "2026-08-09T00:48:22.310Z"), + ))) + if len(message) != 1 { + t.Fatalf("expected the message span, got %d", len(message)) + } + + // A duration long enough to place the call before the message it answers. + call := proxy.semanticSpans(logExport(logRecord( + stringAttr("event.name", eventAPIRequest), + stringAttr("model", "gpt-5.5"), + stringAttr("duration_ms", "5000"), + stringAttr("conversation.id", "conv-1"), + stringAttr("event.timestamp", "2026-08-09T00:48:23.889Z"), + ))) + if len(call) != 1 { + t.Fatalf("expected the call span, got %d", len(call)) + } + if string(call[0].ParentSpanId) != string(message[0].SpanId) { + t.Fatal("expected the call to hang off the message it answers") + } + if call[0].StartTimeUnixNano < message[0].StartTimeUnixNano { + t.Fatal("expected the call not to open before the message it answers") + } +}