Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .agents/skills/develop-lithe/references/logging.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` 删除本会话的崩溃文件,排空并写完队列。写入器打不开时客户端照常启动,没有日志窗口,“查看日志”只提示日志不可用。

| 位置 | 记录方式 |
| --- | --- |
Expand All @@ -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 缓冲。
Expand Down
3 changes: 3 additions & 0 deletions desktop/cmd/lithe/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
5 changes: 4 additions & 1 deletion desktop/internal/core/events_bridge.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
192 changes: 192 additions & 0 deletions desktop/internal/core/log_text.go
Original file line number Diff line number Diff line change
@@ -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
}
130 changes: 130 additions & 0 deletions desktop/internal/core/log_text_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
Loading
Loading