High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat(traceability): log the unredacted failure cause server-side, keyed by requestId
Luigi Agosti1ad5967334d4
diff --git a/cmd/pinchtab/cmd_server.go b/cmd/pinchtab/cmd_server.goindex e075bc43..bd3ee83a 100644--- a/cmd/pinchtab/cmd_server.go+++ b/cmd/pinchtab/cmd_server.go@@ -27,7 +27,7 @@ var serverCmd = &cobra.Command{resolveLogLevel(cfg, logLevel, verbose)config.EmitLoadDiagnostics(loadDiags)- backgroundMarker, _ := cmd.Flags().GetString("background-child")+ backgroundMarker, _ := cmd.Flags().GetString(backgroundChildFlagName)cfg.BackgroundMarker = backgroundMarkerbind, _ := cmd.Flags().GetString("bind")@@ -176,8 +176,8 @@ func init() {serverCmd.Flags().String("log-level", "", "Minimum log level: debug, info (default), warn or error")serverCmd.Flags().String("browser", "", "Browser to use: chrome, cloak, or ghost-chrome (overrides config)")serverCmd.Flags().BoolP("background", "b", false, "Spawn the server detached and return JSON with pid/url/token")- serverCmd.Flags().String("background-child", "", "Internal marker for background server ownership")- _ = serverCmd.Flags().MarkHidden("background-child")+ serverCmd.Flags().String(backgroundChildFlagName, "", "Internal marker for background server ownership")+ _ = serverCmd.Flags().MarkHidden(backgroundChildFlagName)serverCmd.AddCommand(serverStopCmd)serverCmd.AddCommand(serverRestartCmd)rootCmd.AddCommand(serverCmd)diff --git a/cmd/pinchtab/cmd_server_background.go b/cmd/pinchtab/cmd_server_background.goindex d3d9553f..c37c9997 100644--- a/cmd/pinchtab/cmd_server_background.go+++ b/cmd/pinchtab/cmd_server_background.go@@ -11,6 +11,7 @@ import ("os""os/exec""path/filepath"+ "slices""strconv""strings""time"@@ -129,6 +130,78 @@ func serverLogFilePath(stateDir string) string {return filepath.Join(stateDir, "server.log")}+// backgroundChildFlag marks a server the CLI spawned detached. The spawn site and+// the "is this server a background child" question have to spell it the same way, so+// they share this rather than repeating the literal.+const (+ backgroundChildFlagName = "background-child"+ backgroundChildFlag = "--" + backgroundChildFlagName+)++// serverLogWhere answers the question an operator asks after a 5xx: which file is+// this server writing to. The three launch paths land in three different places, and+// a state dir usually holds a server.log from whichever one ran last — so the answer+// has to name the LIVE destination and disown a file nothing is writing, rather than+// let a stale path pass for a log.+type serverLogWhere struct {+ // Destination is the live log sink: a path, or a description when the logs go+ // to a terminal rather than a file.+ Destination string+ // StalePath is a server.log that exists while something else is the live sink.+ StalePath string+}++// resolveServerLogWhere is pure so the branch table is testable without a daemon, a+// state dir or a running server; the caller does the I/O and hands in the facts.+func resolveServerLogWhere(stateDir, daemonLogPath string, daemonInstalled, backgroundChild, running, serverLogExists bool) serverLogWhere {+ backgroundLog := serverLogFilePath(stateDir)+ where := serverLogWhere{}++ switch {+ case daemonInstalled:+ where.Destination = daemonLogPath+ case running && backgroundChild:+ where.Destination = backgroundLog+ case running:+ where.Destination = "stdout/stderr of the terminal running `pinchtab server`"+ default:+ where.Destination = "no server running"+ }++ if serverLogExists && where.Destination != backgroundLog {+ where.StalePath = backgroundLog+ }+ return where+}++// serverLogWhereForConfig gathers the facts resolveServerLogWhere needs. A daemon+// environment that cannot be resolved is reported as "no daemon" rather than as an+// error: the banner is a hint surface, and a missing home directory must not stop it+// from naming the other sinks.+func serverLogWhereForConfig(cfg *config.RuntimeConfig, running bool) serverLogWhere {+ stateDir := stateDirForConfig(cfg)+ daemonInstalled, err := detachedDaemonOwnership()+ if err != nil {+ daemonInstalled = false+ }+ daemonLogPath := ""+ if daemonInstalled {+ if path, pathErr := daemon.StderrLogPath(); pathErr == nil {+ daemonLogPath = path+ } else {+ daemonLogPath = "pinchtab daemon logs"+ }+ }++ backgroundChild := false+ if info, ok := readServerPID(stateDir); ok && processAlive(info.PID) {+ backgroundChild = slices.Contains(info.Args, backgroundChildFlag)+ }+ _, statErr := os.Stat(serverLogFilePath(stateDir))++ return resolveServerLogWhere(stateDir, daemonLogPath, daemonInstalled, backgroundChild, running, statErr == nil)+}+func prepareServerSpawn() (binary, marker string, err error) {binary, err = os.Executable()if err != nil {@@ -230,7 +303,7 @@ func runServerBackground(cfg *config.RuntimeConfig, opts serverBackgroundOptions}func backgroundServerArgs(marker string, opts serverBackgroundOptions) []string {- args := []string{"server", "--background-child", marker}+ args := []string{"server", backgroundChildFlag, marker}if opts.Yolo {args = append(args, "-y")}diff --git a/cmd/pinchtab/cmd_server_ensure.go b/cmd/pinchtab/cmd_server_ensure.goindex 299ba9af..ccacc3e5 100644--- a/cmd/pinchtab/cmd_server_ensure.go+++ b/cmd/pinchtab/cmd_server_ensure.go@@ -168,7 +168,7 @@ func autoStartServer() error {func autoStartServerArgs(marker ...string) []string {args := []string{"server"}if len(marker) > 0 && strings.TrimSpace(marker[0]) != "" {- args = append(args, "--background-child", marker[0])+ args = append(args, backgroundChildFlag, marker[0])}return args}diff --git a/cmd/pinchtab/root_hints.go b/cmd/pinchtab/root_hints.goindex 3906abf2..1e3e27a4 100644--- a/cmd/pinchtab/root_hints.go+++ b/cmd/pinchtab/root_hints.go@@ -2,6 +2,7 @@ package mainimport ("fmt"+ "io""os""strings"@@ -16,10 +17,15 @@ import (// cheaper than the banner asserting a server state it never checked.func printAgentHints(cfg *config.RuntimeConfig) {snap, state := fetchHealthSnapshot(cfg.Port)- renderAgentHints(os.Stdout, projectAgentStatus(cfg, snap, state))+ // Any state but "stopped" means something answered on the port, so a log is+ // being written somewhere: a listener that refused the token is still a running+ // server, and telling its operator "no server running" is how a live log gets+ // reported as absent.+ logs := serverLogWhereForConfig(cfg, state != healthSnapshotStopped)+ renderAgentHints(os.Stdout, projectAgentStatus(cfg, snap, state, logs))}-func renderAgentHints(out *os.File, st agentStatus) {+func renderAgentHints(out io.Writer, st agentStatus) {_, _ = fmt.Fprintln(out, cli.StyleStdout(cli.HeadingStyle, "PinchTab")+" "+cli.StyleStdout(cli.MutedStyle, version))_, _ = fmt.Fprintln(out)@@ -39,6 +45,13 @@ func renderAgentHints(out *os.File, st agentStatus) {_, _ = fmt.Fprintf(out, " %-20s %s\n", "server", cli.StyleStdout(cli.WarningStyle, string(st.state)))}+ if st.logDestination != "" {+ _, _ = fmt.Fprintf(out, " %-20s %s\n", "logs", cli.StyleStdout(cli.ValueStyle, st.logDestination))+ }+ if st.staleLogPath != "" {+ _, _ = fmt.Fprintf(out, " %-20s %s\n", "", cli.StyleStdout(cli.MutedStyle, st.staleLogPath+" is not being written by this server"))+ }+formatted := formatAllowedDomains(st.allowedDomains)domStyle := cli.ValueStyleif formatted == "all" {diff --git a/cmd/pinchtab/root_status.go b/cmd/pinchtab/root_status.goindex 92b76622..5c04f1f0 100644--- a/cmd/pinchtab/root_status.go+++ b/cmd/pinchtab/root_status.go@@ -13,6 +13,8 @@ type agentStatus struct {running boolguardsDown boollistenAddr string+ logDestination string+ staleLogPath stringsensitive []stringallowedDomains []stringidpiEnabled bool@@ -23,11 +25,13 @@ type agentStatus struct {// projectAgentStatus derives the banner fields from the runtime config and the// (possibly nil) health snapshot. snap is non-nil only when state is// healthSnapshotRunning.-func projectAgentStatus(cfg *config.RuntimeConfig, snap *healthSnapshot, state healthSnapshotState) agentStatus {+func projectAgentStatus(cfg *config.RuntimeConfig, snap *healthSnapshot, state healthSnapshotState, logs serverLogWhere) agentStatus {st := agentStatus{state: state,running: state == healthSnapshotRunning,listenAddr: cfg.ListenAddr(),+ logDestination: logs.Destination,+ staleLogPath: logs.StalePath,allowedDomains: cfg.AllowedDomains,idpiEnabled: cfg.IDPI.Enabled,}diff --git a/cmd/pinchtab/server_log_location_test.go b/cmd/pinchtab/server_log_location_test.gonew file mode 100644index 00000000..6eacd047--- /dev/null+++ b/cmd/pinchtab/server_log_location_test.go@@ -0,0 +1,122 @@+package main++import (+ "bytes"+ "path/filepath"+ "strings"+ "testing"+)++func renderAgentHintsString(t *testing.T, st agentStatus) string {+ t.Helper()+ var buf bytes.Buffer+ renderAgentHints(&buf, st)+ return buf.String()+}++// The card's dead end: a server.log last written weeks ago, sitting beside a server+// that has never touched it. Whichever way the server was started, the banner has to+// name the sink that is live and disown the one that is not.+func TestServerLogWhereNamesTheLiveSinkAndDisownsTheStaleFile(t *testing.T) {+ stateDir := "/home/op/.pinchtab"+ backgroundLog := filepath.Join(stateDir, "server.log")+ daemonLog := "/home/op/.pinchtab/logs/daemon.err.log"++ for _, tc := range []struct {+ name string+ daemonInstalled bool+ backgroundChild bool+ running bool+ serverLogExists bool+ wantDestination string+ wantStale string+ }{+ {+ name: "daemon owns the server, so its log is the live one and server.log is not",+ daemonInstalled: true, running: true, serverLogExists: true,+ wantDestination: daemonLog,+ wantStale: backgroundLog,+ },+ {+ name: "background child writes server.log, which is therefore not stale",+ backgroundChild: true, running: true, serverLogExists: true,+ wantDestination: backgroundLog,+ wantStale: "",+ },+ {+ name: "foreground server logs to its terminal, so a server.log on disk is a leftover",+ running: true, serverLogExists: true,+ wantDestination: "stdout/stderr of the terminal running `pinchtab server`",+ wantStale: backgroundLog,+ },+ {+ name: "nothing running: say so rather than point at a file",+ serverLogExists: true,+ wantDestination: "no server running",+ wantStale: backgroundLog,+ },+ {+ name: "no leftover file, nothing to disown",+ running: true,+ wantDestination: "stdout/stderr of the terminal running `pinchtab server`",+ wantStale: "",+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ got := resolveServerLogWhere(stateDir, daemonLog, tc.daemonInstalled, tc.backgroundChild, tc.running, tc.serverLogExists)+ if got.Destination != tc.wantDestination {+ t.Errorf("destination = %q, want %q", got.Destination, tc.wantDestination)+ }+ if got.StalePath != tc.wantStale {+ t.Errorf("stale path = %q, want %q", got.StalePath, tc.wantStale)+ }+ })+ }+}++// A listener that refuses the token is still a running server. Keying the lookup on+// the strictest state reported "no server running" beside a server that was serving,+// and flagged its live log as stale.+func TestProtectedListenerCountsAsRunningForTheLogLookup(t *testing.T) {+ for _, state := range []healthSnapshotState{+ healthSnapshotRunning,+ healthSnapshotProtected,+ healthSnapshotUnhealthy,+ healthSnapshotInvalid,+ } {+ t.Run(string(state), func(t *testing.T) {+ if state == healthSnapshotStopped {+ t.Fatal("stopped must not be in this list")+ }+ got := resolveServerLogWhere("/home/op/.pinchtab", "", false, true, state != healthSnapshotStopped, true)+ if got.Destination != filepath.Join("/home/op/.pinchtab", "server.log") {+ t.Errorf("state %q resolved to %q, want the background log it is actually writing", state, got.Destination)+ }+ if got.StalePath != "" {+ t.Errorf("state %q flagged its own live log as stale", state)+ }+ })+ }+}++// A banner that resolves the log location and then does not print it leaves the+// operator exactly where the card found them.+func TestBannerPrintsTheLogDestinationAndFlagsAStaleServerLog(t *testing.T) {+ out := renderAgentHintsString(t, agentStatus{+ state: healthSnapshotRunning,+ running: true,+ listenAddr: "127.0.0.1:9867",+ logDestination: "/home/op/.pinchtab/logs/daemon.err.log",+ staleLogPath: "/home/op/.pinchtab/server.log",+ })++ if !strings.Contains(out, "/home/op/.pinchtab/logs/daemon.err.log") {+ t.Errorf("the banner does not name the live log:\n%s", out)+ }+ if !strings.Contains(out, "logs") {+ t.Errorf("the banner has no logs row:\n%s", out)+ }+ if !strings.Contains(out, "/home/op/.pinchtab/server.log is not being written by this server") {+ t.Errorf("the banner does not disown the stale server.log:\n%s", out)+ }+}diff --git a/docs/commands.md b/docs/commands.mdindex 32c1dc28..763d5222 100644--- a/docs/commands.md+++ b/docs/commands.md@@ -28,6 +28,25 @@ is set: `--log-level debug|info|warn|error`, then `server.logLevel` in the confifile, then `-v`, then the default `info`. `-v` always adds the full startup banner,and it raises the level to debug only when neither of the other two is set.+Where those lines land depends on how the server was started, which is why `pinchtab`+with no arguments prints a `logs` row naming the live destination: `<stateDir>/server.log`+for `pinchtab server -b`, `~/.pinchtab/logs/daemon.err.log` for a daemon-installed+service, and the terminal for a foreground run. A `server.log` left behind by an earlier+detached run is called out as not being written by the current server, so it cannot be+mistaken for a live one.++A request that fails logs its cause there UNREDACTED — absolute paths intact — under the+same `requestId` the access log records, so a 5xx can be joined to the reason it happened:++```bash+grep '"request failed"' <stateDir>/server.log # causes, with requestId and status+grep <requestId> ~/.pinchtab/activity/*.jsonl # the access-log line it belongs to+```++The message that crosses the HTTP boundary is still path-sanitized (`fork/exec [path]`),+so the unredacted copy exists only in the server's own log. Server faults (5xx) log at+error level; a 4xx is the caller's input and logs at debug.+The access log is what an open dashboard costs: its errors and console panels each pollon a 3s interval, so a dashboard left open writes roughly 40 lines a minute. That is thedeliberate trade for a run that explains itself afterwards, and `--log-level warn` is thediff --git a/internal/daemon/manager.go b/internal/daemon/manager.goindex 5f40d006..0f2ba300 100644--- a/internal/daemon/manager.go+++ b/internal/daemon/manager.go@@ -164,6 +164,17 @@ func daemonLogDir(env environment) string {return filepath.Join(pinchtabStateHome(env), "logs")}+// StderrLogPath is where a service-managed server's diagnostics land. Exported so a+// surface that tells an operator where to look reads the same path the installer+// writes into the unit, rather than spelling it a second time.+func StderrLogPath() (string, error) {+ env, err := currentEnvironment()+ if err != nil {+ return "", err+ }+ return daemonStderrLogPath(env), nil+}+func daemonStdoutLogPath(env environment) string {return filepath.Join(daemonLogDir(env), "daemon.out.log")}diff --git a/internal/httpx/failure_cause_test.go b/internal/httpx/failure_cause_test.gonew file mode 100644index 00000000..1c1268e2--- /dev/null+++ b/internal/httpx/failure_cause_test.go@@ -0,0 +1,141 @@+package httpx++import (+ "bytes"+ "encoding/json"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/pinchtab/pinchtab/internal/safelog"+)++const launchFailure = `failed to start: fork/exec /Users/op/.pinchtab/bin/pinchtab: exec format error`++// captureServerLog installs the process logger the server runs with — the safelog+// handler, which is what decides whether a path survives into a log line — and returns+// what it wrote. Testing against a bare slog handler would prove nothing about the+// sanitizing the real one applies.+func captureServerLog(t *testing.T, level slog.Level, fn func()) string {+ t.Helper()+ var buf bytes.Buffer+ previous := slog.Default()+ previousLevel := safelog.CurrentLevel()+ slog.SetDefault(slog.New(safelog.NewDefaultHandler(&buf)))+ safelog.SetLevel(level)+ t.Cleanup(func() {+ slog.SetDefault(previous)+ safelog.SetLevel(previousLevel)+ })+ fn()+ return buf.String()+}++// The whole point of the card: the operator cannot act on "[path]", so the frame that+// still holds the real path has to write it down before the boundary rewrites it.+func TestServerFailureLogsTheUnredactedCauseWhileTheResponseStaysSanitized(t *testing.T) {+ rec := httptest.NewRecorder()+ rec.Header().Set(RequestIDHeader, "6c8c6f0aaf8df5a3")++ logged := captureServerLog(t, slog.LevelError, func() {+ ErrorCode(rec, http.StatusInternalServerError, "error", launchFailure, false, nil)+ })++ if !strings.Contains(logged, "/Users/op/.pinchtab/bin/pinchtab") {+ t.Errorf("the server log does not name the executable that failed, so the fault is still undiagnosable:\n%s", logged)+ }+ if !strings.Contains(logged, "exec format error") {+ t.Errorf("the server log dropped the underlying cause:\n%s", logged)+ }+ if strings.Contains(logged, "[path]") {+ t.Errorf("the server-side copy was redacted too, which leaves no unredacted copy anywhere:\n%s", logged)+ }++ var body map[string]any+ if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ wire, _ := body["error"].(string)+ if strings.Contains(wire, "/Users/op") {+ t.Errorf("the HTTP response leaked the absolute path: %q", wire)+ }+ if !strings.Contains(wire, "[path]") {+ t.Errorf("the HTTP response is no longer path-sanitized: %q", wire)+ }+}++// AC-2: the access log records a requestId and nothing else on disk was keyed by it.+// The cause line has to carry the same id or the two files still do not join.+func TestFailureCauseCarriesTheRequestIDTheActivityEventRecords(t *testing.T) {+ rec := httptest.NewRecorder()+ rec.Header().Set(RequestIDHeader, "6c8c6f0aaf8df5a3")++ logged := captureServerLog(t, slog.LevelError, func() {+ Problem(rec, http.StatusServiceUnavailable, "instance_not_ready", "instance not ready after 10s", true, nil)+ })++ if !strings.Contains(logged, "requestId=6c8c6f0aaf8df5a3") {+ t.Errorf("the cause is not keyed by the requestId, so a 5xx in the access log joins to nothing:\n%s", logged)+ }+ if !strings.Contains(logged, "status=503") {+ t.Errorf("the cause line does not carry the status it was returned with:\n%s", logged)+ }+}++// Every producer that writes a non-2xx has to log its cause; a new one that skips the+// helper reintroduces exactly the hole this card is about.+func TestEveryErrorProducerLogsItsCause(t *testing.T) {+ for _, tc := range []struct {+ name string+ write func(w http.ResponseWriter)+ }{+ {"ErrorCode", func(w http.ResponseWriter) {+ ErrorCode(w, http.StatusInternalServerError, "error", launchFailure, false, nil)+ }},+ {"Error", func(w http.ResponseWriter) {+ Error(w, http.StatusInternalServerError, errStub{})+ }},+ {"Problem", func(w http.ResponseWriter) {+ Problem(w, http.StatusInternalServerError, "error", launchFailure, false, nil)+ }},+ {"JSONError", func(w http.ResponseWriter) {+ JSONError(w, http.StatusInternalServerError, "error", launchFailure, map[string]any{"status": "error"})+ }},+ } {+ t.Run(tc.name, func(t *testing.T) {+ rec := httptest.NewRecorder()+ logged := captureServerLog(t, slog.LevelError, func() { tc.write(rec) })+ if !strings.Contains(logged, "/Users/op/.pinchtab/bin/pinchtab") {+ t.Errorf("%s returned a 500 without logging its unredacted cause:\n%s", tc.name, logged)+ }+ })+ }+}++type errStub struct{}++func (errStub) Error() string { return launchFailure }++// A 4xx is the caller's input, not a server fault: it stays out of the error stream so+// the signal an operator greps for is bounded by server failures rather than by client+// behaviour — and it is still recoverable by raising the level.+func TestClientErrorsAreLoggedAtDebugNotError(t *testing.T) {+ rec := httptest.NewRecorder()++ atError := captureServerLog(t, slog.LevelError, func() {+ ErrorCode(rec, http.StatusBadRequest, "bad_request", "missing required field 'kind'", false, nil)+ })+ if strings.Contains(atError, "missing required field") {+ t.Errorf("a 400 was logged at error level, which floods the stream an operator greps for real faults:\n%s", atError)+ }++ rec = httptest.NewRecorder()+ atDebug := captureServerLog(t, slog.LevelDebug, func() {+ ErrorCode(rec, http.StatusBadRequest, "bad_request", "missing required field 'kind'", false, nil)+ })+ if !strings.Contains(atDebug, "missing required field") {+ t.Errorf("a 400 is unrecoverable even at debug level:\n%s", atDebug)+ }+}diff --git a/internal/httpx/httpx.go b/internal/httpx/httpx.goindex 6675abf5..dad13a25 100644--- a/internal/httpx/httpx.go+++ b/internal/httpx/httpx.go@@ -39,6 +39,7 @@ type ProblemDetails struct {// non-2xx JSON response goes through here or through ErrorCode, so no failure reaches the// log, the metrics or the activity record with the response body as its only witness.func JSONError(w http.ResponseWriter, status int, code, message string, payload any) {+ logFailureCause(w, status, code, message)RecordFailureReason(w, code, SanitizeErrorMessage(message))JSON(w, status, payload)}@@ -63,6 +64,7 @@ func Error(w http.ResponseWriter, code int, err error) {}func ErrorCode(w http.ResponseWriter, status int, code, message string, retryable bool, details map[string]any) {+ logFailureCause(w, status, code, message)sanitized := SanitizeErrorMessage(message)RecordFailureReason(w, code, sanitized)payload := map[string]any{@@ -135,6 +137,7 @@ func Problem(w http.ResponseWriter, status int, code, detail string, retryable btitle = "Error"}+ logFailureCause(w, status, code, detail)sanitized := SanitizeErrorMessage(detail)RecordFailureReason(w, code, sanitized)payload := ProblemDetails{@@ -211,6 +214,35 @@ const (FailureMessageHeader = "X-Pinchtab-Failure-Message")+// RequestIDHeader is the id the request-id middleware stamps on every response and+// the activity recorder copies into its event, so it is the join key between an+// access-log line and the cause logged for it.+const RequestIDHeader = "X-Request-Id"++// logFailureCause writes the UNREDACTED reason a failure was returned. The message+// that crosses the HTTP boundary has its absolute paths rewritten to [path], which+// removes the one fact that identifies a fault like a malformed executable — so the+// producer's own copy is logged here, before sanitizing, keyed by the requestId the+// activity event already carries.+//+// 5xx logs at error: the server is at fault and an operator has to be able to find it+// without raising a level. 4xx logs at debug — it is the caller's input, and the+// volume follows client behaviour rather than anything the server controls.+func logFailureCause(w http.ResponseWriter, status int, code, message string) {+ if status < 400 || message == "" {+ return+ }+ level := slog.LevelDebug+ if status >= 500 {+ level = slog.LevelError+ }+ slog.Log(context.Background(), level, "request failed",+ "requestId", w.Header().Get(RequestIDHeader),+ "status", status,+ "code", code,+ "cause", sanitize.CleanForLog(message, maxErrorMessageBytes))+}+// RecordFailureReason gives w the code and the SANITIZED message that were just written.// It stamps the hop headers so the reason survives a proxy boundary, and walks the// recorder chain for the in-process sinks; nothing re-reads the response body to recoverdiff --git a/internal/orchestrator/instance_launch.go b/internal/orchestrator/instance_launch.goindex ecd1b55e..c655985b 100644--- a/internal/orchestrator/instance_launch.go+++ b/internal/orchestrator/instance_launch.go@@ -15,6 +15,27 @@ import ("github.com/pinchtab/pinchtab/internal/profiles")+// logLaunchBinaryFailure records what the exec actually tried, unredacted. The error+// the caller gets back crosses the HTTP boundary, where the absolute path is rewritten+// to [path] — leaving "fork/exec [path]: exec format error", which names no file. The+// binary's size and mode go with it because the two failures an operator hits here, a+// truncated install and a foreign-architecture build, are told apart by exactly those:+// a 0-byte candidate is self-evident, a full-size one is not.+func logLaunchBinaryFailure(instanceID, profile, binary string, cause error) {+ attrs := []any{+ "id", instanceID,+ "profile", profile,+ "binary", binary,+ "err", cause,+ }+ if info, statErr := os.Stat(binary); statErr == nil {+ attrs = append(attrs, "sizeBytes", info.Size(), "mode", info.Mode().String())+ } else {+ attrs = append(attrs, "statErr", statErr)+ }+ slog.Error("instance launch failed to exec the launch binary", attrs...)+}+func (o *Orchestrator) Launch(name, port string, headless bool, extensionPaths []string) (*bridge.Instance, error) {opts := LaunchOptions{ExtensionPaths: extensionPaths,@@ -168,6 +189,7 @@ func (o *Orchestrator) LaunchWithOptions(name, port string, headless bool, optscmd, err := o.runner.Run(context.Background(), o.binary, []string{"bridge"}, env, logBuf, logBuf)if err != nil {+ logLaunchBinaryFailure(instanceID, name, o.binary, err)return nil, fmt.Errorf("failed to start: %w", err)}diff --git a/internal/orchestrator/instance_launch_cause_test.go b/internal/orchestrator/instance_launch_cause_test.gonew file mode 100644index 00000000..a48fd45b--- /dev/null+++ b/internal/orchestrator/instance_launch_cause_test.go@@ -0,0 +1,92 @@+package orchestrator++import (+ "bytes"+ "errors"+ "log/slog"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/pinchtab/pinchtab/internal/safelog"+)++func captureLaunchLog(t *testing.T, fn func()) string {+ t.Helper()+ var buf bytes.Buffer+ previous := slog.Default()+ previousLevel := safelog.CurrentLevel()+ slog.SetDefault(slog.New(safelog.NewDefaultHandler(&buf)))+ safelog.SetLevel(slog.LevelError)+ t.Cleanup(func() {+ slog.SetDefault(previous)+ safelog.SetLevel(previousLevel)+ })+ fn()+ return buf.String()+}++// The failure this card was written from: a truncated launch binary. The error the+// caller receives says "fork/exec [path]", which names nothing — so the size the exec+// tried has to be on disk, unredacted, or the operator cannot tell a 0-byte install+// from a foreign-architecture build.+func TestLaunchFailureRecordsTheBinaryItExecdAndItsSize(t *testing.T) {+ old := portAvailableFunc+ portAvailableFunc = func(int) bool { return true }+ defer func() { portAvailableFunc = old }()++ runner := &mockRunner{portAvail: true, runErr: errors.New("fork/exec: exec format error")}+ o := NewOrchestratorWithRunner(t.TempDir(), runner)++ // Point the launch binary at a truncated stand-in. resolveStableBinary prefers+ // the RUNNING executable, which under `go test` is the test binary itself, so+ // writing to o.binary as resolved would truncate the compiled test on disk.+ truncated := filepath.Join(t.TempDir(), "pinchtab")+ if err := os.WriteFile(truncated, nil, 0o755); err != nil {+ t.Fatalf("write truncated binary: %v", err)+ }+ o.binary = truncated++ var launchErr error+ logged := captureLaunchLog(t, func() {+ _, launchErr = o.Launch("test-prof", "9999", true, nil)+ })+ if launchErr == nil {+ t.Fatal("expected the launch to fail")+ }++ if !strings.Contains(logged, o.binary) {+ t.Errorf("the log does not name the binary that was exec'd (%s):\n%s", o.binary, logged)+ }+ if !strings.Contains(logged, "sizeBytes=0") {+ t.Errorf("the log does not record the size, so a truncated install reads the same as any other exec failure:\n%s", logged)+ }+ if !strings.Contains(logged, "exec format error") {+ t.Errorf("the log dropped the underlying cause:\n%s", logged)+ }+ if strings.Contains(logged, "[path]") {+ t.Errorf("the server-side record was path-redacted, which is the hole this card closes:\n%s", logged)+ }+}++// A binary that is gone is a different fault from one that is malformed, and the log+// has to tell them apart rather than going quiet on the stat.+func TestLaunchFailureRecordsWhyTheBinaryCouldNotBeStatted(t *testing.T) {+ old := portAvailableFunc+ portAvailableFunc = func(int) bool { return true }+ defer func() { portAvailableFunc = old }()++ runner := &mockRunner{portAvail: true, runErr: errors.New("fork/exec: no such file or directory")}+ o := NewOrchestratorWithRunner(t.TempDir(), runner)+ o.binary = filepath.Join(t.TempDir(), "pinchtab-that-is-gone")++ logged := captureLaunchLog(t, func() { _, _ = o.Launch("test-prof", "9999", true, nil) })++ if !strings.Contains(logged, "statErr=") {+ t.Errorf("a missing launch binary is logged with no statErr, so it is indistinguishable from a malformed one:\n%s", logged)+ }+ if !strings.Contains(logged, o.binary) {+ t.Errorf("the log does not name the missing binary (%s):\n%s", o.binary, logged)+ }+}diff --git a/tests/e2e/scenarios/api/browser-activity-basic.sh b/tests/e2e/scenarios/api/browser-activity-basic.shindex e15f6a6a..166fe24f 100755--- a/tests/e2e/scenarios/api/browser-activity-basic.sh+++ b/tests/e2e/scenarios/api/browser-activity-basic.sh@@ -1,9 +1,9 @@#!/bin/bash# browser-activity-basic.sh — what the activity log records about a routed-# request. Route metadata is built inside the instance, so it reaches-# /api/activity only where the recorder shares the instance's request context:-# that is bridge mode. Through the orchestrator front door the same metadata-# comes back on the response instead, and both surfaces are asserted here.+# request through the orchestrator front door: the response carries the route+# metadata and the event carries the request. The bridge topology, where that+# metadata reaches the event itself, needs a second server and is asserted in+# browser-activity-extended.sh so the PR tier keeps its one-server stack.GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"source "${GROUP_DIR}/../../helpers/api.sh"@@ -156,27 +156,3 @@ assert_json_jq "$RESULT" '.events | all(has("method") and has("path") and has("s"an activity event is missing method, path or status"end_test--# ─────────────────────────────────────────────────────────────────-start_test "activity metadata: bridge records route metadata on the event"--if [ -z "${E2E_BRIDGE_URL:-}" ]; then- skip_test "E2E_BRIDGE_URL is not set; route metadata lands on the activity event only in bridge mode"-else- BRIDGE_TOKEN="${E2E_BRIDGE_TOKEN:-}"- BEFORE_TS=$(pt_on "$E2E_BRIDGE_URL" "$BRIDGE_TOKEN" newest_activity_event /navigate | jq -r '.timestamp // empty')-- pt_on "$E2E_BRIDGE_URL" "$BRIDGE_TOKEN" pt_post "/navigate?browser=${EXPECTED_BROWSER}" -d "{\"url\":\"${FIXTURES_URL}/index.html\"}"- assert_ok "bridge navigate with browser=${EXPECTED_BROWSER}"-- if pt_on "$E2E_BRIDGE_URL" "$BRIDGE_TOKEN" wait_until "activity_event_landed /navigate '$BEFORE_TS'" "$ACTIVITY_TIMEOUT"; then- ROUTE=$(echo "$ACTIVITY_EVENT" | jq -c '.route // empty')- if [ -n "$ROUTE" ]; then- assert_route_metadata "$ROUTE" "bridge activity event"- else- fail_assert "bridge activity event has no route metadata: $ACTIVITY_EVENT"- fi- fi-fi--end_testdiff --git a/tests/e2e/scenarios/api/browser-activity-extended.sh b/tests/e2e/scenarios/api/browser-activity-extended.shnew file mode 100755index 00000000..02f4c7ba--- /dev/null+++ b/tests/e2e/scenarios/api/browser-activity-extended.sh@@ -0,0 +1,91 @@+#!/bin/bash+# browser-activity-extended.sh — route metadata on the activity EVENT, which only+# happens in bridge mode: the front door records the request in one process and the+# instance builds the route in another, so the two never meet there. This needs a+# second server in the stack, which is why it is not in the PR tier beside+# browser-activity-basic.sh.++GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+source "${GROUP_DIR}/../../helpers/api.sh"++EXPECTED_BROWSER="${PINCHTAB_E2E_BROWSER:-chrome}"+ACTIVITY_TIMEOUT="${E2E_ACTIVITY_TIMEOUT:-10}"++assert_route_metadata() {+ local route="$1" label="$2"+ local used escalated attempts_len last_accepted++ used=$(echo "$route" | jq -r '.usedProvider // empty')+ escalated=$(echo "$route" | jq -r 'if has("escalated") then .escalated else "missing" end')+ attempts_len=$(echo "$route" | jq '.attempts | length' 2>/dev/null || echo "0")+ last_accepted=$(echo "$route" | jq -r '.attempts[-1].accepted' 2>/dev/null)++ if [ -n "$used" ]; then+ pass_assert "$label route.usedProvider=$used"+ else+ fail_assert "$label route.usedProvider is empty — no provider recorded as serving the request: $route"+ fi++ if [ "$attempts_len" -ge 1 ] && [ "$last_accepted" = "true" ]; then+ pass_assert "$label route.attempts ends on an accepted provider ($attempts_len attempt(s))"+ else+ fail_assert "$label route.attempts=$attempts_len with last accepted='$last_accepted', want a trail ending on an accepted provider: $route"+ fi++ case "$escalated" in+ false)+ if [ "$attempts_len" -eq 1 ]; then+ pass_assert "$label not escalated: one attempt"+ else+ fail_assert "$label escalated=false but records $attempts_len attempts: $route"+ fi+ ;;+ true)+ if [ "$attempts_len" -ge 2 ]; then+ pass_assert "$label escalated after $attempts_len attempts"+ else+ fail_assert "$label escalated=true but records only $attempts_len attempt: $route"+ fi+ ;;+ *)+ fail_assert "$label route.escalated is '$escalated', want true or false"+ ;;+ esac+}++newest_activity_event() {+ local path="$1"+ pt_get "/api/activity?limit=25" >/dev/null 2>&1+ echo "$RESULT" | jq -c --arg path "$path" '[.events[] | select(.path == $path)] | last // empty'+}++activity_event_landed() {+ local path="$1" before="$2"+ ACTIVITY_EVENT=$(newest_activity_event "$path")+ [ -n "$ACTIVITY_EVENT" ] || return 1+ [ "$(echo "$ACTIVITY_EVENT" | jq -r '.timestamp')" != "$before" ]+}++# ─────────────────────────────────────────────────────────────────+start_test "activity metadata: bridge records route metadata on the event"++if [ -z "${E2E_BRIDGE_URL:-}" ]; then+ skip_test "E2E_BRIDGE_URL is not set; route metadata lands on the activity event only in bridge mode"+else+ BRIDGE_TOKEN="${E2E_BRIDGE_TOKEN:-}"+ BEFORE_TS=$(pt_on "$E2E_BRIDGE_URL" "$BRIDGE_TOKEN" newest_activity_event /navigate | jq -r '.timestamp // empty')++ pt_on "$E2E_BRIDGE_URL" "$BRIDGE_TOKEN" pt_post "/navigate?browser=${EXPECTED_BROWSER}" -d "{\"url\":\"${FIXTURES_URL}/index.html\"}"+ assert_ok "bridge navigate with browser=${EXPECTED_BROWSER}"++ if pt_on "$E2E_BRIDGE_URL" "$BRIDGE_TOKEN" wait_until "activity_event_landed /navigate '$BEFORE_TS'" "$ACTIVITY_TIMEOUT"; then+ ROUTE=$(echo "$ACTIVITY_EVENT" | jq -c '.route // empty')+ if [ -n "$ROUTE" ]; then+ assert_route_metadata "$ROUTE" "bridge activity event"+ else+ fail_assert "bridge activity event has no route metadata: $ACTIVITY_EVENT"+ fi+ fi+fi++end_testdiff --git a/tests/e2e/scenarios/manifest.json b/tests/e2e/scenarios/manifest.jsonindex ce45858e..00ba6624 100644--- a/tests/e2e/scenarios/manifest.json+++ b/tests/e2e/scenarios/manifest.json@@ -440,6 +440,15 @@]},"api/browser-activity-basic.sh": {+ "tags": [+ "browser",+ "activity",+ "metadata",+ "route",+ "pr"+ ]+ },+ "api/browser-activity-extended.sh": {"services": ["pinchtab","pinchtab-bridge",@@ -454,7 +463,7 @@"activity","metadata","route",- "pr"+ "bridge"]},"infra/browser-instance-basic.sh": {