Repository navigation
Add durable mcpx daemon call ledger #11789
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| package daemon | ||
|
|
||
| import ( | ||
| "os" | ||
| "path/filepath" | ||
| "strings" | ||
| "time" | ||
| ) | ||
|
|
||
| // pruneCallLedger keeps eight calendar days of daily JSONL files. FileSink | ||
| // separately caps each active file and retains eight size/line/age rotations; | ||
| // together these bounds prevent old daily files from accumulating forever. | ||
| func pruneCallLedger(dir string, now time.Time) { | ||
| entries, err := os.ReadDir(dir) | ||
| if err != nil { | ||
| return | ||
| } | ||
| today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()) | ||
| cutoff := today.AddDate(0, 0, -7) | ||
| for _, entry := range entries { | ||
| name := entry.Name() | ||
| if !strings.HasPrefix(name, "mcpx-") || !strings.HasSuffix(name, ".jsonl") { | ||
| continue | ||
| } | ||
| stem := strings.TrimSuffix(strings.TrimPrefix(name, "mcpx-"), ".jsonl") | ||
| if len(stem) < len("2006-01-02") { | ||
| continue | ||
| } | ||
| day, err := time.Parse("2006-01-02", stem[:len("2006-01-02")]) | ||
| if err != nil || (len(stem) > len("2006-01-02") && stem[len("2006-01-02")] != '-') { | ||
| continue | ||
| } | ||
| if day.Before(cutoff) { | ||
| _ = os.Remove(filepath.Join(dir, name)) | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -144,8 +144,13 @@ type Server struct { | |
|
|
||
| // sink is the durable log POST /v1/log appends to. Nil when the log | ||
| // could not be opened, which the daemon survives and the route reports. | ||
| sink *logging.FileSink | ||
| lastReq atomic.Int64 | ||
| sink *logging.FileSink | ||
| // callLedger is the dedicated, payload-free execution ledger. It is | ||
| // separate from the mixed diagnostic log so analytics can read it safely. | ||
| callLedger *logging.FileSink | ||
| callLedgerDir string | ||
| lastLedgerPrune atomic.Int64 | ||
| lastReq atomic.Int64 | ||
|
|
||
| // cfgMu guards cfg, contentHash and stamp. The daemon re-reads its | ||
| // configuration from a request goroutine now, so what used to be | ||
|
|
@@ -241,24 +246,43 @@ func NewServer(opts Options) (*Server, error) { | |
| if err := ValidateBearerToken(opts.Settings); err != nil { | ||
| return nil, err | ||
| } | ||
| // This dedicated, payload-free JSONL surface has an explicit rotation | ||
| // contract independent of general logging defaults: 16 MiB, 200k records, | ||
| // or 24 hours per file, retaining eight rotated files. FileSink names the | ||
| // active file mcpx-YYYY-MM-DD.jsonl and rotated files with a time suffix. | ||
| callLedger, ledgerErr := logging.NewFileSink(logging.FileOptions{ | ||
| Dir: filepath.Join(opts.Paths.State, "call-ledger"), | ||
|
Comment on lines
+253
to
+254
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When different project configurations run concurrently, their daemons share Useful? React with 👍 / 👎. |
||
| MaxBytes: 16 * 1024 * 1024, | ||
| MaxLines: 200_000, | ||
| MaxAge: 24 * time.Hour, | ||
| Keep: 8, | ||
| }) | ||
| if ledgerErr == nil { | ||
| pruneCallLedger(filepath.Join(opts.Paths.State, "call-ledger"), time.Now()) | ||
| } | ||
| if ledgerErr != nil { | ||
| opts.Logger.Printf("call ledger unavailable: %v", ledgerErr) | ||
| } | ||
| // logging.trace, which is MCPX_TRACE. It was read here by name, so a | ||
| // configuration file or `mcpx daemon --logging-trace` could not turn it on. | ||
| if opts.Settings.Bool("logging.trace") { | ||
| pool.Trace = func(f string, a ...any) { opts.Logger.Printf(f, a...) } | ||
| } | ||
| srv := &Server{ | ||
| set: opts.Settings, | ||
| reg: reg, | ||
| paths: opts.Paths, | ||
| cfg: opts.Config, | ||
| logger: opts.Logger, | ||
| version: opts.Version, | ||
| idleExit: opts.IdleExit, | ||
| sink: opts.Sink, | ||
| augment: opts.Augment, | ||
| Events: events.New(opts.Settings.Int("events.history")), | ||
| httpErr: make(chan error, 4), | ||
| handedOff: make(chan struct{}), | ||
| set: opts.Settings, | ||
| reg: reg, | ||
| paths: opts.Paths, | ||
| cfg: opts.Config, | ||
| logger: opts.Logger, | ||
| version: opts.Version, | ||
| idleExit: opts.IdleExit, | ||
| sink: opts.Sink, | ||
| callLedger: callLedger, | ||
| callLedgerDir: filepath.Join(opts.Paths.State, "call-ledger"), | ||
| augment: opts.Augment, | ||
| Events: events.New(opts.Settings.Int("events.history")), | ||
| httpErr: make(chan error, 4), | ||
| handedOff: make(chan struct{}), | ||
| } | ||
| // The broker is optional: a daemon whose state directory cannot hold a | ||
| // database still serves tools, and answers every server question with | ||
|
|
@@ -761,6 +785,9 @@ func (s *Server) shutdown() error { | |
| if s.tokenStore != nil { | ||
| _ = s.tokenStore.Close() | ||
| } | ||
| if s.callLedger != nil { | ||
| _ = s.callLedger.Close() | ||
| } | ||
| _ = os.Remove(s.paths.Socket) | ||
| s.paths.RemoveInfo() | ||
| s.logger.Printf("stopped") | ||
|
|
@@ -1253,7 +1280,7 @@ func (s *Server) handleCall(w http.ResponseWriter, r *http.Request) { | |
| res, err = s.reg.Call(ctx, req.Server, req.Tool, cc, args) | ||
| } | ||
| dur := time.Since(start).Truncate(time.Millisecond) | ||
| s.reportCallFrame(ctx, req.Server, req.Tool, args, start, res, err) | ||
| s.reportCallFrame(ctx, req.Server, req.Tool, cc.SessionID, args, start, res, err) | ||
|
|
||
| toolKey := req.Server + ":" + req.Tool | ||
| var inBytes, outBytes []byte | ||
|
|
@@ -1405,7 +1432,7 @@ func (s *Server) handleBatch(w http.ResponseWriter, r *http.Request) { | |
| // Batch items bypass the single-call handlers, so report each | ||
| // completed one here: a script's batch(...) calls belong in | ||
| // its exec stream like any other call. | ||
| s.reportCallFrame(ctx, server, tool, args, start, res, err) | ||
| s.reportCallFrame(ctx, server, tool, cc.SessionID, args, start, res, err) | ||
|
|
||
| if err != nil { | ||
| return map[string]any{ | ||
|
|
@@ -1914,18 +1941,41 @@ func (s *Server) callRegistry() *execsvc.CallRegistry { | |
| // reportCallFrame tells the exec stream that is running this call, if | ||
| // any, that the call happened: a call frame with the tool's resolved | ||
| // destructiveHint. A call with no run id, or a run this daemon is not | ||
| // executing, has no stream to join and is not reported. | ||
| func (s *Server) reportCallFrame(ctx context.Context, server, tool string, args any, start time.Time, res json.RawMessage, callErr error) { | ||
| // executing, has no stream to join but still belongs in the call ledger. | ||
| func (s *Server) reportCallFrame(ctx context.Context, server, tool, callerSession string, args any, start time.Time, res json.RawMessage, callErr error) { | ||
| run := runFrom(ctx) | ||
| if run == "" { | ||
| return | ||
| } | ||
| // A tool that ran and returned isError failed, even though the | ||
| // transport call itself succeeded: the frame must say so, the way | ||
| // the path-per-tool handler already does with resultFailed. | ||
| if callErr == nil && resultFailed(res) { | ||
| callErr = errors.New("tool returned an error result (isError)") | ||
| } | ||
| if s.callLedger != nil { | ||
| attrs := map[string]any{ | ||
| "server": server, | ||
| "tool": tool, | ||
| "outcome": "success", | ||
|
Comment on lines
+1953
to
+1957
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When an exec request uses Useful? React with 👍 / 👎. |
||
| "duration_ms": time.Since(start).Milliseconds(), | ||
| } | ||
| if callErr != nil { | ||
| attrs["outcome"] = "error" | ||
| } | ||
| if run != "" { | ||
| attrs["caller_run"] = run | ||
| } | ||
| if callerSession != "" { | ||
| attrs["caller_session"] = callerSession | ||
| } | ||
| s.callLedger.Write(logging.Record{Time: time.Now(), Msg: "tool_call", Attrs: attrs}, nil) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Calls executed through Useful? React with 👍 / 👎. |
||
| now := time.Now() | ||
| last := s.lastLedgerPrune.Load() | ||
| if now.Unix()-last >= 3600 && s.lastLedgerPrune.CompareAndSwap(last, now.Unix()) { | ||
| pruneCallLedger(s.callLedgerDir, now) | ||
| } | ||
| } | ||
| if run == "" { | ||
| return | ||
| } | ||
| var dh *bool | ||
| if picked := s.pickTool(server, tool); picked != nil { | ||
| d := destructiveHint(picked.Annotations) | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
On hosts west of UTC,
time.Parseinterprets the filename as UTC midnight whilecutoffuses local midnight. For example, on November 18 in Los Angeles,mcpx-2026-11-11.jsonlparses to November 11 at 00:00Z, before the cutoff at 08:00Z, and is deleted even though November 11 is the eighth retained calendar day. That file can still contain calls within the aggregator's rolling seven-day window. Usetime.ParseInLocationwithnow.Location(), or compare calendar dates consistently, to avoid prematurely deleting valid history.Useful? React with 👍 / 👎.