01b2cafa7b
normalizeLogLine stripped timestamp= first, so a signature could not say
when it was seen: an ENOSPC from Oct 22 that was fixed the same day and a
provider billing rejection from Nov 1 rendered as identical-looking lines.
A digest is only useful if a resolved fault can be told apart from a live
one, and the date is the one volatile field that carries that meaning.
Signatures are now held as {text, first, last} and rendered with their day
('2026-10-22 ...') or range ('2026-10-01..2026-11-01 ...'), ordered most
recently seen first so the summary's err: sample leads with what is live
now instead of whatever sorts first alphabetically.
Times of day, run ids and session/message ids still normalize away, so the
content hash stays stable within a day and moves only when a recurring
error recurs on a new day. Version bumped to log-parser/v3.
293 lines
7.4 KiB
Go
293 lines
7.4 KiB
Go
package ingest
|
|
|
|
import (
|
|
"bufio"
|
|
"crypto/sha256"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
var _ Ingester = (*LogIngester)(nil)
|
|
|
|
type LogIngester struct {
|
|
Version string
|
|
}
|
|
|
|
func NewLogIngester() *LogIngester {
|
|
return &LogIngester{Version: "log-parser/v3"}
|
|
}
|
|
|
|
func (l *LogIngester) SourceID() string { return "opencode-log" }
|
|
|
|
var (
|
|
sessionIDRE = regexp.MustCompile(`session[=_ ]?([a-zA-Z0-9_-]+)`)
|
|
modelRE = regexp.MustCompile(`model[=_ ]?([a-zA-Z0-9_.-]+)`)
|
|
agentRE = regexp.MustCompile(`agent[=_ ]?([a-zA-Z0-9_.-]+)`)
|
|
levelRE = regexp.MustCompile(`\blevel=([A-Za-z]+)`)
|
|
)
|
|
|
|
// Log lines are structured as `timestamp=... level=... run=... message=...`.
|
|
// Only real WARN/ERROR/FATAL lines are "errors"; the previous substring match
|
|
// flagged INFO permission lines that merely contained the word "timeout".
|
|
var seriousLevels = map[string]bool{"ERROR": true, "WARN": true, "FATAL": true}
|
|
|
|
func (l *LogIngester) Ingest(path string) (*IngestResult, error) {
|
|
f, err := os.Open(path)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("open log: %w", err)
|
|
}
|
|
defer f.Close()
|
|
|
|
var (
|
|
sessionIDs []string
|
|
models []string
|
|
agents []string
|
|
sigs = map[string]*logSig{}
|
|
totalLines int
|
|
errCount int
|
|
warnCount int
|
|
)
|
|
|
|
scanner := bufio.NewScanner(f)
|
|
scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
|
|
for scanner.Scan() {
|
|
line := scanner.Text()
|
|
totalLines++
|
|
|
|
if m := sessionIDRE.FindStringSubmatch(line); len(m) > 1 {
|
|
sessionIDs = append(sessionIDs, m[1])
|
|
}
|
|
if m := modelRE.FindStringSubmatch(line); len(m) > 1 {
|
|
models = append(models, m[1])
|
|
}
|
|
if m := agentRE.FindStringSubmatch(line); len(m) > 1 {
|
|
agents = append(agents, m[1])
|
|
}
|
|
|
|
m := levelRE.FindStringSubmatch(line)
|
|
if len(m) < 2 {
|
|
continue
|
|
}
|
|
level := strings.ToUpper(m[1])
|
|
if !seriousLevels[level] {
|
|
continue
|
|
}
|
|
if level == "WARN" {
|
|
warnCount++
|
|
} else {
|
|
errCount++
|
|
}
|
|
recordSignature(sigs, line)
|
|
}
|
|
|
|
base := filepath.Base(path)
|
|
fp := Fingerprint([]byte("log:" + base))
|
|
createdAt := ""
|
|
if fi, err := os.Stat(path); err == nil {
|
|
createdAt = fi.ModTime().UTC().Format(time.RFC3339)
|
|
}
|
|
|
|
ordered := sortedSignatures(sigs)
|
|
rendered := renderSignatures(ordered)
|
|
|
|
contentHash := hashSignatures(ordered, errCount, warnCount)
|
|
|
|
summary := buildLogSummary(ordered, errCount, warnCount)
|
|
|
|
confidence := 0.6
|
|
if errCount > 0 || warnCount > 0 {
|
|
confidence = 0.8
|
|
}
|
|
|
|
return &IngestResult{
|
|
Fingerprint: fp,
|
|
SourceID: l.SourceID(),
|
|
SourcePath: base,
|
|
ContentType: ".log",
|
|
Title: "Log " + base,
|
|
Summary: summary,
|
|
Content: strings.Join(rendered, "\n"),
|
|
CreatedAt: createdAt,
|
|
Confidence: confidence,
|
|
IngesterVersion: l.Version,
|
|
LineEnd: totalLines,
|
|
ContentHash: contentHash,
|
|
Provenance: map[string]any{
|
|
"session_ids": uniqueSlice(sessionIDs),
|
|
"models": uniqueSlice(models),
|
|
"agents": uniqueSlice(agents),
|
|
"error_count": errCount,
|
|
"warn_count": warnCount,
|
|
"errors_sample": firstN(rendered, 5),
|
|
"file_size": fmt.Sprintf("%d lines", totalLines),
|
|
},
|
|
}, nil
|
|
}
|
|
|
|
// Normalization patterns strip values that change between identical log events
|
|
// so the same error yields the same signature.
|
|
var (
|
|
tsPrefixRE = regexp.MustCompile(`^timestamp=\S+\s*`)
|
|
runRE = regexp.MustCompile(`run=[0-9a-fA-F]+`)
|
|
sesRE = regexp.MustCompile(`ses_[A-Za-z0-9]+`)
|
|
msgRE = regexp.MustCompile(`msg_[A-Za-z0-9]+`)
|
|
hexRE = regexp.MustCompile(`\b[0-9a-fA-F]{6,}\b`)
|
|
numRE = regexp.MustCompile(`[0-9]+`)
|
|
)
|
|
|
|
func normalizeLogLine(line string) string {
|
|
s := tsPrefixRE.ReplaceAllString(line, "")
|
|
s = runRE.ReplaceAllString(s, "run=<RUN>")
|
|
s = sesRE.ReplaceAllString(s, "<SES>")
|
|
s = msgRE.ReplaceAllString(s, "<MSG>")
|
|
s = hexRE.ReplaceAllString(s, "<HEX>")
|
|
s = numRE.ReplaceAllString(s, "<N>")
|
|
s = strings.Join(strings.Fields(s), " ")
|
|
return truncate(s, 160)
|
|
}
|
|
|
|
// logSig is one normalized error signature plus the dates it was seen on.
|
|
//
|
|
// The date range is the point of the digest: a signature with volatile values
|
|
// stripped cannot tell a failure that was fixed last week from one that is
|
|
// happening right now.
|
|
type logSig struct {
|
|
text string
|
|
first, last string // YYYY-MM-DD, empty when the line carries no timestamp
|
|
}
|
|
|
|
var tsDateRE = regexp.MustCompile(`^timestamp=(\d{4}-\d{2}-\d{2})`)
|
|
|
|
// logLineDate returns the day a log line was written, or "" when it has no
|
|
// leading timestamp.
|
|
func logLineDate(line string) string {
|
|
if m := tsDateRE.FindStringSubmatch(line); len(m) > 1 {
|
|
return m[1]
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// recordSignature folds one serious log line into the signature map, widening
|
|
// the date range of an existing signature instead of repeating it.
|
|
func recordSignature(sigs map[string]*logSig, line string) {
|
|
text := normalizeLogLine(line)
|
|
day := logLineDate(line)
|
|
|
|
s, ok := sigs[text]
|
|
if !ok {
|
|
sigs[text] = &logSig{text: text, first: day, last: day}
|
|
return
|
|
}
|
|
if day == "" {
|
|
return
|
|
}
|
|
if s.first == "" || day < s.first {
|
|
s.first = day
|
|
}
|
|
if day > s.last {
|
|
s.last = day
|
|
}
|
|
}
|
|
|
|
// sortedSignatures orders by most recently seen first, so the digest leads with
|
|
// what is happening now rather than whatever sorts first alphabetically.
|
|
func sortedSignatures(sigs map[string]*logSig) []*logSig {
|
|
out := make([]*logSig, 0, len(sigs))
|
|
for _, s := range sigs {
|
|
out = append(out, s)
|
|
}
|
|
sort.Slice(out, func(i, j int) bool {
|
|
if out[i].last != out[j].last {
|
|
return out[i].last > out[j].last
|
|
}
|
|
if out[i].first != out[j].first {
|
|
return out[i].first > out[j].first
|
|
}
|
|
return out[i].text < out[j].text
|
|
})
|
|
return out
|
|
}
|
|
|
|
func renderSignature(s *logSig) string {
|
|
switch {
|
|
case s.first == "":
|
|
return s.text
|
|
case s.first == s.last:
|
|
return s.first + " " + s.text
|
|
default:
|
|
return s.first + ".." + s.last + " " + s.text
|
|
}
|
|
}
|
|
|
|
func renderSignatures(sigs []*logSig) []string {
|
|
out := make([]string, len(sigs))
|
|
for i, s := range sigs {
|
|
out[i] = renderSignature(s)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// hashSignatures is the change signal: it depends on the set of distinct error
|
|
// signatures with the dates they were seen — not on total line count or
|
|
// ordering. Volatile values (run ids, session ids, times of day) are already
|
|
// stripped, so a recurring error only moves the hash when it recurs on a new
|
|
// day, which is exactly when the digest needs rewriting.
|
|
func hashSignatures(sigs []*logSig, errCount, warnCount int) string {
|
|
h := sha256.New()
|
|
for _, s := range sigs {
|
|
h.Write([]byte(s.text))
|
|
h.Write([]byte{'\t'})
|
|
h.Write([]byte(s.first))
|
|
h.Write([]byte{'~'})
|
|
h.Write([]byte(s.last))
|
|
h.Write([]byte{'\n'})
|
|
}
|
|
fmt.Fprintf(h, "E=%d W=%d", errCount, warnCount)
|
|
return fmt.Sprintf("%x", h.Sum(nil)[:8])
|
|
}
|
|
|
|
func buildLogSummary(sigs []*logSig, errCount, warnCount int) string {
|
|
if errCount == 0 && warnCount == 0 {
|
|
return "no errors"
|
|
}
|
|
var b strings.Builder
|
|
fmt.Fprintf(&b, "levels: E%d W%d", errCount, warnCount)
|
|
if len(sigs) > 0 {
|
|
b.WriteString(" | err: ")
|
|
b.WriteString(strings.Join(firstN(renderSignatures(sigs), 5), " ;; "))
|
|
}
|
|
return b.String()
|
|
}
|
|
|
|
func firstN(items []string, n int) []string {
|
|
if len(items) > n {
|
|
return items[:n]
|
|
}
|
|
return items
|
|
}
|
|
|
|
func uniqueJoin(items []string, max int) string {
|
|
uniq := uniqueSlice(items)
|
|
if len(uniq) > max {
|
|
uniq = uniq[:max]
|
|
}
|
|
return strings.Join(uniq, ", ")
|
|
}
|
|
|
|
func uniqueSlice(items []string) []string {
|
|
seen := make(map[string]bool)
|
|
var uniq []string
|
|
for _, s := range items {
|
|
if !seen[s] {
|
|
seen[s] = true
|
|
uniq = append(uniq, s)
|
|
}
|
|
}
|
|
return uniq
|
|
}
|