From d4bde62ef079429d301a241f3a2754b61b96df23 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 15 Nov 2026 13:26:27 +0800 Subject: [PATCH] =?UTF-8?q?fix(desktop):=20panic=E3=80=81=E7=AA=97?= =?UTF-8?q?=E5=8F=A3=E5=BE=AA=E7=8E=AF=E9=94=99=E8=AF=AF=E5=92=8C=E8=87=B4?= =?UTF-8?q?=E5=91=BD=E5=B4=A9=E6=BA=83=E5=85=A8=E9=83=A8=E6=8E=A5=E5=85=A5?= =?UTF-8?q?=E7=BB=9F=E4=B8=80=E6=97=A5=E5=BF=97=20(#1949)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - logstore:新增 Store.RecordPanic,无锁 panicQueue 暂存恢复的 panic(最多 8 条,超出计入丢弃), Close 途中记录的也写进最后一次排空;事件 app.runtime.panic_interrupted。 - logstore:新增 Store.CaptureCrashes,用 debug.SetCrashOutput 把致命崩溃写进默认日志目录的 .crash/<会话名>;下次启动认领旧文件,记 app.session.previous_interrupted 或 close_missing, 失败记 app.session.crash_capture_failed。macOS 用 flock,Windows 用独占打开加 DELETE_ON_CLOSE。 - core:WatchCoreEvents 增加 recovered 回调;日志唤醒回调和请求事件观察者 recover 后交给写入器, 不再静默丢弃。新增 log_text.go(LogText、LogFirstLine、LogToken、LogPanicStack), LogErrorFields 共用截断。 - workbench:Run 在窗口循环期间安装 Viva fault handler,记为 viva:<位置>;窗口循环错误记 app.window.loop_failed,已由恢复的 panic 造成时不重复记录。 - cmd/lithe:ObserveCoreFacts 之后调用 CaptureCrashes。 - PINNED_CORE_REVISION 升到 Core fix/panic-logging 的 f4f3e93(事件声明与 Core panic hook)。 - develop-lithe 日志参考页补上 panic 与致命崩溃的记录入口。 --- .../develop-lithe/references/logging.md | 5 +- desktop/cmd/lithe/main.go | 3 + desktop/internal/core/events_bridge.go | 5 +- desktop/internal/core/log_text.go | 192 ++++++++++++++++++ desktop/internal/core/log_text_test.go | 130 ++++++++++++ desktop/internal/core/log_waker.go | 72 ++++++- desktop/internal/core/log_waker_test.go | 70 +++++++ desktop/internal/core/logging.go | 15 +- desktop/internal/logstore/crash.go | 168 +++++++++++++++ desktop/internal/logstore/crash_test.go | 160 +++++++++++++++ desktop/internal/logstore/crash_unix.go | 81 ++++++++ desktop/internal/logstore/crash_windows.go | 67 ++++++ desktop/internal/logstore/panics.go | 76 +++++++ desktop/internal/logstore/panics_test.go | 191 +++++++++++++++++ desktop/internal/logstore/store.go | 35 +++- desktop/internal/logstore/writer_test.go | 28 ++- desktop/internal/workbench/app.go | 50 +++++ desktop/internal/workbench/fault_test.go | 96 +++++++++ scripts/desktop/build-desktop-core.sh | 2 +- 19 files changed, 1408 insertions(+), 38 deletions(-) create mode 100644 desktop/internal/core/log_text.go create mode 100644 desktop/internal/core/log_text_test.go create mode 100644 desktop/internal/core/log_waker_test.go create mode 100644 desktop/internal/logstore/crash.go create mode 100644 desktop/internal/logstore/crash_test.go create mode 100644 desktop/internal/logstore/crash_unix.go create mode 100644 desktop/internal/logstore/crash_windows.go create mode 100644 desktop/internal/logstore/panics.go create mode 100644 desktop/internal/logstore/panics_test.go create mode 100644 desktop/internal/workbench/fault_test.go diff --git a/.agents/skills/develop-lithe/references/logging.md b/.agents/skills/develop-lithe/references/logging.md index bddf7462d9..5a5019e016 100644 --- a/.agents/skills/develop-lithe/references/logging.md +++ b/.agents/skills/develop-lithe/references/logging.md @@ -108,7 +108,7 @@ if errors.Is(err, app.ErrCanceled) { ## 五、写入器与记录入口 -每个进程只有一个日志写入器 `desktop/internal/logstore.Store`。`cmd/lithe/main.go` 用 `logstore.Open` 创建它,调用 `ObserveCoreFacts` 安装 Core 唤醒回调,再经 `workbench.DesktopOptions.Logs` 交给窗口;退出时 `Close` 排空并写完队列。写入器打不开时客户端照常启动,没有日志窗口,“查看日志”只提示日志不可用。 +每个进程只有一个日志写入器 `desktop/internal/logstore.Store`。`cmd/lithe/main.go` 用 `logstore.Open` 创建它,调用 `ObserveCoreFacts` 安装 Core 唤醒回调、`CaptureCrashes` 接住致命崩溃,再经 `workbench.DesktopOptions.Logs` 交给窗口;退出时 `Close` 删除本会话的崩溃文件,排空并写完队列。写入器打不开时客户端照常启动,没有日志窗口,“查看日志”只提示日志不可用。 | 位置 | 记录方式 | | --- | --- | @@ -121,9 +121,12 @@ if errors.Is(err, app.ErrCanceled) { | Core 引擎随插件会话事件带来的目录事实 | `recordEngineFact`(7.8) | | Core 请求处理、执行轨迹和没有请求上下文的 Core 代码 | Core 的进程级有界事件队列;写入器在每次写入批次、flush 和关闭时排空,唤醒回调再安排一次排空(7.7) | | 链接进 Core 的辅助 crate | 本 crate 的 `failure_log` 模块,sink 由 Core 的 `runtime::helper_failures::install()` 注入;规则见 Core README | +| 被恢复的 panic:Viva 回调、Core 调进 Go 的回调(唤醒、请求的事件观察者) | `Store.RecordPanic` 记 `app.runtime.panic_interrupted`,边界写成 `viva:<位置>` 或 `core:<回调>`。它不加锁,可在任何线程、关闭途中调用:Viva 经工作台安装的 `app.SetFaultHandler`,Core 回调经 `WatchCoreEvents` 的 `recovered` | +| 没有被恢复的致命崩溃、被强制退出的会话 | `CaptureCrashes` 让 Go runtime 把崩溃报告写进本会话的崩溃文件;下次启动记 `app.session.previous_interrupted` 或 `app.session.close_missing` | 规则: +- 新增 `recover()` 边界时,把恢复的值和栈交给上表的 panic 入口,不得只恢复不记录;记录路径自身的 panic 属于写入器自身的失败,只能丢弃。 - 不得新增全局可变日志单例,不得在下层自行创建写入器,不得用 `log`、`slog`、`fmt.Fprint(os.Stderr, …)` 或 `println` 输出诊断。 - 新增构造参数、回调或接口字段用于记录失败时,同一次改动把真实实现接到每个生产构造处。`nil` 只能出现在测试里;生产路径留空等于没有记录。 - 写入器同时实现 `logwindow.Source`:日志窗口和诊断包只读取 v2 会话文件,没有 v1 缓冲。 diff --git a/desktop/cmd/lithe/main.go b/desktop/cmd/lithe/main.go index 823155ad96..06b4265266 100644 --- a/desktop/cmd/lithe/main.go +++ b/desktop/cmd/lithe/main.go @@ -46,6 +46,9 @@ func main() { } else { // Core holds one waker for the process; this client's log is the one that drains it. logs.ObserveCoreFacts() + // The runtime writes a fatal crash only to stderr, which a packaged app sends nowhere; + // the log keeps it for the next start, and tells how earlier sessions ended. + logs.CaptureCrashes() options.Logs = logs } err = workbench.New(options).Run() diff --git a/desktop/internal/core/events_bridge.go b/desktop/internal/core/events_bridge.go index 342274a112..b7c589179c 100644 --- a/desktop/internal/core/events_bridge.go +++ b/desktop/internal/core/events_bridge.go @@ -83,9 +83,12 @@ func goLitheRequestEvent(event *C.char, identity C.uintptr_t) { } // A Go panic must never unwind through Rust. The final request result is // still returned separately because Core may already have changed state. + // The panic is recorded here, where it is recovered; callers that see + // ErrCoreEventsLost do not record it again. defer func() { - if recover() != nil { + if recovered := recover(); recovered != nil { observer.failed.Store(true) + currentLogWatch.Load().report("core:events-observer", recovered) } }() if event == nil { diff --git a/desktop/internal/core/log_text.go b/desktop/internal/core/log_text.go new file mode 100644 index 0000000000..9aa7b46642 --- /dev/null +++ b/desktop/internal/core/log_text.go @@ -0,0 +1,192 @@ +package core + +import ( + "slices" + "strings" + "unicode/utf8" +) + +// logTextLimit bounds the text fields the helpers of this file build, in bytes. +const logTextLimit = 1024 + +// logTokenLimit bounds a catalog token, in bytes. +const logTokenLimit = 64 + +// visible replaces a control character with a space, so a value stays on one line. +func visible(r rune) rune { + if r < 0x20 || r == 0x7f || (r >= 0x80 && r < 0xa0) { + return ' ' + } + return r +} + +// cutText shortens text to at most limit bytes without splitting a character. +func cutText(text string, limit int) string { + if len(text) <= limit { + return text + } + cut := limit + for cut > 0 && !utf8.RuneStart(text[cut]) { + cut-- + } + return text[:cut] +} + +// LogText encodes free text, such as a panic value, the way the catalog asks for a text field: +// control characters become spaces, every run of white space becomes one space and the result +// is cut to 1024 bytes. The kernel still redacts it before it reaches the disk. +func LogText(text string) string { + return cutText(strings.Join(strings.Fields(strings.Map(visible, text)), " "), logTextLimit) +} + +// LogFirstLine is the first line of text that is not blank, encoded with LogText. It reads the +// headline of a Go crash report, such as "panic: …" or "fatal error: …". +func LogFirstLine(text string) string { + for line := range strings.Lines(text) { + if line = strings.TrimSpace(line); line != "" { + return LogText(line) + } + } + return "" +} + +// LogToken turns a short description such as "darwin: AppKit callback" into a catalog token +// such as darwin:appkit-callback. Letters are lowercased, every run of characters a token +// cannot hold becomes one hyphen, a hyphen next to a separator (".", ":" or "/") or at either +// end is dropped, and the result is cut to 64 bytes. A description with nothing left is +// "unknown". +func LogToken(text string) string { + mapped := strings.Map(func(r rune) rune { + if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || strings.ContainsRune("._:/$", r) { + return r + } + return '-' + }, strings.ToLower(text)) + keepsHyphen := func(c byte) bool { return c != 0 && c != '-' && !isTokenSeparator(c) } + out := make([]byte, 0, len(mapped)) + for i := 0; i < len(mapped); i++ { + c := mapped[i] + if c != '-' { + out = append(out, c) + continue + } + var previous, next byte + if len(out) > 0 { + previous = out[len(out)-1] + } + if i+1 < len(mapped) { + next = mapped[i+1] + } + if keepsHyphen(previous) && keepsHyphen(next) { + out = append(out, '-') + } + } + token := strings.TrimRight(cutText(string(out), logTokenLimit), "-") + if token == "" { + return "unknown" + } + return token +} + +func isTokenSeparator(c byte) bool { + return c == '.' || c == ':' || c == '/' +} + +// LogPanicStack compacts the first goroutine of a Go stack trace, as runtime/debug.Stack or a +// crash report prints it, into the frames that led to the panic. Each frame is the function +// without its package path and arguments, then the base name of its file and the line; frames +// are joined innermost first by " < ". The frames up to and including the panic call, and the +// runtime's frames before the first frame of the program, are left out. The result ends at a +// frame boundary within 1024 bytes. Base file names keep the user's directories out of the log. +func LogPanicStack(stack []byte) string { + type frame struct { + function, file string + runtime bool + } + var frames []frame + started := false + for line := range strings.Lines(string(stack)) { + line = strings.TrimRight(line, "\r\n") + if !started { + started = strings.HasPrefix(line, "goroutine ") && strings.HasSuffix(line, "]:") + continue + } + if strings.TrimSpace(line) == "" { + // The first goroutine ends at a blank line; the next one is another stack. + break + } + switch { + case strings.HasPrefix(line, "\t"): + if n := len(frames); n > 0 && frames[n-1].file == "" { + frames[n-1].file = stackFile(line) + } + case strings.HasPrefix(line, "..."): + // "...additional frames elided..." is not a frame. + default: + frames = append(frames, frame{ + function: stackFunction(line), + runtime: strings.HasPrefix(line, "runtime.") || strings.HasPrefix(line, "internal/runtime/"), + }) + } + } + for i := len(frames) - 1; i >= 0; i-- { + if frames[i].function == "panic" { + frames = frames[i+1:] + break + } + } + if program := slices.IndexFunc(frames, func(f frame) bool { return !f.runtime }); program > 0 { + frames = frames[program:] + } + var b strings.Builder + for _, f := range frames { + text := f.function + if f.file != "" { + text += " " + f.file + } + text = strings.Join(strings.Fields(strings.Map(visible, text)), " ") + separator := "" + if b.Len() > 0 { + separator = " < " + } + if b.Len()+len(separator)+len(text) > logTextLimit { + break + } + b.WriteString(separator) + b.WriteString(text) + } + return b.String() +} + +// stackFunction is the function a stack trace line names, without its package path and +// arguments, for example workbench.(*App).draw. A goroutine's creator keeps "created by". +func stackFunction(line string) string { + prefix := "" + if rest, ok := strings.CutPrefix(line, "created by "); ok { + prefix, line = "created by ", rest + if at := strings.Index(line, " in goroutine "); at >= 0 { + line = line[:at] + } + } else if at := strings.LastIndexByte(line, '('); at > 0 { + // Arguments are hexadecimal words, braces, question marks and dots, never + // parentheses, so the last opening parenthesis starts them, also after (*Type). + line = line[:at] + } + if at := strings.LastIndexByte(line, '/'); at >= 0 { + line = line[at+1:] + } + return prefix + line +} + +// stackFile is the base name and line of a stack trace file line such as +// "\t/path/app.go:900 +0x30". +func stackFile(line string) string { + line = strings.TrimSpace(line) + if at := strings.Index(line, " +0x"); at >= 0 { + line = line[:at] + } + if at := strings.LastIndexAny(line, `/\`); at >= 0 { + line = line[at+1:] + } + return line +} diff --git a/desktop/internal/core/log_text_test.go b/desktop/internal/core/log_text_test.go new file mode 100644 index 0000000000..227ee349c8 --- /dev/null +++ b/desktop/internal/core/log_text_test.go @@ -0,0 +1,130 @@ +package core + +import ( + "runtime/debug" + "strings" + "testing" +) + +func TestLogTextKeepsOneBoundedLine(t *testing.T) { + if got := LogText("index out of range\n\t[3] with\x00 length 2 "); got != "index out of range [3] with length 2" { + t.Fatalf("LogText = %q", got) + } + long := strings.Repeat("é", 600) + got := LogText(long) + if len(got) > logTextLimit || !strings.HasPrefix(long, got) || len(got) != 1024 { + t.Fatalf("LogText cut %d bytes to %d", len(long), len(got)) + } +} + +func TestLogFirstLineReadsTheCrashHeadline(t *testing.T) { + text := "\n\npanic: runtime error: invalid memory address or nil pointer dereference\n[signal SIGSEGV]\n\ngoroutine 1 [running]:\n" + if got := LogFirstLine(text); got != "panic: runtime error: invalid memory address or nil pointer dereference" { + t.Fatalf("LogFirstLine = %q", got) + } + if got := LogFirstLine(" \n\t\n"); got != "" { + t.Fatalf("LogFirstLine of blank text = %q", got) + } +} + +func TestLogTokenNormalizesFaultBoundaries(t *testing.T) { + for _, c := range []struct{ in, want string }{ + {"darwin: AppKit callback", "darwin:appkit-callback"}, + {"darwin: AppKit fullscreen callback", "darwin:appkit-fullscreen-callback"}, + {"windows: shortcut handler", "windows:shortcut-handler"}, + {"status icon window procedure", "status-icon-window-procedure"}, + {" -- odd (name) -- ", "odd-name"}, + {"UI Automation / IAccessible", "ui-automation/iaccessible"}, + {"界面", "unknown"}, + {"", "unknown"}, + {strings.Repeat("a", 63) + " b", strings.Repeat("a", 63)}, + } { + if got := LogToken(c.in); got != c.want { + t.Errorf("LogToken(%q) = %q, want %q", c.in, got, c.want) + } + } +} + +//go:noinline +func panicFixture() { + panic("fixture") +} + +// recoveredStack recovers panicFixture's panic the way a boundary does and returns the stack +// debug.Stack prints there. +func recoveredStack() (stack []byte) { + defer func() { + if recover() != nil { + stack = debug.Stack() + } + }() + panicFixture() + return nil +} + +func TestLogPanicStackStartsAtThePanickingFrame(t *testing.T) { + got := LogPanicStack(recoveredStack()) + if !strings.HasPrefix(got, "core.panicFixture log_text_test.go:") || + !strings.Contains(got, " < core.recoveredStack log_text_test.go:") { + t.Fatalf("LogPanicStack = %q", got) + } + for _, leaked := range []string{"debug.Stack", "panic ", "/", "+0x", "\t"} { + if strings.Contains(got, leaked) { + t.Fatalf("LogPanicStack = %q, which contains %q", got, leaked) + } + } +} + +func TestLogPanicStackReadsACrashReport(t *testing.T) { + report := "panic: boom [recovered]\n\tpanic: boom\n\n" + + "goroutine 7 [running]:\n" + + "github.com/1lck/Lithe-IDEA/desktop/internal/workbench.(*App).draw.func1()\n" + + "\t/Users/someone/src/desktop/internal/workbench/app.go:910 +0x5c\n" + + "panic({0x1006c8e40?, 0x1400012a0b0?})\n" + + "\t/usr/local/go/src/runtime/panic.go:787 +0x124\n" + + "github.com/1lck/Lithe-IDEA/desktop/internal/workbench.parse[...](...)\n" + + "\tC:/Users/someone/src/desktop/internal/workbench/parse.go:12\n" + + "github.com/1lck/Lithe-IDEA/desktop/internal/workbench.(*App).draw(0x14000156000, {0x1, 0x2})\n" + + "\t/Users/someone/src/desktop/internal/workbench/app.go:905 +0x30\n" + + "...additional frames elided...\n" + + "created by github.com/1lck/Lithe-IDEA/desktop/internal/workbench.(*App).Run in goroutine 1\n" + + "\t/Users/someone/src/desktop/internal/workbench/app.go:840 +0x88\n" + + "\n" + + "goroutine 1 [chan receive]:\n" + + "main.main()\n" + + "\t/Users/someone/src/desktop/cmd/lithe/main.go:40 +0x10\n" + want := "workbench.parse[...] parse.go:12 < workbench.(*App).draw app.go:905 < created by workbench.(*App).Run app.go:840" + if got := LogPanicStack([]byte(report)); got != want { + t.Fatalf("LogPanicStack =\n%q\nwant\n%q", got, want) + } +} + +func TestLogPanicStackOfAFatalErrorKeepsTheProgramFrames(t *testing.T) { + report := "fatal error: concurrent map writes\n\n" + + "goroutine 9 [running]:\n" + + "internal/runtime/maps.fatal({0x100f, 0x15})\n" + + "\t/usr/local/go/src/runtime/panic.go:1058 +0x20\n" + + "runtime.mapassign_faststr(0x1, 0x2, {0x3, 0x4})\n" + + "\t/usr/local/go/src/runtime/map_faststr.go:264 +0x2c\n" + + "main.record(...)\n" + + "\t/src/main.go:20\n" + want := "main.record main.go:20" + if got := LogPanicStack([]byte(report)); got != want { + t.Fatalf("LogPanicStack = %q, want %q", got, want) + } +} + +func TestLogPanicStackStopsAtAFrameWithinTheLimit(t *testing.T) { + var report strings.Builder + report.WriteString("goroutine 1 [running]:\n") + for range 200 { + report.WriteString("example.com/pkg.deeplyNestedFunctionName()\n\t/src/pkg/file.go:1 +0x1\n") + } + got := LogPanicStack([]byte(report.String())) + if len(got) > logTextLimit || !strings.HasSuffix(got, "pkg.deeplyNestedFunctionName file.go:1") { + t.Fatalf("LogPanicStack is %d bytes and ends %q", len(got), got[max(0, len(got)-40):]) + } + if LogPanicStack(nil) != "" || LogPanicStack([]byte("no goroutine here")) != "" { + t.Fatal("LogPanicStack of text without a stack is not empty") + } +} diff --git a/desktop/internal/core/log_waker.go b/desktop/internal/core/log_waker.go index 7b1867228d..63f52cafcf 100644 --- a/desktop/internal/core/log_waker.go +++ b/desktop/internal/core/log_waker.go @@ -21,48 +21,104 @@ static int32_t lithe_go_remove_log_waker(uintptr_t identity) { import "C" import ( + "fmt" + "runtime/debug" "sync" "sync/atomic" ) +// RecoveredPanic is a panic the client recovered in a callback Core made into Go, where +// unwinding would cross into Rust and abort the process. +type RecoveredPanic struct { + // Boundary is the catalog token of the callback that recovered it: core:log-waker for the + // waker, core:events-observer for a request's event observer. + Boundary string + // Value is the panic value as text. + Value string + // Stack is the panicking goroutine's stack as runtime/debug.Stack prints it. + Stack []byte +} + +// logWatch is one WatchCoreEvents registration. +type logWatch struct { + wake func() + recovered func(RecoveredPanic) +} + // C only receives integer identities; the registry owns the Go callbacks until Core has // removed the waker and no longer calls it. var logWakers sync.Map var logWakerID atomic.Uint64 +// currentLogWatch is the registration Core's single, process-wide waker belongs to, so it +// changes exactly when that waker does. A request's event observer has no writer of its own, +// so the panics it recovers are reported here: this is not a second log sink but the one the +// writer installed with WatchCoreEvents. +var currentLogWatch atomic.Pointer[logWatch] + // WatchCoreEvents asks the kernel to call wake when it queues a fact for the host's writer // while the previous drain has not been followed by a wake yet, and at once when facts are // already queued. wake runs on a kernel thread while the kernel holds its waker lock: it must -// only schedule a drain and never call into the kernel. A later watch replaces this one. stop -// removes the waker; once it returns wake is not running and is never called again, and -// calling stop again does nothing. -func (c *Client) WatchCoreEvents(wake func()) (stop func()) { +// only schedule a drain and never call into the kernel. +// +// recovered receives every panic the client recovers in a callback Core makes into Go, in +// wake and in the event observer of any request, on the thread Core called. It must return +// quickly and must neither block nor call into the kernel; its own panic is dropped. +// +// A later watch replaces this one. stop removes the waker; once it returns wake is not running +// and is never called again, and calling stop again does nothing. +func (c *Client) WatchCoreEvents(wake func(), recovered func(RecoveredPanic)) (stop func()) { + watch := &logWatch{wake: wake, recovered: recovered} var id uintptr for { id = uintptr(logWakerID.Add(1)) if id != 0 { - if _, loaded := logWakers.LoadOrStore(id, wake); !loaded { + if _, loaded := logWakers.LoadOrStore(id, watch); !loaded { break } } } + currentLogWatch.Store(watch) C.lithe_go_install_log_waker(C.uintptr_t(id)) var once sync.Once return func() { once.Do(func() { C.lithe_go_remove_log_waker(C.uintptr_t(id)) logWakers.Delete(id) + currentLogWatch.CompareAndSwap(watch, nil) }) } } +// report hands a panic recovered at boundary to the watch. It must be called from the deferred +// function that recovered the panic, so the stack is the panicking one. It runs inside a +// callback Core made, so its own panic, including one formatting the value, is dropped instead +// of unwinding into Rust. A nil watch, while no writer observes Core, drops the panic. +func (w *logWatch) report(boundary string, recovered any) { + if w == nil || w.recovered == nil { + return + } + defer func() { _ = recover() }() + w.recovered(RecoveredPanic{Boundary: boundary, Value: fmt.Sprint(recovered), Stack: debug.Stack()}) +} + //export goLitheLogWake func goLitheLogWake(identity C.uintptr_t) { - value, ok := logWakers.Load(uintptr(identity)) + wakeLogWatch(uintptr(identity)) +} + +// wakeLogWatch calls the wake of the watch registered as identity, if any. +func wakeLogWatch(identity uintptr) { + value, ok := logWakers.Load(identity) if !ok { return } + watch := value.(*logWatch) // A Go panic must never unwind through Rust; a lost wake only delays the next drain. - defer func() { _ = recover() }() - value.(func())() + defer func() { + if recovered := recover(); recovered != nil { + watch.report("core:log-waker", recovered) + } + }() + watch.wake() } diff --git a/desktop/internal/core/log_waker_test.go b/desktop/internal/core/log_waker_test.go new file mode 100644 index 0000000000..5687f1129f --- /dev/null +++ b/desktop/internal/core/log_waker_test.go @@ -0,0 +1,70 @@ +package core + +import ( + "encoding/json" + "errors" + "strings" + "testing" +) + +func TestObserverPanicIsReportedToTheWatch(t *testing.T) { + client := NewClient() + reports := make(chan RecoveredPanic, 4) + stop := client.WatchCoreEvents(func() {}, func(p RecoveredPanic) { + select { + case reports <- p: + default: + } + }) + observationErr, requestErr := client.ExecuteWithEvents(testContext(t), "core.ping", nil, nil, func(json.RawMessage) { + panicFixture() + }) + if !errors.Is(observationErr, ErrCoreEventsLost) || requestErr != nil { + t.Fatalf("observe=%v request=%v", observationErr, requestErr) + } + // The observer reports on the thread Core called, before the request returns. + select { + case p := <-reports: + if p.Boundary != "core:events-observer" || p.Value != "fixture" || + !strings.HasPrefix(LogPanicStack(p.Stack), "core.panicFixture log_text_test.go:") { + t.Fatalf("reported %q %q %q", p.Boundary, p.Value, LogPanicStack(p.Stack)) + } + default: + t.Fatal("the observer's panic was not reported") + } + + stop() + if currentLogWatch.Load() != nil { + t.Fatal("the watch is still current after stop") + } + // Without a watch the panic is dropped, and the request still answers. + observationErr, requestErr = client.ExecuteWithEvents(testContext(t), "core.ping", nil, nil, func(json.RawMessage) { + panicFixture() + }) + if !errors.Is(observationErr, ErrCoreEventsLost) || requestErr != nil || len(reports) != 0 { + t.Fatalf("observe=%v request=%v reports=%d after stop", observationErr, requestErr, len(reports)) + } +} + +func TestWakerPanicIsReportedToTheWatch(t *testing.T) { + var reports []RecoveredPanic + watch := &logWatch{wake: panicFixture, recovered: func(p RecoveredPanic) { reports = append(reports, p) }} + // WatchCoreEvents counts identities up from 1, so a test never meets this one. + const id = ^uintptr(0) + logWakers.Store(id, watch) + defer logWakers.Delete(id) + + wakeLogWatch(id) + if len(reports) != 1 || reports[0].Boundary != "core:log-waker" || reports[0].Value != "fixture" || + !strings.HasPrefix(LogPanicStack(reports[0].Stack), "core.panicFixture log_text_test.go:") { + t.Fatalf("reports = %+v", reports) + } + + // A receiver that panics itself must not unwind into Core either. + watch.recovered = func(RecoveredPanic) { panic("receiver broke") } + wakeLogWatch(id) + // Neither must a watch without a receiver, nor an identity Core no longer knows. + watch.recovered = nil + wakeLogWatch(id) + wakeLogWatch(id - 1) +} diff --git a/desktop/internal/core/logging.go b/desktop/internal/core/logging.go index b932657112..48ddf2af5e 100644 --- a/desktop/internal/core/logging.go +++ b/desktop/internal/core/logging.go @@ -6,7 +6,6 @@ import ( "fmt" "strings" "syscall" - "unicode/utf8" ) // LogLevel is the severity of a log record, in the kernel's canonical disk spelling. @@ -39,19 +38,7 @@ func (e *LogError) Error() string { // message without control characters, a code and the domain the code belongs to. The message // is still redacted by the kernel before it reaches the disk. func LogErrorFields(err error) map[string]any { - message := strings.Map(func(r rune) rune { - if r < 0x20 || r == 0x7f || (r >= 0x80 && r < 0xa0) { - return ' ' - } - return r - }, err.Error()) - if len(message) > 1024 { - cut := 1024 - for cut > 0 && !utf8.RuneStart(message[cut]) { - cut-- - } - message = message[:cut] - } + message := cutText(strings.Map(visible, err.Error()), logTextLimit) code, domain := any("unknown"), "go" var logErr *LogError var coreErr *Error diff --git a/desktop/internal/logstore/crash.go b/desktop/internal/logstore/crash.go new file mode 100644 index 0000000000..c516455034 --- /dev/null +++ b/desktop/internal/logstore/crash.go @@ -0,0 +1,168 @@ +package logstore + +import ( + "errors" + "os" + "path/filepath" + "runtime/debug" + "strings" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// Crash capture. +// +// The Go runtime prints a fatal crash (a panic nobody recovers, a fatal error such as concurrent +// map writes) only to stderr, which a packaged application sends nowhere. CaptureCrashes also +// has the runtime write it to a file of this session, .crash/ in the default log +// directory. That directory is the platform's writable per-user location the store already owns +// (see DefaultDir), never the application bundle or installation directory, so the file affects +// neither the code signature nor the base of a Sparkle delta update. +// +// The file is empty while the session runs, and Close removes it. A file an earlier process left +// behind is therefore either the crash report the runtime wrote, or empty because the process +// was killed, force quit or crashed outside the Go runtime; the next CaptureCrashes logs which, +// then removes the file. Only the process that created a file holds its lock, so the file of a +// session that is still running is never claimed. The directory is hidden, so log inventory, +// retention and Clear Logs leave it alone. +const ( + crashDirName = ".crash" + // crashClaimLimit bounds the earlier files one start reads; the rest wait for the next one. + crashClaimLimit = 8 + // crashReadLimit bounds the bytes read of one crash report. The crashing goroutine, the + // only one the report keeps, comes first. + crashReadLimit = 64 << 10 +) + +// crashFile is this session's crash file, open and locked for as long as the session runs. +type crashFile struct { + file *os.File + path string +} + +// release removes the file, then closes it, so no other process can claim it in between. +func (c *crashFile) release() error { + removeErr := os.Remove(c.path) + return errors.Join(removeErr, c.file.Close()) +} + +// CaptureCrashes logs how earlier sessions that did not close their log ended, then has the Go +// runtime write a fatal crash of this process to this session's crash file. The runtime keeps a +// single crash output per process, so only the application's one store may capture; it must be +// called once, after Open. Failures are logged as app.session.crash_capture_failed; the +// application runs on without the capture. +func (s *Store) CaptureCrashes() { + s.crashMu.Lock() + defer s.crashMu.Unlock() + s.mu.Lock() + stopped := s.stopped + s.mu.Unlock() + if stopped || s.crash != nil || s.defaultDir == "" { + return + } + dir := filepath.Join(s.defaultDir, crashDirName) + if err := makeCrashDir(dir); err != nil { + s.crashCaptureFailed("create", err) + return + } + session := sessionName(s.SessionPath()) + // This session's file is locked before anything is claimed, so a process that starts at + // the same time cannot take it for a leftover. + own, err := createCrashFile(dir, session) + if err != nil { + s.crashCaptureFailed("create", err) + } + s.claimCrashes(dir, session) + if own == nil { + return + } + if err := debug.SetCrashOutput(own.file, debug.CrashOptions{}); err != nil { + s.crashCaptureFailed("create", errors.Join(err, own.release())) + return + } + s.crash = own +} + +// releaseCrashFile stops the crash capture and removes this session's file. Close calls it +// before the store stops taking events, so a failure can still be logged. +func (s *Store) releaseCrashFile() { + s.crashMu.Lock() + defer s.crashMu.Unlock() + own := s.crash + s.crash = nil + if own == nil { + return + } + err := debug.SetCrashOutput(nil, debug.CrashOptions{}) + if err = errors.Join(err, own.release()); err != nil { + s.crashCaptureFailed("release", err) + } +} + +// makeCrashDir creates the crash directory, private to the user, and refuses anything there +// that is not a directory, such as a symbolic link. +func makeCrashDir(dir string) error { + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + info, err := os.Lstat(dir) + if err != nil { + return err + } + if !info.IsDir() { + return &os.PathError{Op: "mkdir", Path: dir, Err: errors.New("not a directory")} + } + return nil +} + +// claimCrashes logs and removes the crash files earlier processes left in dir, at most +// crashClaimLimit of them. own is this session's file, which is never claimed. +func (s *Store) claimCrashes(dir, own string) { + entries, err := os.ReadDir(dir) + if err != nil { + s.crashCaptureFailed("claim", err) + return + } + claimed := 0 + for _, entry := range entries { + if claimed >= crashClaimLimit { + return + } + name := entry.Name() + stale := strings.HasPrefix(name, ".") && strings.HasSuffix(name, crashTempSuffix) + if name == own || !entry.Type().IsRegular() || (!stale && !sessionNamePattern.MatchString(name)) { + continue + } + report, ok, err := claimCrashFile(filepath.Join(dir, name)) + if err != nil { + s.crashCaptureFailed("claim", err) + continue + } + if !ok || stale { + // log-exempt: 预期的缺失:文件属于仍在运行的会话、已被同时启动的进程认领,或是创建到一半的临时文件。 + continue + } + claimed++ + s.previousSessionEnded("sessions/"+name, report) + } +} + +// previousSessionEnded logs how the session whose crash file held report ended. +func (s *Store) previousSessionEnded(session string, report []byte) { + headline := core.LogFirstLine(string(report)) + if headline == "" { + s.Emit(core.LevelWarn, "app.session.close_missing", "", map[string]any{"session": session}) + return + } + fields := map[string]any{"session": session, "panic": headline} + if frames := core.LogPanicStack(report); frames != "" { + fields["stack"] = frames + } + s.Emit(core.LevelError, "app.session.previous_interrupted", "", fields) +} + +func (s *Store) crashCaptureFailed(stage string, err error) { + fields := core.LogErrorFields(err) + fields["stage"] = stage + s.Emit(core.LevelWarn, "app.session.crash_capture_failed", "", fields) +} diff --git a/desktop/internal/logstore/crash_test.go b/desktop/internal/logstore/crash_test.go new file mode 100644 index 0000000000..1a27631fea --- /dev/null +++ b/desktop/internal/logstore/crash_test.go @@ -0,0 +1,160 @@ +package logstore + +import ( + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "slices" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +const crashedSession = "2026-11-08T09-00-00_0123abcd" +const killedSession = "2026-11-08T08-00-00_89abcdef" + +// crashDir makes the crash directory of the log directory dir and returns it. +func crashDir(t *testing.T, dir string) string { + t.Helper() + crashes := filepath.Join(dir, crashDirName) + if err := os.MkdirAll(crashes, 0o700); err != nil { + t.Fatal(err) + } + return crashes +} + +func writeFile(t *testing.T, path, text string) { + t.Helper() + if err := os.WriteFile(path, []byte(text), 0o600); err != nil { + t.Fatal(err) + } +} + +func fileExists(t *testing.T, path string) bool { + t.Helper() + _, err := os.Lstat(path) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + t.Fatal(err) + } + return err == nil +} + +// recordsOf lists the written records of event in the current session. +func recordsOf(t *testing.T, s *Store, event string) []core.LogRecord { + t.Helper() + var records []core.LogRecord + for _, record := range window(t, s, Query{Session: "current"}).Records { + if record.Event == event { + records = append(records, record) + } + } + return records +} + +func TestEarlierSessionsThatDidNotCloseAreLogged(t *testing.T) { + dir := t.TempDir() + crashes := crashDir(t, dir) + writeFile(t, filepath.Join(crashes, crashedSession), "panic: boom [recovered]\n\tpanic: boom\n\n"+ + "goroutine 1 [running]:\nmain.main()\n\t/src/cmd/lithe/main.go:9 +0x1c\n") + writeFile(t, filepath.Join(crashes, killedSession), "") + writeFile(t, filepath.Join(crashes, "notes.txt"), "not a crash file") + + s, _, _ := openStore(t, func(o *Options) { o.Dir = dir }) + s.CaptureCrashes() + flush(t, s) + + crashed := recordsOf(t, s, "app.session.previous_interrupted") + if len(crashed) != 1 || crashed[0].Fields["session"] != "sessions/"+crashedSession || + crashed[0].Fields["panic"] != "panic: boom [recovered]" || crashed[0].Fields["stack"] != "main.main main.go:9" { + t.Fatalf("previous_interrupted = %+v", crashed) + } + killed := recordsOf(t, s, "app.session.close_missing") + if len(killed) != 1 || killed[0].Fields["session"] != "sessions/"+killedSession { + t.Fatalf("close_missing = %+v", killed) + } + if fileExists(t, filepath.Join(crashes, crashedSession)) || fileExists(t, filepath.Join(crashes, killedSession)) || + !fileExists(t, filepath.Join(crashes, "notes.txt")) { + t.Fatal("the claimed files are not removed, or a file that is not a crash file is") + } + + // This session's file exists while it runs; Clear Logs leaves it, and Close removes it. + own := filepath.Join(crashes, sessionName(s.SessionPath())) + if !fileExists(t, own) { + t.Fatalf("this session's crash file %s is missing", own) + } + if err := s.ClearLogs(); err != nil { + t.Fatalf("ClearLogs: %v", err) + } + if !fileExists(t, own) { + t.Fatal("Clear Logs removed this session's crash file") + } + s.Close() + if fileExists(t, own) { + t.Fatal("Close left this session's crash file") + } +} + +func TestTheCrashFileOfARunningSessionIsNotClaimed(t *testing.T) { + dir := t.TempDir() + crashes := crashDir(t, dir) + live, err := createCrashFile(crashes, crashedSession) + if err != nil { + t.Fatalf("createCrashFile: %v", err) + } + t.Cleanup(func() { _ = live.release() }) + + s, _, _ := openStore(t, func(o *Options) { o.Dir = dir }) + s.CaptureCrashes() + flush(t, s) + if got := eventCounts(window(t, s, Query{Session: "current"}).Records); got["app.session.close_missing"] != 0 || + got["app.session.previous_interrupted"] != 0 || got["app.session.crash_capture_failed"] != 0 { + t.Fatalf("records = %v, want the running session's file left alone", got) + } + if !fileExists(t, live.path) { + t.Fatal("the running session's crash file was removed") + } +} + +func TestOneStartClaimsABoundedNumberOfCrashFiles(t *testing.T) { + dir := t.TempDir() + crashes := crashDir(t, dir) + var names []string + for i := range crashClaimLimit + 2 { + name := fmt.Sprintf("2026-11-08T07-00-%02d_%08x", i, i) + names = append(names, name) + writeFile(t, filepath.Join(crashes, name), "") + } + slices.Sort(names) + + s, _, _ := openStore(t, func(o *Options) { o.Dir = dir }) + s.CaptureCrashes() + flush(t, s) + if got := len(recordsOf(t, s, "app.session.close_missing")); got != crashClaimLimit { + t.Fatalf("close_missing records = %d, want %d", got, crashClaimLimit) + } + left := 0 + for _, name := range names { + if fileExists(t, filepath.Join(crashes, name)) { + left++ + } + } + if left != 2 { + t.Fatalf("%d crash files are left, want 2 for the next start", left) + } +} + +func TestAFailedCrashCaptureIsLogged(t *testing.T) { + dir := t.TempDir() + // A file where the crash directory belongs. + writeFile(t, filepath.Join(dir, crashDirName), "") + + s, _, _ := openStore(t, func(o *Options) { o.Dir = dir }) + s.CaptureCrashes() + flush(t, s) + failed := recordsOf(t, s, "app.session.crash_capture_failed") + if len(failed) != 1 || failed[0].Fields["stage"] != "create" || failed[0].Fields["error_code"] == "" { + t.Fatalf("crash_capture_failed = %+v", failed) + } +} diff --git a/desktop/internal/logstore/crash_unix.go b/desktop/internal/logstore/crash_unix.go new file mode 100644 index 0000000000..039883def2 --- /dev/null +++ b/desktop/internal/logstore/crash_unix.go @@ -0,0 +1,81 @@ +//go:build !windows + +package logstore + +import ( + "errors" + "io" + "io/fs" + "os" + "path/filepath" + + "golang.org/x/sys/unix" +) + +// crashTempSuffix ends the hidden name a crash file has until it is locked. +const crashTempSuffix = ".tmp" + +// createCrashFile creates and locks this session's crash file in dir. It is made under a hidden +// name, which is never claimed, and renamed only once locked, so no other process can claim it +// in between. The lock is an flock, which the descriptor the runtime duplicates shares and the +// kernel drops when the process ends, however it ends. +func createCrashFile(dir, session string) (*crashFile, error) { + if session == "" { + return nil, errors.New("logstore: the session has no name for its crash file") + } + temp := filepath.Join(dir, "."+session+crashTempSuffix) + file, err := os.OpenFile(temp, os.O_WRONLY|os.O_CREATE|os.O_EXCL|unix.O_NOFOLLOW, 0o600) + if err != nil { + return nil, err + } + target := filepath.Join(dir, session) + if err := unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil { + return nil, errors.Join(&os.PathError{Op: "flock", Path: temp, Err: err}, os.Remove(temp), file.Close()) + } + if err := os.Rename(temp, target); err != nil { + return nil, errors.Join(err, os.Remove(temp), file.Close()) + } + return &crashFile{file: file, path: target}, nil +} + +// claimCrashFile reads and removes the crash file at path when no running process holds it. +// claimed is false, without an error, when the file belongs to a running session or another +// starting process claimed it first. +func claimCrashFile(path string) (report []byte, claimed bool, err error) { + file, err := os.OpenFile(path, os.O_RDONLY|unix.O_NOFOLLOW, 0) + if errors.Is(err, fs.ErrNotExist) { + // log-exempt: 预期的缺失:同时启动的进程刚认领并删除了它。 + return nil, false, nil + } + if err != nil { + return nil, false, err + } + defer file.Close() + if err := unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil { + if errors.Is(err, unix.EWOULDBLOCK) { + // log-exempt: 预期的缺失:文件属于仍在运行的会话。 + return nil, false, nil + } + return nil, false, &os.PathError{Op: "flock", Path: path, Err: err} + } + // Another process may have claimed and removed the file between the open and the lock. + opened, err := file.Stat() + if err != nil { + return nil, false, err + } + current, err := os.Lstat(path) + if errors.Is(err, fs.ErrNotExist) || (err == nil && !os.SameFile(opened, current)) { + // log-exempt: 预期的缺失:加锁之前同时启动的进程已认领并删除了它。 + return nil, false, nil + } + if err != nil { + return nil, false, err + } + if report, err = io.ReadAll(io.LimitReader(file, crashReadLimit)); err != nil { + return nil, false, err + } + if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) { + return nil, false, err + } + return report, true, nil +} diff --git a/desktop/internal/logstore/crash_windows.go b/desktop/internal/logstore/crash_windows.go new file mode 100644 index 0000000000..1723406346 --- /dev/null +++ b/desktop/internal/logstore/crash_windows.go @@ -0,0 +1,67 @@ +//go:build windows + +package logstore + +import ( + "errors" + "io" + "os" + "path/filepath" + + "golang.org/x/sys/windows" +) + +// crashTempSuffix ends the hidden name of a half-made crash file. Windows makes the file locked +// from the start, so it never has one; the name is shared with other platforms. +const crashTempSuffix = ".tmp" + +// createCrashFile creates this session's crash file in dir. Its handle shares reading, writing +// and deletion, but every claim asks for exclusive access, so no other process can claim the +// file while this one, or the handle the runtime duplicates, keeps it open; Windows closes both +// when the process ends, however it ends. +func createCrashFile(dir, session string) (*crashFile, error) { + if session == "" { + return nil, errors.New("logstore: the session has no name for its crash file") + } + target := filepath.Join(dir, session) + name, err := windows.UTF16PtrFromString(target) + if err != nil { + return nil, &os.PathError{Op: "create", Path: target, Err: err} + } + handle, err := windows.CreateFile(name, windows.GENERIC_WRITE, + windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, + nil, windows.CREATE_NEW, windows.FILE_ATTRIBUTE_NORMAL, 0) + if err != nil { + return nil, &os.PathError{Op: "create", Path: target, Err: err} + } + return &crashFile{file: os.NewFile(uintptr(handle), target), path: target}, nil +} + +// claimCrashFile reads and removes the crash file at path when no running process holds it. +// claimed is false, without an error, when the file belongs to a running session, is being +// removed by the session that ended, or another starting process claimed it first. +func claimCrashFile(path string) (report []byte, claimed bool, err error) { + name, err := windows.UTF16PtrFromString(path) + if err != nil { + return nil, false, &os.PathError{Op: "open", Path: path, Err: err} + } + // Exclusive access, and Windows deletes the file when this handle closes. + handle, err := windows.CreateFile(name, windows.GENERIC_READ|windows.DELETE, 0, nil, + windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL|windows.FILE_FLAG_DELETE_ON_CLOSE, 0) + switch { + case errors.Is(err, windows.ERROR_FILE_NOT_FOUND), errors.Is(err, windows.ERROR_PATH_NOT_FOUND): + // log-exempt: 预期的缺失:同时启动的进程刚认领并删除了它。 + return nil, false, nil + case errors.Is(err, windows.ERROR_SHARING_VIOLATION), errors.Is(err, windows.ERROR_ACCESS_DENIED): + // log-exempt: 预期的缺失:文件属于仍在运行的会话,或正被结束的会话删除。 + return nil, false, nil + case err != nil: + return nil, false, &os.PathError{Op: "open", Path: path, Err: err} + } + file := os.NewFile(uintptr(handle), path) + report, err = io.ReadAll(io.LimitReader(file, crashReadLimit)) + if err = errors.Join(err, file.Close()); err != nil { + return nil, false, err + } + return report, true, nil +} diff --git a/desktop/internal/logstore/panics.go b/desktop/internal/logstore/panics.go new file mode 100644 index 0000000000..19675de977 --- /dev/null +++ b/desktop/internal/logstore/panics.go @@ -0,0 +1,76 @@ +package logstore + +import ( + "slices" + "sync/atomic" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// panicLimit bounds the recovered panics one drain writes; the rest are counted as dropped. +const panicLimit = 8 + +// panicQueue holds recovered panics until the writer's next drain. A panic is recovered on +// whatever thread raised it, often inside a callback of AppKit, Win32 or the kernel that holds +// its own lock, so recording one may neither block nor take a lock: the queue is a lock-free +// stack the drain empties at once. It is filled even while the store is stopping, which is why +// it does not go through Emit, and the final drain still writes it. +type panicQueue struct { + now func() time.Time + head atomic.Pointer[panicNode] + count atomic.Int64 + lost atomic.Uint64 +} + +type panicNode struct { + event queued + next *panicNode +} + +// Emit queues one event, or counts it as lost while panicLimit events are already waiting. +func (q *panicQueue) Emit(level core.LogLevel, event, op string, fields map[string]any) { + if q.count.Add(1) > panicLimit { + q.count.Add(-1) + q.lost.Add(1) + return + } + node := &panicNode{event: queued{ts: q.now(), level: level, event: event, op: op, fields: fields}} + for { + node.next = q.head.Load() + if q.head.CompareAndSwap(node.next, node) { + return + } + } +} + +// take empties the queue and returns its events oldest first, with the number lost since the +// previous take. +func (q *panicQueue) take() ([]queued, uint64) { + var events []queued + for node := q.head.Swap(nil); node != nil; node = node.next { + events = append(events, node.event) + } + q.count.Add(-int64(len(events))) + slices.Reverse(events) + return events, q.lost.Swap(0) +} + +// RecordPanic logs a panic recovered at boundary, such as viva:window-procedure or +// core:events-observer, as app.runtime.panic_interrupted: value is the panic value as text and +// stack the panicking goroutine's stack as runtime/debug.Stack prints it, nil when there is +// none. It may be called from any thread, including inside a platform or kernel callback that +// holds a lock: it neither blocks, nor takes a lock, nor calls the kernel. The record reaches +// the disk with the writer's next drain, which it schedules, and also when Close is already +// running; a panic recorded after Close has returned is not written. +func (s *Store) RecordPanic(boundary, value string, stack []byte) { + fields := map[string]any{"boundary": core.LogToken(boundary), "panic": core.LogText(value)} + if fields["panic"] == "" { + fields["panic"] = "" + } + if frames := core.LogPanicStack(stack); frames != "" { + fields["stack"] = frames + } + s.panics.Emit(core.LevelError, "app.runtime.panic_interrupted", "", fields) + signal(s.wake) +} diff --git a/desktop/internal/logstore/panics_test.go b/desktop/internal/logstore/panics_test.go new file mode 100644 index 0000000000..4161da717d --- /dev/null +++ b/desktop/internal/logstore/panics_test.go @@ -0,0 +1,191 @@ +package logstore + +import ( + "context" + "encoding/json" + "runtime/debug" + "strconv" + "strings" + "sync" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +const panicEvent = "app.runtime.panic_interrupted" + +//go:noinline +func panicFixture() { + panic("fixture") +} + +// recoveredStack recovers panicFixture's panic the way a boundary does and returns the stack +// debug.Stack prints there. +func recoveredStack() (stack []byte) { + defer func() { + if recover() != nil { + stack = debug.Stack() + } + }() + panicFixture() + return nil +} + +// panicRecords lists the written app.runtime.panic_interrupted records of the current session. +func panicRecords(t *testing.T, s *Store) []core.LogRecord { + t.Helper() + var records []core.LogRecord + for _, record := range window(t, s, Query{Session: "current"}).Records { + if record.Event == panicEvent { + records = append(records, record) + } + } + return records +} + +func TestRecoveredPanicReachesTheDisk(t *testing.T) { + s, _, _ := openStore(t, nil) + flush(t, s) + + // Nothing but RecordPanic schedules the drain that writes it. + written := awaitLine(t, s, panicEvent) + s.RecordPanic("viva:darwin: AppKit callback", "index out of range\n[3] with length 2", recoveredStack()) + written() + + records := panicRecords(t, s) + if len(records) != 1 { + t.Fatalf("panic records = %+v, want one", records) + } + fields := records[0].Fields + if fields["boundary"] != "viva:darwin:appkit-callback" || fields["panic"] != "index out of range [3] with length 2" { + t.Fatalf("panic fields = %+v", fields) + } + if !strings.HasPrefix(fields["stack"], "logstore.panicFixture panics_test.go:") { + t.Fatalf("panic stack = %q, want it to start at the panicking frame", fields["stack"]) + } +} + +func TestPanicRecordedWhileClosingIsWritten(t *testing.T) { + s, _, dir := openStore(t, nil) + flush(t, s) + + // Close has begun: the store takes no more events, but the panic that ends the + // application still reaches the final drain. + s.mu.Lock() + s.stopped = true + s.mu.Unlock() + action(s, "after_close_began") + s.RecordPanic("viva:window procedure", "", nil) + s.Close() + + text := readTree(t, dir) + if !strings.Contains(text, panicEvent) || !strings.Contains(text, "viva:window-procedure") || !strings.Contains(text, "") { + t.Fatalf("the panic recorded while closing is missing from the log:\n%s", text) + } + if strings.Contains(text, "after_close_began") { + t.Fatal("an ordinary event queued after Close began was written") + } +} + +func TestPanicQueueKeepsTheOldestWithinItsLimit(t *testing.T) { + clock := newTestClock() + q := panicQueue{now: clock.Now} + for i := range panicLimit + 12 { + q.Emit(core.LevelError, panicEvent, "", map[string]any{"panic": strconv.Itoa(i)}) + } + events, lost := q.take() + if len(events) != panicLimit || lost != 12 { + t.Fatalf("took %d events, %d lost; want %d and 12", len(events), lost, panicLimit) + } + for i, event := range events { + if event.fields["panic"] != strconv.Itoa(i) || (i > 0 && !events[i-1].ts.Before(event.ts)) { + t.Fatalf("event %d = %+v, want the queue's order", i, event) + } + } + // Taking frees the room and resets the loss. + q.Emit(core.LevelError, panicEvent, "", nil) + if events, lost := q.take(); len(events) != 1 || lost != 0 { + t.Fatalf("after taking: %d events, %d lost; want 1 and 0", len(events), lost) + } +} + +func TestLostPanicsAreReportedAsDropped(t *testing.T) { + s, _, _ := openStore(t, nil) + flush(t, s) + + s.panics.lost.Add(3) + flush(t, s) + if dropped, _ := s.Stats(); dropped != 3 { + t.Fatalf("dropped = %d, want the 3 lost panics", dropped) + } + counts := fieldValues(window(t, s, Query{Session: "current"}).Records, droppedEvent, "count") + if len(counts) != 1 || counts[0] != "3" { + t.Fatalf("log.dropped counts = %v, want [3]", counts) + } +} + +func TestPanicsAndEventsRecordedTogether(t *testing.T) { + s, _, _ := openStore(t, nil) + flush(t, s) + + const workers, each = 4, 10 + var wg sync.WaitGroup + for w := range workers { + wg.Go(func() { + for i := range each { + s.RecordPanic("viva:shortcut hook", "worker "+strconv.Itoa(w)+" panic "+strconv.Itoa(i), nil) + action(s, "worker_"+strconv.Itoa(w)+"_"+strconv.Itoa(i)) + } + }) + } + wg.Wait() + flush(t, s) + + // Every panic is either written or counted; the ordinary events all arrive. + records := window(t, s, Query{Session: "current"}).Records + dropped, failures := s.Stats() + if got := eventCounts(records); got[panicEvent]+dropped != workers*each || got["app.action.performed"] != workers*each || failures != 0 { + t.Fatalf("written %v, dropped %d, failures %d; want %d panics written or dropped", got, dropped, failures, workers*each) + } +} + +func TestKernelPanicsReachTheStore(t *testing.T) { + kernel := &wakingKernel{Kernel: core.NewClient()} + s, _, _ := openStore(t, func(o *Options) { o.Kernel = kernel }) + s.ObserveCoreFacts() + flush(t, s) + + written := awaitLine(t, s, "core:events-observer") + kernel.reportPanic(core.RecoveredPanic{Boundary: "core:events-observer", Value: "observer broke", Stack: recoveredStack()}) + written() + + s.Close() + // After Close the store no longer receives the kernel's panics. + kernel.reportPanic(core.RecoveredPanic{Boundary: "core:log-waker", Value: "late"}) + if events, _ := s.panics.take(); len(events) != 0 { + t.Fatalf("a closed store received %d kernel panics", len(events)) + } +} + +func TestObserverPanicOfARealRequestIsWritten(t *testing.T) { + s, _, _ := openStore(t, nil) + s.ObserveCoreFacts() + flush(t, s) + + written := awaitLine(t, s, "core:events-observer") + ctx, cancel := context.WithTimeout(context.Background(), waitLimit) + defer cancel() + var result json.RawMessage + observationErr, requestErr := s.kernel.(*core.Client).ExecuteWithEvents(ctx, "core.ping", nil, &result, func(json.RawMessage) { + panic("observer broke") + }) + if requestErr != nil || observationErr == nil { + t.Fatalf("ExecuteWithEvents = %v, %v; want the observation lost and the request answered", observationErr, requestErr) + } + written() + records := panicRecords(t, s) + if len(records) != 1 || records[0].Fields["panic"] != "observer broke" || + !strings.Contains(records[0].Fields["stack"], "panics_test.go:") { + t.Fatalf("panic records = %+v", records) + } +} diff --git a/desktop/internal/logstore/store.go b/desktop/internal/logstore/store.go index f321058d75..0ae7b9c4ee 100644 --- a/desktop/internal/logstore/store.go +++ b/desktop/internal/logstore/store.go @@ -115,8 +115,9 @@ type Kernel interface { PlanLogRetention(ctx context.Context, request core.LogRetentionRequest) (core.LogRetentionPlan, error) DrainCoreEvents(ctx context.Context) (core.CoreEvents, error) ConfigureCoreEvents(ctx context.Context, debug bool, roots []string) error - // WatchCoreEvents installs the kernel's single, process-wide waker; see ObserveCoreFacts. - WatchCoreEvents(wake func()) (stop func()) + // WatchCoreEvents installs the kernel's single, process-wide waker, and the receiver of the + // panics the client recovers in callbacks the kernel makes; see ObserveCoreFacts. + WatchCoreEvents(wake func(), recovered func(core.RecoveredPanic)) (stop func()) } // Rejection counts the events the kernel refused to encode for one reason. A rejected event is @@ -233,6 +234,13 @@ type Store struct { // unwatch removes the kernel's waker; nil while the store does not observe the kernel. unwatch func() + // panics holds recovered panics until the next drain; it takes no lock (see RecordPanic). + panics panicQueue + // crash is the file the Go runtime writes a fatal crash report to; nil without one (see + // CaptureCrashes). crashMu guards it, and is held across the file operations. + crashMu sync.Mutex + crash *crashFile + wake chan struct{} // work was queued; arm the coalescing timer full chan struct{} // a whole batch is waiting; drain now jobs chan func() // control operations, run on the writer @@ -349,6 +357,7 @@ func Open(opts Options) (*Store, error) { headers: make(map[string]string), handles: make(map[string]*openLog), } + s.panics.now = now redirectErr := s.switchDirectory(chosen) if redirectErr != nil { if defaultDir == "" || chosen == defaultDir { @@ -397,8 +406,11 @@ func (s *Store) ObserveCoreFacts() { return } // The kernel calls wake while holding its waker lock: it may only signal the writer, and - // signal neither blocks nor takes s.mu. - s.unwatch = s.kernel.WatchCoreEvents(func() { signal(s.wake) }) + // signal neither blocks nor takes s.mu. The client may report a panic at once, while s.mu is + // held here, so RecordPanic takes no lock either. + s.unwatch = s.kernel.WatchCoreEvents(func() { signal(s.wake) }, func(p core.RecoveredPanic) { + s.RecordPanic(p.Boundary, p.Value, p.Stack) + }) } // newSessionID returns a random version 4 UUID in lowercase, the form the kernel's session @@ -541,8 +553,10 @@ func (s *Store) Emit(level core.LogLevel, event, op string, fields map[string]an } // Close drains the queue one last time, closes every file and ends the writer. It is safe to -// call more than once. It must not be called from a Subscribe callback. +// call more than once. It must not be called from a Subscribe callback. The crash capture ends +// first, while a failure to remove the session's crash file can still be logged. func (s *Store) Close() { + s.releaseCrashFile() s.mu.Lock() s.stopped = true s.mu.Unlock() @@ -1007,9 +1021,20 @@ func (s *Store) drain(ctx context.Context) error { } ctx = context.WithoutCancel(ctx) + // Recovered panics are taken even while the store is stopping, so the final drain writes + // the panic that made the application quit. + recovered, lostPanics := s.panics.take() s.mu.Lock() work := s.pending s.pending = nil + if len(recovered) > 0 { + work = append(work, recovered...) + slices.SortStableFunc(work, func(a, b queued) int { return a.ts.Compare(b.ts) }) + } + if lostPanics > 0 { + s.dropped = saturatingAdd(s.dropped, lostPanics) + s.unreportedDropped = saturatingAdd(s.unreportedDropped, lostPanics) + } unreported := s.unreportedDropped s.unreportedDropped = 0 s.scheduled, s.urgent = false, false diff --git a/desktop/internal/logstore/writer_test.go b/desktop/internal/logstore/writer_test.go index 017fa289b4..c8dc17c097 100644 --- a/desktop/internal/logstore/writer_test.go +++ b/desktop/internal/logstore/writer_test.go @@ -21,26 +21,38 @@ import ( // the store installed, the way the kernel does when one of its own facts is recorded. type wakingKernel struct { Kernel - mu sync.Mutex - wake func() - installs int - removals int - facts []core.CoreEvent + mu sync.Mutex + wake func() + recovered func(core.RecoveredPanic) + installs int + removals int + facts []core.CoreEvent } -func (k *wakingKernel) WatchCoreEvents(wake func()) func() { +func (k *wakingKernel) WatchCoreEvents(wake func(), recovered func(core.RecoveredPanic)) func() { k.mu.Lock() defer k.mu.Unlock() - k.wake = wake + k.wake, k.recovered = wake, recovered k.installs++ return func() { k.mu.Lock() defer k.mu.Unlock() - k.wake = nil + k.wake, k.recovered = nil, nil k.removals++ } } +// reportPanic hands a panic to the receiver the store installed, the way the client does when it +// recovers one in a callback of the kernel. +func (k *wakingKernel) reportPanic(p core.RecoveredPanic) { + k.mu.Lock() + recovered := k.recovered + k.mu.Unlock() + if recovered != nil { + recovered(p) + } +} + func (k *wakingKernel) record(fact core.CoreEvent) { k.mu.Lock() k.facts = append(k.facts, fact) diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 365ec063e1..f03c8fdc13 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -257,6 +257,13 @@ type diagnosticsWatchSink interface { WatchDiagnostics(watch func(on bool)) (stop func()) } +// panicSink is the part of the client's log that records a panic recovered on any thread, +// without taking a lock. *logstore.Store implements it; with a sink without it the panics Viva +// recovers in its callbacks are not logged. +type panicSink interface { + RecordPanic(boundary, value string, stack []byte) +} + // logsShortcut opens the log window, as on macOS. const logsShortcut = "⇧⌘L" @@ -836,6 +843,8 @@ func (a *App) Run() error { app.SetNativeAppearance(nativeAppearance(a.settings.Theme)) stop := app.WatchSystemAppearance(a.systemAppearanceChanged) defer stop() + faulted := a.watchFaults() + defer app.SetFaultHandler(nil) // app.Run opens a bare window that never paints; the window with the frame callbacks // is opened by the application. err := app.RunApplication(func(application *app.Application) error { @@ -866,6 +875,7 @@ func (a *App) Run() error { } return nil }) + a.windowLoopEnded(err, faulted.Load()) for _, session := range a.sessions.everyOne() { session.unsubscribeSettings() session.stopWatchingDiagnostics() @@ -886,6 +896,46 @@ func (a *App) Run() error { return err } +// watchFaults has Viva hand each panic it recovers in a callback to the client's log, as +// app.runtime.panic_interrupted under the boundary viva:. Viva calls the handler on the +// panicking thread, which may hold the framework's locks, so it only records and sets the +// returned flag; Run removes the handler when the window loop ends. Without a log that records +// panics the flag stays false. +func (a *App) watchFaults() *atomic.Bool { + faulted := new(atomic.Bool) + if record := a.faultRecorder(faulted); record != nil { + app.SetFaultHandler(record) + } + return faulted +} + +// faultRecorder is the fault handler watchFaults installs: it records the fault in the client's +// log and sets faulted. It is nil without a log that records panics. +func (a *App) faultRecorder(faulted *atomic.Bool) func(app.Fault) { + sink, ok := a.logSink.(panicSink) + if !ok { + return nil + } + return func(fault app.Fault) { + faulted.Store(true) + sink.RecordPanic("viva:"+fault.Where, fault.Message, fault.Stack) + } +} + +// windowLoopEnded logs the error the window loop ended with, as app.window.loop_failed. When +// Viva recovered a panic during the loop the error is the one that panic caused, which is +// already logged. +func (a *App) windowLoopEnded(err error, faulted bool) { + if err == nil { + return + } + if faulted { + // log-exempt: 同一次失败已经记录过:Viva 恢复的 panic 已经记成 app.runtime.panic_interrupted,窗口循环返回的就是它造成的错误。 + return + } + a.emitAs("", core.LevelError, "app.window.loop_failed", core.LogErrorFields(err)) +} + // systemAppearanceChanged hands the system event to the workbench thread before // publishing the effective palette to its other windows. func (a *App) systemAppearanceChanged() { diff --git a/desktop/internal/workbench/fault_test.go b/desktop/internal/workbench/fault_test.go new file mode 100644 index 0000000000..c6a0e1d28b --- /dev/null +++ b/desktop/internal/workbench/fault_test.go @@ -0,0 +1,96 @@ +package workbench + +import ( + "errors" + "sync" + "sync/atomic" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/logstore" + "github.com/vivaui/viva/app" +) + +// The window finds the log that records Viva's recovered panics by a type assertion on its log +// sink, which would silently leave them unlogged if the store stopped implementing it. +var _ panicSink = (*logstore.Store)(nil) + +type recordedPanic struct { + boundary, value string + stack []byte +} + +type recordedEvent struct { + event, op string + fields map[string]any +} + +// faultLog is a log sink that keeps the panics and events it is given. +type faultLog struct { + opRecordingLog + mu sync.Mutex + panics []recordedPanic + events []recordedEvent +} + +func (l *faultLog) RecordPanic(boundary, value string, stack []byte) { + l.mu.Lock() + defer l.mu.Unlock() + l.panics = append(l.panics, recordedPanic{boundary: boundary, value: value, stack: stack}) +} + +func (l *faultLog) Emit(level core.LogLevel, event, op string, fields map[string]any) { + l.mu.Lock() + defer l.mu.Unlock() + l.events = append(l.events, recordedEvent{event: event, op: op, fields: fields}) +} + +// TestVivaFaultsAreRecordedAsPanics checks that the fault handler the window installs records +// each panic Viva recovers under the boundary viva:, with its message and stack, and +// marks the window loop as faulted, and that a window without a log that records panics +// installs none. +func TestVivaFaultsAreRecordedAsPanics(t *testing.T) { + log := &faultLog{} + a := &App{logSink: log} + faulted := new(atomic.Bool) + record := a.faultRecorder(faulted) + if record == nil { + t.Fatal("no fault handler for a log that records panics") + } + stack := []byte("goroutine 1 [running]:\n") + record(app.Fault{Where: "darwin: AppKit callback", Message: "boom", Stack: stack}) + if len(log.panics) != 1 || log.panics[0].boundary != "viva:darwin: AppKit callback" || + log.panics[0].value != "boom" || string(log.panics[0].stack) != string(stack) { + t.Fatalf("recorded panics = %+v", log.panics) + } + if !faulted.Load() { + t.Fatal("the window loop is not marked as faulted") + } + + plain := &App{logSink: &opRecordingLog{}} + if plain.faultRecorder(new(atomic.Bool)) != nil { + t.Fatal("a fault handler for a log that cannot record panics") + } + if (&App{}).faultRecorder(new(atomic.Bool)) != nil { + t.Fatal("a fault handler without a log") + } +} + +// TestAFailedWindowLoopIsLogged checks that an error the window loop ends with is logged as +// app.window.loop_failed under no action, unless a recovered panic caused it, and that a loop +// that ends cleanly logs nothing. +func TestAFailedWindowLoopIsLogged(t *testing.T) { + log := &faultLog{} + a := &App{logSink: log} + a.windowLoopEnded(nil, false) + a.windowLoopEnded(errors.New("panic in AppKit callback"), true) + if len(log.events) != 0 { + t.Fatalf("events = %+v, want none for a clean end or a panic already recorded", log.events) + } + a.windowLoopEnded(errors.New("window: create failed"), false) + if len(log.events) != 1 || log.events[0].event != "app.window.loop_failed" || log.events[0].op != "" || + log.events[0].fields["error_code"] == "" || log.events[0].fields["error"] == nil { + t.Fatalf("events = %+v, want one app.window.loop_failed with the error", log.events) + } + (&App{}).windowLoopEnded(errors.New("no log"), false) +} diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index dc0a334377..2a7553321d 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -96,7 +96,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # the contract, plugin guides, reference and SDKs live only in shared/plugins; on top of #16 (reported Git queries folded in the console), # #15 (git.write cherryPick, revert and reset fields), #14 (word-level changed ranges of diff # rows), #13, #8, #7, #6 and #4. -PINNED_CORE_REVISION="e81106827b3f0e5c8178742b6ef61a7a8a225f57" +PINNED_CORE_REVISION="f4f3e93568598c622819d8fda900eacdd7fe1c98" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in