Fully autonomous AI Agents system capable of performing complex penetration testing tasks
Go ai-agentsai-security-toolanthropicautonomous-agentsgolanggptgraphqlmulti-agent-systemoffensive-securityopen-sourceopenaipenetration-testingpenetration-testing-toolsreactsecurity-automationsecurity-testingsecurity-toolsself-hosted
fix(observability,flows): drain telemetry sinks in parallel, stop leaking docker errors, dedup listing failures
Sergey Kozyrenko2c524faea96b
diff --git a/backend/cmd/pentagi/main.go b/backend/cmd/pentagi/main.goindex 00ab153d..435a78ac 100644--- a/backend/cmd/pentagi/main.go+++ b/backend/cmd/pentagi/main.go@@ -173,28 +173,13 @@ func main() {select {case <-ctx.Done():logrus.Warn("Shutdown signal received, cleaning up resources...")- // ctx is already cancelled here, so drain telemetry on a fresh deadline.- // Flush before Shutdown: langfuse's Shutdown cancels without flushing, so its- // final batch drains only via Flush. The drain runs in a goroutine bounded by- // the select below because a provider Shutdown can ignore a spent context and- // block on its own — an unreachable collector must not stall process exit.- flushCtx, cancelFlush := context.WithTimeout(context.Background(), 5*time.Second)- drained := make(chan struct{})- go func() {- defer close(drained)- if err := obs.Observer.Flush(flushCtx); err != nil {- logrus.WithError(err).Warn("Telemetry flush incomplete")- }- if err := obs.Observer.Shutdown(flushCtx); err != nil {- logrus.WithError(err).Warn("Telemetry shutdown incomplete")- }- }()- select {- case <-drained:- case <-flushCtx.Done():- logrus.Warn("Telemetry cleanup exceeded its deadline")+ // ctx is already cancelled here — drain telemetry on a fresh deadline so the+ // final batch still reaches the collector before the process exits.+ drainCtx, cancelDrain := context.WithTimeout(context.Background(), 5*time.Second)+ if err := obs.Observer.Drain(drainCtx); err != nil {+ logrus.WithError(err).Warn("Telemetry drain incomplete")}- cancelFlush()+ cancelDrain()case err := <-serverErrChan:logrus.Fatalf("Server terminated unexpectedly: %v", err)}diff --git a/backend/pkg/docker/client.go b/backend/pkg/docker/client.goindex b1970e1c..18ac9862 100644--- a/backend/pkg/docker/client.go+++ b/backend/pkg/docker/client.go@@ -46,6 +46,10 @@ const (// so a hostile /work with hundreds of thousands of files can't fan out into// that many Docker API calls per request.maxListEntries = 10000+ // maxListStdoutBytes bounds the exec stdout buffered before parsing so a+ // compromised sandbox can't stream unbounded output into memory; sized as the+ // entry cap × a generous per-path length (PATH_MAX).+ maxListStdoutBytes = maxListEntries * 4096)type dockerClient struct {@@ -710,6 +714,9 @@ func demuxExecStdout(r io.Reader) ([]byte, error) {if _, err := io.CopyN(sink, r, size); err != nil {return nil, err}+ if stdout.Len() > maxListStdoutBytes {+ return nil, fmt.Errorf("listing output exceeded %d bytes", maxListStdoutBytes)+ }}return stdout.Bytes(), nil}diff --git a/backend/pkg/observability/drain_starvation_test.go b/backend/pkg/observability/drain_starvation_test.gonew file mode 100644index 00000000..e5bb2ffb--- /dev/null+++ b/backend/pkg/observability/drain_starvation_test.go@@ -0,0 +1,114 @@+package observability++import (+ "context"+ "net"+ "sync/atomic"+ "testing"+ "time"++ "pentagi/pkg/config"+ "pentagi/pkg/observability/langfuse"++ collogsv1 "go.opentelemetry.io/proto/otlp/collector/logs/v1"+ colmetricsv1 "go.opentelemetry.io/proto/otlp/collector/metrics/v1"+ coltracev1 "go.opentelemetry.io/proto/otlp/collector/trace/v1"+ "google.golang.org/grpc"+)++type recordingTraceCollector struct {+ coltracev1.UnimplementedTraceServiceServer+ spanBatches int32+}++func (r *recordingTraceCollector) Export(context.Context, *coltracev1.ExportTraceServiceRequest) (*coltracev1.ExportTraceServiceResponse, error) {+ atomic.AddInt32(&r.spanBatches, 1)+ return &coltracev1.ExportTraceServiceResponse{}, nil+}++// blockingLangfuse models the real langfuse leg: ForceFlush/Shutdown ignore the+// passed ctx and block on the observer's own machinery, so a pending batch against+// a down endpoint blocks past the drain budget.+type blockingLangfuse struct {+ release chan struct{}+ flushCalls int32+}++func (b *blockingLangfuse) API() langfuse.Client { return langfuse.Client{} }+func (b *blockingLangfuse) Observer() langfuse.Observer { return langfuse.NewNoopObserver() }+func (b *blockingLangfuse) ForceFlush(context.Context) error {+ atomic.AddInt32(&b.flushCalls, 1)+ <-b.release+ return nil+}+func (b *blockingLangfuse) Shutdown(context.Context) error {+ <-b.release+ return nil+}++func newRecordingOtel(t *testing.T) (*telemetryClient, *recordingTraceCollector) {+ t.Helper()+ ln, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatalf("listen: %v", err)+ }+ rec := &recordingTraceCollector{}+ srv := grpc.NewServer()+ collogsv1.RegisterLogsServiceServer(srv, fakeLogsCollector{})+ colmetricsv1.RegisterMetricsServiceServer(srv, fakeMetricsCollector{})+ coltracev1.RegisterTraceServiceServer(srv, rec)+ go func() { _ = srv.Serve(ln) }()+ t.Cleanup(srv.Stop)++ tc, err := NewTelemetryClient(context.Background(), &config.Config{TelemetryEndpoint: ln.Addr().String()})+ if err != nil {+ t.Fatalf("NewTelemetryClient: %v", err)+ }+ return tc.(*telemetryClient), rec+}++func bufferOneSpan(o *observer) {+ _, span := o.otelclient.Tracer().Tracer("drain-test").Start(context.Background(), "s")+ span.End()+}++// A healthy otel sink is delivered even while an unhealthy langfuse sink blocks.+func TestObserverDrain_DeliversOtelDespiteBlockedLangfuse(t *testing.T) {+ otel, rec := newRecordingOtel(t)+ lf := &blockingLangfuse{release: make(chan struct{})}+ t.Cleanup(func() { close(lf.release) })++ obs := &observer{lfclient: lf, otelclient: otel}+ bufferOneSpan(obs)++ ctx, cancel := context.WithTimeout(context.Background(), 800*time.Millisecond)+ defer cancel()+ _ = obs.Drain(ctx)++ if atomic.LoadInt32(&lf.flushCalls) == 0 {+ t.Fatal("precondition: langfuse ForceFlush should have been attempted")+ }+ if got := atomic.LoadInt32(&rec.spanBatches); got != 1 {+ t.Fatalf("otel span must be delivered despite a blocked langfuse; got %d export batches", got)+ }+}++func TestObserverDrain_ReturnsWithinDeadlineWhenSinkBlocks(t *testing.T) {+ otel, _ := newRecordingOtel(t)+ lf := &blockingLangfuse{release: make(chan struct{})}+ t.Cleanup(func() { close(lf.release) })++ obs := &observer{lfclient: lf, otelclient: otel}++ start := time.Now()+ ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)+ defer cancel()+ err := obs.Drain(ctx)++ if elapsed := time.Since(start); elapsed > time.Second {+ t.Fatalf("Drain hung past its deadline: %v", elapsed)+ }+ if err == nil {+ t.Fatal("Drain should report the deadline was hit while a sink was blocked")+ }+}diff --git a/backend/pkg/observability/obs.go b/backend/pkg/observability/obs.goindex d3095912..7c0a857b 100644--- a/backend/pkg/observability/obs.go+++ b/backend/pkg/observability/obs.go@@ -80,6 +80,7 @@ var Observer Observabilitytype Observability interface {Flush(ctx context.Context) errorShutdown(ctx context.Context) error+ Drain(ctx context.Context) errorMeterTracerCollector@@ -230,6 +231,53 @@ func (obs *observer) Shutdown(ctx context.Context) error {return errors.Join(errs...)}+// Drain flushes then shuts down every telemetry sink, each in its own goroutine,+// bounded by ctx. Draining concurrently (not serially like Flush/Shutdown) is+// load-bearing: a sink can ignore ctx and block on its own timeout — langfuse's+// ForceFlush/Shutdown do — so a serial drain lets one unhealthy sink burn the+// whole budget and starve a healthy one. On deadline the still-blocked sink is+// abandoned (the process is exiting), rather than holding up shutdown.+func (obs *observer) Drain(ctx context.Context) error {+ type sink struct {+ name string+ flush, shutdown func(context.Context) error+ }+ var sinks []sink+ if obs.lfclient != nil {+ sinks = append(sinks, sink{"langfuse", obs.lfclient.ForceFlush, obs.lfclient.Shutdown})+ }+ if obs.otelclient != nil {+ sinks = append(sinks, sink{"opentelemetry", obs.otelclient.ForceFlush, obs.otelclient.Shutdown})+ }++ results := make(chan error, len(sinks))+ for _, s := range sinks {+ go func(s sink) {+ var errs []error+ if err := s.flush(ctx); err != nil {+ errs = append(errs, fmt.Errorf("%s flush: %w", s.name, err))+ }+ if err := s.shutdown(ctx); err != nil {+ errs = append(errs, fmt.Errorf("%s shutdown: %w", s.name, err))+ }+ results <- errors.Join(errs...)+ }(s)+ }++ var errs []error+ for range sinks {+ select {+ case err := <-results:+ if err != nil {+ errs = append(errs, err)+ }+ case <-ctx.Done():+ return errors.Join(append(errs, ctx.Err())...)+ }+ }+ return errors.Join(errs...)+}+func (obs *observer) StartProcessMetricCollect(attrs ...attribute.KeyValue) error {if obs.meter == nil {return nildiff --git a/backend/pkg/server/services/flow_files.go b/backend/pkg/server/services/flow_files.goindex 26155ae0..cae13891 100644--- a/backend/pkg/server/services/flow_files.go+++ b/backend/pkg/server/services/flow_files.go@@ -25,6 +25,7 @@ import ("pentagi/pkg/server/models""pentagi/pkg/server/response""pentagi/pkg/tools"+ "pentagi/pkg/version""github.com/docker/docker/api/types/container""github.com/gin-gonic/gin"@@ -968,6 +969,18 @@ func (s *FlowFileService) GetFlowContainerFiles(c *gin.Context) {allFiles := make([]models.ContainerFile, 0)allFailures := make([]models.ContainerFileError, 0)+ // The client-facing failure Message is generic unless running in develop mode:+ // the raw error carries docker-layer detail (container ids, the daemon address)+ // that must not leave in an API body. rawFailureMessages keeps the unredacted+ // text keyed by path for the server-side log only.+ rawFailureMessages := make(map[string]string)+ failureMessage := func(err error) string {+ if version.IsDevelopMode() {+ return err.Error()+ }+ return "entry could not be read"+ }+// A directory-level failure on ONE path (nonexistent, not a directory, list// command failed) records that path as a failure and keeps serving the paths// that worked — only a cancelled request (client gone) aborts the response. If@@ -983,10 +996,11 @@ func (s *FlowFileService) GetFlowContainerFiles(c *gin.Context) {return}seenFailPaths[p] = struct{}{}+ rawFailureMessages[p] = err.Error()allFailures = append(allFailures, models.ContainerFileError{Name: path.Base(p),Path: p,- Message: err.Error(),+ Message: failureMessage(err),})}@@ -1029,19 +1043,15 @@ func (s *FlowFileService) GetFlowContainerFiles(c *gin.Context) {}}for _, fe := range listing.Failures {- // If an overlapping path already read this entry successfully, keep the- // success and drop the contradictory failure.- if _, ok := seenPaths[fe.Path]; ok {- continue- }if _, seen := seenFailPaths[fe.Path]; seen {continue}seenFailPaths[fe.Path] = struct{}{}+ rawFailureMessages[fe.Path] = fe.Err.Error()allFailures = append(allFailures, models.ContainerFileError{Name: fe.Name,Path: fe.Path,- Message: fe.Err.Error(),+ Message: failureMessage(fe.Err),})}}@@ -1054,6 +1064,19 @@ func (s *FlowFileService) GetFlowContainerFiles(c *gin.Context) {return}+ // A path read successfully by any query wins over a contradictory failure for+ // the same path, regardless of the order the paths were processed, so the same+ // path can never appear in both Files and Failures.+ if len(allFailures) > 0 && len(seenPaths) > 0 {+ kept := allFailures[:0]+ for _, fe := range allFailures {+ if _, ok := seenPaths[fe.Path]; !ok {+ kept = append(kept, fe)+ }+ }+ allFailures = kept+ }+// Sort by name for deterministic output across all paths.sort.Slice(allFiles, func(i, j int) bool {if allFiles[i].Path < allFiles[j].Path {@@ -1094,7 +1117,7 @@ func (s *FlowFileService) GetFlowContainerFiles(c *gin.Context) {"flow_id": flowID,"entry": fe.Name,"entry_path": fe.Path,- "error": fe.Message,+ "error": rawFailureMessages[fe.Path],}).Warn("container entry skipped: could not stat")}log.WithFields(map[string]any{diff --git a/backend/pkg/server/services/flow_files_partial_test.go b/backend/pkg/server/services/flow_files_partial_test.gonew file mode 100644index 00000000..77be6fdb--- /dev/null+++ b/backend/pkg/server/services/flow_files_partial_test.go@@ -0,0 +1,104 @@+package services++import (+ "fmt"+ "net/http"+ "os"+ "testing"++ "pentagi/pkg/docker"+ "pentagi/pkg/server/models"+ "pentagi/pkg/version"++ "github.com/docker/docker/api/types/container"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func containsFilePath(files []models.ContainerFile, p string) bool {+ for _, f := range files {+ if f.Path == p {+ return true+ }+ }+ return false+}++func containsFailurePath(failures []models.ContainerFileError, p string) bool {+ for _, f := range failures {+ if f.Path == p {+ return true+ }+ }+ return false+}++func listContainerFiles(t *testing.T, fake *fakeDockerClient, query string) (*int, models.ContainerFiles) {+ t.Helper()+ db := setupFlowFileServiceTestDB(t)+ seedFlow(t, db, 1, 1)+ svc := NewFlowFileService(db, t.TempDir(), fake, nil)+ c, w := newFlowFileTestContext(http.MethodGet, "/flows/1/files/container?"+query, nil,+ []string{"flow_files.view", "containers.view"}, 1, 1)+ svc.GetFlowContainerFiles(c)+ return &w.Code, decodeContainerFilesResponse(t, w)+}++// The client body must not carry docker-layer error detail (container ids, the+// daemon address) outside develop mode — the same dev-gate response.Error applies.+func TestGetFlowContainerFiles_FailureMessageIsDevGated(t *testing.T) {+ rawErr := "Error response from daemon: container 9f8e7d6c5b4a on tcp://10.0.0.5:2376 lstat failed"+ newFake := func() *fakeDockerClient {+ f := &fakeDockerClient{running: true}+ f.statPathMap = map[string]container.PathStat{"/work": {Mode: os.ModeDir | 0755}}+ f.listDirMap = map[string][]container.PathStat{"/work": {{Name: "readme", Mode: 0644, Size: 1}}}+ f.listDirFailMap = map[string][]docker.ContainerEntryError{+ "/work": {{Name: "secret", Path: "/work/secret", Err: fmt.Errorf("%s", rawErr)}},+ }+ return f+ }++ t.Run("production hides the raw error", func(t *testing.T) {+ version.PackageVer = "1.0.0"+ t.Cleanup(func() { version.PackageVer = "" })+ code, resp := listContainerFiles(t, newFake(), "paths[]=/work")+ require.Equal(t, http.StatusOK, *code)+ require.Len(t, resp.Failures, 1)+ assert.NotContains(t, resp.Failures[0].Message, "tcp://10.0.0.5:2376")+ assert.NotContains(t, resp.Failures[0].Message, "9f8e7d6c5b4a")+ assert.Equal(t, "entry could not be read", resp.Failures[0].Message)+ })++ t.Run("develop mode still exposes it for debugging", func(t *testing.T) {+ version.PackageVer = "" // develop mode+ code, resp := listContainerFiles(t, newFake(), "paths[]=/work")+ require.Equal(t, http.StatusOK, *code)+ require.Len(t, resp.Failures, 1)+ assert.Contains(t, resp.Failures[0].Message, "tcp://10.0.0.5:2376")+ })+}++// A path read successfully by any query must never also appear in Failures,+// regardless of the order the paths were processed.+func TestGetFlowContainerFiles_PathNeverInBothArrays(t *testing.T) {+ newFake := func() *fakeDockerClient {+ f := &fakeDockerClient{running: true}+ f.statPathMap = map[string]container.PathStat{+ "/work": {Mode: os.ModeDir | 0755},+ "/work/x": {Name: "x", Mode: 0644, Size: 1},+ }+ f.listDirMap = map[string][]container.PathStat{"/work": {}}+ f.listDirFailMap = map[string][]docker.ContainerEntryError{+ "/work": {{Name: "x", Path: "/work/x", Err: fmt.Errorf("stat: no such file")}},+ }+ return f+ }++ for _, order := range []string{"paths[]=/work&paths[]=/work/x", "paths[]=/work/x&paths[]=/work"} {+ code, resp := listContainerFiles(t, newFake(), order)+ require.Equal(t, http.StatusOK, *code)+ assert.True(t, containsFilePath(resp.Files, "/work/x"), "order %q: /work/x should be in Files", order)+ assert.False(t, containsFailurePath(resp.Failures, "/work/x"),+ "order %q: /work/x must NOT also be in Failures", order)+ }+}