refactor(session-projection): acquire retained readers during activation
This commit is contained in:
1 parent
d8d942c82a
commit
5ecf33aab1
22 files changed
+388
-270
No files matched your search
@@ -39,8 +39,8 @@
|
||||
en: 2a8b93869eb5a2f9
|
||||
zh: ddab8e738d188a61
|
||||
/deepseek-ai-dsh-agent-loop/understand-the-implementation/creation-and-teardown:
|
||||
en: d079cf181ece9267
|
||||
zh: 047f76fecfc5497c
|
||||
en: 79aa89d1db536612
|
||||
zh: a86635bf4aa54b59
|
||||
/deepseek-ai-dsh-agent-loop/understand-the-implementation/persistence-integration:
|
||||
en: 3c5721bc00a0bbf4
|
||||
zh: 711f832343ffbb75
|
||||
|
||||
@@ -109,7 +109,7 @@ The loop deep-freezes each derived message identity on its first request and reu
|
||||
|
||||
Creation is one rollback-covered transaction: construct a private session, concrete agent, and scoped context; await optional setup; enter both registries; announce `session/created`; await serial `agent/created` listeners; then release queued input. A caller creating a runtime child sets `options.parentAgent`; the caller Context separately owns the transaction and live handle. Setup, commit, or listener failure and owner disposal roll back the prepared resources. Announcements already delivered remain observable and receive matching disposal notifications. Teardown stops and drains the driver, unwinds the scope, closes the session's write path, detaches the agent, then detaches the session. Every detach binds the exact entered object, so a stale disposer cannot remove a later same-id replacement.
|
||||
|
||||
Factory unload retains the inbox and turn-boundary projections through scope cleanup, including cancellation from scoped abort listeners, until every Agent teardown and startup task settles. Cleanup failures do not release those projections early. Caller unload, factory unload, and handle disposal await the same teardown.
|
||||
The loop awaits inbox and turn-boundary registration before publishing its factory and passes those handles into synchronous Agent construction. During factory unload, global registrations may disappear before teardown finishes; retained handles remain readable through scope cleanup, including cancellation from scoped abort listeners. Caller unload, factory unload, and handle disposal await the same teardown.
|
||||
|
||||
### Persistence integration
|
||||
|
||||
|
||||
@@ -109,7 +109,7 @@ const handle = await ctx.agents.create({
|
||||
|
||||
创建是同一个受回滚保护的事务:构造私有会话、具象 agent 与带作用域上下文;等待可选 setup;进入两个注册表;宣告 `session/created`;等待串行 `agent/created` 监听器;随后释放已排队输入。创建运行时子 Agent 的调用方设置 `options.parentAgent`;调用方 Context 则单独拥有事务和存活句柄。Setup、commit、监听器失败或所有者 dispose 都会回滚已准备的资源。已送达的宣告仍可被观察,并有配对的销毁通知。Teardown 停止并排空驱动器、撤销作用域、关闭会话写路径、detach agent,再 detach 会话。每次 detach 都绑定到确切进入的对象,因此陈旧 disposer 无法移除之后出现的同 id 替代项。
|
||||
|
||||
工厂卸载时在整个作用域清理期间保留 inbox 投影与轮次边界投影,包括作用域内 abort 监听器发起取消的时刻,直到所有 Agent teardown 和启动任务结束。清理失败不会使这些投影提前释放。调用方卸载、工厂卸载和句柄释放等待同一次 teardown。
|
||||
loop 在发布工厂前等待 inbox 与轮次边界注册完成,并将句柄传入 Agent 的同步构造过程。工厂卸载时,全局注册可以先于 teardown 完成而消失;保留句柄在整个作用域清理期间仍可读取,包括作用域内 abort 监听器发起取消的时刻。调用方卸载、工厂卸载和句柄释放等待同一次 teardown。
|
||||
|
||||
### 持久化集成
|
||||
|
||||
|
||||
@@ -12,6 +12,8 @@ import type {
|
||||
AgentStatus,
|
||||
CancelOptions,
|
||||
InboxTarget,
|
||||
InboxState,
|
||||
TurnBoundaryProjection,
|
||||
PreStepDecision,
|
||||
RequestErrorAction,
|
||||
} from '@deepseek-ai/dsh-agent'
|
||||
@@ -31,7 +33,7 @@ import type { EpochHeader, RequestContext, Session, SessionId, SessionSeq, TurnE
|
||||
import { canonicalHeader, headerEquals, ToolCallRecovery } from '@deepseek-ai/dsh-session'
|
||||
import { joinContextSections, renderContextSections, renderPrompt } from '@deepseek-ai/dsh-system-prompt'
|
||||
import type { PromptAssembly } from '@deepseek-ai/dsh-system-prompt'
|
||||
import type {} from '@deepseek-ai/dsh-session-projection'
|
||||
import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import { ReactLoopInbox } from './inbox.ts'
|
||||
import { RuntimeContextProjection } from './runtime-context.ts'
|
||||
@@ -124,15 +126,15 @@ export class ReactLoopAgent implements Agent {
|
||||
public readonly id: SessionId,
|
||||
public readonly options: AgentOptions,
|
||||
public readonly session: Session,
|
||||
inbox: ProjectionHandle<InboxState>,
|
||||
boundary: ProjectionHandle<TurnBoundaryProjection>,
|
||||
) {
|
||||
this.requestSurfaceGeneration = session.surface.contentGeneration
|
||||
this.dispatch = agentEvents(loopCtx, this)
|
||||
this.scope = createScope(loopCtx, this)
|
||||
this.ctx = this.scope.ctx
|
||||
this.inbox = new ReactLoopInbox(this.ctx.sessionProjections, session, this.dispatch)
|
||||
/* v8 ignore next -- the loop registers its own turnBoundary unit, so the key is always present */
|
||||
const lastTurn = this.loopCtx.sessionProjections.stateOf(session, 'turnBoundary')?.lastTurn ?? 0
|
||||
this.phase = { kind: 'idle', lastTurn }
|
||||
this.inbox = new ReactLoopInbox(() => inbox.stateOf(session), session, this.dispatch)
|
||||
this.phase = { kind: 'idle', lastTurn: boundary.stateOf(session).lastTurn }
|
||||
this.runtimeContext = new RuntimeContextProjection(this.ctx, session)
|
||||
this.systemPrompt = new SystemPromptProjection(session)
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
|
||||
import type { MessageId } from '@deepseek-ai/dsh-llm'
|
||||
import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection'
|
||||
import type SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
|
||||
import type { Session, SessionEventMap, UserMessage } from '@deepseek-ai/dsh-session'
|
||||
import type {
|
||||
AgentEventDispatch,
|
||||
@@ -67,30 +66,30 @@ export const inboxProjectionDefinition = {
|
||||
/**
|
||||
* Driver-owned durable Inbox implementation used by ReactLoopAgent and focused
|
||||
* provider tests.
|
||||
* @param projections - registry with the standard Inbox projection registered by AgentLoop.
|
||||
* @param readState - reader for the live Inbox projection state.
|
||||
* @param session - session whose durable events store pending input.
|
||||
* @param dispatch - agent-scoped notifications for Inbox lifecycle events.
|
||||
*/
|
||||
export class ReactLoopInbox implements InboxContract {
|
||||
constructor(
|
||||
private readonly projections: SessionProjectionRegistry,
|
||||
private readonly readState: () => InboxState,
|
||||
private readonly session: Session,
|
||||
private readonly dispatch: AgentEventDispatch,
|
||||
) {}
|
||||
|
||||
/** Prompts awaiting individual turns. */
|
||||
get nextTurn(): readonly UserMessage[] {
|
||||
return this.current()['next-turn']
|
||||
return this.readState()['next-turn']
|
||||
}
|
||||
|
||||
/** Input awaiting the next step boundary. */
|
||||
get nextStep(): readonly UserMessage[] {
|
||||
return this.current()['next-step']
|
||||
return this.readState()['next-step']
|
||||
}
|
||||
|
||||
/** Whether either pending-message list contains work. */
|
||||
get hasPending(): boolean {
|
||||
const state = this.current()
|
||||
const state = this.readState()
|
||||
return state['next-turn'].length > 0 || state['next-step'].length > 0
|
||||
}
|
||||
|
||||
@@ -119,7 +118,7 @@ export class ReactLoopInbox implements InboxContract {
|
||||
* @param message - message to append.
|
||||
*/
|
||||
append(target: InboxTarget, message: UserMessage): void {
|
||||
this.splice(target, this.current()[target].length, 0, [message])
|
||||
this.splice(target, this.readState()[target].length, 0, [message])
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -175,7 +174,7 @@ export class ReactLoopInbox implements InboxContract {
|
||||
|
||||
/** Locate one pending identity across both owned lists. */
|
||||
private locate(messageId: MessageId): { target: InboxTarget; index: number } | undefined {
|
||||
const state = this.current()
|
||||
const state = this.readState()
|
||||
for (const target of ['next-turn', 'next-step'] as const) {
|
||||
const index = state[target].findIndex(message => message.id === messageId)
|
||||
if (index >= 0) return { target, index }
|
||||
@@ -183,17 +182,6 @@ export class ReactLoopInbox implements InboxContract {
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** Read the current durable projection state. */
|
||||
private current(): InboxState {
|
||||
const state = this.projections.stateOf(this.session, 'inbox')
|
||||
if (state === undefined) {
|
||||
throw new Error(
|
||||
`agent "${this.session.id}" cannot read inbox state: its projection registration is not active`,
|
||||
)
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
/** Commit one normalized mutation and publish its live events. */
|
||||
private mutate(
|
||||
target: InboxTarget,
|
||||
@@ -202,7 +190,7 @@ export class ReactLoopInbox implements InboxContract {
|
||||
inserted: UserMessage[],
|
||||
discardRemoved: boolean,
|
||||
): UserMessage[] {
|
||||
const state = this.current()
|
||||
const state = this.readState()
|
||||
const inbox = state[target]
|
||||
const truncatedStart = Math.trunc(start)
|
||||
const offset = Number.isNaN(truncatedStart) ? 0 : truncatedStart
|
||||
|
||||
@@ -9,26 +9,26 @@ import type { Volatile } from '@deepseek-ai/cosmokit'
|
||||
import { Context, FiberState, Service } from '@deepseek-ai/cordis'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import z from '@deepseek-ai/schemastery'
|
||||
import { z as zod } from 'zod'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import type {
|
||||
Agent,
|
||||
AgentFactory,
|
||||
AgentHandle,
|
||||
AgentOptions,
|
||||
AgentSetup,
|
||||
CreateAgentOptions,
|
||||
ResumeAgentOptions,
|
||||
SessionStartSource,
|
||||
TurnBoundaryProjection,
|
||||
import {
|
||||
turnBoundaryProjectionDefinition,
|
||||
type Agent,
|
||||
type AgentFactory,
|
||||
type AgentHandle,
|
||||
type AgentOptions,
|
||||
type AgentSetup,
|
||||
type CreateAgentOptions,
|
||||
type ResumeAgentOptions,
|
||||
type SessionStartSource,
|
||||
type InboxState,
|
||||
type TurnBoundaryProjection,
|
||||
} from '@deepseek-ai/dsh-agent'
|
||||
import { errorChain, ReasoningEffortId } from '@deepseek-ai/dsh-llm'
|
||||
import { interruptedTurnClosers, SessionLogOffset, SessionPreparation, SessionSeq } from '@deepseek-ai/dsh-session'
|
||||
import { interruptedTurnClosers, SessionLogOffset, SessionPreparation } from '@deepseek-ai/dsh-session'
|
||||
import type { Session, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type {} from '@deepseek-ai/dsh-system-prompt'
|
||||
import type {} from '@deepseek-ai/dsh-tools'
|
||||
import type {} from '@deepseek-ai/dsh-session-projection'
|
||||
import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection'
|
||||
import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection'
|
||||
import { SessionPersistenceNotFoundError } from '@deepseek-ai/dsh-session-persistence'
|
||||
import type { SessionHandle, SessionPersistence } from '@deepseek-ai/dsh-session-persistence'
|
||||
import { ReactLoopAgent } from './agent.ts'
|
||||
@@ -36,6 +36,8 @@ import { inboxProjectionDefinition } from './inbox.ts'
|
||||
import { DEFAULT_MAX_PARALLEL_TOOL_CALLS } from './constants.ts'
|
||||
import type {} from './runtime-context.ts'
|
||||
|
||||
export { turnBoundaryProjectionDefinition } from '@deepseek-ai/dsh-agent'
|
||||
|
||||
/** Fiber states that cannot own or serve a new lifecycle. */
|
||||
const INACTIVE_STATES: ReadonlySet<FiberState> = new Set([
|
||||
FiberState.UNLOADING,
|
||||
@@ -43,57 +45,6 @@ const INACTIVE_STATES: ReadonlySet<FiberState> = new Set([
|
||||
FiberState.FAILED,
|
||||
])
|
||||
|
||||
const turnBoundaryProjectionSchema: zod.ZodType<TurnBoundaryProjection> = zod.object({
|
||||
openTurnStartSeq: zod.number().int().nonnegative().transform(SessionSeq).nullable(),
|
||||
lastStepStartSeq: zod.number().int().nonnegative().transform(SessionSeq).nullable(),
|
||||
lastStepBoundary: zod.object({
|
||||
kind: zod.union([zod.literal('start'), zod.literal('end')]),
|
||||
seq: zod.number().int().nonnegative().transform(SessionSeq),
|
||||
}).nullable(),
|
||||
lastTurn: zod.number().int().nonnegative(),
|
||||
})
|
||||
|
||||
/** Host projection of agent turn and step boundaries. */
|
||||
export const turnBoundaryProjectionDefinition = {
|
||||
key: 'turnBoundary',
|
||||
stateVersion: 2,
|
||||
stateSchema: turnBoundaryProjectionSchema,
|
||||
init: () => ({
|
||||
openTurnStartSeq: null,
|
||||
lastStepStartSeq: null,
|
||||
lastStepBoundary: null,
|
||||
lastTurn: 0,
|
||||
}),
|
||||
apply: (state, event) => {
|
||||
switch (event.type) {
|
||||
case 'turn/start':
|
||||
return {
|
||||
...state,
|
||||
openTurnStartSeq: event.seq,
|
||||
lastTurn: event.data.turn,
|
||||
}
|
||||
case 'turn/end':
|
||||
return {
|
||||
...state,
|
||||
openTurnStartSeq: null,
|
||||
}
|
||||
case 'step/start':
|
||||
return {
|
||||
...state,
|
||||
lastStepStartSeq: event.seq,
|
||||
lastStepBoundary: { kind: 'start', seq: event.seq },
|
||||
}
|
||||
case 'step/end':
|
||||
return {
|
||||
...state,
|
||||
lastStepBoundary: { kind: 'end', seq: event.seq },
|
||||
}
|
||||
default:
|
||||
return state
|
||||
}
|
||||
},
|
||||
} satisfies ProjectionDefinition<'turnBoundary', TurnBoundaryProjection>
|
||||
|
||||
/** Re-throw one collected failure as itself, or several as one `AggregateError`. */
|
||||
function throwCollectedFailures(failures: readonly unknown[], message: string): void {
|
||||
if (failures.length === 1) throw failures[0]
|
||||
@@ -361,6 +312,8 @@ export class AgentLoop extends Service implements AgentFactory {
|
||||
private readonly ownership: FactoryOwnership
|
||||
/** Plain holder prevents Cordis from re-tracing the factory's dependency context through a caller shadow. */
|
||||
private readonly runtime: { ctx: Context }
|
||||
private inbox!: ProjectionHandle<InboxState>
|
||||
private turnBoundary!: ProjectionHandle<TurnBoundaryProjection>
|
||||
|
||||
constructor(ctx: Context, config: Config) {
|
||||
super(ctx, 'agentLoop')
|
||||
@@ -372,19 +325,17 @@ export class AgentLoop extends Service implements AgentFactory {
|
||||
validateConfiguredAgents(this.config.agents)
|
||||
// Register only after every config validation above has passed, so a
|
||||
// rejected constructor leaves no projection unit behind.
|
||||
const ownership = this.ownership = new FactoryOwnership(ctx.fiber)
|
||||
this.ownership = new FactoryOwnership(ctx.fiber)
|
||||
this.runtime = { ctx }
|
||||
ctx.effect(function* () {
|
||||
const unregisterTurnBoundary = ctx.sessionProjections.register(turnBoundaryProjectionDefinition)
|
||||
yield unregisterTurnBoundary
|
||||
const unregisterInbox = ctx.sessionProjections.register(inboxProjectionDefinition)
|
||||
yield unregisterInbox
|
||||
// Cordis skips later disposers after a rejection; finally still releases projections.
|
||||
yield () => ownership.dispose().finally(() => {
|
||||
unregisterInbox()
|
||||
unregisterTurnBoundary()
|
||||
})
|
||||
}, 'agentLoop.transactions()')
|
||||
}
|
||||
|
||||
protected async [Service.init](): Promise<void> {
|
||||
const ctx = this.runtime.ctx
|
||||
const ownership = this.ownership
|
||||
// Agents retain readers while fiber disposal removes global projection registrations.
|
||||
ctx.effect(() => () => ownership.dispose(), 'agentLoop.transactions()')
|
||||
this.turnBoundary = await ctx.sessionProjections.register(turnBoundaryProjectionDefinition)
|
||||
this.inbox = await ctx.sessionProjections.register(inboxProjectionDefinition)
|
||||
ctx.effect(() => ctx.agents.setFactory(this), 'agentLoop.setFactory()')
|
||||
ctx.systemPrompt.variable('provider', context => context.agent?.options.provider)
|
||||
ctx.systemPrompt.variable('model', context => context.agent?.options.model)
|
||||
@@ -599,9 +550,10 @@ export class AgentLoop extends Service implements AgentFactory {
|
||||
}
|
||||
}
|
||||
const untrack = this.ownership.track(dispose)
|
||||
const { inbox, turnBoundary } = this
|
||||
try {
|
||||
unfollowOwner = ownerCtx.effect(function* () {
|
||||
const created = machine = new ReactLoopAgent(loopCtx, id, options, session)
|
||||
const created = machine = new ReactLoopAgent(loopCtx, id, options, session, inbox, turnBoundary)
|
||||
machineReady.resolve()
|
||||
// Adopt the scope on its original fiber so it cannot unload before teardown.
|
||||
// A loop already unloading during minting owns the provisional scope itself.
|
||||
|
||||
@@ -49,10 +49,10 @@ async function inboxAgent(rawId: string): Promise<{
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionProjectionRegistry)
|
||||
ctx.sessionProjections.register(inboxProjectionDefinition)
|
||||
const projection = await ctx.sessionProjections.register(inboxProjectionDefinition)
|
||||
const session = ctx.sessions.create(SessionId(rawId))
|
||||
const agent = stubAgent(rawId, { ctx, session })
|
||||
const inbox = new ReactLoopInbox(ctx.sessionProjections, session, agentEvents(ctx, agent))
|
||||
const inbox = new ReactLoopInbox(() => projection.stateOf(session), session, agentEvents(ctx, agent))
|
||||
Object.assign(agent, { inbox })
|
||||
return { ctx, session, agent, inbox }
|
||||
}
|
||||
@@ -67,9 +67,9 @@ async function reconstructPersistedInbox(
|
||||
const session = ctx.sessions.create(SessionId(rawId))
|
||||
populate(session)
|
||||
await ctx.plugin(SessionProjectionRegistry)
|
||||
ctx.sessionProjections.register(inboxProjectionDefinition)
|
||||
const projection = await ctx.sessionProjections.register(inboxProjectionDefinition)
|
||||
const agent = stubAgent(rawId, { ctx, session })
|
||||
const inbox = new ReactLoopInbox(ctx.sessionProjections, session, agentEvents(ctx, agent))
|
||||
const inbox = new ReactLoopInbox(() => projection.stateOf(session), session, agentEvents(ctx, agent))
|
||||
try {
|
||||
void inbox.nextTurn
|
||||
} catch (error: unknown) {
|
||||
@@ -80,12 +80,12 @@ async function reconstructPersistedInbox(
|
||||
}
|
||||
|
||||
describe('ReactLoopInbox', () => {
|
||||
it('reads the shared projection without owning its registration', async () => {
|
||||
it('retains inbox reads after the shared registration is released', async () => {
|
||||
const ctx = new Context()
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionProjectionRegistry)
|
||||
const unregister = ctx.sessionProjections.register(inboxProjectionDefinition)
|
||||
const projection = await ctx.sessionProjections.register(inboxProjectionDefinition)
|
||||
const session = ctx.sessions.create(SessionId('inbox-projection'))
|
||||
const pending = createUserMessage({
|
||||
content: [{ type: 'text', text: 'pending' }],
|
||||
@@ -96,8 +96,8 @@ describe('ReactLoopInbox', () => {
|
||||
})
|
||||
const agent = stubAgent('inbox-projection', { ctx, session })
|
||||
const dispatch = agentEvents(ctx, agent)
|
||||
const first = new ReactLoopInbox(ctx.sessionProjections, session, dispatch)
|
||||
const second = new ReactLoopInbox(ctx.sessionProjections, session, dispatch)
|
||||
const first = new ReactLoopInbox(() => projection.stateOf(session), session, dispatch)
|
||||
const second = new ReactLoopInbox(() => projection.stateOf(session), session, dispatch)
|
||||
|
||||
expect(first.nextTurn).toEqual([pending])
|
||||
expect(second.nextTurn).toEqual([pending])
|
||||
@@ -106,9 +106,12 @@ describe('ReactLoopInbox', () => {
|
||||
'next-step': [],
|
||||
})
|
||||
|
||||
unregister()
|
||||
expect(ctx.sessionProjections.stateOf(session, 'inbox')).toBeUndefined()
|
||||
expect(() => first.nextTurn).toThrow('its projection registration is not active')
|
||||
await projection.dispose()
|
||||
expect(ctx.sessionProjections.checkpoint(session).inbox?.val).toBeUndefined()
|
||||
expect(first.nextTurn).toEqual([pending])
|
||||
first.clear()
|
||||
expect(second.nextTurn).toEqual([])
|
||||
expect(ctx.sessionProjections.snapshot(session).values.inbox).toBeUndefined()
|
||||
})
|
||||
|
||||
it('rejects invalid durable coordinates and duplicate identities during reconstruction', async () => {
|
||||
@@ -141,10 +144,10 @@ describe('ReactLoopInbox', () => {
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionProjectionRegistry)
|
||||
ctx.sessionProjections.register(inboxProjectionDefinition)
|
||||
const projection = await ctx.sessionProjections.register(inboxProjectionDefinition)
|
||||
const parent = ctx.sessions.create(SessionId('inbox-fork-parent'))
|
||||
const parentAgent = stubAgent('inbox-fork-parent', { ctx, session: parent })
|
||||
const parentInbox = new ReactLoopInbox(ctx.sessionProjections, parent, agentEvents(ctx, parentAgent))
|
||||
const parentInbox = new ReactLoopInbox(() => projection.stateOf(parent), parent, agentEvents(ctx, parentAgent))
|
||||
const inherited = createUserMessage({
|
||||
content: [{ type: 'text', text: 'parent pending' }],
|
||||
source: { kind: 'user' },
|
||||
@@ -152,7 +155,7 @@ describe('ReactLoopInbox', () => {
|
||||
parentInbox.append('next-turn', inherited)
|
||||
const child = ctx.sessions.fork(parent, undefined, SessionId('inbox-fork-child'))
|
||||
const childAgent = stubAgent('inbox-fork-child', { ctx, session: child })
|
||||
const childInbox = new ReactLoopInbox(ctx.sessionProjections, child, agentEvents(ctx, childAgent))
|
||||
const childInbox = new ReactLoopInbox(() => projection.stateOf(child), child, agentEvents(ctx, childAgent))
|
||||
|
||||
expect(child.inheritedEventCount).toBe(parent.snapshotEvents().length)
|
||||
expect(childInbox.nextTurn).toEqual([inherited])
|
||||
@@ -175,7 +178,7 @@ describe('ReactLoopInbox', () => {
|
||||
let observed: readonly UserMessage[] | undefined
|
||||
ctx.on('session/event', (subject, event) => {
|
||||
if (subject === session && event.type === 'agent/inbox/spliced') {
|
||||
observed = ctx.sessionProjections.stateOf(session, 'inbox')?.['next-turn']
|
||||
observed = inbox.nextTurn
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import LlmRuntime, { createUserMessage, ToolCallId, LlmError, ReasoningEffortId, StreamChunk, expandAssistantStream } from '@deepseek-ai/dsh-llm'
|
||||
import type { ContextFormed } from '@deepseek-ai/dsh-llm'
|
||||
@@ -1912,6 +1912,7 @@ describe('agent loop', () => {
|
||||
defaultEffort: effort,
|
||||
})
|
||||
const ctx = new Context()
|
||||
onTestFinished(async () => { await ctx.fiber.dispose() })
|
||||
await ctx.plugin(LlmRuntime)
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionProjectionRegistry)
|
||||
@@ -1923,6 +1924,7 @@ describe('agent loop', () => {
|
||||
})
|
||||
ctx.llm.registerAdapter(['mock'], adapter)
|
||||
|
||||
await vi.waitFor(() => { expect(ctx.agents.list()).toHaveLength(1) })
|
||||
const agent = ctx.agents.list()[0]!
|
||||
expect(agent).toBeDefined()
|
||||
expect(agent.id).toBe(agent.session.id)
|
||||
@@ -1940,6 +1942,7 @@ describe('agent loop', () => {
|
||||
|
||||
it('attaches config agent cwd to the fresh session header', async () => {
|
||||
const ctx = new Context()
|
||||
onTestFinished(async () => { await ctx.fiber.dispose() })
|
||||
await ctx.plugin(LlmRuntime)
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionProjectionRegistry)
|
||||
@@ -1950,6 +1953,7 @@ describe('agent loop', () => {
|
||||
agents: [{ id: SessionId('config-agent'), provider: 'mock', model: 'mock', cwd: '/work/project' }],
|
||||
})
|
||||
|
||||
await vi.waitFor(() => { expect(ctx.agents.list()).toHaveLength(1) })
|
||||
const agent = ctx.agents.list()[0]!
|
||||
expect(agent.session.header.cwd).toBe('/work/project')
|
||||
})
|
||||
|
||||
@@ -3,12 +3,13 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import AgentLoop from '@deepseek-ai/dsh-agent-loop'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import { turnBoundaryProjectionDefinition, type Agent } from '@deepseek-ai/dsh-agent'
|
||||
import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
|
||||
import { createAssistantMessage, createUserMessage, isAgentLoopRequest } from '@deepseek-ai/dsh-llm'
|
||||
import type { GenerateOptions, ToolSchema } from '@deepseek-ai/dsh-llm'
|
||||
import { Session, SessionId, SessionLogOffset, SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session'
|
||||
import * as values from '@deepseek-ai/dsh-util-values'
|
||||
import { inboxProjectionDefinition } from '../src/inbox.ts'
|
||||
import { ReactLoopAgent } from '../src/agent.ts'
|
||||
import { MockAdapter, textResponse } from './mock-adapter.ts'
|
||||
|
||||
@@ -73,7 +74,9 @@ describe('loop-owned request freezing', () => {
|
||||
expect(Object.isFrozen(userEvent.data.content)).toBe(false)
|
||||
expect(Object.isFrozen(assistantEvent.data.message)).toBe(false)
|
||||
ctx.effect(() => ctx.sessions.enter(session))
|
||||
const agent = new ReactLoopAgent(loopCtx, id, { provider: 'mock', model: 'mock' }, session)
|
||||
const agent = new ReactLoopAgent(loopCtx, id, { provider: 'mock', model: 'mock' }, session,
|
||||
await loopCtx.sessionProjections.register(inboxProjectionDefinition),
|
||||
await loopCtx.sessionProjections.register(turnBoundaryProjectionDefinition))
|
||||
cleanups.push(async () => {
|
||||
agent.cancel({ kind: 'disposed' })
|
||||
await agent.whenIdle()
|
||||
@@ -122,7 +125,9 @@ describe('loop-owned request freezing', () => {
|
||||
expect(Object.isFrozen(session.deriveMessages())).toBe(false)
|
||||
expect(freeze.mock.calls.filter(([value]) => value === userEvent.data)).toHaveLength(1)
|
||||
expect(freeze.mock.calls.filter(([value]) => value === replacement.data)).toHaveLength(1)
|
||||
const resumed = new ReactLoopAgent(loopCtx, id, { provider: 'mock', model: 'mock' }, session)
|
||||
const resumed = new ReactLoopAgent(loopCtx, id, { provider: 'mock', model: 'mock' }, session,
|
||||
await loopCtx.sessionProjections.register(inboxProjectionDefinition),
|
||||
await loopCtx.sessionProjections.register(turnBoundaryProjectionDefinition))
|
||||
cleanups.push(async () => {
|
||||
resumed.cancel({ kind: 'disposed' })
|
||||
await resumed.whenIdle()
|
||||
|
||||
@@ -38,7 +38,6 @@ it.each([0, 1, 2])('retains Agent resources until all work exits with %i failed
|
||||
const aborted = Promise.withResolvers<undefined>()
|
||||
let workExited = false
|
||||
let scopeDisposedBeforeWorkExit = false
|
||||
let projectionPresentAtWorkExit = false
|
||||
let scopeDisposed = false
|
||||
let abortHandled = 0
|
||||
const controller = new AbortController()
|
||||
@@ -57,8 +56,6 @@ it.each([0, 1, 2])('retains Agent resources until all work exits with %i failed
|
||||
const work = agent.runMaintenance(async (signal) => {
|
||||
signal.addEventListener('abort', () => { aborted.resolve(undefined) }, { once: true })
|
||||
await release.promise
|
||||
projectionPresentAtWorkExit = projections.stateOf(agent.session, 'inbox') !== undefined
|
||||
&& projections.stateOf(agent.session, 'turnBoundary') !== undefined
|
||||
workExited = true
|
||||
})
|
||||
const disposal = loop.dispose()
|
||||
@@ -71,11 +68,10 @@ it.each([0, 1, 2])('retains Agent resources until all work exits with %i failed
|
||||
await Promise.all([disposal, ownerDisposal])
|
||||
for (const { handle, error } of failed) await expect(handle.dispose()).rejects.toBe(error)
|
||||
expect(scopeDisposedBeforeWorkExit).toBe(false)
|
||||
expect(projectionPresentAtWorkExit).toBe(true)
|
||||
expect(scopeDisposed).toBe(true)
|
||||
expect(abortHandled).toBe(1)
|
||||
expect(projections.stateOf(agent.session, 'inbox')).toBeUndefined()
|
||||
expect(projections.stateOf(agent.session, 'turnBoundary')).toBeUndefined()
|
||||
expect(projections.checkpoint(agent.session).inbox).toBeUndefined()
|
||||
expect(projections.checkpoint(agent.session).turnBoundary).toBeUndefined()
|
||||
expect(ctx.agents.get(agent.id)).toBeUndefined()
|
||||
expect(ctx.sessions.get(agent.session.id)).toBeUndefined()
|
||||
})
|
||||
|
||||
@@ -288,7 +288,7 @@ describe('agent scope lifecycle', () => {
|
||||
const { ctx, loopFiber } = await harnessWithLoop()
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
const cold = ctx.sessions.create(SessionId('projection-before-any-agent'))
|
||||
expect(ctx.sessionProjections.stateOf(cold, 'inbox')).toEqual({ 'next-turn': [], 'next-step': [] })
|
||||
expect(ctx.sessionProjections.checkpoint(cold).inbox?.val).toEqual({ 'next-turn': [], 'next-step': [] })
|
||||
let first!: Awaited<ReturnType<typeof ctx.agents.create>>
|
||||
let second!: Awaited<ReturnType<typeof ctx.agents.create>>
|
||||
const firstOwner = await ctx.plugin(Object.assign(async (inner: Context) => {
|
||||
@@ -304,15 +304,15 @@ describe('agent scope lifecycle', () => {
|
||||
})
|
||||
}, { inject: ['agents'] }))
|
||||
|
||||
expect(ctx.sessionProjections.stateOf(first.agent.session, 'inbox')).toBeDefined()
|
||||
expect(ctx.sessionProjections.checkpoint(first.agent.session).inbox?.val).toBeDefined()
|
||||
await firstOwner.dispose()
|
||||
expect(ctx.sessionProjections.stateOf(second.agent.session, 'inbox')).toBeDefined()
|
||||
expect(ctx.sessionProjections.checkpoint(second.agent.session).inbox?.val).toBeDefined()
|
||||
await secondOwner.dispose()
|
||||
expect(ctx.sessionProjections.stateOf(second.agent.session, 'inbox')).toBeDefined()
|
||||
expect(ctx.sessionProjections.checkpoint(second.agent.session).inbox?.val).toBeDefined()
|
||||
|
||||
await Promise.all([first.dispose(), second.dispose()])
|
||||
await loopFiber.dispose()
|
||||
expect(ctx.sessionProjections.stateOf(second.agent.session, 'inbox')).toBeUndefined()
|
||||
expect(ctx.sessionProjections.checkpoint(second.agent.session).inbox?.val).toBeUndefined()
|
||||
})
|
||||
|
||||
it('agent.ctx listeners hear only their own agent (scoped dispatch end to end)', async () => {
|
||||
@@ -567,7 +567,7 @@ describe('agent scope lifecycle', () => {
|
||||
await ctx.fiber.dispose()
|
||||
})
|
||||
|
||||
it('factory unload during scope minting skips setup and awaits provisional cleanup', async () => {
|
||||
it('factory unload during scope minting drains provisional setup and cleanup', async () => {
|
||||
const { ctx, loopFiber } = await harnessWithLoop()
|
||||
let unloaded = false
|
||||
let setupCalls = 0
|
||||
|
||||
@@ -60,5 +60,8 @@
|
||||
"@deepseek-ai/dsh-util-values": "workspace:*",
|
||||
"@deepseek-ai/dsh-workspace": "workspace:*",
|
||||
"@deepseek-ai/cordis": "workspace:~"
|
||||
},
|
||||
"dependencies": {
|
||||
"zod": "4.4.3"
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,7 @@ import type { AgentOptions, SessionStartSource } from './runtime-types.ts'
|
||||
|
||||
export * from './runtime-types.ts'
|
||||
export * from './types.ts'
|
||||
export type * from './projection.ts'
|
||||
export { turnBoundaryProjectionDefinition } from './projection.ts'
|
||||
export * from './consumed-work.ts'
|
||||
export * from './model-selection.ts'
|
||||
export { agentCarrier, agentEvents, assembleContextFor, emitAgentEvent } from './dispatch.ts'
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
/** Shared pure fold of the Session's turn and step events. */
|
||||
import type { TurnBoundaryProjection } from './types.ts'
|
||||
import type {} from '@deepseek-ai/dsh-session-projection'
|
||||
import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection'
|
||||
import { SessionSeq } from '@deepseek-ai/dsh-session'
|
||||
import { z as zod } from 'zod'
|
||||
|
||||
declare module '@deepseek-ai/dsh-session-projection/types' {
|
||||
interface SessionProjectionStateMap {
|
||||
@@ -8,4 +11,53 @@ declare module '@deepseek-ai/dsh-session-projection/types' {
|
||||
}
|
||||
}
|
||||
|
||||
export {}
|
||||
const turnBoundaryProjectionSchema: zod.ZodType<TurnBoundaryProjection> = zod.object({
|
||||
openTurnStartSeq: zod.number().int().nonnegative().transform(SessionSeq).nullable(),
|
||||
lastStepStartSeq: zod.number().int().nonnegative().transform(SessionSeq).nullable(),
|
||||
lastStepBoundary: zod.object({
|
||||
kind: zod.union([zod.literal('start'), zod.literal('end')]),
|
||||
seq: zod.number().int().nonnegative().transform(SessionSeq),
|
||||
}).nullable(),
|
||||
lastTurn: zod.number().int().nonnegative(),
|
||||
})
|
||||
|
||||
/** Host projection of agent turn and step boundaries. */
|
||||
export const turnBoundaryProjectionDefinition = {
|
||||
key: 'turnBoundary',
|
||||
stateVersion: 2,
|
||||
stateSchema: turnBoundaryProjectionSchema,
|
||||
init: () => ({
|
||||
openTurnStartSeq: null,
|
||||
lastStepStartSeq: null,
|
||||
lastStepBoundary: null,
|
||||
lastTurn: 0,
|
||||
}),
|
||||
apply: (state, event) => {
|
||||
switch (event.type) {
|
||||
case 'turn/start':
|
||||
return {
|
||||
...state,
|
||||
openTurnStartSeq: event.seq,
|
||||
lastTurn: event.data.turn,
|
||||
}
|
||||
case 'turn/end':
|
||||
return {
|
||||
...state,
|
||||
openTurnStartSeq: null,
|
||||
}
|
||||
case 'step/start':
|
||||
return {
|
||||
...state,
|
||||
lastStepStartSeq: event.seq,
|
||||
lastStepBoundary: { kind: 'start', seq: event.seq },
|
||||
}
|
||||
case 'step/end':
|
||||
return {
|
||||
...state,
|
||||
lastStepBoundary: { kind: 'end', seq: event.seq },
|
||||
}
|
||||
default:
|
||||
return state
|
||||
}
|
||||
},
|
||||
} satisfies ProjectionDefinition<'turnBoundary', TurnBoundaryProjection>
|
||||
@@ -149,7 +149,7 @@ async function harness(options: HarnessOptions = {}) {
|
||||
await ctx.plugin({ name: storageDomainName, inject: storageDomainInject, apply: storageDomainApply, Config: storageDomainConfig }, { backend: 'json' })
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionProjectionRegistry)
|
||||
ctx.sessionProjections.register(marksUnit(options.stateVersion))
|
||||
await ctx.sessionProjections.register(marksUnit(options.stateVersion))
|
||||
const fiber = await ctx.plugin(SessionProjectionCache, options.config ?? { writeEveryEvents: 100, writeIntervalMs: 60_000 })
|
||||
return { ctx, root, fiber, cache: ctx.sessionProjectionCache }
|
||||
}
|
||||
@@ -300,7 +300,7 @@ describe('SessionProjectionCache write policy', () => {
|
||||
await ctx.sessionProjectionCache.write(clean)
|
||||
expect((await storedRows(root, clean.id))?.['cache-test/marks']).toEqual({ ver: 1, seq: -1, val: null })
|
||||
// A unit whose state violates the plain-JSON contract fails the write loud.
|
||||
ctx.sessionProjections.register({
|
||||
await ctx.sessionProjections.register({
|
||||
key: 'cache-test/marks2',
|
||||
stateSchema: z.custom<Map<string, string>>(() => true),
|
||||
init: () => new Map<string, string>(),
|
||||
@@ -336,7 +336,7 @@ describe('SessionProjectionCache write policy', () => {
|
||||
await ctx.plugin({ name: storageDomainName, inject: storageDomainInject, apply: storageDomainApply, Config: storageDomainConfig }, { backend: 'json' })
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionProjectionRegistry)
|
||||
ctx.sessionProjections.register(marksUnit())
|
||||
await ctx.sessionProjections.register(marksUnit())
|
||||
await ctx.plugin(SessionProjectionCache, { writeEveryEvents: 100, writeIntervalMs: 60_000 })
|
||||
const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
|
||||
// A directory where the record document must land makes the atomic
|
||||
@@ -387,7 +387,7 @@ describe('SessionProjectionCache listing read', () => {
|
||||
'cache-test/secondary-marks': { ver: 1, seq: SessionSeq(6), val: { marks: ['secondary'] } },
|
||||
})
|
||||
const { ctx, cache } = await harness({ root })
|
||||
ctx.sessionProjections.register(secondaryMarksUnit)
|
||||
await ctx.sessionProjections.register(secondaryMarksUnit)
|
||||
|
||||
// The block carries one watermark: the seq every served value has folded
|
||||
// through at least, so the lower of the two rows names the block.
|
||||
@@ -457,7 +457,7 @@ describe('SessionProjectionCache listing read', () => {
|
||||
},
|
||||
)
|
||||
const { ctx, cache } = await harness({ root })
|
||||
ctx.sessionProjections.register(titleUnit)
|
||||
await ctx.sessionProjections.register(titleUnit)
|
||||
const seededHeader = { ...headerOf(id), isSeeded: true }
|
||||
|
||||
// An older format generation never serves the full block, but its title
|
||||
@@ -509,7 +509,7 @@ describe('SessionProjectionCache listing read', () => {
|
||||
'cache-test/secret': { ver: 1, seq: SessionSeq(4), val: 'private prompt text' },
|
||||
})
|
||||
const { ctx, cache } = await harness({ root })
|
||||
ctx.sessionProjections.register(secretUnit)
|
||||
await ctx.sessionProjections.register(secretUnit)
|
||||
const header = headerOf(SessionId('host-state'))
|
||||
|
||||
expect(cache.cachedSnapshot(header)).toEqual({
|
||||
@@ -546,7 +546,7 @@ describe('SessionProjectionCache listing read', () => {
|
||||
'cache-test/marks3': { ver: 1, seq: SessionSeq(4), val: { marks: ['b'] } },
|
||||
})
|
||||
const { ctx, cache } = await harness({ root })
|
||||
ctx.sessionProjections.register(marks3Unit)
|
||||
await ctx.sessionProjections.register(marks3Unit)
|
||||
const block = cache.cachedSnapshot(headerOf(SessionId('multi-row')))
|
||||
expect(block?.values).toEqual({
|
||||
'cache-test/marks': { marks: ['a'] },
|
||||
@@ -752,7 +752,7 @@ describe('SessionProjectionCache cold-read seeding', () => {
|
||||
})
|
||||
const { cache, ctx } = await harness({ root })
|
||||
const apply = vi.fn((_state: number, _event: SessionEvent) => 1)
|
||||
ctx.sessionProjections.register({
|
||||
await ctx.sessionProjections.register({
|
||||
key: 'cache-test/count',
|
||||
stateSchema: z.number().int().nonnegative(),
|
||||
init: () => 0,
|
||||
@@ -794,7 +794,7 @@ describe('SessionProjectionCache cold-read seeding', () => {
|
||||
await ctx.plugin({ name: storageDomainName, inject: storageDomainInject, apply: storageDomainApply, Config: storageDomainConfig }, { backend: 'json' })
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionProjectionRegistry)
|
||||
ctx.sessionProjections.register(marksUnit())
|
||||
await ctx.sessionProjections.register(marksUnit())
|
||||
await ctx.plugin(SessionProjectionCache, { writeEveryEvents: 100, writeIntervalMs: 60_000 })
|
||||
const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
|
||||
// A directory where the record document must land makes the write-back
|
||||
|
||||
@@ -110,7 +110,7 @@ async function harness(root: string) {
|
||||
const ctx = await storageHarness(root)
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionProjectionRegistry)
|
||||
ctx.sessionProjections.register(titleUnit)
|
||||
await ctx.sessionProjections.register(titleUnit)
|
||||
await ctx.plugin(SessionProjectionCache, { writeEveryEvents: 100, writeIntervalMs: 60_000 })
|
||||
return { ctx, cache: ctx.sessionProjectionCache }
|
||||
}
|
||||
@@ -324,7 +324,7 @@ describe('archived version recovery', () => {
|
||||
await ctx.plugin({ name: storageDomainName, inject: storageDomainInject, apply: storageDomainApply, Config: storageDomainConfig }, { backend: 'json' })
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionProjectionRegistry)
|
||||
ctx.sessionProjections.register(titleUnit)
|
||||
await ctx.sessionProjections.register(titleUnit)
|
||||
const error = vi.spyOn(ctx.logger, 'error').mockImplementation(() => {})
|
||||
// The boot survives the broken record — this line rejecting IS the fixed bug.
|
||||
await ctx.plugin(SessionProjectionCache, { writeEveryEvents: 100, writeIntervalMs: 60_000 })
|
||||
|
||||
@@ -18,14 +18,14 @@
|
||||
en: 3a15581f0b043e79
|
||||
zh: 302fc8afe8fb45fa
|
||||
/deepseek-ai-dsh-session-projection/use-this-package/when-to-choose-it:
|
||||
en: 90b7c26cb45be52a
|
||||
zh: 386e294ec09607c1
|
||||
en: 7ea79ed69e0ea085
|
||||
zh: b7791be4c547495c
|
||||
/deepseek-ai-dsh-session-projection/use-this-package/define-a-projection-unit:
|
||||
en: 09758d1475fad86e
|
||||
zh: 473637cb34aebe72
|
||||
/deepseek-ai-dsh-session-projection/use-this-package/register-and-read:
|
||||
en: 6a19c075f826b3f7
|
||||
zh: c200277cb58062be
|
||||
en: e10e44c46035dbdb
|
||||
zh: dff312b52f4ec2ce
|
||||
/deepseek-ai-dsh-session-projection/use-this-package/persisted-checkpoints:
|
||||
en: 45f1c05fb7e08180
|
||||
zh: f8d62c749899651a
|
||||
|
||||
@@ -29,7 +29,7 @@ Mount `dsh-session-projection` wherever client carriers need current values of l
|
||||
|
||||
### When to choose it
|
||||
|
||||
Choose it when a domain keeps state that clients should see without re-deriving it — a todo list, a goal snapshot, conversation statistics. The registry drives units eagerly over committed events, so any registered unit's value is current by construction. Skip it for host-only bookkeeping that no client reads: a unit without a `wire` block stays host-only. A host reader either declares `sessionProjections` in its plugin `inject` or fails explicitly when the registry or required key is absent. Contributors may preserve optional registration through `ctx.inject(['sessionProjections'], ...)`.
|
||||
Choose it when a domain keeps state that clients should see without re-deriving it — a todo list, a goal snapshot, conversation statistics. The registry drives units eagerly over committed events, so any registered unit's value is current by construction. A unit without a `wire` block keeps its state host-only. Host readers declare `sessionProjections` in their plugin dependencies and await registration before exposing synchronous reads.
|
||||
|
||||
### Define a projection unit
|
||||
|
||||
@@ -55,10 +55,11 @@ const definition = {
|
||||
|
||||
### Register and read
|
||||
|
||||
`register(definition)` installs the unit; registrants with the same key and `stateVersion` share its cells, while an incompatible version or invalid `stateVersion` throws. Registration is an effect on the calling fiber, so the last unload removes the key and its cached cells. The returned disposer can be yielded into a composite `ctx.effect()` on the same fiber to keep the unit available through dependent cleanup. Carriers read a consistent synchronous cut over every client-visible unit with `snapshot(session)` — `{ asOfSeq, values }`, where `asOfSeq` is the seq of the last event every value reflects — and subscribe to per-change notifications with `onChanged(listener)`. `stateOf(session, key)` reads one unit's live read-only host state without computing unrelated views.
|
||||
`await register(definition)` installs the unit and returns a handle with synchronous `stateOf(session)` reads and `dispose()`. Registrants with the same key and `stateVersion` share cells; incompatible or invalid versions reject registration. Registration belongs to the calling fiber. The last unregister removes the unit from global event drives, snapshots, checkpoints, and change notifications. Existing handles remain readable: each retains its original unit and folds new Session events on demand, even if another version later registers the same key. Reading a handle does not initialize unrelated units or register it again. Carriers use `snapshot(session)` for a consistent client-view cut and `onChanged(listener)` for changes to registered units.
|
||||
|
||||
```text
|
||||
const dispose = ctx.sessionProjections.register(definition)
|
||||
const projection = await ctx.sessionProjections.register(definition)
|
||||
const state = projection.stateOf(session)
|
||||
const { asOfSeq, values } = ctx.sessionProjections.snapshot(session)
|
||||
```
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ kind: "package-reference"
|
||||
|
||||
### 何时选择
|
||||
|
||||
当领域保存客户端应看到、但不应自行重新派生的状态——todo 清单、goal 快照、对话统计——时选择本包。注册表在已提交事件上主动驱动单元,因此任何已注册单元的值按构造即为当前值。当维护的是无客户端读取的 host-only 记账时跳过:不带 `wire` 块的单元保持 host-only。host 读取方要么在插件 `inject` 中声明 `sessionProjections`,要么在注册表或必需 key 缺席时明确失败。贡献方可以继续通过 `ctx.inject(['sessionProjections'], ...)` 保持可选注册。
|
||||
当领域保存客户端应看到、但不应自行重新派生的状态——todo 清单、goal 快照、对话统计——时选择本包。注册表在已提交事件上主动驱动单元,因此任何已注册单元的值按构造即为当前值。不带 `wire` 块的单元将状态保留在 host。host 读取方在插件依赖中声明 `sessionProjections`,并等待注册完成后才提供同步读取。
|
||||
|
||||
### 定义投影单元
|
||||
|
||||
@@ -55,10 +55,11 @@ const definition = {
|
||||
|
||||
### 注册与读取
|
||||
|
||||
`register(definition)` 安装单元;具有相同 key 和 `stateVersion` 的注册方共享其 cell,版本不兼容或 `stateVersion` 非法时会 throw。注册是挂在调用方 fiber 上的 effect,因此最后一个注册方卸载后会移除 key 及其缓存 cell。返回的 disposer 可以 yield 到同一 fiber 上的复合 `ctx.effect()` 中,使单元在依赖它的清理完成前保持可用。载体用 `snapshot(session)` 对每个客户端可见单元读取一致的同步切面——`{ asOfSeq, values }`,其中 `asOfSeq` 是所有值共同反映到的最后一个事件的 seq——并用 `onChanged(listener)` 订阅逐变更通知。`stateOf(session, key)` 读取一个单元的实时只读 host 状态,不计算无关视图。
|
||||
`await register(definition)` 安装单元,返回提供同步 `stateOf(session)` 读取和 `dispose()` 的 handle。具有相同 key 和 `stateVersion` 的注册方共享 cell;版本不兼容或非法时注册会拒绝。注册归调用方 fiber 所有。最后一个注册方注销后,单元退出全局事件驱动、快照、检查点和变更通知。已有 handle 仍可读取:它保留原有单元,按需折叠新增的 Session 事件,即使同一 key 后来注册了其他版本也不受影响。读取 handle 不会初始化无关单元,也不会重新注册。载体用 `snapshot(session)` 读取一致的客户端视图切面,用 `onChanged(listener)` 订阅已注册单元的变更。
|
||||
|
||||
```text
|
||||
const dispose = ctx.sessionProjections.register(definition)
|
||||
const projection = await ctx.sessionProjections.register(definition)
|
||||
const state = projection.stateOf(session)
|
||||
const { asOfSeq, values } = ctx.sessionProjections.snapshot(session)
|
||||
```
|
||||
|
||||
|
||||
@@ -37,6 +37,19 @@ import type { SessionProjectionMap, SessionProjectionStateMap } from './types.ts
|
||||
|
||||
export type { SessionProjectionMap, SessionProjectionStateMap } from './types.ts'
|
||||
|
||||
/** An effect-owned registration with a reader retained independently of registration. */
|
||||
export interface ProjectionHandle<S> {
|
||||
/**
|
||||
* Read the current state, including after unregistering, by folding new
|
||||
* Session events with this handle's original unit. Do not mutate the live value.
|
||||
* @param session - Session whose committed events are folded.
|
||||
* @returns the projection state at the Session's current cursor.
|
||||
*/
|
||||
stateOf(session: Session): S
|
||||
/** Unregister from global drives and snapshots without invalidating this reader. */
|
||||
dispose(): void | Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* One domain's state-driven computation unit: a pure synchronous fold plus
|
||||
* declarations and an optional client view — never an opaque getter. The framework drives
|
||||
@@ -156,8 +169,8 @@ interface UnitCell {
|
||||
}
|
||||
|
||||
/**
|
||||
* One live registration: the unit plus its per-session cells (dropped whole
|
||||
* once the last registrant releases it).
|
||||
* One shared unit and its per-session cells, retained by acquired readers after
|
||||
* the final registration leaves the live table.
|
||||
*
|
||||
* `refs` exists because one unit definition already serves every session — the
|
||||
* cells are keyed by `Session` — while registrants are per-session:
|
||||
@@ -186,15 +199,11 @@ function cursorBefore(offset: SessionLogOffset): SessionSeqCursor {
|
||||
* raw result changes by `Object.is`.
|
||||
* Cells build lazily — a unit registered after events flowed, or a session
|
||||
* older than the registry, folds `init` over the in-memory log on first
|
||||
* touch (event or read). Registration is an effect (disposer rides the
|
||||
* calling fiber): an unloaded domain plugin's key disappears from snapshots
|
||||
* and clients read it as capability absence. A host reader either declares
|
||||
* `sessionProjections` in its plugin `inject` or fails explicitly when the
|
||||
* registry or required key is absent. Contributors may preserve optional
|
||||
* registration through `ctx.inject(['sessionProjections'], ...)`. Registrants sharing a key
|
||||
* share one unit and are counted: the same tool package mounted in N agent
|
||||
* presets registers N times, and the key survives until the last one
|
||||
* unloads.
|
||||
* touch (event or read). Consumers declare `sessionProjections` as a required
|
||||
* injection, await registration during activation, and retain its ready handle.
|
||||
* Registrants sharing a key share one unit and are counted. The last release
|
||||
* removes the unit from live drives, checkpoints, and client snapshots; retained
|
||||
* handles still fold new events on demand using the original unit.
|
||||
*/
|
||||
export class SessionProjectionRegistry extends Service {
|
||||
private readonly registrations = new Map<string, Registration>()
|
||||
@@ -223,12 +232,12 @@ export class SessionProjectionRegistry extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* Register one domain's unit. The registration is an effect on the calling
|
||||
* context's fiber: disposing the fiber (or calling the returned disposer)
|
||||
* removes the key — and the unit's cached cells — from subsequent drives
|
||||
* and snapshots.
|
||||
* Register one domain's unit on the calling context's fiber. Fiber or handle
|
||||
* disposal releases one reference; the final release removes live participation.
|
||||
* Retained handles remain readable after release.
|
||||
* Callers must await registration before publishing consumers; registration may perform asynchronous work.
|
||||
* @param definition - key, state schema, pure unit functions, and stateVersion.
|
||||
* @returns the exact disposer that unregisters this unit.
|
||||
* @returns a ready handle with synchronous state reads and the effect disposer.
|
||||
*/
|
||||
register<
|
||||
K extends keyof SessionProjectionMap,
|
||||
@@ -237,22 +246,23 @@ export class SessionProjectionRegistry extends Service {
|
||||
definition: Omit<ProjectionDefinition<K, S>, 'wire'> & {
|
||||
wire: NonNullable<ProjectionDefinition<K, S>['wire']>
|
||||
},
|
||||
): () => void
|
||||
): Promise<ProjectionHandle<S>>
|
||||
/**
|
||||
* Register one host-only unit. Its state is omitted from client snapshots
|
||||
* and always checkpointed like every other unit.
|
||||
* Callers must await registration before publishing consumers; registration may perform asynchronous work.
|
||||
* @param definition - key, state schema, pure unit functions, and stateVersion.
|
||||
* @returns the exact disposer that unregisters this unit.
|
||||
* @returns a ready handle with synchronous state reads and the effect disposer.
|
||||
*/
|
||||
register<
|
||||
K extends Exclude<keyof SessionProjectionStateMap, keyof SessionProjectionMap>,
|
||||
S extends SessionProjectionStateMap[K],
|
||||
>(
|
||||
definition: Omit<ProjectionDefinition<K, S>, 'wire'>,
|
||||
): () => void
|
||||
register<K extends keyof SessionProjectionStateMap, S extends SessionProjectionStateMap[K]>(
|
||||
): Promise<ProjectionHandle<S>>
|
||||
async register<K extends keyof SessionProjectionStateMap, S extends SessionProjectionStateMap[K]>(
|
||||
definition: ProjectionDefinition<K, S>,
|
||||
): () => void {
|
||||
): Promise<ProjectionHandle<S>> {
|
||||
const wire = definition.wire as {
|
||||
viewSchema: ZodType
|
||||
view(state: S): unknown
|
||||
@@ -270,27 +280,34 @@ export class SessionProjectionRegistry extends Service {
|
||||
if (!Number.isSafeInteger(definition.stateVersion) || definition.stateVersion < 0) {
|
||||
throw new Error(`session projection ${JSON.stringify(definition.key)} stateVersion must be a non-negative integer, got ${String(definition.stateVersion)}`)
|
||||
}
|
||||
const dispose = this.ctx.effect(function* (this: SessionProjectionRegistry) {
|
||||
let registration!: Registration
|
||||
const dispose = this.ctx.effect(() => {
|
||||
const key = erased.key
|
||||
const existing = this.registrations.get(key)
|
||||
if (existing === undefined) {
|
||||
this.registrations.set(key, { def: erased, cells: new WeakMap(), refs: 1 })
|
||||
registration = { def: erased, cells: new WeakMap(), refs: 1 }
|
||||
this.registrations.set(key, registration)
|
||||
} else {
|
||||
if (existing.def.stateVersion !== erased.stateVersion) {
|
||||
throw new Error(`session projection key ${JSON.stringify(key)} is already registered at stateVersion ${String(existing.def.stateVersion)}; refusing to share it with stateVersion ${String(erased.stateVersion)}`)
|
||||
}
|
||||
existing.refs += 1
|
||||
registration = existing
|
||||
}
|
||||
yield () => {
|
||||
const live = this.registrations.get(key)
|
||||
/* v8 ignore next -- the disposer runs once per successful registration, so the entry it counted is still here */
|
||||
if (live === undefined) return
|
||||
live.refs -= 1
|
||||
if (live.refs === 0) this.registrations.delete(key)
|
||||
return () => {
|
||||
registration.refs -= 1
|
||||
if (registration.refs === 0) this.registrations.delete(key)
|
||||
}
|
||||
}.bind(this), 'sessionProjections.register()')
|
||||
// oxlint-disable-next-line typescript/no-misused-promises -- synchronous cleanup; keep the Cordis disposer so effects can adopt it.
|
||||
return dispose
|
||||
}, 'sessionProjections.register()')
|
||||
// Observe disposal during the asynchronous registration handoff before exposing a reader.
|
||||
await Promise.resolve()
|
||||
this.ctx.fiber.assertActive()
|
||||
return {
|
||||
dispose,
|
||||
stateOf: (session) => {
|
||||
return this.cellFor(registration, session).state as S
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -309,24 +326,6 @@ export class SessionProjectionRegistry extends Service {
|
||||
return () => void dispose()
|
||||
}
|
||||
|
||||
/**
|
||||
* Read one unit's current host state after materializing every registered
|
||||
* unit at the Session cursor. Unrelated wire views are not produced.
|
||||
* The returned value is live; callers must not mutate it.
|
||||
* @param session - the session whose state is read.
|
||||
* @param key - the registered unit key.
|
||||
* @returns current state, or `undefined` when the key is not registered.
|
||||
*/
|
||||
stateOf<K extends keyof SessionProjectionStateMap>(
|
||||
session: Session,
|
||||
key: K,
|
||||
): SessionProjectionStateMap[K] | undefined {
|
||||
const registration = this.registrations.get(key)
|
||||
if (registration === undefined) return undefined
|
||||
this.materializeCells(session)
|
||||
return this.cellFor(registration, session).state as SessionProjectionStateMap[K]
|
||||
}
|
||||
|
||||
/**
|
||||
* One consistent cut over every registered client-visible unit for one session, read from
|
||||
* the watermark cache (missing cells fold lazily over the in-memory log).
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
/** Retained readers follow Session events independently of registry participation. */
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import SessionStore from '@deepseek-ai/dsh-session'
|
||||
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
|
||||
import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection'
|
||||
import { describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { z } from 'zod'
|
||||
|
||||
declare module '@deepseek-ai/dsh-session-projection/types' {
|
||||
interface SessionProjectionStateMap {
|
||||
'test/reader': number
|
||||
'test/unrelated-reader': number
|
||||
}
|
||||
interface SessionProjectionMap {
|
||||
'test/reader': number
|
||||
}
|
||||
}
|
||||
|
||||
const definition = {
|
||||
key: 'test/reader',
|
||||
stateSchema: z.number(),
|
||||
stateVersion: 1,
|
||||
init: () => 0,
|
||||
apply: (state: number) => state + 1,
|
||||
wire: { viewSchema: z.number(), view: (state: number) => state },
|
||||
} satisfies ProjectionDefinition<'test/reader', number>
|
||||
|
||||
async function setup() {
|
||||
const ctx = new Context()
|
||||
onTestFinished(async () => { await ctx.fiber.dispose() })
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionProjectionRegistry)
|
||||
const owner = await ctx.plugin(Object.assign(function registrationOwner() {}, { inject: ['sessionProjections'] }))
|
||||
const session = ctx.sessions.create()
|
||||
return { ctx, owner, session }
|
||||
}
|
||||
|
||||
describe('retained projection readers', () => {
|
||||
it.each(['handle', 'fiber'] as const)('reads new events after %s disposal without rejoining snapshots or notifications', async (release) => {
|
||||
const { ctx, owner, session } = await setup()
|
||||
const apply = vi.fn(definition.apply)
|
||||
const handle = await owner.ctx.sessionProjections.register({ ...definition, apply })
|
||||
const changed = vi.fn()
|
||||
ctx.sessionProjections.onChanged(changed)
|
||||
expect(handle.stateOf(session)).toBe(0)
|
||||
session.append('turn/start', { turn: 1 })
|
||||
expect(handle.stateOf(session)).toBe(1)
|
||||
expect(changed).toHaveBeenCalledOnce()
|
||||
if (release === 'handle') await handle.dispose()
|
||||
else await owner.dispose()
|
||||
session.append('turn/start', { turn: 2 })
|
||||
expect(apply).toHaveBeenCalledTimes(1)
|
||||
expect(handle.stateOf(session)).toBe(2)
|
||||
expect(apply).toHaveBeenCalledTimes(2)
|
||||
expect(changed).toHaveBeenCalledOnce()
|
||||
expect(ctx.sessionProjections.snapshot(session).values).toEqual({})
|
||||
expect(ctx.sessionProjections.checkpoint(session)).toEqual({})
|
||||
const later = ctx.sessions.create()
|
||||
later.append('turn/start', { turn: 1 })
|
||||
expect(handle.stateOf(later)).toBe(1)
|
||||
})
|
||||
|
||||
it('keeps the original unit when the same key is registered with a new version', async () => {
|
||||
const { ctx, owner, session } = await setup()
|
||||
const original = await owner.ctx.sessionProjections.register(definition)
|
||||
expect(original.stateOf(session)).toBe(0)
|
||||
await original.dispose()
|
||||
const replacement = await ctx.sessionProjections.register({ ...definition, stateVersion: 2, apply: state => state + 10 })
|
||||
session.append('turn/start', { turn: 1 })
|
||||
expect(original.stateOf(session)).toBe(1)
|
||||
expect(replacement.stateOf(session)).toBe(10)
|
||||
expect(ctx.sessionProjections.snapshot(session).values).toEqual({ 'test/reader': 10 })
|
||||
})
|
||||
|
||||
it('reads only the selected unit without materializing unrelated registrations', async () => {
|
||||
const { ctx, owner, session } = await setup()
|
||||
const unrelatedInit = vi.fn(() => 0)
|
||||
await ctx.sessionProjections.register({
|
||||
key: 'test/unrelated-reader', stateSchema: z.number(), stateVersion: 1,
|
||||
init: unrelatedInit, apply: state => state,
|
||||
})
|
||||
const handle = await owner.ctx.sessionProjections.register(definition)
|
||||
expect(handle.stateOf(session)).toBe(0)
|
||||
expect(unrelatedInit).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects initialization when the owner unloads before the handle is returned', async () => {
|
||||
const { ctx, owner, session } = await setup()
|
||||
const registration = owner.ctx.sessionProjections.register(definition)
|
||||
const rejected = expect(registration).rejects.toThrow()
|
||||
await owner.dispose()
|
||||
await rejected
|
||||
expect(ctx.sessionProjections.checkpoint(session)).toEqual({})
|
||||
})
|
||||
|
||||
it.each(['twice', 'owner-unload'] as const)('releases one reference once under %s disposal', async (release) => {
|
||||
const { ctx, owner, session } = await setup()
|
||||
const retained = await ctx.sessionProjections.register(definition)
|
||||
const handle = await owner.ctx.sessionProjections.register(definition)
|
||||
if (release === 'twice') {
|
||||
await handle.dispose()
|
||||
await handle.dispose()
|
||||
} else {
|
||||
await Promise.all([owner.dispose(), Promise.resolve(handle.dispose())])
|
||||
}
|
||||
session.append('turn/start', { turn: 1 })
|
||||
expect(ctx.sessionProjections.snapshot(session).values).toEqual({ 'test/reader': 1 })
|
||||
expect(handle.stateOf(session)).toBe(1)
|
||||
await retained.dispose()
|
||||
expect(ctx.sessionProjections.snapshot(session).values).toEqual({})
|
||||
})
|
||||
|
||||
})
|
||||
@@ -165,7 +165,7 @@ describe('SessionProjectionRegistry drive', () => {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionProjectionRegistry)
|
||||
ctx.sessionProjections.register(cutUnit())
|
||||
const cut = await ctx.sessionProjections.register(cutUnit())
|
||||
const inherited: SessionEvent[] = [
|
||||
{ type: 'turn/start', seq: SessionSeq(0), time: 1, data: { turn: 1 } },
|
||||
{ type: 'turn/end', seq: SessionSeq(1), time: 2, data: { turn: 1, reason: { kind: 'completed' } } },
|
||||
@@ -176,7 +176,7 @@ describe('SessionProjectionRegistry drive', () => {
|
||||
meta: { isSeeded: true },
|
||||
})
|
||||
|
||||
expect(ctx.sessionProjections.stateOf(session, 'test/cut')).toBe(inherited.length)
|
||||
expect(cut.stateOf(session)).toBe(inherited.length)
|
||||
const restored = ctx.sessionProjections.restore(
|
||||
{},
|
||||
inherited,
|
||||
@@ -197,12 +197,12 @@ describe('SessionProjectionRegistry drive', () => {
|
||||
inherited,
|
||||
SessionLogOffset(0),
|
||||
).asOfSeq).toBe(1)
|
||||
expect(ctx.sessionProjections.stateOf(prepared, 'test/cut')).toBe(inherited.length)
|
||||
expect(cut.stateOf(prepared)).toBe(inherited.length)
|
||||
})
|
||||
|
||||
it('drives a registered unit over committed events and snapshots the current value', async () => {
|
||||
const { ctx, session } = await harness()
|
||||
ctx.sessionProjections.register(marksUnit())
|
||||
await ctx.sessionProjections.register(marksUnit())
|
||||
mark(session, ['a'])
|
||||
mark(session, ['a', 'b'])
|
||||
const snapshot = ctx.sessionProjections.snapshot(session)
|
||||
@@ -213,7 +213,7 @@ describe('SessionProjectionRegistry drive', () => {
|
||||
it('builds the cell lazily from the full log for a unit registered after events flowed', async () => {
|
||||
const { ctx, session } = await harness()
|
||||
mark(session, ['pre-registration'])
|
||||
ctx.sessionProjections.register(marksUnit())
|
||||
await ctx.sessionProjections.register(marksUnit())
|
||||
expect(ctx.sessionProjections.snapshot(session).values['test/marks']).toEqual({ marks: ['pre-registration'] })
|
||||
// The lazily-built cell then continues on the live drive path.
|
||||
mark(session, ['after'])
|
||||
@@ -222,7 +222,7 @@ describe('SessionProjectionRegistry drive', () => {
|
||||
|
||||
it('serves init-derived state and asOfSeq -1 for an empty log', async () => {
|
||||
const { ctx, session } = await harness()
|
||||
ctx.sessionProjections.register(marksUnit())
|
||||
await ctx.sessionProjections.register(marksUnit())
|
||||
const snapshot = ctx.sessionProjections.snapshot(session)
|
||||
expect(snapshot.asOfSeq).toBe(-1)
|
||||
expect(snapshot.values['test/marks']).toEqual({ marks: [] })
|
||||
@@ -230,7 +230,7 @@ describe('SessionProjectionRegistry drive', () => {
|
||||
|
||||
it('notifies onChanged with the validated view and the causing seq, and skips same-reference applies', async () => {
|
||||
const { ctx, session } = await harness()
|
||||
ctx.sessionProjections.register(marksUnit())
|
||||
await ctx.sessionProjections.register(marksUnit())
|
||||
const seen: { key: string; value: unknown; seq: SessionSeq; sessionId: string }[] = []
|
||||
ctx.sessionProjections.onChanged((changedSession, key, value, seq) => {
|
||||
seen.push({ key, value, seq, sessionId: String(changedSession.id) })
|
||||
@@ -244,19 +244,19 @@ describe('SessionProjectionRegistry drive', () => {
|
||||
it('does not compute a view while no change listener exists', async () => {
|
||||
const { ctx, session } = await harness()
|
||||
const view = vi.fn((state: StableViewState) => state.value)
|
||||
ctx.sessionProjections.register(stableViewUnit(view))
|
||||
const handle = await ctx.sessionProjections.register(stableViewUnit(view))
|
||||
|
||||
session.append('turn/start', { turn: 1 })
|
||||
session.append('turn/start', { turn: 2 })
|
||||
|
||||
expect(ctx.sessionProjections.stateOf(session, 'test/stable-view')?.revision).toBe(2)
|
||||
expect(handle.stateOf(session).revision).toBe(2)
|
||||
expect(view).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('publishes the first observed view and suppresses later same-reference views', async () => {
|
||||
const { ctx, session } = await harness()
|
||||
const view = vi.fn((state: StableViewState) => state.value)
|
||||
ctx.sessionProjections.register(stableViewUnit(view))
|
||||
await ctx.sessionProjections.register(stableViewUnit(view))
|
||||
|
||||
const seen: unknown[] = []
|
||||
ctx.sessionProjections.onChanged((_session, key, value) => {
|
||||
@@ -277,7 +277,7 @@ describe('SessionProjectionRegistry drive', () => {
|
||||
it('publishes the first view after an unobserved state change', async () => {
|
||||
const { ctx, session } = await harness()
|
||||
const view = vi.fn((state: StableViewState) => state.value)
|
||||
ctx.sessionProjections.register(stableViewUnit(view))
|
||||
await ctx.sessionProjections.register(stableViewUnit(view))
|
||||
const first: unknown[] = []
|
||||
const stop = ctx.sessionProjections.onChanged((_session, key, value) => {
|
||||
if (key === 'test/stable-view') first.push(value)
|
||||
@@ -305,7 +305,7 @@ describe('SessionProjectionRegistry drive', () => {
|
||||
const stateByEvent = new Map<string, MarksState>()
|
||||
const viewByState = new Map<MarksState, MarksView>()
|
||||
const computedViews: MarksView[] = []
|
||||
ctx.sessionProjections.register({
|
||||
await ctx.sessionProjections.register({
|
||||
key: 'test/marks',
|
||||
stateSchema: marksViewSchema.nullable(),
|
||||
init: () => initialState,
|
||||
@@ -431,7 +431,7 @@ describe('SessionProjectionRegistry drive', () => {
|
||||
it('drives independently per session (cells are per-session watermarks)', async () => {
|
||||
const { ctx, session } = await harness()
|
||||
const other = ctx.sessions.create()
|
||||
ctx.sessionProjections.register(marksUnit())
|
||||
await ctx.sessionProjections.register(marksUnit())
|
||||
mark(session, ['one'])
|
||||
mark(other, ['two'])
|
||||
expect(ctx.sessionProjections.snapshot(session).values['test/marks']).toEqual({ marks: ['one'] })
|
||||
@@ -440,70 +440,71 @@ describe('SessionProjectionRegistry drive', () => {
|
||||
|
||||
it('updates host-only units without publishing them to wire listeners', async () => {
|
||||
const { ctx, session } = await harness()
|
||||
ctx.sessionProjections.register(marksUnit())
|
||||
ctx.sessionProjections.register(countUnit())
|
||||
await ctx.sessionProjections.register(marksUnit())
|
||||
const count = await ctx.sessionProjections.register(countUnit())
|
||||
const changedKeys: string[] = []
|
||||
ctx.sessionProjections.onChanged((_session, key) => {
|
||||
changedKeys.push(key)
|
||||
})
|
||||
session.append('turn/start', { turn: 1 })
|
||||
expect(changedKeys).toEqual([])
|
||||
expect(ctx.sessionProjections.stateOf(session, 'test/count')).toBe(1)
|
||||
expect(count.stateOf(session)).toBe(1)
|
||||
expect(ctx.sessionProjections.snapshot(session).values).toEqual({ 'test/marks': { marks: [] } })
|
||||
})
|
||||
|
||||
it('shares one unit between registrants of the same key', async () => {
|
||||
const { ctx, session } = await harness()
|
||||
ctx.sessionProjections.register(marksUnit())
|
||||
await ctx.sessionProjections.register(marksUnit())
|
||||
|
||||
// One definition already serves every session (cells are keyed by
|
||||
// Session), and registrants are per-session now: an agent preset mounts
|
||||
// the same tool package once per agent.
|
||||
expect(() => ctx.sessionProjections.register(marksUnit())).not.toThrow()
|
||||
const handle = await ctx.sessionProjections.register(marksUnit())
|
||||
expect(typeof handle.stateOf).toBe('function')
|
||||
mark(session, ['kept'])
|
||||
expect(ctx.sessionProjections.snapshot(session).values['test/marks']).toEqual({ marks: ['kept'] })
|
||||
})
|
||||
|
||||
it('keeps the unit until the last registrant releases it', async () => {
|
||||
const { ctx, session } = await harness()
|
||||
const first = ctx.sessionProjections.register(marksUnit())
|
||||
const second = ctx.sessionProjections.register(marksUnit())
|
||||
const first = await ctx.sessionProjections.register(marksUnit())
|
||||
const second = await ctx.sessionProjections.register(marksUnit())
|
||||
mark(session, ['kept'])
|
||||
|
||||
first()
|
||||
await first.dispose()
|
||||
|
||||
// The regression this counts against: without last-release semantics, one
|
||||
// session ending strips the projection from every other live session,
|
||||
// because the first registrant owns the only disposer.
|
||||
expect(ctx.sessionProjections.snapshot(session).values['test/marks']).toEqual({ marks: ['kept'] })
|
||||
second()
|
||||
await second.dispose()
|
||||
expect(ctx.sessionProjections.snapshot(session).values).toEqual({})
|
||||
})
|
||||
|
||||
it('refuses to share a key across a stateVersion change', async () => {
|
||||
const { ctx } = await harness()
|
||||
ctx.sessionProjections.register(marksUnit())
|
||||
await ctx.sessionProjections.register(marksUnit())
|
||||
|
||||
// The one incompatibility a runtime comparison can name: the versioned
|
||||
// contract says the cached state shape differs, so the two cannot share
|
||||
// cells. Everything else about a definition is functions.
|
||||
expect(() => ctx.sessionProjections.register({ ...marksUnit(), stateVersion: 9 }))
|
||||
.toThrow(/already registered at stateVersion 1; refusing to share it with stateVersion 9/)
|
||||
await expect(ctx.sessionProjections.register({ ...marksUnit(), stateVersion: 9 }))
|
||||
.rejects.toThrow(/already registered at stateVersion 1; refusing to share it with stateVersion 9/)
|
||||
})
|
||||
|
||||
it('rejects a non-integer or negative stateVersion at register time', async () => {
|
||||
const { ctx } = await harness()
|
||||
expect(() => ctx.sessionProjections.register({ ...marksUnit(), stateVersion: -1 })).toThrow(/stateVersion/)
|
||||
expect(() => ctx.sessionProjections.register({ ...marksUnit(), stateVersion: 1.5 })).toThrow(/stateVersion/)
|
||||
await expect(ctx.sessionProjections.register({ ...marksUnit(), stateVersion: -1 })).rejects.toThrow(/stateVersion/)
|
||||
await expect(ctx.sessionProjections.register({ ...marksUnit(), stateVersion: 1.5 })).rejects.toThrow(/stateVersion/)
|
||||
})
|
||||
|
||||
it('register() disposer removes the key (with its cells) and frees it for re-registration', async () => {
|
||||
const { ctx, session } = await harness()
|
||||
const dispose = ctx.sessionProjections.register(marksUnit())
|
||||
const dispose = await ctx.sessionProjections.register(marksUnit())
|
||||
mark(session, ['cached'])
|
||||
dispose()
|
||||
await dispose.dispose()
|
||||
expect(ctx.sessionProjections.snapshot(session).values).toEqual({})
|
||||
ctx.sessionProjections.register(marksUnit())
|
||||
await ctx.sessionProjections.register(marksUnit())
|
||||
// Fresh registration rebuilds from the log, not from a stale cell.
|
||||
expect(ctx.sessionProjections.snapshot(session).values['test/marks']).toEqual({ marks: ['cached'] })
|
||||
})
|
||||
@@ -511,8 +512,8 @@ describe('SessionProjectionRegistry drive', () => {
|
||||
it('removes registrations and change listeners when their owning fiber unloads (HMR safety)', async () => {
|
||||
const { ctx, session } = await harness()
|
||||
const notifications: string[] = []
|
||||
const fiber = await ctx.plugin(Object.assign((inner: Context) => {
|
||||
inner.sessionProjections.register(marksUnit())
|
||||
const fiber = await ctx.plugin(Object.assign(async (inner: Context) => {
|
||||
await inner.sessionProjections.register(marksUnit())
|
||||
inner.sessionProjections.onChanged((_session, key) => {
|
||||
notifications.push(key)
|
||||
})
|
||||
@@ -525,38 +526,36 @@ describe('SessionProjectionRegistry drive', () => {
|
||||
expect(ctx.sessionProjections.snapshot(session).values).toEqual({})
|
||||
})
|
||||
|
||||
it('keeps a yielded registration live until the composite finishes using it', async () => {
|
||||
it('retains readable state during owner teardown', async () => {
|
||||
const { ctx, session } = await harness()
|
||||
onTestFinished(async () => { await ctx.fiber.dispose() })
|
||||
let observed: MarksState | undefined
|
||||
const fiber = await ctx.plugin(Object.assign((inner: Context) => {
|
||||
inner.effect(function* () {
|
||||
yield inner.sessionProjections.register(marksUnit())
|
||||
yield () => { observed = inner.sessionProjections.stateOf(session, 'test/marks') }
|
||||
})
|
||||
const fiber = await ctx.plugin(Object.assign(async (inner: Context) => {
|
||||
const handle = await inner.sessionProjections.register(marksUnit())
|
||||
inner.effect(() => () => { observed = handle.stateOf(session) })
|
||||
}, { inject: ['sessionProjections'] }))
|
||||
mark(session, ['live'])
|
||||
await fiber.dispose()
|
||||
expect(observed).toEqual({ marks: ['live'] })
|
||||
expect(ctx.sessionProjections.stateOf(session, 'test/marks')).toBeUndefined()
|
||||
expect(ctx.sessionProjections.snapshot(session).values['test/marks']).toBeUndefined()
|
||||
})
|
||||
|
||||
it('snapshot serves client views and excludes host-only state', async () => {
|
||||
const { ctx, session } = await harness()
|
||||
ctx.sessionProjections.register(marksUnit())
|
||||
ctx.sessionProjections.register(countUnit())
|
||||
await ctx.sessionProjections.register(marksUnit())
|
||||
const count = await ctx.sessionProjections.register(countUnit())
|
||||
mark(session, ['a', 'b'])
|
||||
const values = ctx.sessionProjections.snapshot(session).values
|
||||
expect(values['test/marks']).toEqual({ marks: ['a', 'b'] })
|
||||
expect('test/count' in values).toBe(false)
|
||||
expect(ctx.sessionProjections.stateOf(session, 'test/count')).toBe(1)
|
||||
expect(count.stateOf(session)).toBe(1)
|
||||
expect('test/unregistered' in values).toBe(false)
|
||||
})
|
||||
|
||||
it('checkpoints every persisted unit with its stateVersion and per-cell watermark', async () => {
|
||||
const { ctx, session } = await harness()
|
||||
ctx.sessionProjections.register(marksUnit())
|
||||
ctx.sessionProjections.register({ ...countUnit(), stateVersion: 7 })
|
||||
await ctx.sessionProjections.register(marksUnit())
|
||||
await ctx.sessionProjections.register({ ...countUnit(), stateVersion: 7 })
|
||||
const markEvent = mark(session, ['a'])
|
||||
const rows = ctx.sessionProjections.checkpoint(session)
|
||||
expect(rows['test/marks']).toEqual({ ver: 1, seq: markEvent.seq, val: { marks: ['a'] } })
|
||||
@@ -568,7 +567,7 @@ describe('SessionProjectionRegistry drive', () => {
|
||||
|
||||
it('checkpoint states are detached clones — mutating them cannot corrupt the watermark cache', async () => {
|
||||
const { ctx, session } = await harness()
|
||||
ctx.sessionProjections.register(marksUnit())
|
||||
await ctx.sessionProjections.register(marksUnit())
|
||||
mark(session, ['a'])
|
||||
const rows = ctx.sessionProjections.checkpoint(session)
|
||||
// Hostile (or merely careless) consumer mutates the handed-out state.
|
||||
@@ -582,8 +581,8 @@ describe('SessionProjectionRegistry drive', () => {
|
||||
it('restoreFloor anchors one below the lowest usable watermark and at 0 for missing or mismatched rows', async () => {
|
||||
const { ctx } = await harness()
|
||||
expect(ctx.sessionProjections.restoreFloor({})).toBeUndefined() // no unit registered
|
||||
ctx.sessionProjections.register(marksUnit())
|
||||
ctx.sessionProjections.register(countUnit())
|
||||
await ctx.sessionProjections.register(marksUnit())
|
||||
await ctx.sessionProjections.register(countUnit())
|
||||
expect(ctx.sessionProjections.restoreFloor({})).toBe(0)
|
||||
// Lowest usable watermark is count's 5 → the anchored tail starts AT 5
|
||||
// (one below the first needed seq 6), so the read proves seq 5 still exists.
|
||||
@@ -605,8 +604,8 @@ describe('SessionProjectionRegistry drive', () => {
|
||||
|
||||
it('restore folds the tail past each usable row and refolds from init on version mismatch', async () => {
|
||||
const { ctx } = await harness()
|
||||
ctx.sessionProjections.register(marksUnit())
|
||||
ctx.sessionProjections.register(countUnit())
|
||||
await ctx.sessionProjections.register(marksUnit())
|
||||
await ctx.sessionProjections.register(countUnit())
|
||||
const tail: SessionEvent[] = [
|
||||
{ type: 'test/mark', seq: SessionSeq(3), time: 3, data: { marks: ['new'] } },
|
||||
{ type: 'turn/end', seq: SessionSeq(4), time: 4, data: { turn: 1, reason: { kind: 'completed' } } },
|
||||
@@ -639,8 +638,8 @@ describe('SessionProjectionRegistry drive', () => {
|
||||
|
||||
it('restore over a suffix folds only past each row watermark and serves an exact empty-tail cut', async () => {
|
||||
const { ctx } = await harness()
|
||||
ctx.sessionProjections.register(marksUnit())
|
||||
ctx.sessionProjections.register(countUnit())
|
||||
await ctx.sessionProjections.register(marksUnit())
|
||||
await ctx.sessionProjections.register(countUnit())
|
||||
const rows = {
|
||||
'test/marks': { ver: 1, seq: SessionSeq(4), val: { marks: ['done'] } },
|
||||
'test/count': { ver: 1, seq: SessionSeq(2), val: 3 },
|
||||
@@ -675,8 +674,8 @@ describe('SessionProjectionRegistry drive', () => {
|
||||
|
||||
it('viewCheckpoint serves version-matching rows without any log and skips mismatched keys', async () => {
|
||||
const { ctx } = await harness()
|
||||
ctx.sessionProjections.register(marksUnit())
|
||||
ctx.sessionProjections.register(countUnit())
|
||||
await ctx.sessionProjections.register(marksUnit())
|
||||
await ctx.sessionProjections.register(countUnit())
|
||||
const values = ctx.sessionProjections.viewCheckpoint({
|
||||
'test/marks': { ver: 1, seq: SessionSeq(4), val: { marks: ['stored'] } },
|
||||
'test/count': { ver: 99, seq: SessionSeq(4), val: 5 }, // mismatched: absent
|
||||
@@ -688,8 +687,8 @@ describe('SessionProjectionRegistry drive', () => {
|
||||
|
||||
it('viewCheckpoint and restore exclude host-only state while retaining its checkpoint', async () => {
|
||||
const { ctx } = await harness()
|
||||
ctx.sessionProjections.register(marksUnit())
|
||||
ctx.sessionProjections.register(countUnit())
|
||||
await ctx.sessionProjections.register(marksUnit())
|
||||
await ctx.sessionProjections.register(countUnit())
|
||||
const rows = {
|
||||
'test/marks': { ver: 1, seq: SessionSeq(4), val: { marks: ['stored'] } },
|
||||
'test/count': { ver: 1, seq: SessionSeq(4), val: 5 },
|
||||
@@ -713,7 +712,7 @@ describe('SessionProjectionRegistry drive', () => {
|
||||
|
||||
it('rejects version-matching rows whose state no longer matches the registered schema', async () => {
|
||||
const { ctx } = await harness()
|
||||
ctx.sessionProjections.register(marksUnit())
|
||||
await ctx.sessionProjections.register(marksUnit())
|
||||
const drifted = {
|
||||
'test/marks': { ver: 1, seq: SessionSeq(2), val: { marks: 'not-an-array' } },
|
||||
}
|
||||
@@ -730,7 +729,7 @@ describe('SessionProjectionRegistry drive', () => {
|
||||
|
||||
it('restore rejects a row claiming events past the supplied log end (shrunk log ⇒ re-read)', async () => {
|
||||
const { ctx } = await harness()
|
||||
ctx.sessionProjections.register(countUnit())
|
||||
await ctx.sessionProjections.register(countUnit())
|
||||
const rows = { 'test/count': { ver: 1, seq: SessionSeq(9), val: 10 } }
|
||||
// The anchored floor sits ON the watermark, so the tail read must return
|
||||
// at least seq 9 from an intact log…
|
||||
@@ -775,7 +774,7 @@ describe('SessionProjectionRegistry drive', () => {
|
||||
|
||||
it('fails loud when a unit view violates its own schema (async unit output is unrepresentable)', async () => {
|
||||
const { ctx, session } = await harness()
|
||||
ctx.sessionProjections.register({
|
||||
await ctx.sessionProjections.register({
|
||||
key: 'test/marks',
|
||||
stateSchema: z.object({ marks: z.array(z.string()) }).nullable(),
|
||||
init: () => null as MarksState,
|
||||
|
||||
Reference in new issue
Block a user