Add optional DuckDB debug log database with typed schema

New --debug-db flag writes the redacted debug record stream to a DuckDB database alongside or instead of the NDJSON --debug-file. Frequent type-stable attributes are promoted to typed columns; the complete record remains in attrs JSON. libduckdb is dlopen'ed at runtime (build tag duckdb, Arch optdepends) so the reader runs unchanged without it. v1 databases upgrade in place on append.
This commit is contained in:
hjozwiak committed 2026-11-10 21:13:41 -05:00
1 parent 64f60fe4e8
commit b03cb8917d
14 files changed
+1906 -14

No files matched your search

+52 -8
View File
@@ -27,6 +27,7 @@ import (
"os"
"os/signal"
"os/user"
"path/filepath"
"syscall"
"time"
@@ -80,8 +81,9 @@ func run(ctx context.Context, arguments []string, stdout, stderr io.Writer) (res
clipboardWatch := options.Bool("clipboard-watch", false, "run the internal clipboard change helper (private pipe protocol)")
ocrCapture := options.Bool("ocr-capture", false, "run the internal OCR capture helper (private pipe protocol)")
ocrConfirm := options.Bool("ocr-confirm", false, "run the internal OCR click confirmation helper")
appendLog := options.Bool("append", false, "preserve existing debug log contents (requires --debug-file)")
appendLog := options.Bool("append", false, "preserve existing debug log contents (requires --debug-file or --debug-db)")
debugFile := options.String("debug-file", "", "enable debug logging only to this file, replacing existing contents")
debugDB := options.String("debug-db", "", "enable debug logging only to this DuckDB database, replacing existing contents")
speechSocket := options.String(
"speech-socket",
"",
@@ -127,8 +129,11 @@ func run(ctx context.Context, arguments []string, stdout, stderr io.Writer) (res
if options.NArg() != 0 {
return fmt.Errorf("unexpected argument %q", options.Arg(0))
}
if *appendLog && *debugFile == "" {
return errors.New("--append requires --debug-file")
if *appendLog && *debugFile == "" && *debugDB == "" {
return errors.New("--append requires --debug-file or --debug-db")
}
if *debugFile != "" && *debugDB != "" && sameDestination(*debugFile, *debugDB) {
return errors.New("--debug-file and --debug-db must be different files")
}
if *showVersion || *shortVersion {
fmt.Fprintln(stdout, version.Details(
@@ -181,12 +186,36 @@ func run(ctx context.Context, arguments []string, stdout, stderr io.Writer) (res
}
}
logger := slog.New(slog.DiscardHandler)
if *debugFile != "" {
fileWriter, err := logging.OpenFile(*debugFile, nil, *appendLog)
if err != nil {
return fmt.Errorf("open debug log: %w", err)
if *debugFile != "" || *debugDB != "" {
// Open the database first: its routine failure modes (libduckdb not
// installed, foreign file) must not destroy an existing debug log
// by truncating it before the run even starts.
var databaseWriter, fileWriter logging.DiagnosticsWriter
if *debugDB != "" {
var err error
databaseWriter, err = logging.OpenDuckDB(*debugDB, *appendLog, os.Getpid())
if err != nil {
return fmt.Errorf("open debug database: %w", err)
}
}
diagnostics := logging.NewAsync(fileWriter, logging.AsyncOptions{
if *debugFile != "" {
var err error
fileWriter, err = logging.OpenFile(*debugFile, nil, *appendLog)
if err != nil {
if databaseWriter != nil {
_ = databaseWriter.Close()
}
return fmt.Errorf("open debug log: %w", err)
}
}
sinks := make([]logging.DiagnosticsWriter, 0, 2)
if fileWriter != nil {
sinks = append(sinks, fileWriter)
}
if databaseWriter != nil {
sinks = append(sinks, databaseWriter)
}
diagnostics := logging.NewAsync(logging.NewMultiWriter(sinks...), logging.AsyncOptions{
Options: logging.Options{Level: slog.LevelDebug, AddSource: true},
})
defer func() {
@@ -261,3 +290,18 @@ func run(ctx context.Context, arguments []string, stdout, stderr io.Writer) (res
}
return err
}
// sameDestination reports whether two sink paths name the same file, via
// cleaned absolute paths or, when both exist, file identity (symlink and
// ./ aliases). Sharing one file between the NDJSON and DuckDB sinks would
// corrupt both.
func sameDestination(a, b string) bool {
absA, errA := filepath.Abs(a)
absB, errB := filepath.Abs(b)
if errA == nil && errB == nil && absA == absB {
return true
}
infoA, errA := os.Stat(a)
infoB, errB := os.Stat(b)
return errA == nil && errB == nil && os.SameFile(infoA, infoB)
}
+78
View File
@@ -0,0 +1,78 @@
//go:build duckdb && cgo
// Cthulhu screen reader.
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program. If not, see <https://www.gnu.org/licenses/gpl-3.0.html>.
package main
import (
"bytes"
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
// --debug-db and --debug-file together must both receive the session: the
// NDJSON file stays available for existing tooling while the database gets
// the same records in queryable form.
func TestDebugDBAndFileBothReceiveRecords(t *testing.T) {
directory := t.TempDir()
databasePath := filepath.Join(directory, "debug.duckdb")
logPath := filepath.Join(directory, "debug.log")
configPath := filepath.Join(directory, "absent.toml")
var stdout, stderr bytes.Buffer
if err := run(context.Background(), []string{
"--check-config", "--config", configPath,
"--debug-file", logPath, "--debug-db", databasePath,
}, &stdout, &stderr); err != nil {
t.Fatal(err)
}
if stderr.Len() != 0 {
t.Fatalf("debug sinks wrote to terminal: %q", stderr.String())
}
logData, err := os.ReadFile(logPath)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(logData), `"starting Cthulhu"`) {
t.Fatalf("debug file missing startup record: %s", logData)
}
cli, err := exec.LookPath("duckdb")
if err != nil {
t.Skip("duckdb CLI not installed; cannot verify database contents")
}
output, err := exec.Command(cli, "-readonly", "-noheader", "-list", databasePath,
"-c", "SELECT message || '|' || (attrs->>'$.pid' IS NOT NULL) FROM logs WHERE seq = 1").CombinedOutput()
if err != nil {
t.Fatalf("duckdb query: %v\n%s", err, output)
}
if got := strings.TrimSpace(string(output)); got != "starting Cthulhu|true" {
t.Fatalf("first database record = %q", got)
}
}
func TestDebugDBOpenFailure(t *testing.T) {
var output bytes.Buffer
err := run(context.Background(), []string{"--debug-db", t.TempDir()}, &output, &output)
if err == nil || !strings.Contains(err.Error(), "open debug database") {
t.Fatalf("error = %v", err)
}
}
@@ -0,0 +1,56 @@
//go:build !duckdb || !cgo
// Cthulhu screen reader.
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program. If not, see <https://www.gnu.org/licenses/gpl-3.0.html>.
package main
import (
"bytes"
"context"
"errors"
"path/filepath"
"strings"
"testing"
"git.stormux.org/storm/cthulhu/internal/logging"
)
func TestDebugDBUnavailableWithoutBuildTag(t *testing.T) {
databasePath := filepath.Join(t.TempDir(), "debug.duckdb")
var output bytes.Buffer
err := run(context.Background(), []string{"--debug-db", databasePath}, &output, &output)
if !errors.Is(err, logging.ErrDuckDBUnavailable) {
t.Fatalf("error = %v, want ErrDuckDBUnavailable", err)
}
if !strings.Contains(err.Error(), "open debug database") {
t.Fatalf("error = %v, want open context", err)
}
}
func TestAppendAcceptsDebugDBAsSink(t *testing.T) {
databasePath := filepath.Join(t.TempDir(), "debug.duckdb")
var output bytes.Buffer
err := run(context.Background(), []string{"--append", "--debug-db", databasePath}, &output, &output)
if err != nil && strings.Contains(err.Error(), "--append requires") {
t.Fatalf("--append rejected --debug-db as its sink: %v", err)
}
// In this build the run then fails opening the database instead.
if !errors.Is(err, logging.ErrDuckDBUnavailable) {
t.Fatalf("error = %v, want ErrDuckDBUnavailable", err)
}
}
+17 -2
View File
@@ -301,14 +301,29 @@ func TestStandaloneDebugFlagRejected(t *testing.T) {
}
}
func TestAppendRequiresDebugFile(t *testing.T) {
func TestAppendRequiresDebugSink(t *testing.T) {
var output bytes.Buffer
err := run(context.Background(), []string{"--append"}, &output, &output)
if err == nil || err.Error() != "--append requires --debug-file" {
if err == nil || err.Error() != "--append requires --debug-file or --debug-db" {
t.Fatalf("error = %v", err)
}
}
func TestDebugFileAndDBSameFileRejected(t *testing.T) {
shared := filepath.Join(t.TempDir(), "debug.out")
alias := filepath.Dir(shared) + string(filepath.Separator) + "." + string(filepath.Separator) + "debug.out"
for _, arguments := range [][]string{
{"--debug-file", shared, "--debug-db", shared},
{"--debug-file", shared, "--debug-db", alias},
} {
var output bytes.Buffer
err := run(context.Background(), arguments, &output, &output)
if err == nil || !strings.Contains(err.Error(), "must be different files") {
t.Fatalf("arguments %v: error = %v", arguments, err)
}
}
}
func TestDebugFileStartsFresh(t *testing.T) {
logPath := filepath.Join(t.TempDir(), "debug.log")
configPath := filepath.Join(t.TempDir(), "absent.toml")