Skip to content

Commit b4fe936

Browse files
committed
fix(stats): log and skip corrupted sessions in storage
1 parent e5a8681 commit b4fe936

1 file changed

Lines changed: 23 additions & 3 deletions

File tree

‎packages/opencode/src/cli/cmd/stats.ts‎

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { bootstrap } from "../bootstrap"
55
import { Storage } from "../../storage/storage"
66
import { Project } from "../../project/project"
77
import { Instance } from "../../project/instance"
8+
import { Log } from "../../util/log"
89

910
interface SessionStats {
1011
totalSessions: number
@@ -83,16 +84,31 @@ async function getCurrentProject(): Promise<Project.Info> {
8384
}
8485

8586
async function getAllSessions(): Promise<Session.Info[]> {
87+
const log = Log.create({ service: "stats" })
8688
const sessions: Session.Info[] = []
8789

8890
const projectKeys = await Storage.list(["project"])
89-
const projects = await Promise.all(projectKeys.map((key) => Storage.read<Project.Info>(key)))
91+
const projects = await Promise.all(
92+
projectKeys.map((key) =>
93+
Storage.read<Project.Info>(key).catch((e) => {
94+
log.warn(`Failed to read project ${key.join("/")}`, { error: e.message })
95+
return null
96+
}),
97+
),
98+
)
9099

91100
for (const project of projects) {
92101
if (!project) continue
93102

94103
const sessionKeys = await Storage.list(["session", project.id])
95-
const projectSessions = await Promise.all(sessionKeys.map((key) => Storage.read<Session.Info>(key)))
104+
const projectSessions = await Promise.all(
105+
sessionKeys.map((key) =>
106+
Storage.read<Session.Info>(key).catch((e) => {
107+
log.warn(`Failed to read session ${key.join("/")}`, { error: e.message })
108+
return null
109+
}),
110+
),
111+
)
96112

97113
for (const session of projectSessions) {
98114
if (session) {
@@ -105,6 +121,7 @@ async function getAllSessions(): Promise<Session.Info[]> {
105121
}
106122

107123
export async function aggregateSessionStats(days?: number, projectFilter?: string): Promise<SessionStats> {
124+
const log = Log.create({ service: "stats" })
108125
const sessions = await getAllSessions()
109126
const MS_IN_DAY = 24 * 60 * 60 * 1000
110127

@@ -179,7 +196,10 @@ export async function aggregateSessionStats(days?: number, projectFilter?: strin
179196
const batch = filteredSessions.slice(i, i + BATCH_SIZE)
180197

181198
const batchPromises = batch.map(async (session) => {
182-
const messages = await Session.messages({ sessionID: session.id })
199+
const messages = await Session.messages({ sessionID: session.id }).catch((e) => {
200+
log.warn(`Failed to read messages for session ${session.id}`, { error: e.message })
201+
return []
202+
})
183203

184204
let sessionCost = 0
185205
let sessionTokens = { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }

0 commit comments

Comments
 (0)