~bigbes/lethe

ref: 3ae44b2876001b8a2b0e4d8abfd7a35d4a8fa977 lethe/internal/domain/stats/repository.go -rw-r--r-- 13.0 KiB
3ae44b28 — Eugene Blikh tooling: adopt go tool directives; rename air→dev; bundle fmt drift a month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
package stats

import (
	"context"
	"strings"

	"go.bigb.es/auxilia/culpa"

	"sourcecraft.dev/bigbes/lethe/internal/domain/session"
	"sourcecraft.dev/bigbes/lethe/internal/platform/database"
)

// ToolRollup holds aggregate stats for one tool across the requested range.
// DailySparkline has one entry per daily-window bucket (oldest first),
// containing the turn count for that bucket.
type ToolRollup struct {
	Tool           string  `json:"tool"`
	Sessions       int64   `json:"sessions"`
	Turns          int64   `json:"turns"`
	TokensIn       int64   `json:"tokens_in"`
	TokensOut      int64   `json:"tokens_out"`
	DailySparkline []int64 `json:"daily_sparkline"`
}

// DailyBucket is one day in the daily time-series. PerTool maps tool name to
// turn count for that day.
type DailyBucket struct {
	DateUnix int64            `json:"date_unix"`
	PerTool  map[string]int64 `json:"per_tool"`
}

// HeatmapCell is one day in the 84-cell activity heatmap.
type HeatmapCell struct {
	DateUnix int64 `json:"date_unix"`
	Count    int64 `json:"count"`
}

// CwdRow is one entry in the top-cwd ranking.
type CwdRow struct {
	Cwd   string `json:"cwd"`
	Count int64  `json:"count"`
}

// HourBucket is one hour-of-day bucket (0..23) with its turn count.
type HourBucket struct {
	Hour  int   `json:"hour"`
	Count int64 `json:"count"`
}

// HostRow is one entry in the host breakdown.
type HostRow struct {
	Host  string `json:"host"`
	Count int64  `json:"count"`
}

// Stats is the single response bundling all six aggregations.
type Stats struct {
	PerTool   []ToolRollup  `json:"per_tool"`
	Daily     []DailyBucket `json:"daily"`
	Heatmap   []HeatmapCell `json:"heatmap"`
	TopCwd    []CwdRow      `json:"top_cwd"`
	HourOfDay []HourBucket  `json:"hour_of_day"`
	HostSplit []HostRow     `json:"host_split"`
}

// Filter controls which rows Stats includes.
//   - RangeSince=nil means all time (no lower timestamp bound).
//   - Now is injected for deterministic window calculations in tests; in
//     production the handler injects time.Now().Unix().
type Filter struct {
	Owner      session.OwnerScope
	RangeSince *int64 // nil = all
	Now        int64  // injected for determinism
}

// Repository is the SQL steward for the stats aggregation API.
type Repository struct {
	Database *database.Database `inject:""`
}

// Init satisfies the steward Initer contract.
func (r *Repository) Init(_ context.Context) error { return nil }

// ownerClause returns the SQL fragment and arg (if any) for the owner scope,
// joining the given table alias. prefix is the "AND " string prepended when
// used in a WHERE continuation; connector is e.g. "WHERE " for the first clause.
// Returns an empty string and nil arg when AllOwners is set.
func ownerClause(alias string, owner session.OwnerScope) (clause string, arg any, hasArg bool) {
	switch {
	case owner.AllOwners:
		return "", nil, false
	case owner.SpecificOwner != nil:
		return alias + ".owner = ?", *owner.SpecificOwner, true
	default:
		return alias + ".owner = ?", owner.User, true
	}
}

// appendOwnerClause appends the owner WHERE/AND clause to the builder.
// sep should be " WHERE " for the first clause, " AND " for subsequent ones.
func appendOwnerClause(sb *strings.Builder, args *[]any, sep, alias string, owner session.OwnerScope) {
	clause, arg, hasArg := ownerClause(alias, owner)
	if clause == "" {
		return
	}
	sb.WriteString(sep)
	sb.WriteString(clause)
	if hasArg {
		*args = append(*args, arg)
	}
}

// sparklineCap is the maximum number of daily buckets in a ToolRollup sparkline.
const sparklineCap = 60

// Stats runs six queries against the turns/sessions tables and returns a
// fully-populated Stats struct. All returned slices are non-nil; missing
// time-window slots are filled with zero values.
func (r *Repository) Stats(ctx context.Context, f Filter) (*Stats, error) {
	// Determine daily window size from range.
	// dailyDays is the raw request days (may exceed sparklineCap).
	// For all-time (RangeSince=nil) we use sparklineCap so Daily has a
	// bounded, useful window.
	var dailyDays int
	if f.RangeSince != nil {
		dailyDays = int((f.Now - *f.RangeSince) / 86400)
	} else {
		dailyDays = sparklineCap
	}

	// sparklineDays is the sparkline length, capped at sparklineCap.
	sparklineDays := dailyDays
	if sparklineDays > sparklineCap {
		sparklineDays = sparklineCap
	}

	// ── 1. PerTool rollup ───────────────────────────────────────────────────
	type toolRow struct {
		Tool      string `db:"tool"`
		Sessions  int64  `db:"sessions"`
		Turns     int64  `db:"turns"`
		TokensIn  int64  `db:"tokens_in"`
		TokensOut int64  `db:"tokens_out"`
	}
	var toolRows []toolRow
	{
		var sb strings.Builder
		var args []any
		sb.WriteString(`
SELECT
    t.tool,
    COUNT(DISTINCT s.owner || '|' || s.tool || '|' || s.host || '|' || s.session_id) AS sessions,
    COUNT(t.turn_id) AS turns,
    COALESCE(SUM(t.tokens_in),  0) AS tokens_in,
    COALESCE(SUM(t.tokens_out), 0) AS tokens_out
FROM turns t
JOIN sessions s ON s.owner = t.owner AND s.tool = t.tool AND s.host = t.host AND s.session_id = t.session_id
WHERE 1=1`)
		appendOwnerClause(&sb, &args, " AND ", "t", f.Owner)
		if f.RangeSince != nil {
			sb.WriteString(" AND t.timestamp >= ?")
			args = append(args, *f.RangeSince)
		}
		sb.WriteString(" GROUP BY t.tool ORDER BY turns DESC")
		toolRows = make([]toolRow, 0)
		if err := r.Database.DB.SelectContext(ctx, &toolRows, sb.String(), args...); err != nil {
			return nil, culpa.WithCode(culpa.Wrap(err, "stats per_tool"), "DB_QUERY")
		}
	}

	// ── 2. Daily time-series ────────────────────────────────────────────────
	// The daily window spans the full requested range (not capped at 60).
	dailyWindow := DailyWindow(f.Now, dailyDays)

	var dailyDBRows []dailyBucketDBRow
	{
		var sb strings.Builder
		var args []any
		// Bucket by UTC midnight: (timestamp / 86400) * 86400
		sb.WriteString(`
SELECT
    (t.timestamp / 86400) * 86400 AS date_unix,
    t.tool,
    COUNT(t.turn_id) AS turns
FROM turns t
JOIN sessions s ON s.owner = t.owner AND s.tool = t.tool AND s.host = t.host AND s.session_id = t.session_id
WHERE 1=1`)
		appendOwnerClause(&sb, &args, " AND ", "t", f.Owner)
		if f.RangeSince != nil {
			sb.WriteString(" AND t.timestamp >= ?")
			args = append(args, *f.RangeSince)
		}
		sb.WriteString(" GROUP BY date_unix, t.tool ORDER BY date_unix ASC")
		dailyDBRows = make([]dailyBucketDBRow, 0)
		if err := r.Database.DB.SelectContext(ctx, &dailyDBRows, sb.String(), args...); err != nil {
			return nil, culpa.WithCode(culpa.Wrap(err, "stats daily"), "DB_QUERY")
		}
	}

	// Convert DB rows to DailyBucket slice (sparse), then fill the window.
	sparseDaily := buildSparseDaily(dailyDBRows)
	filledDaily := FillDaily(dailyWindow, sparseDaily)

	// ── 3. Heatmap (always 84 cells regardless of range) ───────────────────
	heatmapWindow := HeatmapWindow(f.Now)
	heatmapStart := heatmapWindow[0]

	type heatmapDBRow struct {
		DateUnix int64 `db:"date_unix"`
		Count    int64 `db:"count"`
	}
	var heatmapDBRows []heatmapDBRow
	{
		var sb strings.Builder
		var args []any
		sb.WriteString(`
SELECT
    (t.timestamp / 86400) * 86400 AS date_unix,
    COUNT(t.turn_id) AS count
FROM turns t
JOIN sessions s ON s.owner = t.owner AND s.tool = t.tool AND s.host = t.host AND s.session_id = t.session_id
WHERE t.timestamp >= ?`)
		args = append(args, heatmapStart)
		appendOwnerClause(&sb, &args, " AND ", "t", f.Owner)
		sb.WriteString(" GROUP BY date_unix ORDER BY date_unix ASC")
		heatmapDBRows = make([]heatmapDBRow, 0)
		if err := r.Database.DB.SelectContext(ctx, &heatmapDBRows, sb.String(), args...); err != nil {
			return nil, culpa.WithCode(culpa.Wrap(err, "stats heatmap"), "DB_QUERY")
		}
	}

	// Build heatmap: left-join heatmap DB rows onto the window.
	heatmapByDate := make(map[int64]int64, len(heatmapDBRows))
	for _, row := range heatmapDBRows {
		heatmapByDate[row.DateUnix] = row.Count
	}
	heatmap := make([]HeatmapCell, len(heatmapWindow))
	for i, ts := range heatmapWindow {
		heatmap[i] = HeatmapCell{DateUnix: ts, Count: heatmapByDate[ts]}
	}

	// ── 4. TopCwd (capped at 20) ────────────────────────────────────────────
	var topCwd []CwdRow
	{
		var sb strings.Builder
		var args []any
		sb.WriteString(`
SELECT
    s.working_dir AS cwd,
    COUNT(t.turn_id) AS count
FROM turns t
JOIN sessions s ON s.owner = t.owner AND s.tool = t.tool AND s.host = t.host AND s.session_id = t.session_id
WHERE s.working_dir IS NOT NULL`)
		appendOwnerClause(&sb, &args, " AND ", "t", f.Owner)
		if f.RangeSince != nil {
			sb.WriteString(" AND t.timestamp >= ?")
			args = append(args, *f.RangeSince)
		}
		sb.WriteString(" GROUP BY s.working_dir ORDER BY count DESC LIMIT 20")
		topCwd = make([]CwdRow, 0)
		if err := r.Database.DB.SelectContext(ctx, &topCwd, sb.String(), args...); err != nil {
			return nil, culpa.WithCode(culpa.Wrap(err, "stats top_cwd"), "DB_QUERY")
		}
	}

	// ── 5. HourOfDay ────────────────────────────────────────────────────────
	type hourDBRow struct {
		Hour  int   `db:"hour"`
		Count int64 `db:"count"`
	}
	var hourDBRows []hourDBRow
	{
		var sb strings.Builder
		var args []any
		// SQLite: strftime('%H', ts, 'unixepoch') returns the UTC hour as "00"–"23".
		// CAST to INTEGER gives 0..23.
		sb.WriteString(`
SELECT
    CAST(strftime('%H', t.timestamp, 'unixepoch') AS INTEGER) AS hour,
    COUNT(t.turn_id) AS count
FROM turns t
JOIN sessions s ON s.owner = t.owner AND s.tool = t.tool AND s.host = t.host AND s.session_id = t.session_id
WHERE 1=1`)
		appendOwnerClause(&sb, &args, " AND ", "t", f.Owner)
		if f.RangeSince != nil {
			sb.WriteString(" AND t.timestamp >= ?")
			args = append(args, *f.RangeSince)
		}
		sb.WriteString(" GROUP BY hour ORDER BY hour ASC")
		hourDBRows = make([]hourDBRow, 0)
		if err := r.Database.DB.SelectContext(ctx, &hourDBRows, sb.String(), args...); err != nil {
			return nil, culpa.WithCode(culpa.Wrap(err, "stats hour_of_day"), "DB_QUERY")
		}
	}
	// Fill 24-slot window.
	hourSlots := HourWindow()
	for _, row := range hourDBRows {
		if row.Hour >= 0 && row.Hour < 24 {
			hourSlots[row.Hour].Count = row.Count
		}
	}

	// ── 6. HostSplit ─────────────────────────────────────────────────────────
	var hostSplit []HostRow
	{
		var sb strings.Builder
		var args []any
		sb.WriteString(`
SELECT
    s.host,
    COUNT(t.turn_id) AS count
FROM turns t
JOIN sessions s ON s.owner = t.owner AND s.tool = t.tool AND s.host = t.host AND s.session_id = t.session_id
WHERE 1=1`)
		appendOwnerClause(&sb, &args, " AND ", "t", f.Owner)
		if f.RangeSince != nil {
			sb.WriteString(" AND t.timestamp >= ?")
			args = append(args, *f.RangeSince)
		}
		sb.WriteString(" GROUP BY s.host ORDER BY count DESC")
		hostSplit = make([]HostRow, 0)
		if err := r.Database.DB.SelectContext(ctx, &hostSplit, sb.String(), args...); err != nil {
			return nil, culpa.WithCode(culpa.Wrap(err, "stats host_split"), "DB_QUERY")
		}
	}

	// ── Assemble PerTool with sparklines ─────────────────────────────────────
	// Sparklines are capped at sparklineCap buckets (most recent).
	sparklineSlice := filledDaily
	if len(filledDaily) > sparklineDays+1 {
		sparklineSlice = filledDaily[len(filledDaily)-(sparklineDays+1):]
	}
	perToolOut := make([]ToolRollup, 0, len(toolRows))
	for _, tr := range toolRows {
		sparkline := make([]int64, len(sparklineSlice))
		for i, b := range sparklineSlice {
			sparkline[i] = b.PerTool[tr.Tool]
		}
		perToolOut = append(perToolOut, ToolRollup{
			Tool:           tr.Tool,
			Sessions:       tr.Sessions,
			Turns:          tr.Turns,
			TokensIn:       tr.TokensIn,
			TokensOut:      tr.TokensOut,
			DailySparkline: sparkline,
		})
	}

	return &Stats{
		PerTool:   perToolOut,
		Daily:     filledDaily,
		Heatmap:   heatmap,
		TopCwd:    topCwd,
		HourOfDay: hourSlots,
		HostSplit: hostSplit,
	}, nil
}

// buildSparseDaily converts flat DB rows (date_unix, tool, turns) into
// DailyBucket values. Rows are grouped by date_unix.
func buildSparseDaily(rows []dailyBucketDBRow) []DailyBucket {
	if len(rows) == 0 {
		return []DailyBucket{}
	}
	// Group by date.
	byDate := make(map[int64]map[string]int64)
	for _, r := range rows {
		if byDate[r.DateUnix] == nil {
			byDate[r.DateUnix] = make(map[string]int64)
		}
		byDate[r.DateUnix][r.Tool] += r.Turns
	}
	out := make([]DailyBucket, 0, len(byDate))
	for dateUnix, perTool := range byDate {
		out = append(out, DailyBucket{DateUnix: dateUnix, PerTool: perTool})
	}
	return out
}

// dailyBucketDBRow is the local scan target for the daily query.
type dailyBucketDBRow struct {
	DateUnix int64  `db:"date_unix"`
	Tool     string `db:"tool"`
	Turns    int64  `db:"turns"`
}