refactor(schedule): keep reminder delivery conversational

This commit is contained in:
Tianyi Cui
2026-08-09 15:22:53 +08:00
parent 2f3e8974ec
commit 36ef892559
134 changed files with 598 additions and 3139 deletions
+2 -3
View File
@@ -12,9 +12,8 @@ Creates and holds event-sourced `Session` instances. Persistence is intentionall
### Public API
- `ctx.sessions.create(id?, { seed?, meta? }?)` validates and detaches durable seed/header data, fills the version and id, defaults `createdAt` to now, publishes the session, and binds it to the calling fiber. Persisted reconstruction supplies its original `createdAt`, `seedLength`, `origin`, and `delegationDepth`.
- `ctx.sessions.flush(session)` dispatches an awaited parallel checkpoint through the session's captured scope. Every listener starts and the call waits for all to settle before reporting failure; observe-only listeners return void, while a persistence listener returns literal `true` only after completing durability work. A fully successful checkpoint with at least one such acknowledgement returns `true` and emits contained `session/flushed(session, throughSeq)` with the exclusive event boundary captured at entry; no durability acknowledgement returns `false`, and unpublished, detached, or stale objects reject. A caller that requires durable storage rejects `false` at its own policy boundary.
- `findLastMessageTurnEnd(events)` pairs message-triggered starts with their ends and returns the latest matched `turn/end`. Outcome consumers use this fold instead of the raw latest log event because between-turn records and non-message turns have no prompt outcome.
- `ctx.sessions.create(id?, { seed?, meta? }?)` validates and detaches durable seed/header data, fills the version and id, defaults `createdAt` to now, publishes the session, and binds it to the calling fiber. Persisted reconstruction supplies its original `createdAt`, `seedLength`, and `delegationDepth`.
- `ctx.sessions.flush(session)` dispatches the awaited parallel durability checkpoint through the session's captured scope. Every listener starts and the call waits for all to settle before reporting failure; unpublished, detached, and stale objects reject.
- `ctx.sessions.fork(source, boundary?, childSessionId?): Session` — Resolve a live session object or id, select a seed through the inclusive `boundary` event seq (default: current last event), require that prefix to end outside an open turn, and create a live child session with lineage metadata.
- `ctx.sessions.get(id: SessionId): Session | undefined`
- `ctx.sessions.list(): Session[]`
+2 -3
View File
@@ -12,9 +12,8 @@
### 公共 API
- `ctx.sessions.create(id?, { seed?, meta? }?)` 校验持久种子/头部数据并生成脱离副本,补齐版本和 id,在未提供 `createdAt` 时使用当前时间,发布会话并将其绑定到调用方 fiber。持久化重建会提供原始的 `createdAt`、`seedLength`、`origin` 和 `delegationDepth`。
- `ctx.sessions.flush(session)` 通过会话捕获的作用域分发受等待的并行检查点。每个监听器都会启动,调用会等待全部结算后才报告失败;仅观察的监听器返回 void,持久化监听器只有在完成持久化工作后才返回字面量 `true`。全部成功且至少有一个此类确认时,调用返回 `true`,并发布受包含的 `session/flushed(session, throughSeq)`,其中 `throughSeq` 是入口处捕获的事件排他边界;没有持久化确认时返回 `false`,未发布、已脱离或陈旧对象会被拒绝。要求持久化存储的调用方应在自己的策略边界拒绝 `false`。
- `findLastMessageTurnEnd(events)` 将由消息触发的开始与结束配对,并返回最近匹配的 `turn/end`。结果消费方使用该折叠逻辑,而不直接取日志中最近的事件,因为轮次间记录和非消息轮次没有提示词结果。
- `ctx.sessions.create(id?, { seed?, meta? }?)` 校验持久种子/头部数据并生成脱离副本,补齐版本和 id,在未提供 `createdAt` 时使用当前时间,发布会话并将其绑定到调用方 fiber。持久化重建会提供原始的 `createdAt`、`seedLength` 和 `delegationDepth`。
- `ctx.sessions.flush(session)` 通过会话捕获的作用域分发受等待的并行持久性检查点。每个监听器都会启动;调用会等待全部结算后才报告失败。未发布、已脱离和陈旧的对象会被拒绝。
- `ctx.sessions.fork(source, boundary?, childSessionId?): Session`:解析实时会话对象或 id,选取截至 `boundary` 事件序号(含该事件)的种子(默认为当前最后一个事件),要求所选前缀结束时没有开放轮次,再创建带谱系元数据的实时子会话。
- `ctx.sessions.get(id: SessionId): Session | undefined`
- `ctx.sessions.list(): Session[]`
+12 -61
View File
@@ -95,32 +95,14 @@ declare module 'cordis' {
*/
'session/event'(this: Scoped<Session>, session: Session, event: SessionEvent): void
/**
* Awaited parallel checkpoint: every listener runs and the caller awaits
* all of them, with no waterfall veto. A listener returns literal `true`
* only after completing durability work; observe-only listeners return
* void. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`) reuses the
* session's owner scope.
* Awaited parallel durability checkpoint: every listener runs and the
* caller awaits all of them, with no waterfall veto. Scope-filtered dispatch
* (`@deepseek-ai/dsh-scope`) reuses the session's owner scope.
* @param session - the session whose buffered events must reach durable storage.
* @dshScopeScan unsupported
* @mode parallel
*/
'session/flush'(this: Scoped<Session>, session: Session): Promise<true | void> | true | void
/**
* Observe a successful durability checkpoint. `throughSeq` is the exclusive
* event boundary captured when {@link SessionStore.flush} began; events
* appended while its listeners run require a later successful checkpoint.
* Concurrent checkpoints may publish their boundaries out of order, so a
* consumer retaining progress must advance by the maximum observed value.
* No notification is published when no durability listener participated or
* any listener failed. Observer failures are logged and contained.
* Scope-filtered dispatch (`@deepseek-ai/dsh-scope`) reuses the session's
* owner scope.
* @param session - the session whose prefix completed the checkpoint.
* @param throughSeq - exclusive event sequence boundary proven by the checkpoint.
* @dshScopeScan unsupported
* @mode emit
*/
'session/flushed'(this: Scoped<Session>, session: Session, throughSeq: number): void
'session/flush'(this: Scoped<Session>, session: Session): Promise<void> | void
}
}
@@ -406,16 +388,6 @@ function assertSupportedRequestHeader(type: string, data: unknown, location: str
type SessionCallback = (...args: unknown[]) => unknown
/** Render any thrown observer value without violating callback containment. */
function renderSessionObserverError(error: unknown): string {
try {
return String(error)
} catch {
// String coercion itself may throw.
return '[unrenderable thrown value]'
}
}
/** Resolve one listener snapshot, including Cordis's internal dispatch checks. */
function collectSessionCallbacks(ctx: Context, args: unknown[]): SessionCallback[] {
return [...ctx.events.dispatch('emit', args)] as SessionCallback[]
@@ -424,7 +396,7 @@ function collectSessionCallbacks(ctx: Context, args: unknown[]): SessionCallback
/** Invoke one resolved observe-only listener snapshot with per-listener containment. */
function invokeContainedSessionObservers(
ctx: Context,
name: 'session/event' | 'session/disposed' | 'session/flushed',
name: 'session/event' | 'session/disposed',
id: SessionId,
args: unknown[],
callbacks: SessionCallback[],
@@ -433,10 +405,10 @@ function invokeContainedSessionObservers(
try {
const returned: unknown = callback(...args)
void Promise.resolve(returned).catch((error: unknown) => {
ctx.logger.warn(`session "${id}": ${name} listener rejected: ${renderSessionObserverError(error)}`)
ctx.logger.warn(`session "${id}": ${name} listener rejected: ${String(error)}`)
})
} catch (error: unknown) {
ctx.logger.warn(`session "${id}": ${name} listener threw: ${renderSessionObserverError(error)}`)
ctx.logger.warn(`session "${id}": ${name} listener threw: ${String(error)}`)
}
}
}
@@ -1028,7 +1000,7 @@ export class SessionStore extends Service {
// of becoming unhandled.
const returned: unknown = callback(...callbackArgs)
void Promise.resolve(returned).catch((error: unknown) => {
this.ctx.logger.warn(`session "${entry.id}": session/created listener rejected: ${renderSessionObserverError(error)}`)
this.ctx.logger.warn(`session "${entry.id}": session/created listener rejected: ${String(error)}`)
})
}
} finally {
@@ -1044,7 +1016,7 @@ export class SessionStore extends Service {
const callbacks = collectSessionCallbacks(this.ctx, [entry.carrier, 'session/disposed', entry.session])
invokeContainedSessionObservers(this.ctx, 'session/disposed', entry.id, callbackArgs, callbacks)
} catch (error: unknown) {
this.ctx.logger.warn(`session "${entry.id}": session/disposed dispatch threw: ${renderSessionObserverError(error)}`)
this.ctx.logger.warn(`session "${entry.id}": session/disposed dispatch threw: ${String(error)}`)
}
}
@@ -1057,13 +1029,12 @@ export class SessionStore extends Service {
* rather than dispatch a raw `ctx.parallel('session/flush', …)` — one owner,
* one spelling, and the scoped-dispatch invariant can pin it.
* @param session - the session whose buffered events must reach durable storage.
* @returns whether at least one listener acknowledged completed durability,
* after every listener has settled successfully.
* @returns whether at least one durability listener participated, after every
* listener has settled successfully.
* @throws the first registered listener failure after every listener settles.
*/
async flush(session: Session): Promise<boolean> {
const { carrier } = this.liveEntryFor(session)
const throughSeq = session.seq
const callbackArgs: unknown[] = [session]
const callbacks = collectSessionCallbacks(this.ctx, [carrier, 'session/flush', session])
const results = await Promise.allSettled(callbacks.map((callback) => {
@@ -1078,27 +1049,7 @@ export class SessionStore extends Service {
}))
const failure = results.find((result): result is PromiseRejectedResult => result.status === 'rejected')
if (failure !== undefined) throw failure.reason
const durable = results.some(result => result.status === 'fulfilled' && result.value === true)
if (durable) {
const flushedArgs: unknown[] = [session, throughSeq]
try {
const observers = collectSessionCallbacks(this.ctx, [
carrier,
'session/flushed',
...flushedArgs,
])
invokeContainedSessionObservers(
this.ctx,
'session/flushed',
session.id,
flushedArgs,
observers,
)
} catch (error: unknown) {
this.ctx.logger.warn(`session "${session.id}": session/flushed dispatch threw: ${renderSessionObserverError(error)}`)
}
}
return durable
return callbacks.length > 0
}
/** Return the exact live entry; detached/prepared objects reject. */
+3 -109
View File
@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import { createScope, scopeOf } from '@deepseek-ai/dsh-scope'
import type { Scope, ScopeKey } from '@deepseek-ai/dsh-scope'
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
import SessionStore from '@deepseek-ai/dsh-session'
import type { Session } from '@deepseek-ai/dsh-session'
async function mount(): Promise<Context> {
@@ -83,41 +83,19 @@ describe('sessions.flush()', () => {
it('allows an ordinary flush with no listeners', async () => {
const ctx = await mount()
const session = ctx.sessions.create()
const flushed: number[] = []
ctx.on('session/flushed', (_current, throughSeq) => { flushed.push(throughSeq) })
await expect(ctx.sessions.flush(session)).resolves.toBe(false)
expect(flushed).toEqual([])
})
it('reports a durability listener after it acknowledges success', async () => {
it('reports a participating listener after it succeeds', async () => {
const ctx = await mount()
const session = ctx.sessions.create()
const flushed: Session[] = []
const checkpoints: number[] = []
ctx.on('session/flush', (current) => {
flushed.push(current)
return true as const
})
ctx.on('session/flushed', (_current, throughSeq) => { checkpoints.push(throughSeq) })
ctx.on('session/flush', current => void flushed.push(current))
await expect(ctx.sessions.flush(session)).resolves.toBe(true)
expect(flushed).toEqual([session])
expect(checkpoints).toEqual([0])
})
it('does not treat an observe-only flush listener as durability', async () => {
const ctx = await mount()
const session = ctx.sessions.create()
const observed: Session[] = []
const checkpoints: number[] = []
ctx.on('session/flush', current => void observed.push(current))
ctx.on('session/flushed', (_current, throughSeq) => { checkpoints.push(throughSeq) })
await expect(ctx.sessions.flush(session)).resolves.toBe(false)
expect(observed).toEqual([session])
expect(checkpoints).toEqual([])
})
it('dispatches session/flush with the owning carrier and awaits all listeners', async () => {
@@ -143,13 +121,9 @@ describe('sessions.flush()', () => {
it('propagates a rejecting flush listener (the caller owns the failure policy)', async () => {
const ctx = await mount()
const checkpoints: number[] = []
ctx.on('session/flush', () => Promise.reject(new Error('disk full')))
ctx.on('session/flush', () => true)
ctx.on('session/flushed', (_session, throughSeq) => { checkpoints.push(throughSeq) })
const session = ctx.sessions.create()
await expect(ctx.sessions.flush(session)).rejects.toThrow('disk full')
expect(checkpoints).toEqual([])
})
it('does not let a synchronous flush failure starve later listeners', async () => {
@@ -186,86 +160,6 @@ describe('sessions.flush()', () => {
expect(settled).toBe(true)
})
it('publishes the entry prefix while a concurrent suffix waits for a later checkpoint', async () => {
const ctx = await mount()
const gate = Promise.withResolvers<undefined>()
let attempts = 0
ctx.on('session/flush', async () => {
attempts += 1
if (attempts === 1) await gate.promise
return true as const
})
const checkpoints: number[] = []
ctx.on('session/flushed', (_session, throughSeq) => { checkpoints.push(throughSeq) })
const session = ctx.sessions.create()
session.append('turn/start', { turn: 1 })
const first = ctx.sessions.flush(session)
session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
gate.resolve(undefined)
await first
await ctx.sessions.flush(session)
expect(checkpoints).toEqual([1, 2])
})
it('contains successful-checkpoint observers without reversing the barrier', async () => {
const ctx = await mount()
const checkpoints: number[] = []
ctx.on('session/flush', () => true)
ctx.on('session/flushed', () => { throw new Error('observer failed') })
ctx.on('session/flushed', (_session, throughSeq) => { checkpoints.push(throughSeq) })
const session = ctx.sessions.create()
await expect(ctx.sessions.flush(session)).resolves.toBe(true)
expect(checkpoints).toEqual([0])
})
it('contains successful-checkpoint dispatch resolution failure without reversing the barrier', async () => {
const ctx = await mount()
const warnings: string[] = []
ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
const checkpoints: number[] = []
ctx.on('session/flush', () => true)
ctx.on('internal/dispatch', (_mode, name) => {
if (name === 'session/flushed') throw Object.create(null)
})
ctx.on('session/flushed', (_session, throughSeq) => { checkpoints.push(throughSeq) })
const session = ctx.sessions.create(SessionId('flushed-dispatch'))
await expect(ctx.sessions.flush(session)).resolves.toBe(true)
expect(checkpoints).toEqual([])
expect(warnings).toEqual([
'session "flushed-dispatch": session/flushed dispatch threw: [unrenderable thrown value]',
])
})
it('may publish overlapping checkpoints out of order without widening either boundary', async () => {
const ctx = await mount()
const firstGate = Promise.withResolvers<undefined>()
const secondGate = Promise.withResolvers<undefined>()
const gates = [firstGate, secondGate]
ctx.on('session/flush', async () => {
const gate = gates.shift()
if (gate === undefined) throw new Error('unexpected checkpoint attempt')
await gate.promise
return true as const
})
const checkpoints: number[] = []
ctx.on('session/flushed', (_session, throughSeq) => { checkpoints.push(throughSeq) })
const session = ctx.sessions.create()
const first = ctx.sessions.flush(session)
session.append('turn/start', { turn: 1 })
const second = ctx.sessions.flush(session)
secondGate.resolve(undefined)
await second
firstGate.resolve(undefined)
await first
expect(checkpoints).toEqual([1, 0])
})
it('rejects a never-entered session instead of inventing a carrier', async () => {
const ctx = await mount()
const scope = await mintScope(ctx, 'owner')