8000 refactor(sessions): drop dead session, runtime, and event paths by geminixiang · Pull Request #197 · geminixiang/mikan · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8000
10 changes: 2 additions & 8 deletions src/adapters/slack/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,7 @@ import {
titleAssistantThread,
} from "./assistant.js";
import { createSlackAdapters } from "./context.js";
import {
hasMaterializedChatSession,
registerThreadSession,
} from "../../sessions/chat-history-sync.js";
import { registerThreadSession } from "../../sessions/chat-history-sync.js";
import {
isSlackThreadSessionKey,
parseSlackSessionKey,
Expand Down Expand Up @@ -999,10 +996,7 @@ export class SlackMessagingBot implements MessagingBot {
}

private hasKnownThreadSession(conversationId: string, sessionKey: string): Promise<boolean> {
return hasMaterializedChatSession({
office: this.office(conversationId),
sessionKey,
});
return SessionStore.exists(this.office(conversationId), sessionKey);
}

private channelKindFor(channelId: string): PlatformChannelKind | undefined {
Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/core-interfaces.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ Owns the model turn loop, message persistence, retries, compaction, budget circu

### `SessionStore`

Owns an office's sessions: one pi-durable SQLite storage, `sessions.db` in the office's State dir (ADR 0018). The top-level session is the storage's root conversation, every other session is a conversation found by its session key, and a session's name and last run record live in a durable document. `SessionHeader` (id, createdAt, parentSessionId) identifies a session and its fork parent. One process owns a live storage. `mikan migrate` imports 0.5.3 session files. Entries form one linear transcript of message, custom, and compaction entries; read the model's view with `buildSessionContext()` and the entries still in context with `getContextEntries()` instead of reading the storage.
Owns an office's sessions: one pi-durable SQLite storage, `sessions.db` in the office's State dir (ADR 0018). The top-level session is the storage's root conversation, every other session is a conversation found by its session key, and a session's name and last run record live in a durable document. `SessionHeader` (id, createdAt, parentSessionId) identifies a session and its fork parent. One process owns a live storage. `mikan migrate` imports 0.5.3 session files. Entries form one linear transcript of message, custom, and compaction entries; read the model's view with `buildSessionContext()` instead of reading the storage.

### `MikanModels`

Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/ja/core-interfaces.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ model turn loop、message 永続化、retries、compaction、budget circuit brea

### `SessionStore`

1 つの office のすべての session を所有します。office の State dir にある 1 つの pi-durable SQLite storage、`sessions.db` です(ADR 0018)。top-level session は storage の root conversation で、それ以外の各 session は session key で見つかる conversation です。session 名と直近の run 記録は durable document に保存されます。`SessionHeader`(id、createdAt、parentSessionId)は session と、それがどの親から fork したかを示します。live な storage を所有できるのは 1 つのプロセスだけです。`mikan migrate` は 0.5.3 の session file を取り込みます。entries は message、custom、compaction からなる一本の線形トランスクリプトです。モデルが見る内容は `buildSessionContext()`、context に残っている entries は `getContextEntries()` で読み、storage を直接読まないでください。
1 つの office のすべての session を所有します。office の State dir にある 1 つの pi-durable SQLite storage、`sessions.db` です(ADR 0018)。top-level session は storage の root conversation で、それ以外の各 session は session key で見つかる conversation です。session 名と直近の run 記録は durable document に保存されます。`SessionHeader`(id、createdAt、parentSessionId)は session と、それがどの親から fork したかを示します。live な storage を所有できるのは 1 つのプロセスだけです。`mikan migrate` は 0.5.3 の session file を取り込みます。entries は message、custom、compaction からなる一本の線形トランスクリプトです。モデルが見る内容は `buildSessionContext()` で読み、storage を直接読まないでください。

### `MikanModels`

Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/zh-cn/core-interfaces.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ interface ConversationContext {

### `SessionStore`

负责一间办公室的所有会话:一个 pi-durable SQLite 存储,即办公室 State dir 中的 `sessions.db`(ADR 0018)。顶层会话是存储的 root conversation,其他每个会话都是按会话密钥找到的 conversation;会话名称和最近一次 run 记录放在 durable 文档里。`SessionHeader`(id、createdAt、parentSessionId)标识一个会话及其 fork 自哪个父会话。一个 live 存储只能由一个进程拥有。`mikan migrate` 会导入 0.5.3 的会话文件。条目是一条线性的记录,包含 message、custom 和 compaction;请用 `buildSessionContext()` 读取模型看到的内容,用 `getContextEntries()` 读取仍在 context 中的条目,不要直接读存储。
负责一间办公室的所有会话:一个 pi-durable SQLite 存储,即办公室 State dir 中的 `sessions.db`(ADR 0018)。顶层会话是存储的 root conversation,其他每个会话都是按会话密钥找到的 conversation;会话名称和最近一次 run 记录放在 durable 文档里。`SessionHeader`(id、createdAt、parentSessionId)标识一个会话及其 fork 自哪个父会话。一个 live 存储只能由一个进程拥有。`mikan migrate` 会导入 0.5.3 的会话文件。条目是一条线性的记录,包含 message、custom 和 compaction;请用 `buildSessionContext()` 读取模型看到的内容,不要直接读存储。

### `MikanModels`

Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/zh-tw/core-interfaces.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ runtime/harness 的輸出 port。必要操作涵蓋最終文字、取代、診

### `SessionStore`

擁有一個 office 的所有 session:一個 pi-durable SQLite 儲存,也就是 office State dir 裡的 `sessions.db`(ADR 0018)。top-level session 是儲存的 root conversation,其他每個 session 都是依 session key 找到的 conversation;session 名稱與最近一次 run 紀錄放在 durable 文件裡。`SessionHeader`(id、createdAt、parentSessionId)標識一個 session 與它 fork 自哪個 parent。一個 live 儲存只能由一個行程擁有。`mikan migrate` 會匯入 0.5.3 的 session 檔。項目是一條線性的逐字稿,包含 message、custom 與 compaction;請用 `buildSessionContext()` 讀模型看到的內容,用 `getContextEntries()` 讀仍在 context 內的項目,不要直接讀儲存。
擁有一個 office 的所有 session:一個 pi-durable SQLite 儲存,也就是 office State dir 裡的 `sessions.db`(ADR 0018)。top-level session 是儲存的 root conversation,其他每個 session 都是依 session key 找到的 conversation;session 名稱與最近一次 run 紀錄放在 durable 文件裡。`SessionHeader`(id、createdAt、parentSessionId)標識一個 session 與它 fork 自哪個 parent。一個 live 儲存只能由一個行程擁有。`mikan migrate` 會匯入 0.5.3 的 session 檔。項目是一條線性的逐字稿,包含 message、custom 與 compaction;請用 `buildSessionContext()` 讀模型看到的內容,不要直接讀儲存。

### `MikanModels`

Expand Down
41 changes: 17 additions & 24 deletions src/events/scheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ interface Scheduled {
address: OfficeAddress;
filename: string;
event: MikanEvent;
bot: MessagingBot;
timer?: NodeJS.Timeout;
cron?: Cron;
}
Expand Down Expand Up @@ -91,15 +92,16 @@ export class EventScheduler implements EventScheduleSink {
scheduleRecord(address: OfficeAddress, record: EventRecord): void {
const key = this.key(address, record.filename);
this.cancelKey(key);
let event: MikanEvent;
let resolved: { event: MikanEvent; bot: MessagingBot };
try {
event = this.resolve(record, address);
resolved = this.resolve(record, address);
} catch (error) {
log.logWarning(`Rejecting event ${record.filename}`, errorMessage(error));
this.removeFile(address, record.filename);
return;
}
const entry: Scheduled = { address, filename: record.filename, event };
const { event, bot } = resolved;
const entry: Scheduled = { address, filename: record.filename, event, bot };
switch (event.type) {
case "immediate":
this.execute(entry);
Expand Down Expand Up @@ -153,28 +155,24 @@ export class EventScheduler implements EventScheduleSink {
this.scheduled.delete(key);
}

private resolve(record: EventRecord, address: OfficeAddress): MikanEvent {
private resolve(
record: EventRecord,
address: OfficeAddress,
): { event: MikanEvent; bot: MessagingBot } {
const { payload } = record;
const platform = (payload.platform ?? address.platform).toLowerCase();
if (platform !== address.platform || payload.conversationId !== address.conversationId) {
throw new Error("event payload does not address its owning office");
}
if (!this.botsByPlatform[platform]) {
throw new Error(`no bot configured for platform '${platform}'`);
}
const bot = this.botsByPlatform[platform];
if (!bot) throw new Error(`no bot configured for platform '${platform}'`);
const conversationKind: ConversationKind =
payload.conversationKind ?? inferConversationKind(platform, payload.conversationId);
return { ...payload, platform, conversationKind };
return { event: { ...payload, platform, conversationKind }, bot };
}

private execute(entry: Scheduled, deleteAfter = true): void {
const { event, filename, address } = entry;
const bot = this.botsByPlatform[event.platform];
if (!bot) {
this.reportFailure(entry, deleteAfter, "missing_bot");
if (deleteAfter) this.removeFile(address, filename);
return;
}
const { event, filename, address, bot } = entry;
const enqueued = bot.enqueueEvent(
createConversationEvent({
platform: event.platform as PlatformName,
Expand All @@ -188,25 +186,20 @@ export class EventScheduler implements EventScheduleSink {
);
if (!enqueued) {
log.logWarning(`Event queue full, discarded: ${filename}`);
this.reportFailure(entry, deleteAfter, "queue_full");
this.reportQueueFull(entry, deleteAfter);
}
if (deleteAfter) this.removeFile(address, filename);
}

private reportFailure(
entry: Scheduled,
deleteAfter: boolean,
failure: "missing_bot" | "queue_full",
): void {
const reason = failure === "missing_bot" ? "missing bot" : "queue full";
reportUserFacingError(new Error(`Scheduled event delivery failed: ${reason}`), {
private reportQueueFull(entry: Scheduled, deleteAfter: boolean): void {
reportUserFacingError(new Error("Scheduled event delivery failed: queue full"), {
domain: "events",
surface: "event_delivery",
operation: "event_execute",
severity: "error",
platform: entry.event.platform,
context: {
failure,
failure: "queue_full",
filename: entry.filename,
eventType: entry.event.type,
conversationId: entry.event.conversationId,
Expand Down
9 changes: 3 additions & 6 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,6 @@ const provisioner =
boostLimits: sandboxBoostLimits,
})
: undefined;
const resourceController = sandbox.type === "oci" ? provisioner : undefined;
void provisioner?.prepareImage();

if (sandbox.type === "oci") {
Expand All @@ -319,10 +318,8 @@ const openDesktop =
: undefined;
const runEvents = new RunEventHub();
const adminTokenStore = new InMemoryAdminTokenStore();
setInterval(() => linkTokenStore.purge(), 5 * 60 * 1000).unref();
setInterval(() => sessionViewTokenStore.purge(), 5 * 60 * 1000).unref();
setInterval(() => desktopTokenStore.purge(), 5 * 60 * 1000).unref();
setInterval(() => adminTokenStore.purge(), 5 * 60 * 1000).unref();
const tokenStores = [linkTokenStore, sessionViewTokenStore, desktopTokenStore, adminTokenStore];
setInterval(() => tokenStores.forEach((store) => store.purge()), 5 * 60 * 1000).unref();

function portalBaseUrl(): string | undefined {
if (LINK_BASE_URL) return LINK_BASE_URL;
Expand Down Expand Up @@ -415,7 +412,7 @@ const handler = createConversationRuntime({
sandbox,
vaultManager,
provisioner,
resourceController,
resourceController: provisioner,
linkTokenStore,
sessionViewTokenStore,
desktopTokenStore,
Expand Down
116 changes: 51 additions & 65 deletions src/runtime/conversation-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,7 @@ import {
reportUserFacingError,
withRunSpan,
} from "../observability/index.js";
import {
ChatHistorySync,
hasMaterializedChatSession,
waitForThreadSessionBootstrap,
} from "../sessions/chat-history-sync.js";
import { ChatHistorySync, waitForThreadSessionBootstrap } from "../sessions/chat-history-sync.js";
import {
assertSessionKeyBelongsToConversation,
deriveSessionKey,
Expand Down Expand Up @@ -392,7 +388,7 @@ class ConversationRuntimeImpl implements ConversationRuntime {
const waited = await waitForThreadSessionBootstrap({
parentSessionKey: conversationId,
sessionKey,
hasThreadSession: () => hasMaterializedChatSession({ office, sessionKey }),
hasThreadSession: () => SessionStore.exists(office, sessionKey),
isParentRunning: () => this.sessions.get(address, conversationId)?.running === true,
});
if (waited) {
Expand Down Expand Up @@ -436,79 +432,69 @@ class ConversationRuntimeImpl implements ConversationRuntime {
const { conversationId, sessionKey, startedAt } = meta;
const { message, platform } = context;

const attribution = createRunAttributionAttributes({
const run = {
conversationId,
sessionKey,
messageId: message.id,
platform: platform.name,
conversationKind: message.conversationKind,
userId: message.userId,
threadTs: message.threadTs,
});
};
const attribution = createRunAttributionAttributes(run);

recordCounter("agent.run.started", 1, attribution);

return withRunSpan(
{
conversationId,
sessionKey,
messageId: message.id,
return withRunSpan(run, async () => {
addLifecycleEvent("agent.run.started", {
channel_id: attribution.channel_id,
platform: platform.name,
conversationKind: message.conversationKind,
userId: message.userId,
threadTs: message.threadTs,
},
async () => {
addLifecycleEvent("agent.run.started", {
conversation_kind: message.conversationKind,
has_attachments: (message.attachments?.length ?? 0) > 0,
});

try {
const result = await body();
const durationMs = Date.now() - startedAt;
const completionAttrs = {
...attribution,
stop_reason: result.stopReason,
};
recordDistribution("agent.run.duration", durationMs, {
unit: "millisecond",
attributes: completionAttrs,
});
recordCounter("agent.run.completed", 1, completionAttrs);
addLifecycleEvent("agent.run.completed", {
channel_id: attribution.channel_id,
platform: platform.name,
conversation_kind: message.conversationKind,
has_attachments: (message.attachments?.length ?? 0) > 0,
stop_reason: result.stopReason,
duration_ms: durationMs,
});

try {
const result = await body();
const durationMs = Date.now() - startedAt;
const completionAttrs = {
...attribution,
stop_reason: result.stopReason,
};
recordDistribution("agent.run.duration", durationMs, {
unit: "millisecond",
attributes: completionAttrs,
});
recordCounter("agent.run.completed", 1, completionAttrs);
addLifecycleEvent("agent.run.completed", {
channel_id: attribution.channel_id,
platform: platform.name,
stop_reason: result.stopReason,
duration_ms: durationMs,
});
return result;
} catch (err) {
reportUserFacingError(err, {
domain: "mikan",
surface: "agent_run",
operation: "run",
severity: "error",
platform: platform.name,
context: {
conversationId,
sessionKey,
messageId: message.id,
threadTs: message.threadTs,
attachmentCount: message.attachments?.length ?? 0,
},
});
recordCounter("agent.run.errors", 1, attribution);
log.logWarning(`[${conversationId}] Run error`, errorMessage(err));
await context.responder
.replaceResponse("Could not complete the request. Please reply to retry or revise it.")
.catch(() => {});
return undefined;
}
},
);
return result;
} catch (err) {
reportUserFacingError(err, {
domain: "mikan",
surface: "agent_run",
operation: "run",
severity: "error",
platform: platform.name,
context: {
conversationId,
sessionKey,
messageId: message.id,
threadTs: message.threadTs,
attachmentCount: message.attachments?.length ?? 0,
},
});
recordCounter("agent.run.errors", 1, attribution);
log.logWarning(`[${conversationId}] Run error`, errorMessage(err));
await context.responder
.replaceResponse("Could not complete the request. Please reply to retry or revise it.")
.catch(() => {});
return undefined;
}
});
}

refreshConversation(address: OfficeAddress): boolean {
Expand Down
CB80
16 changes: 5 additions & 11 deletions src/runtime/session-lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,19 +111,13 @@ export class SessionLifecycle {
this.applyDeferredClear(address);
}

settle(
state: ConversationRuntimeState,
work: () => Promise<void>,
options: { markRunning?: boolean } = {},
): Promise<void> {
settle(state: ConversationRuntimeState, work: () => Promise<void>): Promise<void> {
const id = runtimeSessionId(state.address, state.sessionKey);
this.leases.set(id, (this.leases.get(id) ?? 0) + 1);
if (options.markRunning !== false) {
state.running = true;
state.stopRequested = false;
state.startedAt = this.now();
state.lastActivityAt = this.now();
}
state.running = true;
state.stopRequested = false;
state.startedAt = this.now();
state.lastActivityAt = this.now();

let settlement!: Promise<void>;
settlement = Promise.resolve()
Expand Down
Loading
Loading
0