@myclaw163/clawclaw-cli 0.8.19 → 0.8.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/configuration.md +14 -0
- package/package.json +1 -1
- package/src/runtime/clawclaw/owner.ts +1 -0
- package/src/runtime/clawclaw/runtime.ts +8 -0
- package/src/runtime/framework/events/memory-event-repository.ts +24 -1
- package/src/runtime/framework/events/runtime-resume.ts +20 -0
- package/src/runtime/framework/events/sqlite-event-repository.ts +32 -8
- package/src/runtime/framework/participation-manager.ts +10 -1
- package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +20 -1
- package/src/runtime/framework/persistence/memory-first-persistence.ts +116 -13
- package/src/runtime/framework/plugins/runtime-input-journal.ts +13 -8
- package/src/runtime/framework/runtime.ts +7 -7
- package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +11 -8
package/docs/configuration.md
CHANGED
|
@@ -93,6 +93,20 @@ $env:CLAWCLAW_ENABLE_CLAUDE_CHANNELS = '1'
|
|
|
93
93
|
|
|
94
94
|
`allow_upload: true` 目前只保存未来上传的用户同意,并把本地有效采集级别至少提升到 `telemetry`;当前版本尚未实现网络上传,不会因为打开它而发起请求。本地 JSONL 不是可直接上传的数据集;未来上传器必须另做全局字段白名单和投影,不能直接读取并发送这些文件。
|
|
95
95
|
|
|
96
|
+
#### 启动恢复与内存诊断
|
|
97
|
+
|
|
98
|
+
默认 Runtime 不再将账号三个历史库中的全部业务记录加载进内存。新参与只保留必要的旧会话元数据和数据库全局序号;恢复已有参与时,事件与投递记录按可恢复的当前 session 加载,State History、epoch、插件进度/结果/State 按实际复用的当前 segment 加载。同一房间 session 恢复到新 segment 时,不加载上一个游戏 segment 的 State。旧数据不删除,仍能从 SQLite 导出复盘。
|
|
99
|
+
|
|
100
|
+
跨 session 的 source Event ID 去重仍有效:提交 Event 时通过索引按需检查冷库中的身份冲突,只将实际命中的记录及其原有投递状态引入内存,不扫描或复制整个旧 Event Ledger。当前活动 segment 的完整恢复历史,以及当前 session 的事件投递记录仍可能随运行增长;本修复不是统一的内存容量上限,也不是“消费过就全部删除”。
|
|
101
|
+
|
|
102
|
+
`telemetry` 和 `full` 记录以下脱敏诊断,不包含 State/Event 正文或数据库路径:
|
|
103
|
+
|
|
104
|
+
- `runtime.persistence.hydration`:`started`、`selected`、`events_loaded`、`history_loaded`、`input_loaded`、`completed`(失败时 `failed`)阶段;包含累计启动耗时、数据库/WAL 文件字节数、恢复选择、已加载记录数,以及采样时的进程 RSS、Owner JS 堆、external、ArrayBuffers、V8 堆限制。阶段内存是离散采样,不能称为真实瞬时峰值;库文件大小也不等于 JS 对象占用。
|
|
105
|
+
- `runtime.persistence.worker_memory`:持久化 Worker 启动后约每 5 秒报告线程 ID、采样时间、已用/已分配 JS 堆、external、ArrayBuffers 和堆限制;没有将进程级 RSS 冒充 Worker 独占内存。
|
|
106
|
+
- `full` 的 `runtime.diagnostics.sample.persistence` 同时提供异步持久化健康状态及最近一次 Worker 内存样本;判断样本新鲜度时检查其 `sampled_at_ms`。原有 `retained_records` 继续报告各内存仓库保留数量。
|
|
107
|
+
|
|
108
|
+
上述数据用于区分“启动加载旧历史”“Owner 内存增长”“计算/持久化 Worker 内存增长”和“写盘积压”。它们不是完整的对象引用图或 native/SQLite 内存归因;ArrayBuffers 已包含在 external 中,不应重复相加。
|
|
109
|
+
|
|
96
110
|
开发者可以临时用环境变量覆盖 `level`;若 `allow_upload` 为 `true`,仍至少采集 telemetry。日志按单文件容量滚动并自动删除最旧编号文件,不需要另起清理任务:
|
|
97
111
|
|
|
98
112
|
```powershell
|
package/package.json
CHANGED
|
@@ -861,6 +861,7 @@ export async function runClawclawOwner(
|
|
|
861
861
|
},
|
|
862
862
|
scheduler: runtime?.runtimeEpochDiagnosticSnapshot(),
|
|
863
863
|
retained_records: runtime?.runtimeRetainedRecordCounts(),
|
|
864
|
+
persistence: runtime?.runtimePersistenceDiagnostics(),
|
|
864
865
|
behavior: {
|
|
865
866
|
...assembly.behavior.diagnosticSnapshot(),
|
|
866
867
|
effective_source: effectiveBehavior
|
|
@@ -117,6 +117,14 @@ export function createClawclawRuntime(
|
|
|
117
117
|
eventLedgerPath: getProfileEventLedgerPath(profile),
|
|
118
118
|
stateHistoryPath: getProfileStateHistoryPath(profile),
|
|
119
119
|
inputJournalPath: getProfileInputJournalPath(profile),
|
|
120
|
+
recovery: {
|
|
121
|
+
account: { adapterId: CLAWCLAW_ADAPTER_ID, accountId: getRuntimeAccountId(profile) },
|
|
122
|
+
resume: runtimeOptions.resume, resumeKey: runtimeOptions.resumeKey,
|
|
123
|
+
initialSegment: runtimeOptions.initialSegment,
|
|
124
|
+
},
|
|
125
|
+
onDiagnostic: runtimeOptions.observability
|
|
126
|
+
? (name, attributes) => runtimeOptions.observability?.log('info', name, { ...attributes }, { component: 'runtime.persistence' })
|
|
127
|
+
: undefined,
|
|
120
128
|
onDegraded: (error, health) => runtimeOptions.observability?.error(
|
|
121
129
|
'runtime.persistence.async_degraded',
|
|
122
130
|
error,
|
|
@@ -107,7 +107,12 @@ export class MemoryEventRepository implements EventRepository, MailboxRepository
|
|
|
107
107
|
}
|
|
108
108
|
private nextCommitSeq = 1;
|
|
109
109
|
|
|
110
|
-
constructor(
|
|
110
|
+
constructor(
|
|
111
|
+
snapshot?: EventRepositorySnapshot,
|
|
112
|
+
private readonly archivedIdentities?: (event: CommitEventRequest['event']) => Array<{
|
|
113
|
+
event: CanonicalEvent; deliveries: EventDeliveryRecord[];
|
|
114
|
+
}>,
|
|
115
|
+
) {
|
|
111
116
|
if (snapshot) this.restore(snapshot);
|
|
112
117
|
}
|
|
113
118
|
|
|
@@ -297,6 +302,24 @@ export class MemoryEventRepository implements EventRepository, MailboxRepository
|
|
|
297
302
|
throw new Error(`Unknown event segment ${draft.segmentId} in session ${draft.sessionId}`);
|
|
298
303
|
}
|
|
299
304
|
|
|
305
|
+
// Source event IDs are global to their source, unlike epoch recovery scope.
|
|
306
|
+
// A replay of an archived fact must not consume a new in-memory sequence
|
|
307
|
+
// while the SQLite mirror deduplicates it against an older record.
|
|
308
|
+
for (const { event: archived, deliveries } of this.archivedIdentities?.(draft) ?? []) {
|
|
309
|
+
if (this.events.has(archived.eventId)) continue;
|
|
310
|
+
this.events.set(archived.eventId, archived);
|
|
311
|
+
this.eventOrder.push(archived.eventId);
|
|
312
|
+
this.eventOrder.sort((a, b) => this.events.get(a)!.commitSeq - this.events.get(b)!.commitSeq);
|
|
313
|
+
if (archived.sourceEventId) {
|
|
314
|
+
this.remoteEventIds.set(sourceEventKey(archived.sourceId, archived.sourceEventId), archived.eventId);
|
|
315
|
+
}
|
|
316
|
+
if (archived.sourceSequence) {
|
|
317
|
+
this.remoteSequences.set(sourceSequenceKey(archived.sourceId, archived.sessionId,
|
|
318
|
+
archived.segmentId, archived.sourceSequence), archived.eventId);
|
|
319
|
+
}
|
|
320
|
+
for (const delivery of deliveries) this.deliveries.set(deliveryKey(delivery.eventId, delivery.consumerId), delivery);
|
|
321
|
+
}
|
|
322
|
+
|
|
300
323
|
const duplicateId = draft.sourceEventId
|
|
301
324
|
? this.remoteEventIds.get(sourceEventKey(draft.sourceId, draft.sourceEventId))
|
|
302
325
|
: undefined;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { CurrentEventScope } from './types.js';
|
|
2
|
+
|
|
3
|
+
export interface RuntimeResumeSelection {
|
|
4
|
+
resume?: boolean;
|
|
5
|
+
resumeKey?: string;
|
|
6
|
+
initialSegment: { kind: string; identity?: string };
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** Shared by startup hydration and Runtime; never hydrate a scope Runtime will reject. */
|
|
10
|
+
export function canResumeRuntimeScope(
|
|
11
|
+
current: CurrentEventScope | null,
|
|
12
|
+
options: RuntimeResumeSelection,
|
|
13
|
+
): boolean {
|
|
14
|
+
return !!options.resume && !!current && current.session.status === 'open' && (
|
|
15
|
+
(options.resumeKey !== undefined && current.session.resumeKey === options.resumeKey)
|
|
16
|
+
|| (options.initialSegment.identity !== undefined
|
|
17
|
+
&& current.segment.kind === options.initialSegment.kind
|
|
18
|
+
&& current.segment.scopeRef === options.initialSegment.identity)
|
|
19
|
+
);
|
|
20
|
+
}
|
|
@@ -296,14 +296,18 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
296
296
|
}
|
|
297
297
|
|
|
298
298
|
/** Full startup image for the memory-primary runtime. This is never used on a hot tick. */
|
|
299
|
-
snapshot(): EventRepositorySnapshot {
|
|
300
|
-
|
|
301
|
-
|
|
299
|
+
snapshot(sessionId?: string | null): EventRepositorySnapshot {
|
|
300
|
+
// undefined retains the explicit full-export API; null loads no historical payloads.
|
|
301
|
+
const where = sessionId === undefined ? '' : sessionId === null ? ' WHERE 0' : ' WHERE session_id = ?';
|
|
302
|
+
const params = typeof sessionId === 'string' ? [sessionId] : [];
|
|
303
|
+
const events = this.db.prepare(`SELECT * FROM events${where} ORDER BY commit_seq ASC`)
|
|
304
|
+
.all(...params).map(eventFromRow);
|
|
302
305
|
return {
|
|
303
|
-
sessions: this.db.prepare(
|
|
304
|
-
segments: this.db.prepare(
|
|
306
|
+
sessions: this.db.prepare(`SELECT * FROM play_sessions${where}`).all(...params).map(sessionFromRow),
|
|
307
|
+
segments: this.db.prepare(`SELECT * FROM event_segments${where}`).all(...params).map(segmentFromRow),
|
|
305
308
|
events,
|
|
306
|
-
deliveries: this.db.prepare(
|
|
309
|
+
deliveries: this.db.prepare(`SELECT * FROM event_deliveries WHERE event_id IN (SELECT event_id FROM events${where})`)
|
|
310
|
+
.all(...params).map(deliveryFromRow),
|
|
307
311
|
checkpoints: this.db.prepare('SELECT * FROM source_checkpoints').all().map(checkpointFromRow),
|
|
308
312
|
leases: this.db.prepare('SELECT * FROM consumer_leases').all().map((row) => ({
|
|
309
313
|
consumerId: String(row.consumer_id),
|
|
@@ -311,8 +315,9 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
311
315
|
ownerId: String(row.owner_id),
|
|
312
316
|
expiresAt: numberValue(row.expires_at),
|
|
313
317
|
})),
|
|
314
|
-
mailboxItems: this.db.prepare(
|
|
315
|
-
|
|
318
|
+
mailboxItems: this.db.prepare(`SELECT * FROM mailbox_items${where}`).all(...params).map(mailboxItemFromRow),
|
|
319
|
+
// The mirror uses SQLite's global sequence, not the selected session's last row.
|
|
320
|
+
nextCommitSeq: numberValue(this.db.prepare('SELECT MAX(commit_seq) AS seq FROM events').get()?.seq) + 1,
|
|
316
321
|
};
|
|
317
322
|
}
|
|
318
323
|
|
|
@@ -600,6 +605,25 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
600
605
|
});
|
|
601
606
|
}
|
|
602
607
|
|
|
608
|
+
/** Indexed cold-archive identity check; never materializes the historical ledger. */
|
|
609
|
+
archivedEventIdentities(
|
|
610
|
+
event: CommitEventRequest['event'],
|
|
611
|
+
loadedSessionId: string | null,
|
|
612
|
+
throughCommitSeq: number,
|
|
613
|
+
): Array<{ event: CanonicalEvent; deliveries: EventDeliveryRecord[] }> {
|
|
614
|
+
if (throughCommitSeq === 0) return [];
|
|
615
|
+
const rows = this.db.prepare(`SELECT * FROM events
|
|
616
|
+
WHERE (event_id = ? OR (source_id = ? AND source_event_id = ?))
|
|
617
|
+
AND commit_seq <= ? AND (? IS NULL OR session_id <> ?)
|
|
618
|
+
LIMIT 2`).all(event.eventId, event.sourceId, event.sourceEventId ?? null,
|
|
619
|
+
throughCommitSeq, loadedSessionId, loadedSessionId);
|
|
620
|
+
return rows.map((row) => {
|
|
621
|
+
const event = eventFromRow(row);
|
|
622
|
+
return { event, deliveries: this.db.prepare('SELECT * FROM event_deliveries WHERE event_id = ?')
|
|
623
|
+
.all(event.eventId).map(deliveryFromRow) };
|
|
624
|
+
});
|
|
625
|
+
}
|
|
626
|
+
|
|
603
627
|
eventById(eventId: string): CanonicalEvent | null {
|
|
604
628
|
const row = this.db.prepare('SELECT * FROM events WHERE event_id = ?').get(eventId);
|
|
605
629
|
return row ? eventFromRow(row) : null;
|
|
@@ -21,6 +21,15 @@ export interface ParticipationSegment {
|
|
|
21
21
|
endedAt?: string;
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
+
export function canReuseParticipationSegment(
|
|
25
|
+
current: Pick<ParticipationSegment, 'kind' | 'identity' | 'endedAt'>,
|
|
26
|
+
kind: string,
|
|
27
|
+
identity?: string,
|
|
28
|
+
): boolean {
|
|
29
|
+
return !current.endedAt && current.kind === kind
|
|
30
|
+
&& (identity === undefined || current.identity === undefined || current.identity === identity);
|
|
31
|
+
}
|
|
32
|
+
|
|
24
33
|
export interface ParticipationSnapshot {
|
|
25
34
|
session: ParticipationSession;
|
|
26
35
|
segment: ParticipationSegment;
|
|
@@ -146,7 +155,7 @@ export class ParticipationManager {
|
|
|
146
155
|
throw new Error('Cannot activate a segment without an active session.');
|
|
147
156
|
}
|
|
148
157
|
const current = this.currentValue.segment;
|
|
149
|
-
if (
|
|
158
|
+
if (canReuseParticipationSegment(current, kind, identity)) {
|
|
150
159
|
// An omitted identity means "keep the currently known identity". This
|
|
151
160
|
// matters for room reconnect loops, where a caller may only know that it
|
|
152
161
|
// is returning to the lobby while the durable room code is already set.
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { parentPort, workerData } from 'worker_threads';
|
|
1
|
+
import { parentPort, workerData, threadId } from 'worker_threads';
|
|
2
|
+
import { getHeapStatistics } from 'v8';
|
|
2
3
|
import { SqliteEventRepository } from '../events/sqlite-event-repository.js';
|
|
3
4
|
import { SqliteRuntimeInputJournal } from '../plugins/runtime-input-journal.js';
|
|
4
5
|
import { SqliteStateHistoryRepository } from '../state/history/sqlite-state-history-repository.js';
|
|
@@ -7,6 +8,7 @@ interface WorkerPaths {
|
|
|
7
8
|
eventLedgerPath: string;
|
|
8
9
|
stateHistoryPath: string;
|
|
9
10
|
inputJournalPath: string;
|
|
11
|
+
diagnostics?: boolean;
|
|
10
12
|
}
|
|
11
13
|
|
|
12
14
|
interface PersistenceOperation {
|
|
@@ -24,6 +26,21 @@ const stores = {
|
|
|
24
26
|
input: new SqliteRuntimeInputJournal(paths.inputJournalPath),
|
|
25
27
|
};
|
|
26
28
|
|
|
29
|
+
function reportMemory(): void {
|
|
30
|
+
if (!paths.diagnostics) return;
|
|
31
|
+
const memory = process.memoryUsage();
|
|
32
|
+
parentPort?.postMessage({ type: 'diagnostics', memory: {
|
|
33
|
+
sampled_at_ms: Date.now(), thread_id: threadId,
|
|
34
|
+
heap_used_bytes: memory.heapUsed, heap_total_bytes: memory.heapTotal,
|
|
35
|
+
external_bytes: memory.external, array_buffers_bytes: memory.arrayBuffers,
|
|
36
|
+
heap_size_limit_bytes: getHeapStatistics().heap_size_limit,
|
|
37
|
+
// RSS is process-wide; never present it as this Worker's private memory.
|
|
38
|
+
} });
|
|
39
|
+
}
|
|
40
|
+
reportMemory();
|
|
41
|
+
const memoryTimer = paths.diagnostics ? setInterval(reportMemory, 5_000) : undefined;
|
|
42
|
+
memoryTimer?.unref();
|
|
43
|
+
|
|
27
44
|
parentPort?.on('message', (message: {
|
|
28
45
|
type: 'batch' | 'barrier' | 'close';
|
|
29
46
|
id: number;
|
|
@@ -44,6 +61,8 @@ parentPort?.on('message', (message: {
|
|
|
44
61
|
parentPort?.postMessage({ type: 'barrier', id: message.id });
|
|
45
62
|
return;
|
|
46
63
|
}
|
|
64
|
+
if (memoryTimer) clearInterval(memoryTimer);
|
|
65
|
+
reportMemory();
|
|
47
66
|
stores.history.close();
|
|
48
67
|
stores.input.close();
|
|
49
68
|
stores.events.close();
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from 'crypto';
|
|
2
|
+
import { statSync } from 'fs';
|
|
3
|
+
import { getHeapStatistics } from 'v8';
|
|
4
|
+
import { canReuseParticipationSegment } from '../participation-manager.js';
|
|
2
5
|
import { createRequire } from 'module';
|
|
3
6
|
import { pathToFileURL } from 'url';
|
|
4
7
|
import { Worker } from 'worker_threads';
|
|
@@ -13,6 +16,7 @@ import type {
|
|
|
13
16
|
} from '../mailbox/types.js';
|
|
14
17
|
import { MemoryEventRepository } from '../events/memory-event-repository.js';
|
|
15
18
|
import { SqliteEventRepository } from '../events/sqlite-event-repository.js';
|
|
19
|
+
import { canResumeRuntimeScope, type RuntimeResumeSelection } from '../events/runtime-resume.js';
|
|
16
20
|
import type { EventRepository } from '../events/event-repository.js';
|
|
17
21
|
import type {
|
|
18
22
|
AcquireLeaseRequest,
|
|
@@ -58,6 +62,8 @@ export interface MemoryFirstPersistenceOptions {
|
|
|
58
62
|
maxPendingOperations?: number;
|
|
59
63
|
batchSize?: number;
|
|
60
64
|
flushIntervalMs?: number;
|
|
65
|
+
recovery?: RuntimeResumeSelection & { account: EventAccountScope };
|
|
66
|
+
onDiagnostic?: (name: string, attributes: Readonly<Record<string, unknown>>) => void;
|
|
61
67
|
onDegraded?: (error: Error, health: AsyncPersistenceHealth) => void;
|
|
62
68
|
}
|
|
63
69
|
|
|
@@ -69,6 +75,7 @@ interface ResolvedMemoryFirstPersistenceOptions {
|
|
|
69
75
|
batchSize: number;
|
|
70
76
|
flushIntervalMs: number;
|
|
71
77
|
onDegraded?: MemoryFirstPersistenceOptions['onDegraded'];
|
|
78
|
+
onDiagnostic?: MemoryFirstPersistenceOptions['onDiagnostic'];
|
|
72
79
|
}
|
|
73
80
|
|
|
74
81
|
export interface AsyncPersistenceHealth {
|
|
@@ -77,6 +84,21 @@ export interface AsyncPersistenceHealth {
|
|
|
77
84
|
droppedOperations: number;
|
|
78
85
|
degraded: boolean;
|
|
79
86
|
error?: string;
|
|
87
|
+
workerMemory?: Readonly<Record<string, number>>;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function memorySample(): Readonly<Record<string, number>> {
|
|
91
|
+
const memory = process.memoryUsage();
|
|
92
|
+
return {
|
|
93
|
+
sampled_at_ms: Date.now(), rss_bytes: memory.rss,
|
|
94
|
+
heap_used_bytes: memory.heapUsed, heap_total_bytes: memory.heapTotal,
|
|
95
|
+
external_bytes: memory.external, array_buffers_bytes: memory.arrayBuffers,
|
|
96
|
+
heap_size_limit_bytes: getHeapStatistics().heap_size_limit,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function databaseBytes(path: string): number {
|
|
101
|
+
try { return statSync(path).size; } catch { return 0; }
|
|
80
102
|
}
|
|
81
103
|
|
|
82
104
|
class AsyncSqliteMirror {
|
|
@@ -92,6 +114,7 @@ class AsyncSqliteMirror {
|
|
|
92
114
|
private degradedError?: Error;
|
|
93
115
|
private closing?: Promise<void>;
|
|
94
116
|
private references = 3;
|
|
117
|
+
private workerMemory?: Readonly<Record<string, number>>;
|
|
95
118
|
|
|
96
119
|
constructor(private readonly options: ResolvedMemoryFirstPersistenceOptions) {
|
|
97
120
|
const workerUrl = new URL('./async-sqlite-persistence-worker.ts', import.meta.url).href;
|
|
@@ -109,9 +132,15 @@ class AsyncSqliteMirror {
|
|
|
109
132
|
eventLedgerPath: options.eventLedgerPath,
|
|
110
133
|
stateHistoryPath: options.stateHistoryPath,
|
|
111
134
|
inputJournalPath: options.inputJournalPath,
|
|
135
|
+
diagnostics: !!options.onDiagnostic,
|
|
112
136
|
},
|
|
113
137
|
});
|
|
114
|
-
this.worker.on('message', (message: { type: string; id: number; error?: string }) => {
|
|
138
|
+
this.worker.on('message', (message: { type: string; id: number; error?: string; memory?: Readonly<Record<string, number>> }) => {
|
|
139
|
+
if (message.type === 'diagnostics') {
|
|
140
|
+
this.workerMemory = message.memory;
|
|
141
|
+
try { this.options.onDiagnostic?.('runtime.persistence.worker_memory', { worker_memory: message.memory }); } catch { /* observational */ }
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
115
144
|
if (message.type === 'ack') {
|
|
116
145
|
this.acknowledgedOperations += this.batchSizes.get(message.id) ?? 0;
|
|
117
146
|
this.batchSizes.delete(message.id);
|
|
@@ -155,6 +184,7 @@ class AsyncSqliteMirror {
|
|
|
155
184
|
droppedOperations: this.droppedOperations,
|
|
156
185
|
degraded: !!this.degradedError,
|
|
157
186
|
...(this.degradedError ? { error: this.degradedError.message } : {}),
|
|
187
|
+
...(this.workerMemory ? { workerMemory: this.workerMemory } : {}),
|
|
158
188
|
};
|
|
159
189
|
}
|
|
160
190
|
|
|
@@ -231,7 +261,11 @@ abstract class MirroredStore {
|
|
|
231
261
|
}
|
|
232
262
|
|
|
233
263
|
class MemoryFirstEventRepository extends MirroredStore implements EventRepository, MailboxRepository {
|
|
234
|
-
constructor(mirror: AsyncSqliteMirror, private readonly memory: MemoryEventRepository
|
|
264
|
+
constructor(mirror: AsyncSqliteMirror, private readonly memory: MemoryEventRepository,
|
|
265
|
+
private readonly closeArchive: () => void) { super(mirror); }
|
|
266
|
+
override async close(): Promise<void> {
|
|
267
|
+
try { await super.close(); } finally { this.closeArchive(); }
|
|
268
|
+
}
|
|
235
269
|
diagnosticCounts() { return this.memory.diagnosticCounts(); }
|
|
236
270
|
saveSession(value: PlaySessionRecord): void { this.memory.saveSession(value); this.persist('events', 'saveSession', value); }
|
|
237
271
|
saveSegment(value: EventSegmentRecord): void { this.memory.saveSegment(value); this.persist('events', 'saveSegment', value); }
|
|
@@ -351,21 +385,79 @@ export function createMemoryFirstPersistence<
|
|
|
351
385
|
TState extends Record<string, unknown> = Record<string, unknown>,
|
|
352
386
|
TEvent extends Record<string, unknown> = Record<string, unknown>,
|
|
353
387
|
>(options: MemoryFirstPersistenceOptions): MemoryFirstPersistence<TPosition, TState, TEvent> {
|
|
388
|
+
const startedAt = performance.now();
|
|
389
|
+
const diagnostic = (stage: string, attributes: Record<string, unknown> = {}): void => {
|
|
390
|
+
if (!options.onDiagnostic) return;
|
|
391
|
+
try {
|
|
392
|
+
options.onDiagnostic('runtime.persistence.hydration', {
|
|
393
|
+
stage, elapsed_ms: performance.now() - startedAt,
|
|
394
|
+
process_memory: memorySample(), ...attributes,
|
|
395
|
+
});
|
|
396
|
+
} catch { /* Diagnostics must not prevent startup. */ }
|
|
397
|
+
};
|
|
398
|
+
diagnostic('started', {
|
|
399
|
+
event_db_bytes: databaseBytes(options.eventLedgerPath),
|
|
400
|
+
event_wal_bytes: databaseBytes(`${options.eventLedgerPath}-wal`),
|
|
401
|
+
history_db_bytes: databaseBytes(options.stateHistoryPath),
|
|
402
|
+
history_wal_bytes: databaseBytes(`${options.stateHistoryPath}-wal`),
|
|
403
|
+
input_db_bytes: databaseBytes(options.inputJournalPath),
|
|
404
|
+
input_wal_bytes: databaseBytes(`${options.inputJournalPath}-wal`),
|
|
405
|
+
});
|
|
354
406
|
const eventSqlite = SqliteEventRepository.open(options.eventLedgerPath);
|
|
355
|
-
if (!eventSqlite.ok)
|
|
356
|
-
|
|
357
|
-
|
|
407
|
+
if (!eventSqlite.ok) {
|
|
408
|
+
diagnostic('failed', { error_name: eventSqlite.unavailable.code });
|
|
409
|
+
throw new Error(`${eventSqlite.unavailable.code}: ${eventSqlite.unavailable.message}`);
|
|
410
|
+
}
|
|
411
|
+
let historySqlite: SqliteStateHistoryRepository<TPosition, TState> | undefined;
|
|
412
|
+
let inputSqlite: SqliteRuntimeInputJournal<TState, TEvent> | undefined;
|
|
358
413
|
let eventMemory: MemoryEventRepository;
|
|
359
414
|
let historyMemory: MemoryStateHistoryRepository<TPosition, TState>;
|
|
360
415
|
let inputMemory: MemoryRuntimeInputJournal<TState, TEvent>;
|
|
416
|
+
let hydrated = false;
|
|
361
417
|
try {
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
418
|
+
historySqlite = new SqliteStateHistoryRepository<TPosition, TState>(options.stateHistoryPath);
|
|
419
|
+
inputSqlite = new SqliteRuntimeInputJournal<TState, TEvent>(options.inputJournalPath);
|
|
420
|
+
const current = eventSqlite.repository.currentScope(options.recovery?.account);
|
|
421
|
+
const restore = options.recovery
|
|
422
|
+
? canResumeRuntimeScope(current, options.recovery)
|
|
423
|
+
: current?.session.status === 'open';
|
|
424
|
+
const sessionId = restore && current ? current.session.sessionId : null;
|
|
425
|
+
const reuseSegment = !options.recovery || (current && current.segment.status === 'open'
|
|
426
|
+
&& canReuseParticipationSegment({ kind: current.segment.kind, identity: current.segment.scopeRef },
|
|
427
|
+
options.recovery.initialSegment.kind, options.recovery.initialSegment.identity));
|
|
428
|
+
const scope: RuntimeScope | null = restore && current && reuseSegment ? {
|
|
429
|
+
adapterId: current.session.adapterId, accountId: current.session.accountId,
|
|
430
|
+
sessionId: current.session.sessionId, segmentId: current.segment.segmentId,
|
|
431
|
+
segmentSeq: current.segment.sequence,
|
|
432
|
+
} : null;
|
|
433
|
+
diagnostic('selected', {
|
|
434
|
+
restore_session: !!sessionId, event_selection: sessionId ? 'current_session' : 'metadata_only',
|
|
435
|
+
state_selection: scope ? 'current_segment' : 'none',
|
|
436
|
+
});
|
|
437
|
+
// Event consumers can still own pending deliveries in earlier segments of
|
|
438
|
+
// the same session. State/plugin recovery, however, reads the active scope only.
|
|
439
|
+
const events = eventSqlite.repository.snapshot(sessionId);
|
|
440
|
+
if (!sessionId && current) {
|
|
441
|
+
// Runtime must still seal the previous durable scope on a fresh start.
|
|
442
|
+
events.sessions = [current.session];
|
|
443
|
+
events.segments = [current.segment];
|
|
444
|
+
}
|
|
445
|
+
const archiveThrough = events.nextCommitSeq - 1;
|
|
446
|
+
eventMemory = new MemoryEventRepository(events, (event) =>
|
|
447
|
+
eventSqlite.repository.archivedEventIdentities(event, sessionId, archiveThrough));
|
|
448
|
+
diagnostic('events_loaded', { loaded_records: eventMemory.diagnosticCounts() });
|
|
449
|
+
historyMemory = new MemoryStateHistoryRepository(historySqlite.snapshot(scope));
|
|
450
|
+
diagnostic('history_loaded', { loaded_records: historyMemory.diagnosticCounts() });
|
|
451
|
+
inputMemory = new MemoryRuntimeInputJournal(inputSqlite.snapshot(scope));
|
|
452
|
+
diagnostic('input_loaded', { loaded_records: inputMemory.diagnosticCounts() });
|
|
453
|
+
hydrated = true;
|
|
454
|
+
} catch (error) {
|
|
455
|
+
diagnostic('failed', { error_name: error instanceof Error ? error.name : 'unknown' });
|
|
456
|
+
throw error;
|
|
365
457
|
} finally {
|
|
366
|
-
eventSqlite.repository.close();
|
|
367
|
-
historySqlite
|
|
368
|
-
inputSqlite
|
|
458
|
+
if (!hydrated) eventSqlite.repository.close();
|
|
459
|
+
historySqlite?.close();
|
|
460
|
+
inputSqlite?.close();
|
|
369
461
|
}
|
|
370
462
|
const required: ResolvedMemoryFirstPersistenceOptions = {
|
|
371
463
|
...options,
|
|
@@ -373,9 +465,20 @@ export function createMemoryFirstPersistence<
|
|
|
373
465
|
batchSize: options.batchSize ?? 128,
|
|
374
466
|
flushIntervalMs: options.flushIntervalMs ?? 8,
|
|
375
467
|
};
|
|
376
|
-
|
|
468
|
+
let mirror: AsyncSqliteMirror;
|
|
469
|
+
try { mirror = new AsyncSqliteMirror(required); }
|
|
470
|
+
catch (error) {
|
|
471
|
+
eventSqlite.repository.close();
|
|
472
|
+
diagnostic('failed', { error_name: error instanceof Error ? error.name : 'unknown' });
|
|
473
|
+
throw error;
|
|
474
|
+
}
|
|
475
|
+
diagnostic('completed', {
|
|
476
|
+
loaded_records: {
|
|
477
|
+
events: eventMemory.diagnosticCounts(), history: historyMemory.diagnosticCounts(), input: inputMemory.diagnosticCounts(),
|
|
478
|
+
},
|
|
479
|
+
});
|
|
377
480
|
return {
|
|
378
|
-
eventRepository: new MemoryFirstEventRepository(mirror, eventMemory),
|
|
481
|
+
eventRepository: new MemoryFirstEventRepository(mirror, eventMemory, () => eventSqlite.repository.close()),
|
|
379
482
|
stateHistoryRepository: new MemoryFirstStateHistory(mirror, historyMemory),
|
|
380
483
|
inputJournal: new MemoryFirstInputJournal(mirror, inputMemory),
|
|
381
484
|
health: () => mirror.health(),
|
|
@@ -668,15 +668,18 @@ implements RuntimePersistenceStore<TState, TEvent> {
|
|
|
668
668
|
}
|
|
669
669
|
|
|
670
670
|
/** Full startup image for the memory-primary runtime. This is never used on a hot tick. */
|
|
671
|
-
snapshot(): RuntimeInputJournalSnapshot<TState, TEvent> {
|
|
672
|
-
const
|
|
671
|
+
snapshot(scope?: RuntimeScope | null): RuntimeInputJournalSnapshot<TState, TEvent> {
|
|
672
|
+
const where = scope === undefined ? '' : scope === null ? ' WHERE 0'
|
|
673
|
+
: ' WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?';
|
|
674
|
+
const params = scope ? [scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId] : [];
|
|
675
|
+
const epochRows = this.db.prepare(`SELECT * FROM runtime_epochs${where} ORDER BY epoch_seq ASC`).all(...params);
|
|
673
676
|
const epochs = epochRows.map((row) => ({
|
|
674
677
|
epoch: this.fromRow(row),
|
|
675
678
|
closed: row.status === 'closed',
|
|
676
679
|
inputEventsCommitted: typeof row.input_events_committed_at === 'string',
|
|
677
680
|
eventWatermark: numberValue(row.event_commit_watermark),
|
|
678
681
|
}));
|
|
679
|
-
const pluginProgress = this.db.prepare(
|
|
682
|
+
const pluginProgress = this.db.prepare(`SELECT * FROM runtime_plugin_progress${where}`).all(...params).map((row) => ({
|
|
680
683
|
scope: {
|
|
681
684
|
adapterId: String(row.adapter_id),
|
|
682
685
|
accountId: String(row.account_id),
|
|
@@ -691,8 +694,9 @@ implements RuntimePersistenceStore<TState, TEvent> {
|
|
|
691
694
|
updatedAt: String(row.updated_at),
|
|
692
695
|
},
|
|
693
696
|
}));
|
|
694
|
-
const pluginRecords = this.db.prepare(
|
|
695
|
-
|
|
697
|
+
const pluginRecords = this.db.prepare(`SELECT * FROM runtime_plugin_outcomes
|
|
698
|
+
WHERE epoch_seq IN (SELECT epoch_seq FROM runtime_epochs${where}) ORDER BY epoch_seq, plugin_id`)
|
|
699
|
+
.all(...params).map((row) => ({
|
|
696
700
|
epochSeq: numberValue(row.epoch_seq),
|
|
697
701
|
pluginId: String(row.plugin_id),
|
|
698
702
|
invocationId: String(row.invocation_id),
|
|
@@ -705,8 +709,9 @@ implements RuntimePersistenceStore<TState, TEvent> {
|
|
|
705
709
|
eventCursorAfter: numberValue(row.event_cursor_after),
|
|
706
710
|
recordedAt: String(row.recorded_at),
|
|
707
711
|
}));
|
|
708
|
-
const states = this.db.prepare(
|
|
709
|
-
|
|
712
|
+
const states = this.db.prepare(`SELECT * FROM runtime_plugin_states
|
|
713
|
+
WHERE epoch_seq IN (SELECT epoch_seq FROM runtime_epochs${where}) ORDER BY epoch_seq, plugin_id, topic`)
|
|
714
|
+
.all(...params).map((row) => ({
|
|
710
715
|
epochSeq: numberValue(row.epoch_seq),
|
|
711
716
|
pluginId: String(row.plugin_id),
|
|
712
717
|
topic: String(row.topic),
|
|
@@ -717,7 +722,7 @@ implements RuntimePersistenceStore<TState, TEvent> {
|
|
|
717
722
|
pluginProgress,
|
|
718
723
|
pluginRecords,
|
|
719
724
|
states,
|
|
720
|
-
nextEpochSeq: (
|
|
725
|
+
nextEpochSeq: numberValue(this.db.prepare('SELECT MAX(epoch_seq) AS seq FROM runtime_epochs').get()?.seq) + 1,
|
|
721
726
|
};
|
|
722
727
|
}
|
|
723
728
|
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { canResumeRuntimeScope } from './events/runtime-resume.js';
|
|
1
2
|
import {
|
|
2
3
|
ActionRegistry,
|
|
3
4
|
ObservationRegistry,
|
|
@@ -502,13 +503,7 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
502
503
|
const durableCurrent = this.repository.currentScope(accountScope);
|
|
503
504
|
const resumesBySessionKey = options.resumeKey !== undefined
|
|
504
505
|
&& durableCurrent?.session.resumeKey === options.resumeKey;
|
|
505
|
-
const
|
|
506
|
-
&& durableCurrent?.segment.kind === options.initialSegment.kind
|
|
507
|
-
&& durableCurrent.segment.scopeRef === options.initialSegment.identity;
|
|
508
|
-
const canResume = !!options.resume
|
|
509
|
-
&& !!durableCurrent
|
|
510
|
-
&& durableCurrent.session.status === 'open'
|
|
511
|
-
&& (resumesBySessionKey || resumesByCurrentSegment);
|
|
506
|
+
const canResume = canResumeRuntimeScope(durableCurrent, options);
|
|
512
507
|
if (!canResume && durableCurrent) this.sealDurableScope(durableCurrent);
|
|
513
508
|
|
|
514
509
|
this.participation = new ParticipationManager({
|
|
@@ -626,6 +621,11 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
626
621
|
};
|
|
627
622
|
}
|
|
628
623
|
|
|
624
|
+
runtimePersistenceDiagnostics(): Readonly<Record<string, unknown>> {
|
|
625
|
+
return (this.repository as { persistenceHealth?: () => Readonly<Record<string, unknown>> })
|
|
626
|
+
.persistenceHealth?.() ?? {};
|
|
627
|
+
}
|
|
628
|
+
|
|
629
629
|
runtimePluginDescriptors(): RuntimePluginDescriptor[] {
|
|
630
630
|
return [
|
|
631
631
|
...[...this.sourcePlugins.values()].map(({ plugin }) => ({
|
|
@@ -357,17 +357,20 @@ export class SqliteStateHistoryRepository<
|
|
|
357
357
|
}
|
|
358
358
|
|
|
359
359
|
/** Full startup image for the memory-primary runtime. This is never used on a hot tick. */
|
|
360
|
-
snapshot(): StateHistorySnapshot<TPosition, TState> {
|
|
361
|
-
const
|
|
362
|
-
|
|
363
|
-
const
|
|
364
|
-
|
|
360
|
+
snapshot(scope?: RuntimeScope | null): StateHistorySnapshot<TPosition, TState> {
|
|
361
|
+
const where = scope === undefined ? '' : scope === null ? ' WHERE 0'
|
|
362
|
+
: ' WHERE adapter_id = ? AND account_id = ? AND session_id = ? AND segment_id = ?';
|
|
363
|
+
const params = scope ? [scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId] : [];
|
|
364
|
+
const stateFrames = this.db.prepare(`SELECT * FROM state_frames${where} ORDER BY frame_seq ASC`)
|
|
365
|
+
.all(...params).map((row) => this.stateFrameFromRow(row));
|
|
366
|
+
const records = this.db.prepare(`SELECT * FROM trajectory_records${where} ORDER BY record_seq ASC`)
|
|
367
|
+
.all(...params).map((row) => this.recordFromRow(row));
|
|
365
368
|
return {
|
|
366
|
-
scopes: this.db.prepare(
|
|
369
|
+
scopes: this.db.prepare(`SELECT * FROM history_scopes${where}`).all(...params).map((row) => this.scopeFromRow(row)),
|
|
367
370
|
stateFrames,
|
|
368
371
|
records,
|
|
369
|
-
nextFrameSeq: (
|
|
370
|
-
nextRecordSeq: (
|
|
372
|
+
nextFrameSeq: Number(this.db.prepare('SELECT MAX(frame_seq) AS seq FROM state_frames').get()?.seq ?? 0) + 1,
|
|
373
|
+
nextRecordSeq: Number(this.db.prepare('SELECT MAX(record_seq) AS seq FROM trajectory_records').get()?.seq ?? 0) + 1,
|
|
371
374
|
};
|
|
372
375
|
}
|
|
373
376
|
|